qt_runtime.cpp 70.2 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

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

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

64
using namespace WebCore;
andersca@apple.com's avatar
andersca@apple.com committed
65

66
namespace JSC {
andersca@apple.com's avatar
andersca@apple.com committed
67 68 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
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 {
96
    Variant = 0,
andersca@apple.com's avatar
andersca@apple.com committed
97 98 99 100 101 102 103 104
    Number,
    Boolean,
    String,
    Date,
    RegExp,
    Array,
    QObj,
    Object,
105
    Null,
hausmann@webkit.org's avatar
hausmann@webkit.org committed
106 107
    RTArray,
    JSByteArray
andersca@apple.com's avatar
andersca@apple.com committed
108 109
} JSRealType;

110 111 112 113 114 115 116 117 118 119 120 121
#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

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
// 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;
    }
};

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
// 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
153
static JSRealType valueRealType(ExecState* exec, JSValue val)
andersca@apple.com's avatar
andersca@apple.com committed
154
{
155
    if (val.isNumber())
andersca@apple.com's avatar
andersca@apple.com committed
156
        return Number;
157
    else if (val.isString())
andersca@apple.com's avatar
andersca@apple.com committed
158
        return String;
159
    else if (val.isBoolean())
andersca@apple.com's avatar
andersca@apple.com committed
160
        return Boolean;
161
    else if (val.isNull())
andersca@apple.com's avatar
andersca@apple.com committed
162
        return Null;
163
    else if (isJSByteArray(&exec->globalData(), val))
hausmann@webkit.org's avatar
hausmann@webkit.org committed
164
        return JSByteArray;
165 166
    else if (val.isObject()) {
        JSObject *object = val.toObject(exec);
167 168
        if (object->inherits(&RuntimeArray::s_info))  // RuntimeArray 'inherits' from Array, but not in C++
            return RTArray;
169
        else if (object->inherits(&JSArray::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
170
            return Array;
171
        else if (object->inherits(&DateInstance::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
172
            return Date;
173
        else if (object->inherits(&RegExpObject::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
174
            return RegExp;
175
        else if (object->inherits(&RuntimeObject::s_info))
andersca@apple.com's avatar
andersca@apple.com committed
176 177 178 179 180 181 182
            return QObj;
        return Object;
    }

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

183 184 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
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;
}

214
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
215
{
216 217 218
    --recursionLimit;

    if (!value || !recursionLimit)
219 220
        return QVariant();

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

        visitedObjects->add(object);
    }

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

ap@webkit.org's avatar
ap@webkit.org committed
240
    JSLock lock(SilenceAssertionsOnly);
andersca@apple.com's avatar
andersca@apple.com committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    JSRealType type = valueRealType(exec, value);
    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;
260
            case Object:
261
                if (object->inherits(&NumberObject::s_info))
262
                    hint = QMetaType::Double;
263
                else if (object->inherits(&BooleanObject::s_info))
264 265 266
                    hint = QMetaType::Bool;
                else
                    hint = QMetaType::QVariantMap;
267
                break;
andersca@apple.com's avatar
andersca@apple.com committed
268 269 270
            case QObj:
                hint = QMetaType::QObjectStar;
                break;
hausmann@webkit.org's avatar
hausmann@webkit.org committed
271 272 273
            case JSByteArray:
                hint = QMetaType::QByteArray;
                break;
andersca@apple.com's avatar
andersca@apple.com committed
274
            case Array:
275
            case RTArray:
andersca@apple.com's avatar
andersca@apple.com committed
276 277 278 279 280
                hint = QMetaType::QVariantList;
                break;
        }
    }

281 282 283
    qConvDebug() << "convertValueToQVariant: jstype is " << type << ", hint is" << hint;

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

    QVariant ret;
    int dist = -1;
    switch (hint) {
        case QMetaType::Bool:
297
            if (type == Object && object->inherits(&BooleanObject::s_info))
298
                ret = QVariant(asBooleanObject(value)->internalValue().toBoolean(exec));
299
            else
300
                ret = QVariant(value.toBoolean(exec));
andersca@apple.com's avatar
andersca@apple.com committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
            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:
317
            ret = QVariant(value.toNumber(exec));
andersca@apple.com's avatar
andersca@apple.com committed
318 319 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
            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) {
355
                ret = QVariant(QChar((ushort)value.toNumber(exec)));
andersca@apple.com's avatar
andersca@apple.com committed
356 357 358 359 360
                if (type == Boolean)
                    dist = 3;
                else
                    dist = 6;
            } else {
361
                UString str = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
362
                ret = QVariant(QChar(str.length() ? *(const ushort*)str.impl()->characters() : 0));
andersca@apple.com's avatar
andersca@apple.com committed
363 364 365 366 367 368 369 370
                if (type == String)
                    dist = 3;
                else
                    dist = 10;
            }
            break;

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

386
        case QMetaType::QVariantMap:
387
            if (type == Object || type == Array || type == RTArray) {
388 389
                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
390 391 392 393 394
                dist = 1;
            }
            break;

        case QMetaType::QVariantList:
395 396 397 398 399 400 401 402
            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
403
                    JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
404
                    result.append(convertValueToQVariant(exec, val, QMetaType::Void, &objdist, visitedObjects, recursionLimit));
405 406 407 408 409 410 411 412 413 414
                    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
415
                JSArray* array = static_cast<JSArray*>(object);
andersca@apple.com's avatar
andersca@apple.com committed
416 417

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

        case QMetaType::QStringList: {
450 451 452 453 454 455
            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
456
                    JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
457
                    UString ustring = val.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
458
                    QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
459 460 461 462 463 464

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

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

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

        case QMetaType::QByteArray: {
hausmann@webkit.org's avatar
hausmann@webkit.org committed
491 492 493 494 495 496
            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
497
                ret = QVariant(QString((const QChar*)ustring.impl()->characters(), ustring.length()).toLatin1());
hausmann@webkit.org's avatar
hausmann@webkit.org committed
498 499 500 501 502
                if (type == String)
                    dist = 5;
                else
                    dist = 10;
            }
andersca@apple.com's avatar
andersca@apple.com committed
503 504 505 506 507 508 509 510
            break;
        }

        case QMetaType::QDateTime:
        case QMetaType::QDate:
        case QMetaType::QTime:
            if (type == Date) {
                DateInstance* date = static_cast<DateInstance*>(object);
511
                GregorianDateTime gdt;
512
                msToGregorianDateTime(exec, date->internalNumber(), true, gdt);
andersca@apple.com's avatar
andersca@apple.com committed
513 514 515 516 517 518 519 520 521 522 523
                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) {
524
                double b = value.toNumber(exec);
525
                GregorianDateTime gdt;
526
                msToGregorianDateTime(exec, b, true, gdt);
andersca@apple.com's avatar
andersca@apple.com committed
527 528 529 530 531 532 533 534 535 536
                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;
                }
537
#ifndef QT_NO_DATESTRING
andersca@apple.com's avatar
andersca@apple.com committed
538
            } else if (type == String) {
539
                UString ustring = value.toString(exec);
barraclough@apple.com's avatar
barraclough@apple.com committed
540
                QString qstring = QString((const QChar*)ustring.impl()->characters(), ustring.length());
andersca@apple.com's avatar
andersca@apple.com committed
541 542 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

                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;
                    }
                }
579
#endif // QT_NO_DATESTRING
andersca@apple.com's avatar
andersca@apple.com committed
580 581 582 583 584
            }
            break;

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

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

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

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

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

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

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

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

        default:
            // Non const type ids
            if (hint == (QMetaType::Type) qMetaTypeId<QObjectList>())
            {
675 676 677 678 679 680
                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
681
                        JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
682
                        int itemdist = -1;
683
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::QObjectStar, &itemdist, visitedObjects, recursionLimit);
684 685 686 687 688 689 690 691 692 693 694
                        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) {
695
                    JSObject* object = value.toObject(exec);
darin@apple.com's avatar
darin@apple.com committed
696
                    JSArray* array = static_cast<JSArray *>(object);
andersca@apple.com's avatar
andersca@apple.com committed
697
                    QObjectList result;
698
                    int len = array->length();
andersca@apple.com's avatar
andersca@apple.com committed
699
                    for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
700
                        JSValue val = array->get(exec, i);
andersca@apple.com's avatar
andersca@apple.com committed
701
                        int itemdist = -1;
702
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::QObjectStar, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
703 704 705 706 707 708 709 710 711 712 713 714 715 716
                        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;
717
                    QVariant item = convertValueToQVariant(exec, value, QMetaType::QObjectStar, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
718 719 720 721 722 723 724 725
                    if (itemdist >= 0) {
                        result.append(item.value<QObject*>());
                        dist = 10;
                        ret = QVariant::fromValue(result);
                    }
                }
                break;
            } else if (hint == (QMetaType::Type) qMetaTypeId<QList<int> >()) {
726 727 728 729 730 731
                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
732
                        JSValue val = rtarray->getConcreteArray()->valueAt(exec, i);
733
                        int itemdist = -1;
734
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::Int, &itemdist, visitedObjects, recursionLimit);
735 736 737 738 739 740 741 742 743 744 745
                        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
