html_formimpl.cpp 96.7 KB
Newer Older
George Staikos's avatar
George Staikos committed
1 2 3 4 5 6
/*
 * This file is part of the DOM implementation for KDE.
 *
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
7
 *           (C) 2004, 2005, 2006 Apple Computer, Inc.
George Staikos's avatar
George Staikos committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#undef FORMS_DEBUG
//#define FORMS_DEBUG

#include "html/html_formimpl.h"

#include "khtmlview.h"
#include "khtml_part.h"
#include "html/html_documentimpl.h"
#include "khtml_settings.h"

#include "css/cssstyleselector.h"
#include "css/cssproperties.h"
#include "css/cssvalues.h"
#include "xml/dom_textimpl.h"
#include "xml/dom_docimpl.h"
#include "xml/dom2_eventsimpl.h"
42
#include "xml/dom_restyler.h"
George Staikos's avatar
George Staikos committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#include "khtml_ext.h"

#include "rendering/render_form.h"

#include <kcharsets.h>
#include <kglobal.h>
#include <kdebug.h>
#include <kmimetype.h>
#include <kmessagebox.h>
#include <krandom.h>
#include <klocale.h>
#ifndef KHTML_NO_WALLET
#include <kwallet.h>
#endif
#include <netaccess.h>
#include <kfileitem.h>
Dirk Mueller's avatar
Dirk Mueller committed
59 60 61
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QTextCodec>
George Staikos's avatar
George Staikos committed
62 63

// for keygen
Dirk Mueller's avatar
Dirk Mueller committed
64
#include <QtCore/QCharRef>
George Staikos's avatar
George Staikos committed
65 66 67 68
#include <ksslkeygen.h>

#include <assert.h>

Maks Orlovich's avatar
Maks Orlovich committed
69

George Staikos's avatar
George Staikos committed
70 71
using namespace DOM;
using namespace khtml;
72
using namespace WTF;
George Staikos's avatar
George Staikos committed
73

Germain Garand's avatar
Germain Garand committed
74
HTMLFormElementImpl::HTMLFormElementImpl(DocumentImpl *doc, bool implicit)
George Staikos's avatar
George Staikos committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    : HTMLElementImpl(doc)
{
    m_implicit = implicit;
    m_post = false;
    m_multipart = false;
    m_autocomplete = true;
    m_insubmit = false;
    m_doingsubmit = false;
    m_inreset = false;
    m_enctype = "application/x-www-form-urlencoded";
    m_boundary = "----------" + KRandom::randomString( 42 + 13 );
    m_acceptcharset = "UNKNOWN";
    m_malformed = false;
}

HTMLFormElementImpl::~HTMLFormElementImpl()
{
92 93
    if (document() && document()->view() && document()->view()->part()) {
        document()->view()->part()->dequeueWallet(this);
George Staikos's avatar
George Staikos committed
94
    }
Germain Garand's avatar
Germain Garand committed
95 96 97 98 99 100
    QListIterator<HTMLGenericFormElementImpl*> it(formElements);
    while (it.hasNext())
        it.next()->m_form = 0;
    QListIterator<HTMLImageElementImpl*> it2(imgElements);
    while (it2.hasNext())
        it2.next()->m_form = 0;
George Staikos's avatar
George Staikos committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
}

NodeImpl::Id HTMLFormElementImpl::id() const
{
    return ID_FORM;
}

HTMLCollectionImpl* HTMLFormElementImpl::elements()
{
    return new HTMLFormCollectionImpl(this);
}

DOMString HTMLFormElementImpl::target() const
{
  return getAttribute(ATTR_TARGET);
}

DOMString HTMLFormElementImpl::action() const
{
  return getAttribute(ATTR_ACTION);
}


long HTMLFormElementImpl::length() const
{
    int len = 0;
Germain Garand's avatar
Germain Garand committed
127 128
    QListIterator<HTMLGenericFormElementImpl*> it(formElements);
    while (it.hasNext())
129
	if (it.next()->isEnumerable())
George Staikos's avatar
George Staikos committed
130 131 132 133 134 135 136 137 138
	    ++len;

    return len;
}

static QByteArray encodeCString(const QByteArray& e)
{
    // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
    // safe characters like NS handles them for compatibility
139
    static const char safe[] = "-._*";
George Staikos's avatar
George Staikos committed
140
    QByteArray encoded(( e.length()+e.count( '\n' ) )*3
141
                     +e.count('\r') * 3 + 1, 0);
George Staikos's avatar
George Staikos committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    int enclen = 0;
    bool crmissing = false;
    unsigned char oldc;
    unsigned char c ='\0';

    //QCString orig(e.data(), e.size());

    unsigned len = e.length();
    for(unsigned pos = 0; pos < len; pos++) {
        oldc = c;
        c = e[pos];

        if (crmissing && c != '\n') {
            encoded[enclen++] = '%';
            encoded[enclen++] = '0';
            encoded[enclen++] = 'D';
            crmissing = false;
        }

        if ( (( c >= 'A') && ( c <= 'Z')) ||
             (( c >= 'a') && ( c <= 'z')) ||
             (( c >= '0') && ( c <= '9')) ||
             (strchr(safe, c))
            )
            encoded[enclen++] = c;
        else if ( c == ' ' )
            encoded[enclen++] = '+';
        else if ( c == '\n' )
        {
            encoded[enclen++] = '%';
            encoded[enclen++] = '0';
            encoded[enclen++] = 'D';
            encoded[enclen++] = '%';
            encoded[enclen++] = '0';
            encoded[enclen++] = 'A';
            crmissing = false;
        }
        else if (c == '\r' && oldc != '\n') {
            crmissing = true;
        }
        else if ( c != '\r' )
        {
            encoded[enclen++] = '%';
            unsigned int h = c / 16;
            h += (h > 9) ? ('A' - 10) : '0';
            encoded[enclen++] = h;

            unsigned int l = c % 16;
            l += (l > 9) ? ('A' - 10) : '0';
            encoded[enclen++] = l;
        }
    }
    encoded.truncate(enclen);
    return encoded;
}

Maks Orlovich's avatar
Maks Orlovich committed
198 199 200 201 202 203 204
inline static QString ampersandEscape(unsigned val)
{
    QString out;
    out.sprintf("&#%u;", val);
    return out;
}

George Staikos's avatar
George Staikos committed
205
inline static QString escapeUnencodeable(const QTextCodec* codec, const QString& s) {
Maks Orlovich's avatar
Maks Orlovich committed
206
    QString encString;
George Staikos's avatar
George Staikos committed
207
    const int len = s.length();
Maks Orlovich's avatar
Maks Orlovich committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

    for (int i = 0; i < len; ++i) {
        QChar c = s[i];

        // We need to hand surrogate pairs to the codec at once;
        // also do validity checking on those
        if (c.isLowSurrogate()) {
            c = QChar::ReplacementCharacter;
        } else if (c.isHighSurrogate()) {
            if ((i + 1) < len && s[i + 1].isLowSurrogate()) {
                // A valid SP..
                ++i;
                QString pair = QString(c) + s[i];
                if (codec->canEncode(pair))
                    encString += pair;
                else
                    encString += ampersandEscape(QChar::surrogateToUcs4(c, s[i]));
                continue;
            } else {
                c  = QChar::ReplacementCharacter;
            }
George Staikos's avatar
George Staikos committed
229
        }
Maks Orlovich's avatar
Maks Orlovich committed
230 231 232 233 234 235

        // Normal characters.
        if (codec->canEncode(c))
            encString.append(c);
        else
            encString.append(ampersandEscape(c.unicode()));
George Staikos's avatar
George Staikos committed
236
    }
Maks Orlovich's avatar
Maks Orlovich committed
237
    return encString;
George Staikos's avatar
George Staikos committed
238 239 240 241 242 243 244 245 246
}

inline static QByteArray fixUpfromUnicode(const QTextCodec* codec, const QString& s)
{
    QByteArray str = codec->fromUnicode(escapeUnencodeable(codec,s));
    str.truncate(str.length());
    return str;
}

247 248 249 250 251 252 253 254 255 256 257 258 259
Vector<HTMLGenericFormElementImpl*> HTMLFormElementImpl::gatherInTreeOrder(NodeImpl* root,
                                                               const HashSet<NodeImpl*>& toGather)
{
    Vector<HTMLGenericFormElementImpl*> out;
    out.reserveCapacity(toGather.size());
    
    for (NodeImpl* cur = root; cur; cur = cur->traverseNextNode(root)) {
        if (toGather.contains(cur))
            out.append(static_cast<HTMLGenericFormElementImpl*>(cur));
    }
    return out;
}

George Staikos's avatar
George Staikos committed
260 261 262
QByteArray HTMLFormElementImpl::formData(bool& ok)
{
#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
263
    kDebug( 6030 ) << "form: formData()";
George Staikos's avatar
George Staikos committed
264 265
#endif

266
    QByteArray form_data;
267
    QByteArray enc_string; // used for non-multipart data
George Staikos's avatar
George Staikos committed
268

269 270
    bool useMultipart = m_multipart && m_post; // as multipart is ignored for GET

George Staikos's avatar
George Staikos committed
271 272 273
    // find out the QTextcodec to use
    QString str = m_acceptcharset.string();
    QTextCodec* codec = 0;
274
    bool codecOk = false;
George Staikos's avatar
George Staikos committed
275

276 277 278 279 280 281 282 283 284 285 286 287 288 289
    if (str == "UNKNOWN") {
        // no accept-charset attribute, try document encoding
        KHTMLView *view = document()->view();
        if (view && view->part()) {
            codec = KGlobal::charsets()->codecForName(view->part()->encoding(), codecOk);
        }
    }

    if (!codecOk) {
        str.replace(QLatin1Char(','), QLatin1Char(' '));
        const QStringList charsets = str.split(QLatin1Char(' '), QString::SkipEmptyParts);
        for (QStringList::ConstIterator it = charsets.constBegin(); it != charsets.constEnd(); ++it) {
            codec = KGlobal::charsets()->codecForName((*it), codecOk);
            if (codecOk) {
George Staikos's avatar
George Staikos committed
290
                break;
291
            }
George Staikos's avatar
George Staikos committed
292 293
        }
    }
294 295 296 297 298 299 300

    if (!codecOk) {
        // none of requested could be used fallback to UTF-8
        codec = KGlobal::charsets()->codecForName("UTF-8", codecOk);
    }

    if (!codecOk)
George Staikos's avatar
George Staikos committed
301 302 303 304 305
        codec = QTextCodec::codecForLocale();

    // we need to map visual hebrew to logical hebrew, as the web
    // server alsways expects responses in logical ordering
    if ( codec->mibEnum() == 11 )
306
        codec = QTextCodec::codecForMib( 85 );
George Staikos's avatar
George Staikos committed
307 308

    QStringList fileUploads, fileNotUploads;
309

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    /**
     Frameworks such as mootools Sortables expect form element values to be submitted in 
     tree order (and HTML5 specifies this behavior); however formElements need not be 
     ordered thus. Hence we walk through the tree and the formElements as we go --- 
     first in our kids, then if needed in the parent
    */
    HashSet<NodeImpl*> formElementsSet;
    foreach (HTMLGenericFormElementImpl* fe, formElements)
        formElementsSet.add(fe);
        
    Vector<HTMLGenericFormElementImpl*> ordered = gatherInTreeOrder(this, formElementsSet);
    
    if (ordered.size() < (unsigned)formElements.size()) {
        // Some of our elements not contained within us due to parsing hijinks -- scan 
        // the entire document.
        ordered = gatherInTreeOrder(document()->documentElement(), formElementsSet);
    }
