qt_runtime.cpp 72.7 KB
Newer Older
andersca@apple.com's avatar
andersca@apple.com committed
1
/*
2
 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
andersca@apple.com's avatar
andersca@apple.com committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "config.h"
#include "qt_runtime.h"
22

23
#include "APICast.h"
mrowe@apple.com's avatar
mrowe@apple.com committed
24
#include "BooleanObject.h"
25 26 27
#include "DateInstance.h"
#include "DateMath.h"
#include "DatePrototype.h"
28
#include "DumpRenderTreeSupportQt.h"
29
#include "FunctionPrototype.h"
hausmann@webkit.org's avatar
hausmann@webkit.org committed
30
#include "Interpreter.h"
31
#include "JSArray.h"
hausmann@webkit.org's avatar
hausmann@webkit.org committed
32
#include "JSByteArray.h"
33
#include "JSDocument.h"
34
#include "JSDOMBinding.h"
35 36
#include "JSDOMWindow.h"
#include <JSFunction.h>
37
#include "JSGlobalObject.h"
38
#include "JSHTMLElement.h"
ap@webkit.org's avatar
ap@webkit.org committed
39
#include "JSLock.h"
darin@apple.com's avatar
darin@apple.com committed
40
#include "JSObject.h"
41
#include "JSRetainPtr.h"
42
#include "ObjectPrototype.h"
43
#include "PropertyNameArray.h"
44
#include "RegExpConstructor.h"
darin@apple.com's avatar
darin@apple.com committed
45
#include "RegExpObject.h"
46 47
#include "qdatetime.h"
#include "qdebug.h"
andersca@apple.com's avatar
andersca@apple.com committed
48
#include "qmetaobject.h"
49
#include "qmetatype.h"
andersca@apple.com's avatar
andersca@apple.com committed
50 51
#include "qobject.h"
#include "qstringlist.h"
52
#include "qt_instance.h"
53
#include "qt_pixmapruntime.h"
andersca@apple.com's avatar
andersca@apple.com committed
54
#include "qvarlengtharray.h"
55
#include "qwebelement.h"
andersca@apple.com's avatar
andersca@apple.com committed
56
#include <limits.h>
mrowe@apple.com's avatar
mrowe@apple.com committed
57
#include <runtime/Error.h>
58 59
#include <runtime_array.h>
#include <runtime_object.h>
andersca@apple.com's avatar
andersca@apple.com committed
60 61 62 63 64 65

// QtScript has these
Q_DECLARE_METATYPE(QObjectList);
Q_DECLARE_METATYPE(QList<int>);
Q_DECLARE_METATYPE(QVariant);

66
using namespace WebCore;
andersca@apple.com's avatar
andersca@apple.com committed
67

68
namespace JSC {
andersca@apple.com's avatar
andersca@apple.com committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
namespace Bindings {

// Debugging
//#define QTWK_RUNTIME_CONVERSION_DEBUG
//#define QTWK_RUNTIME_MATCH_DEBUG

class QWKNoDebug
{
public:
    inline QWKNoDebug(){}
    inline ~QWKNoDebug(){}

    template<typename T>
    inline QWKNoDebug &operator<<(const T &) { return *this; }
};

#ifdef QTWK_RUNTIME_CONVERSION_DEBUG
#define qConvDebug() qDebug()
#else
#define qConvDebug() QWKNoDebug()
#endif

#ifdef QTWK_RUNTIME_MATCH_DEBUG
#define qMatchDebug() qDebug()
#else
#define qMatchDebug() QWKNoDebug()
#endif

typedef enum {
98
    Variant = 0,
andersca@apple.com's avatar
andersca@apple.com committed
99 100 101 102 103 104 105 106
    Number,
    Boolean,
    String,
    Date,
    RegExp,
    Array,
    QObj,
    Object,
107
    Null,
hausmann@webkit.org's avatar
hausmann@webkit.org committed
108 109
    RTArray,
    JSByteArray
andersca@apple.com's avatar
andersca@apple.com committed
110 111
} JSRealType;

112 113 114 115 116 117 118 119 120 121 122 123
#if defined(QTWK_RUNTIME_CONVERSION_DEBUG) || defined(QTWK_RUNTIME_MATCH_DEBUG)
QDebug operator<<(QDebug dbg, const JSRealType &c)
{
     const char *map[] = { "Variant", "Number", "Boolean", "String", "Date",
         "RegExp", "Array", "RTObject", "Object", "Null", "RTArray"};

     dbg.nospace() << "JSType(" << ((int)c) << ", " <<  map[c] << ")";

     return dbg.space();
}
#endif

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
// this is here as a proxy, so we'd have a class to friend in QWebElement,
// as getting/setting a WebCore in QWebElement is private
class QtWebElementRuntime {
public:
    static QWebElement create(Element* element)
    {
        return QWebElement(element);
    }

    static Element* get(const QWebElement& element)
    {
        return element.m_element;
    }
};

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
// this is here as a proxy, so we'd have a class to friend in QDRTNode,
// as getting/setting a WebCore in QDRTNode is private.
// We only need to pass WebCore Nodes for layout tests.
class QtDRTNodeRuntime {
public:
    static QDRTNode create(Node* node)
    {
        return QDRTNode(node);
    }

    static Node* get(const QDRTNode& node)
    {
        return node.m_node;
    }
};

ggaren@apple.com's avatar
ggaren@apple.com committed
155
static JSRealType valueRealType(ExecState* exec, JSValue val)
andersca@apple.com's avatar
andersca@apple.com committed
156
{
157
    if (val.isNumber())
andersca@apple.com's avatar
andersca@apple.com committed
158
        return Number;
159
    else if (val.isString())
andersca@apple.com's avatar
andersca@apple.com committed
160
        return String;
161
    else if (val.isBoolean())
andersca@apple.com's avatar
andersca@apple.com committed
162
        return Boolean;
163
    else if (val.isNull())
andersca@apple.com's avatar
andersca@apple.com committed
164
        return Null;
165
    else if (isJSByteArray(&exec->globalData(), val))
hausmann@webkit.org's avatar
hausmann@webkit.org committed
166
        return JSByteArray;
167 168
    else if (val.isObject()) {
        JSObject *object = val.toObject(exec);
169 170
        if (object->inherits(&RuntimeArray::s_info))  // RuntimeArray 'inherits' from Array, but not in C++
            return RTArray;
171
        else if (object->inherits(&JSArray::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
172
            return Array;
173
        else if (object->inherits(&DateInstance::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
174
            return Date;
175
        else if (object->inherits(&RegExpObject::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
176
            return RegExp;
177
        else if (object->inherits(&RuntimeObject::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
178 179 180 181 182 183 184
            return QObj;
        return Object;
    }

    return String; // I don't know.
}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
QVariant convertValueToQVariant(ExecState*, JSValue, QMetaType::Type, int*, HashSet<JSObject*>*, int);

static QVariantMap convertValueToQVariantMap(ExecState* exec, JSObject* object, HashSet<JSObject*>* visitedObjects, int recursionLimit)
{
    Q_ASSERT(!exec->hadException());

    PropertyNameArray properties(exec);
    object->getPropertyNames(exec, properties);
    PropertyNameArray::const_iterator it = properties.begin();
    QVariantMap result;
    int objdist = 0;

    while (it != properties.end()) {
        if (object->propertyIsEnumerable(exec, *it)) {
            JSValue val = object->get(exec, *it);
            if (exec->hadException())
                exec->clearException();
            else {
                QVariant v = convertValueToQVariant(exec, val, QMetaType::Void, &objdist, visitedObjects, recursionLimit);
                if (objdist >= 0) {
                    UString ustring = (*it).ustring();
                    QString id = QString((const QChar*)ustring.impl()->characters(), ustring.length());
                    result.insert(id, v);
                }
            }
        }
        ++it;
    }
    return result;
}

216
QVariant convertValueToQVariant(ExecState* exec, JSValue value, QMetaType::Type hint, int *distance, HashSet<JSObject*>* visitedObjects, int recursionLimit)
andersca@apple.com's avatar
andersca@apple.com committed
217
{
218 219 220
    --recursionLimit;

    if (!value || !recursionLimit)
221 222
        return QVariant();

223
    JSObject* object = 0;
224 225
    if (value.isObject()) {
        object = value.toObject(exec);
226 227 228 229 230 231
        if (visitedObjects->contains(object))
            return QVariant();

        visitedObjects->add(object);
    }

andersca@apple.com's avatar
andersca@apple.com committed
232
    // check magic pointer values before dereferencing value
233
    if (value == jsNaN()
234 235 236
        || (value == jsUndefined()
            && hint != QMetaType::QString
            && hint != (QMetaType::Type) qMetaTypeId<QVariant>())) {
andersca@apple.com's avatar
andersca@apple.com committed
237 238 239 240 241
        if (distance)
            *distance = -1;
        return QVariant();
    }

ap@webkit.org's avatar
ap@webkit.org committed
242
    JSLock lock(SilenceAssertionsOnly);
andersca@apple.com's avatar
andersca@apple.com committed
243
    JSRealType type = valueRealType(exec, value);
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    if (hint == QMetaType::Void) {
        switch(type) {
            case Number:
                hint = QMetaType::Double;
                break;
            case Boolean:
                hint = QMetaType::Bool;
                break;
            case String:
            default:
                hint = QMetaType::QString;
                break;
            case Date:
                hint = QMetaType::QDateTime;
                break;
            case RegExp:
                hint = QMetaType::QRegExp;
                break;
            case Object:
                if (object->inherits(&NumberObject::s_info))
                    hint = QMetaType::Double;
                else if (object->inherits(&BooleanObject::s_info))
                    hint = QMetaType::Bool;
                else
                    hint = QMetaType::QVariantMap;
                break;
            case QObj:
                hint = QMetaType::QObjectStar;
                break;
            case JSByteArray:
                hint = QMetaType::QByteArray;
                break;
            case Array:
            case RTArray:
                hint = QMetaType::QVariantList;
                break;
        }
    }
andersca@apple.com's avatar
andersca@apple.com committed
282

283 284 285
    qConvDebug() << "convertValueToQVariant: jstype is " << type << ", hint is" << hint;

    if (value == jsNull()
andersca@apple.com's avatar
andersca@apple.com committed
286
        && hint != QMetaType::QObjectStar
287 288 289
        && hint != QMetaType::VoidStar
        && hint != QMetaType::QString
        && hint != (QMetaType::Type) qMetaTypeId<QVariant>()) {
andersca@apple.com's avatar
andersca@apple.com committed
290 291 292 293 294 295 296 297 298
        if (distance)
            *distance = -1;
        return QVariant();
    }

    QVariant ret;
    int dist = -1;
    switch (hint) {
        case QMetaType::Bool:
299
            if (type == Object && object->inherits(&BooleanObject::s_info))
300
                ret = QVariant(asBooleanObject(value)->internalValue().toBoolean(exec));
301
            else
302
                ret = QVariant(value.toBoolean(exec));
andersca@apple.com's avatar
andersca@apple.com committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
            if (type == Boolean)
                dist = 0;
            else
                dist = 10;
            break;

        case QMetaType::Int:
        case QMetaType::UInt:
        case QMetaType::Long:
        case QMetaType::ULong:
        case QMetaType::LongLong:
        case QMetaType::ULongLong:
        case QMetaType::Short:
        case QMetaType::UShort:
        case QMetaType::Float:
        case QMetaType::Double:
319
            ret = QVariant(value.toNumber(exec));
andersca@apple.com's avatar
andersca@apple.com committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
            ret.convert((QVariant::Type)hint);
            if (type == Number) {
                switch (hint) {
                case QMetaType::Double:
                    dist = 0;
                    break;
                case QMetaType::Float:
                    dist = 1;
                    break;
                case QMetaType::LongLong:
                case QMetaType::ULongLong:
                    dist = 2;
                    break;
                case QMetaType::Long:
                case QMetaType::ULong:
                    dist = 3;
                    break;
                case QMetaType::Int:
                case QMetaType::UInt:
                    dist = 4;
                    break;
                case QMetaType::Short:
                case QMetaType::UShort:
                    dist = 5;
                    break;
                    break;
                default:
                    dist = 10;
                    break;
                }
            } else {
                dist = 10;
            }
            break;

        case QMetaType::QChar:
            if (type == Number || type == Boolean) {
357
                ret = QVariant(QChar((ushort)value.toNumber(exec)));
andersca@apple.com's avatar
andersca@apple.com committed
358 359 360 361 362
                if (type == Boolean)
                    dist = 3;
                else
                    dist = 6;
            } else {
363
                UString str = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
364
                ret = QVariant(QChar(str.length() ? *(const ushort*)str.impl()->characters() : 0));
andersca@apple.com's avatar
andersca@apple.com committed
365 366 367 368 369 370 371 372
                if (type == String)
                    dist = 3;
                else
                    dist = 10;
            }
            break;

        case QMetaType::QString: {
373
            if (value.isUndefinedOrNull()) {
374 375 376 377
                if (distance)
                    *distance = 1;
                return QString();
            } else {
378
                UString ustring = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
379
                ret = QVariant(QString((const QChar*)ustring.impl()->characters(), ustring.length()));
380 381 382 383 384
                if (type == String)
                    dist = 0;
                else
                    dist = 10;
            }
andersca@apple.com's avatar
andersca@apple.com committed
385 386 387
            break;
        }

388
        case QMetaType::QVariantMap:
389
            if (type == Object || type == Array || type == RTArray) {
390 391
                ret = QVariant(convertValueToQVariantMap(exec, object, visitedObjects, recursionLimit));
                // Those types can still have perfect matches, e.g. 'bool' if value is a Boolean Object.
andersca@apple.com's avatar
andersca@apple.com committed
392 393 394 395 396
                dist = 1;
            }
            break;

        case QMetaType::QVariantList:
397 398 399 400 401 402 403 404
            if (type == RTArray) {
                RuntimeArray* rtarray = static_cast<RuntimeArray*>(object);

                QVariantList result;
                int len = rtarray->getLength();
                int objdist = 0;
                qConvDebug() << "converting a " << len << " length Array";
                for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
405
                    JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
406
                    result.append(convertValueToQVariant(exec, val, QMetaType::Void, &objdist, visitedObjects, recursionLimit));
407 408 409 410 411 412 413 414 415 416
                    if (objdist == -1) {
                        qConvDebug() << "Failed converting element at index " << i;
                        break; // Failed converting a list entry, so fail the array
                    }
                }
                if (objdist != -1) {
                    dist = 5;
                    ret = QVariant(result);
                }
            } else if (type == Array) {
darin@apple.com's avatar
darin@apple.com committed
417
                JSArray* array = static_cast<JSArray*>(object);
andersca@apple.com's avatar
andersca@apple.com committed
418 419

                QVariantList result;
420
                int len = array->length();
andersca@apple.com's avatar
andersca@apple.com committed
421
                int objdist = 0;
422
                qConvDebug() << "converting a " << len << " length Array";
andersca@apple.com's avatar
andersca@apple.com committed
423
                for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
424
                    JSValue val = array->get(exec, i);
425
                    result.append(convertValueToQVariant(exec, val, QMetaType::Void, &objdist, visitedObjects, recursionLimit));
426 427
                    if (objdist == -1) {
                        qConvDebug() << "Failed converting element at index " << i;
andersca@apple.com's avatar
andersca@apple.com committed
428
                        break; // Failed converting a list entry, so fail the array
429
                    }
andersca@apple.com's avatar
andersca@apple.com committed
430 431 432 433 434 435 436 437
                }
                if (objdist != -1) {
                    dist = 5;
                    ret = QVariant(result);
                }
            } else {
                // Make a single length array
                int objdist;
438
                qConvDebug() << "making a single length variantlist";
439
                QVariant var = convertValueToQVariant(exec, value, QMetaType::Void, &objdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
440
                if (objdist != -1) {
441 442
                    QVariantList result;
                    result << var;
andersca@apple.com's avatar
andersca@apple.com committed
443 444
                    ret = QVariant(result);
                    dist = 10;
445 446
                } else {
                    qConvDebug() << "failed making single length varlist";
andersca@apple.com's avatar
andersca@apple.com committed
447 448 449 450 451
                }
            }
            break;

        case QMetaType::QStringList: {
452 453 454 455 456 457
            if (type == RTArray) {
                RuntimeArray* rtarray = static_cast<RuntimeArray*>(object);

                QStringList result;
                int len = rtarray->getLength();
                for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
458
                    JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
459
                    UString ustring = val.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
460
                    QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
461 462 463 464 465 466

                    result.append(qstring);
                }
                dist = 5;
                ret = QVariant(result);
            } else if (type == Array) {
darin@apple.com's avatar
darin@apple.com committed
467
                JSArray* array = static_cast<JSArray*>(object);
andersca@apple.com's avatar
andersca@apple.com committed
468 469

                QStringList result;
470
                int len = array->length();
andersca@apple.com's avatar
andersca@apple.com committed
471
                for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
472
                    JSValue val = array->get(exec, i);
473
                    UString ustring = val.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
474
                    QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
andersca@apple.com's avatar
andersca@apple.com committed
475 476 477 478 479 480 481

                    result.append(qstring);
                }
                dist = 5;
                ret = QVariant(result);
            } else {
                // Make a single length array
482
                UString ustring = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
483
                QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
andersca@apple.com's avatar
andersca@apple.com committed
484 485 486 487 488 489 490 491 492
                QStringList result;
                result.append(qstring);
                ret = QVariant(result);
                dist = 10;
            }
            break;
        }

        case QMetaType::QByteArray: {
hausmann@webkit.org's avatar
hausmann@webkit.org committed
493 494 495 496 497 498
            if (type == JSByteArray) {
                WTF::ByteArray* arr = asByteArray(value)->storage();
                ret = QVariant(QByteArray(reinterpret_cast<const char*>(arr->data()), arr->length()));
                dist = 0;
            } else {
                UString ustring = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
499
                ret = QVariant(QString((const QChar*)ustring.impl()->characters(), ustring.length()).toLatin1());
hausmann@webkit.org's avatar
hausmann@webkit.org committed
500 501 502 503 504
                if (type == String)
                    dist = 5;
                else
                    dist = 10;
            }
andersca@apple.com's avatar
andersca@apple.com committed
505 506 507 508 509 510 511 512
            break;
        }

        case QMetaType::QDateTime:
        case QMetaType::QDate:
        case QMetaType::QTime:
            if (type == Date) {
                DateInstance* date = static_cast<DateInstance*>(object);
513
                GregorianDateTime gdt;
514
                msToGregorianDateTime(exec, date->internalNumber(), true, gdt);
andersca@apple.com's avatar
andersca@apple.com committed
515 516 517 518 519 520 521 522 523 524 525
                if (hint == QMetaType::QDateTime) {
                    ret = QDateTime(QDate(gdt.year + 1900, gdt.month + 1, gdt.monthDay), QTime(gdt.hour, gdt.minute, gdt.second), Qt::UTC);
                    dist = 0;
                } else if (hint == QMetaType::QDate) {
                    ret = QDate(gdt.year + 1900, gdt.month + 1, gdt.monthDay);
                    dist = 1;
                } else {
                    ret = QTime(gdt.hour + 1900, gdt.minute, gdt.second);
                    dist = 2;
                }
            } else if (type == Number) {
526
                double b = value.toNumber(exec);
527
                GregorianDateTime gdt;
528
                msToGregorianDateTime(exec, b, true, gdt);
andersca@apple.com's avatar
andersca@apple.com committed
529 530 531 532 533 534 535 536 537 538
                if (hint == QMetaType::QDateTime) {
                    ret = QDateTime(QDate(gdt.year + 1900, gdt.month + 1, gdt.monthDay), QTime(gdt.hour, gdt.minute, gdt.second), Qt::UTC);
                    dist = 6;
                } else if (hint == QMetaType::QDate) {
                    ret = QDate(gdt.year + 1900, gdt.month + 1, gdt.monthDay);
                    dist = 8;
                } else {
                    ret = QTime(gdt.hour, gdt.minute, gdt.second);
                    dist = 10;
                }
539
#ifndef QT_NO_DATESTRING
andersca@apple.com's avatar
andersca@apple.com committed
540
            } else if (type == String) {
541
                UString ustring = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
542
                QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
andersca@apple.com's avatar
andersca@apple.com committed
543 544 545 546 547 548 549 550 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 576 577 578 579 580

                if (hint == QMetaType::QDateTime) {
                    QDateTime dt = QDateTime::fromString(qstring, Qt::ISODate);
                    if (!dt.isValid())
                        dt = QDateTime::fromString(qstring, Qt::TextDate);
                    if (!dt.isValid())
                        dt = QDateTime::fromString(qstring, Qt::SystemLocaleDate);
                    if (!dt.isValid())
                        dt = QDateTime::fromString(qstring, Qt::LocaleDate);
                    if (dt.isValid()) {
                        ret = dt;
                        dist = 2;
                    }
                } else if (hint == QMetaType::QDate) {
                    QDate dt = QDate::fromString(qstring, Qt::ISODate);
                    if (!dt.isValid())
                        dt = QDate::fromString(qstring, Qt::TextDate);
                    if (!dt.isValid())
                        dt = QDate::fromString(qstring, Qt::SystemLocaleDate);
                    if (!dt.isValid())
                        dt = QDate::fromString(qstring, Qt::LocaleDate);
                    if (dt.isValid()) {
                        ret = dt;
                        dist = 3;
                    }
                } else {
                    QTime dt = QTime::fromString(qstring, Qt::ISODate);
                    if (!dt.isValid())
                        dt = QTime::fromString(qstring, Qt::TextDate);
                    if (!dt.isValid())
                        dt = QTime::fromString(qstring, Qt::SystemLocaleDate);
                    if (!dt.isValid())
                        dt = QTime::fromString(qstring, Qt::LocaleDate);
                    if (dt.isValid()) {
                        ret = dt;
                        dist = 3;
                    }
                }
581
#endif // QT_NO_DATESTRING
andersca@apple.com's avatar
andersca@apple.com committed
582 583 584 585 586
            }
            break;

        case QMetaType::QRegExp:
            if (type == RegExp) {
587
/*
darin@apple.com's avatar
darin@apple.com committed
588
                RegExpObject *re = static_cast<RegExpObject*>(object);
andersca@apple.com's avatar
andersca@apple.com committed
589 590
*/
                // Attempt to convert.. a bit risky