746
                    JSArray* array = static_cast<JSArray *>(object);
andersca@apple.com's avatar
andersca@apple.com committed
747 748

                    QList<int> result;
749
                    int len = array->length();
andersca@apple.com's avatar
andersca@apple.com committed
750
                    for (int i = 0; i < len; ++i) {
ggaren@apple.com's avatar
ggaren@apple.com committed
751
                        JSValue val = array->get(exec, i);
andersca@apple.com's avatar
andersca@apple.com committed
752
                        int itemdist = -1;
753
                        QVariant item = convertValueToQVariant(exec, val, QMetaType::Int, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767
                        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;
768
                    QVariant item = convertValueToQVariant(exec, value, QMetaType::Int, &itemdist, visitedObjects, recursionLimit);
andersca@apple.com's avatar
andersca@apple.com committed
769 770 771 772 773 774 775
                    if (itemdist >= 0) {
                        result.append(item.value<int>());
                        dist = 10;
                        ret = QVariant::fromValue(result);
                    }
                }
                break;
776 777
            } else if (QtPixmapInstance::canHandle(static_cast<QMetaType::Type>(hint))) {
                ret = QtPixmapInstance::variantFromObject(object, static_cast<QMetaType::Type>(hint));
778 779 780
            } else if (hint == (QMetaType::Type) qMetaTypeId<QWebElement>()) {
                if (object && object->inherits(&JSHTMLElement::s_info))
                    ret = QVariant::fromValue<QWebElement>(QtWebElementRuntime::create((static_cast<JSHTMLElement*>(object))->impl()));
781 782
                else if (object && object->inherits(&JSDocument::s_info))
                    ret = QVariant::fromValue<QWebElement>(QtWebElementRuntime::create((static_cast<JSDocument*>(object))->impl()->documentElement()));
783 784
                else
                    ret = QVariant::fromValue<QWebElement>(QWebElement());
785 786 787
            } 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