George Staikos's avatar
George Staikos committed
327

328 329
    for (unsigned i = 0; i < ordered.size(); ++i) {
        HTMLGenericFormElementImpl* const current = ordered[i];
George Staikos's avatar
George Staikos committed
330 331
        khtml::encodingList lst;

332
        if (!current->disabled() && current->encoding(codec, lst, useMultipart))
George Staikos's avatar
George Staikos committed
333
        {
Laurent Montel's avatar
Laurent Montel committed
334
            //kDebug(6030) << "adding name '" << current->name().string() << "'";
335 336 337
            khtml::encodingList::ConstIterator it = lst.constBegin();
            const khtml::encodingList::ConstIterator itEnd = lst.constEnd();
            for( ; it != itEnd; ++it )
George Staikos's avatar
George Staikos committed
338
            {
339
                if (!useMultipart)
George Staikos's avatar
George Staikos committed
340 341 342 343 344 345 346 347 348 349 350 351
                {
                    // handle ISINDEX / <input name=isindex> special
                    // but only if its the first entry
                    if ( enc_string.isEmpty() && *it == "isindex" ) {
                        ++it;
                        enc_string += encodeCString( *it );
                    }
                    else {
                        if(!enc_string.isEmpty())
                            enc_string += '&';

                        enc_string += encodeCString(*it);
Laurent Montel's avatar
Fix ebn  
Laurent Montel committed
352
                        enc_string += '=';
George Staikos's avatar
George Staikos committed
353 354 355 356 357 358 359
                        ++it;
                        enc_string += encodeCString(*it);
                    }
                }
                else
                {
                    QByteArray hstr("--");
360
                    hstr += m_boundary.toLatin1();
George Staikos's avatar
George Staikos committed
361 362 363 364 365 366 367 368
                    hstr += "\r\n";
                    hstr += "Content-Disposition: form-data; name=\"";
                    hstr += (*it).data();
                    hstr += "\"";

                    // if the current type is FILE, then we also need to
                    // include the filename
                    if (current->id() == ID_INPUT &&
Maks Orlovich's avatar
Maks Orlovich committed
369
                        static_cast<HTMLInputElementImpl*>(current)->inputType() == HTMLInputElementImpl::FILE)
George Staikos's avatar
George Staikos committed
370
                    {
371
                        KUrl path;
George Staikos's avatar
George Staikos committed
372 373 374 375 376 377
                        QString val = static_cast<HTMLInputElementImpl*>(current)->value().string().trimmed();
                        if (!val.isEmpty() &&
                            QDir::isRelativePath(val) &&
                            QFile::exists(KGlobalSettings::documentPath() + val)) {
                            path.setPath(KGlobalSettings::documentPath() + val);
                        } else {
378
                            path = KUrl(val);
George Staikos's avatar
George Staikos committed
379 380 381 382
                        }

                        hstr += fixUpfromUnicode(codec, "; filename=\"" + path.fileName() + "\"");
                        if (path.isValid()) {
383
                            fileUploads << path.pathOrUrl();
384
                            const KMimeType::Ptr ptr = KMimeType::findByUrl(path);
George Staikos's avatar
George Staikos committed
385 386
                            if (!ptr->name().isEmpty()) {
                                hstr += "\r\nContent-Type: ";
387
                                hstr += ptr->name().toLatin1().constData();
George Staikos's avatar
George Staikos committed
388 389
                            }
                        } else if (!val.isEmpty()) {
390
                            fileNotUploads << path.pathOrUrl();
George Staikos's avatar
George Staikos committed
391 392 393 394 395 396 397
                        }
                    }

                    hstr += "\r\n\r\n";
                    ++it;

                    // append body
398 399 400
                    form_data.append(hstr);
                    form_data.append(*it);
                    form_data.append("\r\n");
401

George Staikos's avatar
George Staikos committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		    // reset unsubmittedFormChange flag
                    if (current->id() == ID_INPUT &&
                        static_cast<HTMLInputElementImpl*>(current)->inputType() == HTMLInputElementImpl::TEXT)
                        static_cast<HTMLInputElementImpl*>(current)->setUnsubmittedFormChange(false);

                    if (current->id() == ID_TEXTAREA)
                        static_cast<HTMLTextAreaElementImpl*>(current)->setUnsubmittedFormChange(false);

                }
            }
        }
    }

    if (fileNotUploads.count()) {
        const int result = KMessageBox::warningContinueCancelList( 0,
                                                             i18n("The following files will not be uploaded"
                                                                  " because they could not be found.\n"
                                                                  "Do you want to continue?"),
                                                             fileNotUploads,
421
                                                             i18n("Submit Confirmation"),KGuiItem(i18n("&Submit Anyway"), "dialog-ok"));
George Staikos's avatar
George Staikos committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435


        if (result == KMessageBox::Cancel) {
            ok = false;
            return QByteArray();
        }
    }

    if (fileUploads.count()) {
        const int result = KMessageBox::warningContinueCancelList( 0,
                                                             i18n("You are about to transfer the following files from "
                                                                  "your local computer to the Internet.\n"
                                                                  "Do you really want to continue?"),
                                                             fileUploads,
436
                                                             i18n("Send Confirmation"),KGuiItem(i18np("&Send File", "&Send Files", fileUploads.count()), "document-export"));
George Staikos's avatar
George Staikos committed
437 438 439 440 441 442 443 444


        if (result == KMessageBox::Cancel) {
            ok = false;
            return QByteArray();
        }
    }