591
                UString ustring = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
592
                QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
andersca@apple.com's avatar
andersca@apple.com committed
593 594

                // this is of the form '/xxxxxx/i'
595 596
                int firstSlash = qstring.indexOf(QLatin1Char('/'));
                int lastSlash = qstring.lastIndexOf(QLatin1Char('/'));
andersca@apple.com's avatar
andersca@apple.com committed
597 598 599 600 601
                if (firstSlash >=0 && lastSlash > firstSlash) {
                    QRegExp realRe;

                    realRe.setPattern(qstring.mid(firstSlash + 1, lastSlash - firstSlash - 1));

602
                    if (qstring.mid(lastSlash + 1).contains(QLatin1Char('i')))
andersca@apple.com's avatar
andersca@apple.com committed
603 604
                        realRe.setCaseSensitivity(Qt::CaseInsensitive);

605
                    ret = QVariant::fromValue(realRe);
andersca@apple.com's avatar
andersca@apple.com committed
606 607 608 609 610
                    dist = 0;
                } else {
                    qConvDebug() << "couldn't parse a JS regexp";
                }
            } else if (type == String) {
611
                UString ustring = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
612
                QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
andersca@apple.com's avatar
andersca@apple.com committed
613 614 615

                QRegExp re(qstring);
                if (re.isValid()) {
616
                    ret = QVariant::fromValue(re);
andersca@apple.com's avatar
andersca@apple.com committed
617 618 619 620 621 622 623
                    dist = 10;
                }
            }
            break;

        case QMetaType::QObjectStar:
            if (type == QObj) {
624
                QtInstance* qtinst = QtInstance::getInstance(object);
andersca@apple.com's avatar
andersca@apple.com committed
625 626 627
                if (qtinst) {
                    if (qtinst->getObject()) {
                        qConvDebug() << "found instance, with object:" << (void*) qtinst->getObject();
628
                        ret = QVariant::fromValue(qtinst->getObject());
andersca@apple.com's avatar
andersca@apple.com committed
629 630 631 632 633 634 635 636 637 638
                        qConvDebug() << ret;
                        dist = 0;
                    } else {
                        qConvDebug() << "can't convert deleted qobject";
                    }
                } else {
                    qConvDebug() << "wasn't a qtinstance";
                }
            } else if (type == Null) {
                QObject* nullobj = 0;
639
                ret = QVariant::fromValue(nullobj);
andersca@apple.com's avatar
andersca@apple.com committed
640 641 642 643 644 645 646 647
                dist = 0;
            } else {
                qConvDebug() << "previous type was not an object:" << type;
            }
            break;

        case QMetaType::VoidStar:
            if (type == QObj) {
648
                QtInstance* qtinst = QtInstance::getInstance(object);
andersca@apple.com's avatar
andersca@apple.com committed
649 650 651
                if (qtinst) {
                    if (qtinst->getObject()) {
                        qConvDebug() << "found instance, with object:" << (void*) qtinst->getObject();
652
                        ret = QVariant::fromValue((void *)qtinst->getObject());
andersca@apple.com's avatar
andersca@apple.com committed
653 654 655 656 657 658 659 660 661
                        qConvDebug() << ret;
                        dist = 0;
                    } else {
                        qConvDebug() << "can't convert deleted qobject";
                    }
                } else {
                    qConvDebug() << "wasn't a qtinstance";
                }
            } else if (type == Null) {
662
                ret = QVariant::fromValue((void*)0);
andersca@apple.com's avatar
andersca@apple.com committed
663 664 665 666
                dist = 0;
            } else if (type == Number) {
                // I don't think that converting a double to a pointer is a wise
                // move.  Except maybe 0.
667
                qConvDebug() << "got number for void * - not converting, seems unsafe:" << value.toNumber(exec);
andersca@apple.com's avatar
andersca@apple.com committed
668 669 670 671 672 673 674 675 676
            } else {
                qConvDebug() << "void* - unhandled type" << type;
            }
            break;

        default:
            // Non const type ids
            if (hint == (QMetaType::Type) qMetaTypeId<QObjectList>())
            {
677 678 679 680 681 682
                if (type == RTArray) {
                    RuntimeArray* rtarray = static_cast<RuntimeArray*>(object);

                    QObjectList result;
                    int len = rtarray->getLength();
                    for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
683
                        JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
684
                        int itemdist = -1;
685
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::QObjectStar, &itemdist, visitedObjects, recursionLimit);
686 687 688 689 690 691 692 693 694 695 696
                        if (itemdist >= 0)
                            result.append(item.value<QObject*>());
                        else
                            break;
                    }
                    // If we didn't fail conversion
                    if (result.count() == len) {
                        dist = 5;
                        ret = QVariant::fromValue(result);
                    }
                } else if (type == Array) {
697
                    JSObject* object = value.toObject(exec);
darin@apple.com's avatar
darin@apple.com committed
698
                    JSArray* array = static_cast<JSArray *>(object);
andersca@apple.com's avatar
andersca@apple.com committed
699
                    QObjectList result;
700
                    int len = array->length();
andersca@apple.com's avatar
andersca@apple.com committed
701
                    for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
702
                        JSValue val = array->get(exec, i);
andersca@apple.com's avatar
andersca@apple.com committed
703
                        int itemdist = -1;
704
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::QObjectStar, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718
                        if (itemdist >= 0)
                            result.append(item.value<QObject*>());
                        else
                            break;
                    }
                    // If we didn't fail conversion
                    if (result.count() == len) {
                        dist = 5;
                        ret = QVariant::fromValue(result);
                    }
                } else {
                    // Make a single length array
                    QObjectList result;
                    int itemdist = -1;
719
                    QVariant item = convertValueToQVariant(exec, value, QMetaType::QObjectStar, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
720 721 722 723 724 725 726 727
                    if (itemdist >= 0) {
                        result.append(item.value<QObject*>());
                        dist = 10;
                        ret = QVariant::fromValue(result);
                    }
                }
                break;
            } else if (hint == (QMetaType::Type) qMetaTypeId<QList<int> >()) {
728 729 730 731 732 733
                if (type == RTArray) {
                    RuntimeArray* rtarray = static_cast<RuntimeArray*>(object);

                    QList<int> result;
                    int len = rtarray->getLength();
                    for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
734
                        JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
735
                        int itemdist = -1;
736
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::Int, &itemdist, visitedObjects, recursionLimit);
737 738 739 740 741 742 743 744 745 746 747
                        if (itemdist >= 0)
                            result.append(item.value<int>());
                        else
                            break;
                    }
                    // If we didn't fail conversion
                    if (result.count() == len) {
                        dist = 5;
                        ret = QVariant::fromValue(result);
                    }
                } else if (type == Array) {
darin@apple.com's avatar
darin@apple.com committed
748
                    JSArray* array = static_cast<JSArray *>(object);
andersca@apple.com's avatar
andersca@apple.com committed
749 750

                    QList<int> result;
751
                    int len = array->length();
andersca@apple.com's avatar
andersca@apple.com committed
752
                    for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
753
                        JSValue val = array->get(exec, i);
andersca@apple.com's avatar
andersca@apple.com committed
754
                        int itemdist = -1;
755
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::Int, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
756 757 758 759 760 761 762 763 764 765 766 767 768 769
                        if (itemdist >= 0)
                            result.append(item.value<int>());
                        else
                            break;
                    }
                    // If we didn't fail conversion
                    if (result.count() == len) {
                        dist = 5;
                        ret = QVariant::fromValue(result);
                    }
                } else {
                    // Make a single length array
                    QList<int> result;
                    int itemdist = -1;
770
                    QVariant item = convertValueToQVariant(exec, value, QMetaType::Int, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
771 772 773 774 775 776 777
                    if (itemdist >= 0) {
                        result.append(item.value<int>());
                        dist = 10;
                        ret = QVariant::fromValue(result);
                    }
                }
                break;
778 779
            } else if (QtPixmapInstance::canHandle(static_cast<QMetaType::Type>(hint))) {
                ret = QtPixmapInstance::variantFromObject(object, static_cast<QMetaType::Type>(hint));
780
            } else if (hint == (QMetaType::Type) qMetaTypeId<QWebElement>()) {
781 782 783 784 785 786 787 788 789 790 791 792 793
                if (object && object->inherits(&JSElement::s_info)) {
                    ret = QVariant::fromValue<QWebElement>(QtWebElementRuntime::create((static_cast<JSElement*>(object))->impl()));
                    dist = 0;
                    // Allow other objects to reach this one. This won't cause our algorithm to
                    // loop since when we find an Element we do not recurse.
                    visitedObjects->remove(object);
                    break;
                }
                if (object && object->inherits(&JSDocument::s_info)) {
                    // To support LayoutTestControllerQt::nodesFromRect(), used in DRT, we do an implicit
                    // conversion from 'document' to the QWebElement representing the 'document.documentElement'.
                    // We can't simply use a QVariantMap in nodesFromRect() because it currently times out
                    // when serializing DOMMimeType and DOMPlugin, even if we limit the recursion.
794
                    ret = QVariant::fromValue<QWebElement>(QtWebElementRuntime::create((static_cast<JSDocument*>(object))->impl()->documentElement()));
795
                } else
796
                    ret = QVariant::fromValue<QWebElement>(QWebElement());
797 798 799
            } else if (hint == (QMetaType::Type) qMetaTypeId<QDRTNode>()) {
                if (object && object->inherits(&JSNode::s_info))
                    ret = QVariant::fromValue<QDRTNode>(QtDRTNodeRuntime::create((static_cast<JSNode*>(object))->impl()));
andersca@apple.com's avatar
andersca@apple.com committed
800
            } else if (hint == (QMetaType::Type) qMetaTypeId<QVariant>()) {
801
                if (value.isUndefinedOrNull()) {
802 803 804 805
                    if (distance)
                        *distance = 1;
                    return QVariant();
                } else {
806 807 808 809 810 811
                    if (type == Object) {
                        // Since we haven't really visited this object yet, we remove it
                        visitedObjects->remove(object);
                    }

                    // And then recurse with the autodetect flag
812
                    ret = convertValueToQVariant(exec, value, QMetaType::Void, distance, visitedObjects, recursionLimit);
813 814
                    dist = 10;
                }
andersca@apple.com's avatar
andersca@apple.com committed
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
                break;
            }

            dist = 10;
            break;
    }

    if (!ret.isValid())
        dist = -1;
    if (distance)
        *distance = dist;

    return ret;
}