788
            } else if (hint == (QMetaType::Type) qMetaTypeId<QVariant>()) {
789
                if (value.isUndefinedOrNull()) {
790 791 792 793
                    if (distance)
                        *distance = 1;
                    return QVariant();
                } else {
794 795 796 797 798 799
                    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
800
                    ret = convertValueToQVariant(exec, value, QMetaType::Void, distance, visitedObjects, recursionLimit);
801 802
                    dist = 10;
                }
andersca@apple.com's avatar
andersca@apple.com committed
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
                break;
            }

            dist = 10;
            break;
    }

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

    return ret;
}

ggaren@apple.com's avatar
ggaren@apple.com committed
818
QVariant convertValueToQVariant(ExecState* exec, JSValue value, QMetaType::Type hint, int *distance)
819
{
820
    const int recursionLimit = 200;
821
    HashSet<JSObject*> visitedObjects;
822
    return convertValueToQVariant(exec, value, hint, distance, &visitedObjects, recursionLimit);
823 824
}

ggaren@apple.com's avatar
ggaren@apple.com committed
825
JSValue convertQVariantToValue(ExecState* exec, PassRefPtr<RootObject> root, const QVariant& variant)
andersca@apple.com's avatar
andersca@apple.com committed
826 827 828 829
{
    // 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();
830 831

    qConvDebug() << "convertQVariantToValue: metatype:" << type << ", isnull: " << variant.isNull();
andersca@apple.com's avatar
andersca@apple.com committed
832 833 834 835 836 837 838 839
    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
840
    JSLock lock(SilenceAssertionsOnly);
ap@webkit.org's avatar
ap@webkit.org committed
841

andersca@apple.com's avatar
andersca@apple.com committed
842 843 844 845 846 847 848 849 850 851 852 853 854
    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)
855
        return jsNumber(variant.toDouble());
andersca@apple.com's avatar
andersca@apple.com committed
856 857 858 859 860

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

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

864
            RefPtr<JSC::RegExp> regExp = JSC::RegExp::create(&exec->globalData(), pattern, flags);
865
            if (regExp->isValid())
866
                return new (exec) RegExpObject(exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->regExpStructure(), regExp.release());
barraclough@apple.com's avatar
barraclough@apple.com committed
867
            return jsNull();
andersca@apple.com's avatar
andersca@apple.com committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
        }
    }

    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)
889
        GregorianDateTime dt;
890 891 892 893 894 895 896
        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;
897
        double ms = gregorianDateTimeToMS(exec, dt, time.msec(), /*inputIsUTC*/ false);
898

899
        return new (exec) DateInstance(exec, exec->lexicalGlobalObject()->dateStructure(), trunc(ms));