445
    if (useMultipart)
446
        enc_string = QString("--" + m_boundary + "--\r\n").toLatin1().constData();
George Staikos's avatar
George Staikos committed
447

448
    form_data.append(enc_string.constData());
George Staikos's avatar
George Staikos committed
449 450 451 452
    ok = true;
    return form_data;
}

453
void HTMLFormElementImpl::setEnctype(const DOMString& type)
George Staikos's avatar
George Staikos committed
454
{
455 456 457 458 459
    if (type.isEmpty()) { // optimization: majority of real world cases
        m_enctype = "application/x-www-form-urlencoded";
        m_multipart = false;
    }
    else if (strcasecmp(type, "multipart/form-data") == 0) {
George Staikos's avatar
George Staikos committed
460 461 462
        m_enctype = "multipart/form-data";
        m_multipart = true;
    }
463
    else if (strcasecmp(type, "text/plain") == 0) {
464
        m_enctype = "text/plain";
465 466 467 468 469
        m_multipart = false;
    }
    else {
        m_enctype = "application/x-www-form-urlencoded";
        m_multipart = false;
George Staikos's avatar
George Staikos committed
470 471 472 473 474
    }
}

static QString calculateAutoFillKey(const HTMLFormElementImpl& e)
{
475
    KUrl k(e.document()->URL());
George Staikos's avatar
George Staikos committed
476 477 478 479 480 481 482
    k.setRef(QString());
    k.setQuery(QString());
    // ensure that we have the user / password inside the url
    // otherwise we might have a potential security problem
    // by saving passwords under wrong lookup key.
    const QString name = e.getAttribute(ATTR_NAME).string().trimmed();
    const QRegExp re("[;,!]");
483
    const QStringList url = k.url().split(re);
George Staikos's avatar
George Staikos committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497
    return url[0] + '#' + name;
}

void HTMLFormElementImpl::doAutoFill()
{
#ifndef KHTML_NO_WALLET
    const QString key = calculateAutoFillKey(*this);

    if (KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(),
                                         KWallet::Wallet::FormDataFolder(),
                                         key))
        return;

    // assert(view())
498
    document()->view()->part()->openWallet(this);
George Staikos's avatar
George Staikos committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
#endif // KHTML_NO_WALLET
}


void HTMLFormElementImpl::walletOpened(KWallet::Wallet *w) {
#ifndef KHTML_NO_WALLET
    assert(w);
    const QString key = calculateAutoFillKey(*this);
    if (!w->hasFolder(KWallet::Wallet::FormDataFolder())) {
        return; // failed
    }
    w->setFolder(KWallet::Wallet::FormDataFolder());
    QMap<QString, QString> map;
    if (w->readMap(key, map))
        return; // failed, abort

515 516 517 518
    if(document()->view())
    {
        document()->view()->part()->addWalletFormKey(key);
    }
Germain Garand's avatar
Germain Garand committed
519 520 521 522
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
        HTMLGenericFormElementImpl* const cur = it.next();
        if (cur->id() == ID_INPUT) {
            HTMLInputElementImpl* const current = static_cast<HTMLInputElementImpl*>(cur);
George Staikos's avatar
George Staikos committed
523 524 525 526
            if ((current->inputType() == HTMLInputElementImpl::PASSWORD ||
                    current->inputType() == HTMLInputElementImpl::TEXT) &&
                    !current->readOnly() &&
                    map.contains(current->name().string())) {
527
                document()->setFocusNode(current);
528
                current->setValue(map.value(current->name().string()));
George Staikos's avatar
George Staikos committed
529 530 531 532 533 534 535 536 537 538 539 540
            }
        }
    }