ggaren@apple.com's avatar
ggaren@apple.com committed
830
QVariant convertValueToQVariant(ExecState* exec, JSValue value, QMetaType::Type hint, int *distance)
831
{
832
    const int recursionLimit = 200;
833
    HashSet<JSObject*> visitedObjects;
834
    return convertValueToQVariant(exec, value, hint, distance, &visitedObjects, recursionLimit);
835 836
}

ggaren@apple.com's avatar
ggaren@apple.com committed
837
JSValue convertQVariantToValue(ExecState* exec, PassRefPtr<RootObject> root, const QVariant& variant)
andersca@apple.com's avatar
andersca@apple.com committed
838 839 840 841
{
    // Variants with QObject * can be isNull but not a null pointer
    // An empty QString variant is also null
    QMetaType::Type type = (QMetaType::Type) variant.userType();
842 843

    qConvDebug() << "convertQVariantToValue: metatype:" << type << ", isnull: " << variant.isNull();
andersca@apple.com's avatar
andersca@apple.com committed
844 845 846 847 848 849 850 851
    if (variant.isNull() &&
        type != QMetaType::QObjectStar &&
        type != QMetaType::VoidStar &&
        type != QMetaType::QWidgetStar &&
        type != QMetaType::QString) {
        return jsNull();
    }

ap@webkit.org's avatar
ap@webkit.org committed
852
    JSLock lock(SilenceAssertionsOnly);
ap@webkit.org's avatar
ap@webkit.org committed
853

andersca@apple.com's avatar
andersca@apple.com committed
854 855 856 857 858 859 860 861 862 863 864 865 866
    if (type == QMetaType::Bool)
        return jsBoolean(variant.toBool());

    if (type == QMetaType::Int ||
        type == QMetaType::UInt ||
        type == QMetaType::Long ||
        type == QMetaType::ULong ||
        type == QMetaType::LongLong ||
        type == QMetaType::ULongLong ||
        type == QMetaType::Short ||
        type == QMetaType::UShort ||
        type == QMetaType::Float ||
        type == QMetaType::Double)
867
        return jsNumber(variant.toDouble());
andersca@apple.com's avatar
andersca@apple.com committed
868 869 870 871 872

    if (type == QMetaType::QRegExp) {
        QRegExp re = variant.value<QRegExp>();

        if (re.isValid()) {
873
            UString pattern((UChar*)re.pattern().utf16(), re.pattern().length());
barraclough@apple.com's avatar
barraclough@apple.com committed
874
            RegExpFlags flags = (re.caseSensitivity() == Qt::CaseInsensitive) ? FlagIgnoreCase : NoFlags;
875

876
            JSC::RegExp* regExp = JSC::RegExp::create(exec->globalData(), pattern, flags);
877
            if (regExp->isValid())
878
                return RegExpObject::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->regExpStructure(), regExp);
barraclough@apple.com's avatar
barraclough@apple.com committed
879
            return jsNull();
andersca@apple.com's avatar
andersca@apple.com committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
        }
    }

    if (type == QMetaType::QDateTime ||
        type == QMetaType::QDate ||
        type == QMetaType::QTime) {

        QDate date = QDate::currentDate();
        QTime time(0,0,0); // midnight

        if (type == QMetaType::QDate)
            date = variant.value<QDate>();
        else if (type == QMetaType::QTime)
            time = variant.value<QTime>();
        else {
            QDateTime dt = variant.value<QDateTime>().toLocalTime();
            date = dt.date();
            time = dt.time();
        }

        // Dates specified this way are in local time (we convert DateTimes above)
901
        GregorianDateTime dt;
902 903 904 905 906 907 908
        dt.year = date.year() - 1900;
        dt.month = date.month() - 1;
        dt.monthDay = date.day();
        dt.hour = time.hour();
        dt.minute = time.minute();
        dt.second = time.second();
        dt.isDST = -1;
909
        double ms = gregorianDateTimeToMS(exec, dt, time.msec(), /*inputIsUTC*/ false);
910

911
        return DateInstance::create(exec, exec->lexicalGlobalObject()->dateStructure(), trunc(ms));
andersca@apple.com's avatar
andersca@apple.com committed
912 913 914
    }

    if (type == QMetaType::QByteArray) {
hausmann@webkit.org's avatar
hausmann@webkit.org committed
915 916
        QByteArray qtByteArray = variant.value<QByteArray>();
        WTF::RefPtr<WTF::ByteArray> wtfByteArray = WTF::ByteArray::create(qtByteArray.length());
917
        memcpy(wtfByteArray->data(), qtByteArray.constData(), qtByteArray.length());
918
        return JSC::JSByteArray::create(exec, JSC::JSByteArray::createStructure(exec->globalData(), exec->lexicalGlobalObject(), jsNull()), wtfByteArray.get());
andersca@apple.com's avatar
andersca@apple.com committed
919 920 921 922
    }

    if (type == QMetaType::QObjectStar || type == QMetaType::QWidgetStar) {
        QObject* obj = variant.value<QObject*>();
923 924
        if (!obj)
            return jsNull();
hausmann@webkit.org's avatar
hausmann@webkit.org committed
925
        return QtInstance::getQtInstance(obj, root, QScriptEngine::QtOwnership)->createRuntimeObject(exec);
andersca@apple.com's avatar
andersca@apple.com committed
926 927
    }