andersca@apple.com's avatar
andersca@apple.com committed
900 901 902
    }

    if (type == QMetaType::QByteArray) {
hausmann@webkit.org's avatar
hausmann@webkit.org committed
903 904
        QByteArray qtByteArray = variant.value<QByteArray>();
        WTF::RefPtr<WTF::ByteArray> wtfByteArray = WTF::ByteArray::create(qtByteArray.length());
905
        memcpy(wtfByteArray->data(), qtByteArray.constData(), qtByteArray.length());
906
        return new (exec) JSC::JSByteArray(exec, JSC::JSByteArray::createStructure(exec->globalData(), jsNull()), wtfByteArray.get());
andersca@apple.com's avatar
andersca@apple.com committed
907 908 909 910
    }

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

916
    if (QtPixmapInstance::canHandle(static_cast<QMetaType::Type>(variant.type())))
917
        return QtPixmapInstance::createPixmapRuntimeObject(exec, root, variant);
918

919 920 921 922 923 924 925 926 927 928 929
    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>()));
    }

930 931 932 933 934 935 936 937 938 939 940
    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
941 942
    if (type == QMetaType::QVariantMap) {
        // create a new object, and stuff properties into it
943
        JSObject* ret = constructEmptyObject(exec);
andersca@apple.com's avatar
andersca@apple.com committed
944 945 946 947
        QVariantMap map = variant.value<QVariantMap>();
        QVariantMap::const_iterator i = map.constBegin();
        while (i != map.constEnd()) {
            QString s = i.key();
948
            JSValue val = convertQVariantToValue(exec, root.get(), i.value());
949 950
            if (val) {
                PutPropertySlot slot;
951
                ret->put(exec, Identifier(exec, reinterpret_cast_ptr<const UChar *>(s.constData()), s.length()), val, slot);
952 953
                // ### error case?
            }
andersca@apple.com's avatar
andersca@apple.com committed
954 955 956 957 958 959 960 961 962
            ++i;
        }

        return ret;
    }

    // List types
    if (type == QMetaType::QVariantList) {
        QVariantList vl = variant.toList();
963
        qConvDebug() << "got a " << vl.count() << " length list:" << vl;
ap@webkit.org's avatar
ap@webkit.org committed
964
        return new (exec) RuntimeArray(exec, new QtArray<QVariant>(vl, QMetaType::Void, root));
andersca@apple.com's avatar
andersca@apple.com committed
965 966
    } else if (type == QMetaType::QStringList) {
        QStringList sl = variant.value<QStringList>();
ap@webkit.org's avatar
ap@webkit.org committed
967
        return new (exec) RuntimeArray(exec, new QtArray<QString>(sl, QMetaType::QString, root));
andersca@apple.com's avatar
andersca@apple.com committed
968 969
    } else if (type == (QMetaType::Type) qMetaTypeId<QObjectList>()) {
        QObjectList ol= variant.value<QObjectList>();
ap@webkit.org's avatar
ap@webkit.org committed
970
        return new (exec) RuntimeArray(exec, new QtArray<QObject*>(ol, QMetaType::QObjectStar, root));
andersca@apple.com's avatar
andersca@apple.com committed
971 972
    } else if (type == (QMetaType::Type)qMetaTypeId<QList<int> >()) {
        QList<int> il= variant.value<QList<int> >();
ap@webkit.org's avatar
ap@webkit.org committed
973
        return new (exec) RuntimeArray(exec, new QtArray<int>(il, QMetaType::Int, root));
andersca@apple.com's avatar
andersca@apple.com committed
974 975 976 977 978 979 980 981 982 983 984
    }

    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
985
    UString ustring((UChar*)string.utf16(), string.length());
ap@webkit.org's avatar
ap@webkit.org committed
986
    return jsString(exec, ustring);
andersca@apple.com's avatar
andersca@apple.com committed
987 988 989 990 991 992 993 994
}

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

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

995
const ClassInfo QtRuntimeMethod::s_info = { "QtRuntimeMethod", &InternalFunction::s_info, 0, 0 };
996 997

QtRuntimeMethod::QtRuntimeMethod(QtRuntimeMethodData* dd, ExecState* exec, const Identifier& ident, PassRefPtr<QtInstance> inst)
oliver@apple.com's avatar
oliver@apple.com committed
998
    : InternalFunction(&exec->globalData(), exec->lexicalGlobalObject(), deprecatedGetDOMStructure<QtRuntimeMethod>(exec), ident)
andersca@apple.com's avatar
andersca@apple.com committed
999 1000 1001 1002
    , d_ptr(dd)
{
    QW_D(QtRuntimeMethod);
    d->m_instance = inst;
1003
    d->m_finalizer.set(exec->globalData(), this, d);
andersca@apple.com's avatar
andersca@apple.com committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
}

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

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

QtRuntimeMethodData::~QtRuntimeMethodData()
{
}

1017 1018 1019 1020 1021
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
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 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 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143