#endif // KHTML_NO_WALLET
}

void HTMLFormElementImpl::submitFromKeyboard()
{
    // Activate the first nondisabled submit button
    // if there is none, do a submit anyway if not more
    // than one <input type=text> or <input type=password>
    unsigned int inputtext = 0;
Germain Garand's avatar
Germain Garand committed
541 542 543 544
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
        HTMLGenericFormElementImpl* const cur = it.next();
        if (cur->id() == ID_BUTTON) {
            HTMLButtonElementImpl* const current = static_cast<HTMLButtonElementImpl *>(cur);
George Staikos's avatar
George Staikos committed
545 546 547 548
            if (current->buttonType() == HTMLButtonElementImpl::SUBMIT && !current->disabled()) {
                current->click();
                return;
            }
Germain Garand's avatar
Germain Garand committed
549 550
        } else if (cur->id() == ID_INPUT) {
            HTMLInputElementImpl* const current = static_cast<HTMLInputElementImpl *>(cur);
George Staikos's avatar
George Staikos committed
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
            switch(current->inputType())  {
            case HTMLInputElementImpl::SUBMIT:
            case HTMLInputElementImpl::IMAGE:
		if(!current->disabled()) {
			current->click();
			return;
		}
		break;
            case HTMLInputElementImpl::TEXT:
            case HTMLInputElementImpl::PASSWORD:
                ++inputtext;
            default:
                break;
            }
        }
    }

    if (inputtext <= 1)
        prepareSubmit();
}


void HTMLFormElementImpl::gatherWalletData()
{
#ifndef KHTML_NO_WALLET
576
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
577 578 579 580
    // check if we have any password input's
    m_walletMap.clear();
    m_havePassword = false;
    m_haveTextarea = false;
581
    const KUrl formUrl(document()->URL());
582
    if (view && !view->nonPasswordStorableSite(formUrl.host())) {
Germain Garand's avatar
Germain Garand committed
583 584 585 586
        for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
            HTMLGenericFormElementImpl* const cur = it.next();
            if (cur->id() == ID_INPUT)  {
                HTMLInputElementImpl* const c = static_cast<HTMLInputElementImpl*> (cur);
George Staikos's avatar
George Staikos committed
587 588 589 590 591 592 593 594 595
                if ((c->inputType() == HTMLInputElementImpl::TEXT ||
                        c->inputType() == HTMLInputElementImpl::PASSWORD) &&
                        !c->readOnly())  {
                    m_walletMap.insert(c->name().string(), c->value().string());
                    if (c->inputType() == HTMLInputElementImpl::PASSWORD &&
                            !c->value().isEmpty())
                        m_havePassword = true;
                }
            }
Germain Garand's avatar
Germain Garand committed
596
            else if (cur->id() == ID_TEXTAREA)
George Staikos's avatar
George Staikos committed
597 598 599 600 601 602 603 604 605
                m_haveTextarea = true;
        }
    }
#endif // KHTML_NO_WALLET
}


bool HTMLFormElementImpl::prepareSubmit()
{
606
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    if(m_insubmit || !view || !view->part() || view->part()->onlyLocalReferences())
        return m_insubmit;

    gatherWalletData();

    m_insubmit = true;
    m_doingsubmit = false;

    if ( dispatchHTMLEvent(EventImpl::SUBMIT_EVENT,true,true) && !m_doingsubmit )
        m_doingsubmit = true;

    m_insubmit = false;

    if ( m_doingsubmit )
        submit();

    return m_doingsubmit;
}

void HTMLFormElementImpl::submit(  )
{
    if ( m_insubmit ) {
        m_doingsubmit = true;
        return;
    }

    m_insubmit = true;

#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
636
    kDebug( 6030 ) << "submitting!";
George Staikos's avatar
George Staikos committed
637 638 639
#endif

    bool ok;
640
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
641
    const QByteArray form_data = formData(ok);
642
    const KUrl formUrl(document()->URL());
George Staikos's avatar
George Staikos committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660

    if (ok && view) {
        if (m_walletMap.isEmpty()) {
            gatherWalletData();
        }
#ifndef KHTML_NO_WALLET
        if (m_havePassword && !m_haveTextarea && KWallet::Wallet::isEnabled()) {
            const QString key = calculateAutoFillKey(*this);
            const bool doesnotexist = KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(), KWallet::Wallet::FormDataFolder(), key);
            KWallet::Wallet* const w = view->part()->wallet();
            bool login_changed = false;

            if (!doesnotexist && w) {
                // check if the login information changed from what
                // we had so far.
                if (w->hasFolder(KWallet::Wallet::FormDataFolder())) {
                    w->setFolder(KWallet::Wallet::FormDataFolder());
                    QMap<QString, QString> map;
661
                    if ( !w->readMap(key, map) && (map.count() == m_walletMap.count()) ) {
662 663
                        QMap<QString, QString>::const_iterator it = map.constBegin();
                        const QMap<QString, QString>::const_iterator itEnd = map.constEnd();
George Staikos's avatar
George Staikos committed
664
                        for ( ; it != itEnd; ++it )
665
                            if ( it.value() != m_walletMap.value(it.key()) ) {
George Staikos's avatar
George Staikos committed
666 667 668 669 670 671 672 673 674 675
                                login_changed = true;
                                break;
                            }
                    } else {
                        login_changed = true;
                    }
                }
            }

            if ( doesnotexist || !w || login_changed ) {
676 677
                if (view->part())
                    view->part()->saveLoginInformation(formUrl.host(), key, m_walletMap);
George Staikos's avatar
George Staikos committed
678 679 680 681
            }
        }
#endif // KHTML_NO_WALLET

682
        QString url = getAttribute(ATTR_ACTION).trimSpaces().string();
683
        // ignore base url if 'action' attribute is empty.
684
        if (url.isEmpty())
685
            url = formUrl.url();
George Staikos's avatar
George Staikos committed
686
        if(m_post) {
687
            view->part()->submitForm( "post", url, form_data,
George Staikos's avatar
George Staikos committed
688
                                      m_target.string(),
689
                                      enctype().string(),
George Staikos's avatar
George Staikos committed
690 691 692
                                      m_boundary );
        }
        else {
693
            view->part()->submitForm( "get", url, form_data,
George Staikos's avatar
George Staikos committed
694 695 696 697 698 699 700 701 702 703 704
                                      m_target.string() );
        }
    }

    m_walletMap.clear(); // done with it
    m_havePassword = m_haveTextarea= false;
    m_doingsubmit = m_insubmit = false;
}