928
    if (QtPixmapInstance::canHandle(static_cast<QMetaType::Type>(variant.type())))
929
        return QtPixmapInstance::createPixmapRuntimeObject(exec, root, variant);
930

931 932 933 934 935 936 937 938 939 940 941
    if (type == qMetaTypeId<QWebElement>()) {
        if (!root->globalObject()->inherits(&JSDOMWindow::s_info))
            return jsUndefined();

        Document* document = (static_cast<JSDOMWindow*>(root->globalObject()))->impl()->document();
        if (!document)
            return jsUndefined();

        return toJS(exec, toJSDOMGlobalObject(document, exec), QtWebElementRuntime::get(variant.value<QWebElement>()));
    }

942 943 944 945 946 947 948 949 950 951 952
    if (type == qMetaTypeId<QDRTNode>()) {
        if (!root->globalObject()->inherits(&JSDOMWindow::s_info))
            return jsUndefined();

        Document* document = (static_cast<JSDOMWindow*>(root->globalObject()))->impl()->document();
        if (!document)
            return jsUndefined();

        return toJS(exec, toJSDOMGlobalObject(document, exec), QtDRTNodeRuntime::get(variant.value<QDRTNode>()));
    }

andersca@apple.com's avatar
andersca@apple.com committed
953 954
    if (type == QMetaType::QVariantMap) {
        // create a new object, and stuff properties into it
955
        JSObject* ret = constructEmptyObject(exec);
andersca@apple.com's avatar
andersca@apple.com committed
956 957 958 959
        QVariantMap map = variant.value<QVariantMap>();
        QVariantMap::const_iterator i = map.constBegin();
        while (i != map.constEnd()) {
            QString s = i.key();
960
            JSValue val = convertQVariantToValue(exec, root.get(), i.value());
961 962
            if (val) {
                PutPropertySlot slot;
963
                ret->put(exec, Identifier(exec, reinterpret_cast_ptr<const UChar *>(s.constData()), s.length()), val, slot);
964 965
                // ### error case?
            }
andersca@apple.com's avatar
andersca@apple.com committed
966 967 968 969 970 971 972 973 974
            ++i;
        }

        return ret;
    }

    // List types
    if (type == QMetaType::QVariantList) {
        QVariantList vl = variant.toList();
975
        qConvDebug() << "got a " << vl.count() << " length list:" << vl;
976
        return RuntimeArray::create(exec, new QtArray<QVariant>(vl, QMetaType::Void, root));
andersca@apple.com's avatar
andersca@apple.com committed
977 978
    } else if (type == QMetaType::QStringList) {
        QStringList sl = variant.value<QStringList>();
979
        return RuntimeArray::create(exec, new QtArray<QString>(sl, QMetaType::QString, root));
andersca@apple.com's avatar
andersca@apple.com committed
980 981
    } else if (type == (QMetaType::Type) qMetaTypeId<QObjectList>()) {
        QObjectList ol= variant.value<QObjectList>();
982
        return RuntimeArray::create(exec, new QtArray<QObject*>(ol, QMetaType::QObjectStar, root));
andersca@apple.com's avatar
andersca@apple.com committed
983 984
    } else if (type == (QMetaType::Type)qMetaTypeId<QList<int> >()) {
        QList<int> il= variant.value<QList<int> >();
985
        return RuntimeArray::create(exec, new QtArray<int>(il, QMetaType::Int, root));
andersca@apple.com's avatar
andersca@apple.com committed
986 987 988 989 990 991 992 993 994 995 996
    }

    if (type == (QMetaType::Type)qMetaTypeId<QVariant>()) {
        QVariant real = variant.value<QVariant>();
        qConvDebug() << "real variant is:" << real;
        return convertQVariantToValue(exec, root, real);
    }

    qConvDebug() << "fallback path for" << variant << variant.userType();

    QString string = variant.toString();