void HTMLFormElementImpl::reset(  )
{
705
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
706 707 708 709 710
    if(m_inreset || !view || !view->part()) return;

    m_inreset = true;

#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
711
    kDebug( 6030 ) << "reset pressed!";
George Staikos's avatar
George Staikos committed
712 713 714
#endif

    // ### DOM2 labels this event as not cancelable, however
715
    // common browsers( sick! ) allow it be canceled.
George Staikos's avatar
George Staikos committed
716 717 718 719 720
    if ( !dispatchHTMLEvent(EventImpl::RESET_EVENT,true, true) ) {
        m_inreset = false;
        return;
    }

Germain Garand's avatar
Germain Garand committed
721 722
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();)
        it.next()->reset();
George Staikos's avatar
George Staikos committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739

    m_inreset = false;
}

void HTMLFormElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch(attr->id())
    {
    case ATTR_ACTION:
        break;
    case ATTR_TARGET:
        m_target = attr->value();
        break;
    case ATTR_METHOD:
        m_post = ( strcasecmp( attr->value(), "post" ) == 0 );
        break;
    case ATTR_ENCTYPE:
740
        setEnctype( attr->value() );
George Staikos's avatar
George Staikos committed
741 742 743 744 745 746 747 748 749 750 751 752 753 754
        break;
    case ATTR_ACCEPT_CHARSET:
        // space separated list of charsets the server
        // accepts - see rfc2045
        m_acceptcharset = attr->value();
        break;
    case ATTR_ACCEPT:
        // ignore this one for the moment...
        break;
    case ATTR_AUTOCOMPLETE:
        m_autocomplete = strcasecmp( attr->value(), "off" );
        break;
    case ATTR_ONSUBMIT:
        setHTMLEventListener(EventImpl::SUBMIT_EVENT,
755
	    document()->createHTMLEventListener(attr->value().string(), "onsubmit", this));
George Staikos's avatar
George Staikos committed
756 757 758
        break;
    case ATTR_ONRESET:
        setHTMLEventListener(EventImpl::RESET_EVENT,
759
	    document()->createHTMLEventListener(attr->value().string(), "onreset", this));
George Staikos's avatar
George Staikos committed
760 761 762
        break;
    case ATTR_NAME:
        if (inDocument() && m_name != attr->value()) {
Maks Orlovich's avatar
Maks Orlovich committed
763 764
            document()->underDocNamedCache().remove(m_name,        this);
            document()->underDocNamedCache().add   (attr->value(), this);
George Staikos's avatar
George Staikos committed
765 766 767 768 769 770 771 772 773 774
        }
        m_name = attr->value();
        //Fallthrough intentional
    default:
        HTMLElementImpl::parseAttribute(attr);
    }
}

void HTMLFormElementImpl::removedFromDocument()
{
Maks Orlovich's avatar
Maks Orlovich committed
775
    document()->underDocNamedCache().remove(m_name, this);
George Staikos's avatar
George Staikos committed
776 777 778 779 780
    HTMLElementImpl::removedFromDocument();
}

void HTMLFormElementImpl::insertedIntoDocument()
{
Maks Orlovich's avatar
Maks Orlovich committed
781
    document()->underDocNamedCache().add(m_name, this);
George Staikos's avatar
George Staikos committed
782 783 784
    HTMLElementImpl::insertedIntoDocument();
}

Maks Orlovich's avatar
Maks Orlovich committed
785
void HTMLFormElementImpl::removeId(const DOMString& id)
George Staikos's avatar
George Staikos committed
786
{
787
    document()->underDocNamedCache().remove(id, this);
George Staikos's avatar
George Staikos committed
788 789 790
    HTMLElementImpl::removeId(id);
}

Maks Orlovich's avatar
Maks Orlovich committed
791
void HTMLFormElementImpl::addId   (const DOMString& id)
George Staikos's avatar
George Staikos committed
792
{
793
    document()->underDocNamedCache().add(id, this);
George Staikos's avatar
George Staikos committed
794 795 796 797
    HTMLElementImpl::addId(id);
}


798
void HTMLFormElementImpl::uncheckOtherRadioButtonsInGroup( HTMLGenericFormElementImpl *caller, bool setDefaultChecked )
George Staikos's avatar
George Staikos committed
799
{
Germain Garand's avatar
Germain Garand committed
800 801
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
        HTMLGenericFormElementImpl* const current = it.next();
George Staikos's avatar
George Staikos committed
802 803 804
        if (current->id() == ID_INPUT &&
            static_cast<HTMLInputElementImpl*>(current)->inputType() == HTMLInputElementImpl::RADIO &&
            current != caller && current->form() == caller->form() && current->name() == caller->name())
805
            static_cast<HTMLInputElementImpl*>(current)->setChecked(false, setDefaultChecked);
George Staikos's avatar
George Staikos committed
806 807 808 809 810 811 812 813 814 815
    }
}

void HTMLFormElementImpl::registerFormElement(HTMLGenericFormElementImpl *e)
{
    formElements.append(e);
}

void HTMLFormElementImpl::removeFormElement(HTMLGenericFormElementImpl *e)
{
816
    int i = formElements.indexOf(e);
Germain Garand's avatar
Germain Garand committed
817 818
    if (i != -1)
        formElements.removeAt(i);
819 820 821 822 823 824 825 826 827
        
    if (e->hasPastNames()) {
        QMutableHashIterator<DOMString, HTMLGenericFormElementImpl*> it(m_pastNamesMap);
        while (it.hasNext()) {
            it.next();
            if (it.value() == e)
                it.remove();
        }
    }
George Staikos's avatar
George Staikos committed
828 829 830 831 832 833 834 835 836
}

void HTMLFormElementImpl::registerImgElement(HTMLImageElementImpl *e)
{
    imgElements.append(e);
}

void HTMLFormElementImpl::removeImgElement(HTMLImageElementImpl *e)
{
837
    int i = imgElements.indexOf(e);
Germain Garand's avatar
Germain Garand committed
838 839
    if (i != -1)
        imgElements.removeAt(i);
George Staikos's avatar
George Staikos committed
840 841
}

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
HTMLGenericFormElementImpl* HTMLFormElementImpl::lookupByPastName(const DOMString& id)
{
    return m_pastNamesMap.value(id);
}

void HTMLFormElementImpl::bindPastName(HTMLGenericFormElementImpl* e)
{
    DOMString id = e->getAttribute(ATTR_ID);
    if (!id.isEmpty())
        m_pastNamesMap.insert(id, e);
        
    DOMString nm = e->getAttribute(ATTR_NAME);
    if (!nm.isEmpty())
        m_pastNamesMap.insert(nm, e);
    e->setHasPastNames();
}

George Staikos's avatar
George Staikos committed
859 860
// -------------------------------------------------------------------------

Germain Garand's avatar
Germain Garand committed
861
HTMLGenericFormElementImpl::HTMLGenericFormElementImpl(DocumentImpl *doc, HTMLFormElementImpl *f)
George Staikos's avatar
George Staikos committed
862 863
    : HTMLElementImpl(doc)
{
864
    m_disabled = m_readOnly = m_hasPastNames = false;
George Staikos's avatar
George Staikos committed
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    m_name = 0;

    if (f)
	m_form = f;
    else
	m_form = getForm();
    if (m_form)
        m_form->registerFormElement(this);
}

void HTMLGenericFormElementImpl::insertedIntoDocument()
{
    HTMLElementImpl::insertedIntoDocument();

    if (!m_form) {
        HTMLFormElementImpl* const newform = getForm();
        if (newform) {
            m_form = newform;
            m_form->registerFormElement(this);
        }
    }
}

void HTMLGenericFormElementImpl::removedFromDocument()
{
    HTMLElementImpl::removedFromDocument();

    if (m_form)
        m_form->removeFormElement(this);

    m_form = 0;
}

HTMLGenericFormElementImpl::~HTMLGenericFormElementImpl()
{
    if (m_form)
        m_form->removeFormElement(this);
    if (m_name) m_name->deref();
}

void HTMLGenericFormElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch(attr->id())
    {
    case ATTR_DISABLED:
        setDisabled( attr->val() != 0 );
        break;
    case ATTR_READONLY:
    {
        const bool m_oldreadOnly = m_readOnly;
        m_readOnly = attr->val() != 0;
        if (m_oldreadOnly != m_readOnly) setChanged();
        break;
    }
    default:
        HTMLElementImpl::parseAttribute(attr);
    }
}

void HTMLGenericFormElementImpl::attach()
{
    assert(!attached());

    if (m_render) {
        assert(m_render->style());
        parentNode()->renderer()->addChild(m_render, nextRenderer());
    }

    // FIXME: This handles the case of a new form element being created by
    // JavaScript and inserted inside a form. What it does not handle is
    // a form element being moved from inside a form to outside, or from one
    // inside one form to another. The reason this other case is hard to fix
    // is that during parsing, we may have been passed a form that we are not
    // inside, DOM-tree-wise. If so, it's hard for us to know when we should
    // be removed from that form's element list.
    if (!m_form) {
	m_form = getForm();
	if (m_form)
	    m_form->registerFormElement(this);
    }

    NodeBaseImpl::attach();

    // The call to updateFromElement() needs to go after the call through
    // to the base class's attach() because that can sometimes do a close
    // on the renderer.
    if (m_render)
        m_render->updateFromElement();

}

HTMLFormElementImpl *HTMLGenericFormElementImpl::getForm() const
{
    NodeImpl *p = parentNode();
    while(p)
    {
        if( p->id() == ID_FORM )
            return static_cast<HTMLFormElementImpl *>(p);
963 964 965 966 967
        if( p->parentNode() && p->parentNode()->id() == ID_TABLE && p->previousSibling() )
        {
            p = p->previousSibling();
            continue;
        }
Maks Orlovich's avatar
Maks Orlovich committed
968
        p = p->parentNode();
George Staikos's avatar
George Staikos committed
969 970
    }
#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
971 972
    kDebug( 6030 ) << "couldn't find form!";
    kDebug( 6030 ) << kBacktrace();
George Staikos's avatar
George Staikos committed
973 974 975 976 977 978 979 980 981
#endif
    return 0;
}

DOMString HTMLGenericFormElementImpl::name() const
{
    if (m_name) return m_name;

// ###
982
//     DOMString n = document()->htmlMode() != DocumentImpl::XHtml ?
George Staikos's avatar
George Staikos committed
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
//                   getAttribute(ATTR_NAME) : getAttribute(ATTR_ID);
    const DOMString n = getAttribute(ATTR_NAME);
    if (n.isNull())
        return new DOMStringImpl("");

    return n;
}

void HTMLGenericFormElementImpl::setName(const DOMString& name)
{
    if (m_name) m_name->deref();
    m_name = name.implementation();
    setAttribute( ATTR_NAME, name );
    if (m_name) m_name->ref();
}

void HTMLGenericFormElementImpl::onSelect()
{
    // ### make this work with new form events architecture
    dispatchHTMLEvent(EventImpl::SELECT_EVENT,true,false);
}

void HTMLGenericFormElementImpl::onChange()
{
    // ### make this work with new form events architecture
    dispatchHTMLEvent(EventImpl::CHANGE_EVENT,true,false);
}

void HTMLGenericFormElementImpl::setDisabled( bool _disabled )
{
    if ( m_disabled != _disabled ) {
        m_disabled = _disabled;
1015
        // Trigger dynamic restyles
1016
        document()->dynamicDomRestyler().restyleDependent(this, OtherStateDependency);
1017 1018 1019 1020
        // We need to update rendering under all circumstances
        if (!changed() && m_render) {
            m_render->updateFromElement();
        }
George Staikos's avatar
George Staikos committed
1021 1022 1023
    }
}

1024
bool HTMLGenericFormElementImpl::isFocusableImpl(FocusType ft) const
George Staikos's avatar
George Staikos committed
1025
{
1026 1027 1028
    if (hasTabIndex())
        return HTMLElementImpl::isFocusableImpl(ft);

1029
    if (disabled())
Maks Orlovich's avatar
Maks Orlovich committed
1030 1031 1032 1033 1034 1035 1036 1037 1038
	return false;

    //Non-widget INPUT TYPE="image" and <BUTTON> support focus, too.
    if (id() == ID_INPUT && static_cast<const HTMLInputElementImpl *>(this)->inputType() == HTMLInputElementImpl::IMAGE)
	return true;

    if (id() == ID_BUTTON)
	return true;

1039
    if (!m_render || !m_render->isWidget())
Maks Orlovich's avatar
Maks Orlovich committed
1040 1041 1042 1043
	return false;

    QWidget* widget = static_cast<RenderWidget*>(m_render)->widget();
    return widget && widget->focusPolicy() >= Qt::TabFocus;
George Staikos's avatar
George Staikos committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
}

class FocusHandleWidget : public QWidget
{
public:
    void focusNextPrev(bool n) {
        if (!focusNextPrevChild(n) && inherits("QTextEdit"))
            QWidget::focusNextPrevChild(n);
    }
};