darin@apple.com's avatar
darin@apple.com committed
997
    UString ustring((UChar*)string.utf16(), string.length());
ap@webkit.org's avatar
ap@webkit.org committed
998
    return jsString(exec, ustring);
andersca@apple.com's avatar
andersca@apple.com committed
999 1000 1001 1002 1003 1004 1005 1006
}

// ===============

// Qt-like macros
#define QW_D(Class) Class##Data* d = d_func()
#define QW_DS(Class,Instance) Class##Data* d = Instance->d_func()

1007
const ClassInfo QtRuntimeMethod::s_info = { "QtRuntimeMethod", &InternalFunction::s_info, 0, 0, CREATE_METHOD_TABLE(QtRuntimeMethod) };
1008

1009
QtRuntimeMethod::QtRuntimeMethod(QtRuntimeMethodData* dd, ExecState* exec, Structure* structure, const Identifier& identifier)
1010
    : InternalFunction(exec->lexicalGlobalObject(), structure)
andersca@apple.com's avatar
andersca@apple.com committed
1011 1012
    , d_ptr(dd)
{
1013 1014 1015 1016 1017
}

void QtRuntimeMethod::finishCreation(ExecState* exec, const Identifier& identifier, PassRefPtr<QtInstance> instance)
{
    Base::finishCreation(exec->globalData(), identifier);
andersca@apple.com's avatar
andersca@apple.com committed
1018
    QW_D(QtRuntimeMethod);
1019
    d->m_instance = instance;
1020
    d->m_finalizer.set(exec->globalData(), this, d);
andersca@apple.com's avatar
andersca@apple.com committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
}

QtRuntimeMethod::~QtRuntimeMethod()
{
    delete d_ptr;
}

// ===============

QtRuntimeMethodData::~QtRuntimeMethodData()
{
}

1034 1035 1036 1037 1038
void QtRuntimeMethodData::finalize(Handle<Unknown> value, void*)
{
    m_instance->removeCachedMethod(static_cast<JSObject*>(value.get().asCell()));
}

andersca@apple.com's avatar
andersca@apple.com committed
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132