void HTMLGenericFormElementImpl::defaultEventHandler(EventImpl *evt)
{
    if (evt->target() == this && renderer() && renderer()->isWidget()) {
        switch(evt->id())  {
        case EventImpl::MOUSEDOWN_EVENT:
        case EventImpl::MOUSEUP_EVENT:
        case EventImpl::MOUSEMOVE_EVENT:
        case EventImpl::MOUSEOUT_EVENT:
        case EventImpl::MOUSEOVER_EVENT:
1064
        case EventImpl::KHTML_MOUSEWHEEL_EVENT:
George Staikos's avatar
George Staikos committed
1065 1066 1067
        case EventImpl::KEYDOWN_EVENT:
        case EventImpl::KEYUP_EVENT:
        case EventImpl::KEYPRESS_EVENT:
Germain Garand's avatar
Germain Garand committed
1068 1069
        case EventImpl::DOMFOCUSIN_EVENT:
        case EventImpl::DOMFOCUSOUT_EVENT:
George Staikos's avatar
George Staikos committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
            if (static_cast<RenderWidget*>(renderer())->handleEvent(*evt))
		evt->setDefaultHandled();
        default:
            break;
        }
    }

    if (evt->target()==this && !m_disabled)
    {
        // Report focus in/out changes to the browser extension (editable widgets only)
1080
        KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
1081 1082 1083 1084 1085 1086 1087 1088 1089
        if (view && evt->id() == EventImpl::DOMFOCUSIN_EVENT && isEditable() && m_render && m_render->isWidget()) {
            KHTMLPartBrowserExtension *ext = static_cast<KHTMLPartBrowserExtension *>(view->part()->browserExtension());
            QWidget* const widget = static_cast<RenderWidget*>(m_render)->widget();
            if (ext)
                ext->editableWidgetFocused(widget);
        }
        if (evt->id()==EventImpl::MOUSEDOWN_EVENT || evt->id()==EventImpl::KEYDOWN_EVENT)
        {
            setActive();
Germain Garand's avatar
Germain Garand committed
1090 1091
            if (renderer() && renderer()->isWidget())
                static_cast<RenderWidget*>(renderer())->widget()->setFocus(); // ### mmh..
George Staikos's avatar
George Staikos committed
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
        }
        else if (evt->id() == EventImpl::MOUSEUP_EVENT || evt->id()==EventImpl::KEYUP_EVENT)
        {
	    if (m_active)
	    {
		setActive(false);
		setFocus();
	    }
	    else {
                setActive(false);
            }
        }

	if (!evt->defaultHandled() && m_render && m_render->isWidget()) {
	    // handle tabbing out, either from a single or repeated key event.
Maks Orlovich's avatar
Maks Orlovich committed
1107 1108
	    if ( evt->id() == EventImpl::KEYPRESS_EVENT && evt->isKeyRelatedEvent() ) {
	        QKeyEvent* const k = static_cast<KeyEventBaseImpl *>(evt)->qKeyEvent();
1109 1110
	        if ( k && (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) &&
                        (k->modifiers() & Qt::ControlModifier) == 0 ) {
George Staikos's avatar
George Staikos committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
		    QWidget* const widget = static_cast<RenderWidget*>(m_render)->widget();
		    if (widget)
			{
                        static_cast<FocusHandleWidget *>(widget)
			    ->focusNextPrev(k->key() == Qt::Key_Tab);
			}
                    evt->setDefaultHandled();
	        }
            }
	}


	if (view && evt->id() == EventImpl::DOMFOCUSOUT_EVENT && isEditable() && m_render && m_render->isWidget()) {
	    KHTMLPartBrowserExtension* const ext = static_cast<KHTMLPartBrowserExtension *>(view->part()->browserExtension());
	    QWidget* const widget = static_cast<RenderWidget*>(m_render)->widget();
	    if (ext)
		ext->editableWidgetBlurred(widget);

	    // ### Don't count popup as a valid reason for losing the focus (example: opening the options of a select
	    // combobox shouldn't emit onblur)
	}
    }
1133
    if (evt->target() == this && evt->isMouseEvent() && evt->id() != EventImpl::KHTML_MOUSEWHEEL_EVENT && renderer())
George Staikos's avatar
George Staikos committed
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
        evt->setDefaultHandled();

    HTMLElementImpl::defaultEventHandler(evt);
}

bool HTMLGenericFormElementImpl::isEditable()
{
    return false;
}

// -------------------------------------------------------------------------

Germain Garand's avatar
Germain Garand committed
1146
HTMLButtonElementImpl::HTMLButtonElementImpl(DocumentImpl *doc, HTMLFormElementImpl *f)
George Staikos's avatar
George Staikos committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    : HTMLGenericFormElementImpl(doc, f)
{
    m_clicked = false;
    m_type = SUBMIT;
    m_dirty = true;
    m_activeSubmit = false;
}

HTMLButtonElementImpl::~HTMLButtonElementImpl()
{
}

NodeImpl::Id HTMLButtonElementImpl::id() const
{
    return ID_BUTTON;
}

DOMString HTMLButtonElementImpl::type() const
{
1166 1167 1168 1169 1170 1171 1172 1173
    switch (m_type) {
        case SUBMIT:
            return "submit";
        case RESET:
            return "reset";
        case BUTTON:
            return "button";
    }
1174
    return "";
George Staikos's avatar
George Staikos committed
1175 1176 1177 1178 1179 1180 1181
}

void HTMLButtonElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch(attr->id())
    {
    case ATTR_TYPE:
1182 1183 1184 1185
        // Per WF2.0, any invalid values are to be ignored -- and hence
        // handled as the default, SUBMIT.
        m_type = SUBMIT;
        if ( strcasecmp( attr->value(), "reset" ) == 0 )
George Staikos's avatar
George Staikos committed
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
            m_type = RESET;
        else if ( strcasecmp( attr->value(), "button" ) == 0 )
            m_type = BUTTON;
        break;
    case ATTR_VALUE:
        m_value = attr->value();
        m_currValue = m_value.string();
        break;
    case ATTR_ACCESSKEY:
        break;
    case ATTR_ALIGN:
        break;
    default:
        HTMLGenericFormElementImpl::parseAttribute(attr);
    }
}

void HTMLButtonElementImpl::defaultEventHandler(EventImpl *evt)
{
    if (m_type != BUTTON && !m_disabled) {
	bool act = (evt->id() == EventImpl::DOMACTIVATE_EVENT);
Maks Orlovich's avatar
Maks Orlovich committed
1207 1208
	if (!act && evt->id()==EventImpl::KEYUP_EVENT && evt->isKeyRelatedEvent()) {
	    QKeyEvent* const ke = static_cast<KeyEventBaseImpl *>(evt)->qKeyEvent();
George Staikos's avatar
George Staikos committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
	    if (ke && active() && (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Space))
		act = true;
	}
	if (act)
	    activate();
    }
    HTMLGenericFormElementImpl::defaultEventHandler(evt);
}

void HTMLButtonElementImpl::activate()
{
    m_clicked = true;

    if(m_form && m_type == SUBMIT) {
        m_activeSubmit = true;
        m_form->prepareSubmit();
        m_activeSubmit = false; // in case we were canceled
    }
    if(m_form && m_type == RESET)
        m_form->reset();
}

void HTMLButtonElementImpl::click()
{
1233
    QMouseEvent me(QEvent::MouseButtonRelease, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
George Staikos's avatar
George Staikos committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    dispatchMouseEvent(&me,EventImpl::CLICK_EVENT, 1);
}

bool HTMLButtonElementImpl::encoding(const QTextCodec* codec, khtml::encodingList& encoding, bool /*multipart*/)
{
    if (m_type != SUBMIT || name().isEmpty() || !m_activeSubmit)
        return false;

    encoding += fixUpfromUnicode(codec, name().string());
    const QString enc_str = m_currValue.isNull() ? QString("") : m_currValue;
    encoding += fixUpfromUnicode(codec, enc_str);

    return true;
}

void HTMLButtonElementImpl::attach()
{
    // skip the generic handler
    HTMLElementImpl::attach();
}

// -------------------------------------------------------------------------

Germain Garand's avatar
Germain Garand committed
1257
HTMLFieldSetElementImpl::HTMLFieldSetElementImpl(DocumentImpl *doc, HTMLFormElementImpl *f)
George Staikos's avatar
George Staikos committed
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
    : HTMLGenericFormElementImpl(doc, f)
{
}

HTMLFieldSetElementImpl::~HTMLFieldSetElementImpl()
{
}

NodeImpl::Id HTMLFieldSetElementImpl::id() const
{
    return ID_FIELDSET;
}

void HTMLFieldSetElementImpl::attach()
{
    assert(!attached());
    assert(!m_render);
    assert(parentNode());

1277
    RenderStyle* const _style = document()->styleSelector()->styleForElement(this);
George Staikos's avatar
George Staikos committed
1278
    _style->ref();
1279 1280
    if (parentNode()->renderer() && parentNode()->renderer()->childAllowed() &&
        _style->display() != NONE) {
1281
        m_render = new (document()->renderArena()) RenderFieldset(this);
George Staikos's avatar
George Staikos committed
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
        m_render->setStyle(_style);
    }
    HTMLGenericFormElementImpl::attach();
    _style->deref();
}

void HTMLFieldSetElementImpl::parseAttribute(AttributeImpl *attr)
{
    HTMLElementImpl::parseAttribute(attr);
}

// -------------------------------------------------------------------------

Germain Garand's avatar
Germain Garand committed
1295
HTMLInputElementImpl::HTMLInputElementImpl(DocumentImpl *doc, HTMLFormElementImpl *f)
George Staikos's avatar
George Staikos committed
1296 1297 1298 1299 1300 1301 1302
    : HTMLGenericFormElementImpl(doc, f)
{
    m_type = TEXT;
    m_maxLen = -1;
    m_size = 20;
    m_clicked = false;
    m_checked = false;
1303 1304
    m_defaultChecked = false;
    m_useDefaultChecked = true;
1305
    m_indeterminate = false;
George Staikos's avatar
George Staikos committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321

    m_haveType = false;
    m_activeSubmit = false;
    m_autocomplete = true;
    m_inited = false;
    m_unsubmittedFormChange = false;

    xPos = 0;
    yPos = 0;

    if ( m_form )
        m_autocomplete = f->autoComplete();
}

HTMLInputElementImpl::~HTMLInputElementImpl()
{
1322
    if (document()) document()->deregisterMaintainsState(this);
George Staikos's avatar
George Staikos committed
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
}

NodeImpl::Id HTMLInputElementImpl::id() const
{
    return ID_INPUT;
}

// Called from JS. Can't merge with parseType since we
// also need to actually set ATTR_TYPE, which can't be done there.
void HTMLInputElementImpl::setType(const DOMString& t)
{
    setAttribute(ATTR_TYPE, t);
}

void HTMLInputElementImpl::parseType(const DOMString& t)
{
    typeEnum newType;

    if ( strcasecmp( t, "password" ) == 0 )
        newType = PASSWORD;
    else if ( strcasecmp( t, "checkbox" ) == 0 )
        newType = CHECKBOX;
    else if ( strcasecmp( t, "radio" ) == 0 )
        newType = RADIO;
    else if ( strcasecmp( t, "submit" ) == 0 )
        newType = SUBMIT;
    else if ( strcasecmp( t, "reset" ) == 0 )
        newType = RESET;
    else if ( strcasecmp( t, "file" ) == 0 )
        newType = FILE;
    else if ( strcasecmp( t, "hidden" ) == 0 )
        newType = HIDDEN;
    else if ( strcasecmp( t, "image" ) == 0 )
        newType = IMAGE;
    else if ( strcasecmp( t, "button" ) == 0 )
        newType = BUTTON;
    else if ( strcasecmp( t, "khtml_isindex" ) == 0 )
        newType = ISINDEX;
    else
        newType = TEXT;

    // ### IMPORTANT: Don't allow the type to be changed to FILE after the first
    // type change, otherwise a JavaScript programmer would be able to set a text
    // field's value to something like /etc/passwd and then change it to a file field.
    if (m_type != newType) {
        if (newType == FILE && m_haveType) {
            // Set the attribute back to the old value.
            // Note that this calls parseAttribute again.
            setAttribute(ATTR_TYPE, type());
        } else {
            m_type = newType;
Maks Orlovich's avatar
Maks Orlovich committed
1374 1375 1376 1377 1378 1379

            // force reattach if need be.
            if (attached()) {
                detach();
                attach();
            }
George Staikos's avatar
George Staikos committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        }
    }
    m_haveType = true;
}

DOMString HTMLInputElementImpl::type() const
{
    // needs to be lowercase according to DOM spec
    switch (m_type) {
    case TEXT: return "text";
    case PASSWORD: return "password";
    case CHECKBOX: return "checkbox";
    case RADIO: return "radio";
    case SUBMIT: return "submit";
    case RESET: return "reset";
    case FILE: return "file";
    case HIDDEN: return "hidden";
    case IMAGE: return "image";
    case BUTTON: return "button";
    default: return "";
    }
}

QString HTMLInputElementImpl::state( )
{
    switch (m_type) {
    case PASSWORD:
        return QLatin1String("."); // empty string, avoid restoring
    case CHECKBOX:
    case RADIO:
1410
        return QLatin1String(checked() ? "on" : "off");
George Staikos's avatar
George Staikos committed
1411
    case TEXT:
1412 1413
        if (autoComplete() && value() != getAttribute(ATTR_VALUE) && document()->view())
            document()->view()->addFormCompletionItem(name().string(), value().string());
George Staikos's avatar
George Staikos committed
1414 1415
        /* nobreak */
    default:
1416
        return value().string() + (m_unsubmittedFormChange ? 'M' : '.') + (value().isNull() ? 'N' : '.');
George Staikos's avatar
George Staikos committed
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    }
}

void HTMLInputElementImpl::restoreState(const QString &state)
{
    switch (m_type) {
    case CHECKBOX:
    case RADIO:
        setChecked((state == QLatin1String("on")));
        break;
    case FILE:
1428
        m_value = DOMString(state.left(state.length()-2));
George Staikos's avatar
George Staikos committed
1429 1430
        setChanged();
        break;
1431
    case HIDDEN: