From 562adecf4f938f593674f03b425a79b89e238518 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:17:20 +0200 Subject: Don't block copy sequential files in QFile::rename Block copying a sequential file is potentially a destructive operation, because there is no guarantee copy+remove will succeed. In these cases the fallback should not be tried. The user is better equipped to decide how to handle such failures and to ensure no data losses occur, e.g., copy without removing the original file. Reviewed-by: MariusSO Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index d7da800..4110494 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -718,6 +718,11 @@ QFile::rename(const QString &newName) return true; } + if (isSequential()) { + d->setError(QFile::RenameError, tr("Will not rename sequential file using block copy")); + return false; + } + QFile in(fileName()); QFile out(newName); if (in.open(QIODevice::ReadOnly)) { -- cgit v0.12 From f1e9c0f3d22d611bfaa14c30a34e6042500a0cb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:24:43 +0200 Subject: Allow renaming QTemporaryFiles on windows Changed the fallback implementation to use 'this' instead of a new QFile. This allows a QTemporaryFile to be block-copied to the destination and the source to be removed (QTemporaryFile is special because it isn't really closed). Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index 4110494..d3cee9a 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -723,26 +723,25 @@ QFile::rename(const QString &newName) return false; } - QFile in(fileName()); QFile out(newName); - if (in.open(QIODevice::ReadOnly)) { + if (open(QIODevice::ReadOnly)) { if (out.open(QIODevice::WriteOnly | QIODevice::Truncate)) { bool error = false; char block[4096]; - qint64 read; - while ((read = in.read(block, sizeof(block))) > 0) { - if (read != out.write(block, read)) { + qint64 bytes; + while ((bytes = read(block, sizeof(block))) > 0) { + if (bytes != out.write(block, bytes)) { d->setError(QFile::RenameError, out.errorString()); error = true; break; } } - if (read == -1) { - d->setError(QFile::RenameError, in.errorString()); + if (bytes == -1) { + d->setError(QFile::RenameError, errorString()); error = true; } if(!error) { - if (!in.remove()) { + if (!remove()) { d->setError(QFile::RenameError, tr("Cannot remove source file")); error = true; } @@ -751,10 +750,12 @@ QFile::rename(const QString &newName) out.remove(); else setFileName(newName); + close(); return !error; } + close(); } - d->setError(QFile::RenameError, out.isOpen() ? in.errorString() : out.errorString()); + d->setError(QFile::RenameError, out.isOpen() ? errorString() : out.errorString()); } return false; } -- cgit v0.12 From fd7cb7faa765835de6e7beb24f018c417d9ad7d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 13 May 2009 17:13:48 +0200 Subject: QFile::copy: close source file when using fallback mechanism Also added check in test case for rename fallback. Task-number: 165920 Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 1 + tests/auto/qfile/copy-fallback.qrc | 5 +++++ tests/auto/qfile/test/test.pro | 2 +- tests/auto/qfile/tst_qfile.cpp | 30 ++++++++++++++++++++++++++++++ 4 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/auto/qfile/copy-fallback.qrc diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index d3cee9a..a0bd8b4 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -914,6 +914,7 @@ QFile::copy(const QString &newName) out.setAutoRemove(false); #endif } + close(); } if(!error) { QFile::setPermissions(newName, permissions()); diff --git a/tests/auto/qfile/copy-fallback.qrc b/tests/auto/qfile/copy-fallback.qrc new file mode 100644 index 0000000..864491f --- /dev/null +++ b/tests/auto/qfile/copy-fallback.qrc @@ -0,0 +1,5 @@ + + + copy-fallback.qrc + + diff --git a/tests/auto/qfile/test/test.pro b/tests/auto/qfile/test/test.pro index 68f4c05..8d26f5e 100644 --- a/tests/auto/qfile/test/test.pro +++ b/tests/auto/qfile/test/test.pro @@ -17,7 +17,7 @@ QT = core network DEFINES += SRCDIR=\\\"$$PWD/../\\\" } -RESOURCES += ../qfile.qrc ../rename-fallback.qrc +RESOURCES += ../qfile.qrc ../rename-fallback.qrc ../copy-fallback.qrc TARGET = ../tst_qfile diff --git a/tests/auto/qfile/tst_qfile.cpp b/tests/auto/qfile/tst_qfile.cpp index 98e1859..7e28d12 100644 --- a/tests/auto/qfile/tst_qfile.cpp +++ b/tests/auto/qfile/tst_qfile.cpp @@ -125,6 +125,7 @@ private slots: void copy(); void copyRemovesTemporaryFile() const; void copyShouldntOverwrite(); + void copyFallback(); void link(); void linkToDir(); void absolutePathLinkToRelativePath(); @@ -213,6 +214,9 @@ void tst_QFile::cleanup() // TODO: Add cleanup code here. // This will be executed immediately after each test is run. + // for copyFallback() + QFile::remove("file-copy-destination.txt"); + // for renameFallback() QFile::remove("file-rename-destination.txt"); @@ -907,6 +911,31 @@ void tst_QFile::copyShouldntOverwrite() QFile::remove("tst_qfile.cpy"); } +void tst_QFile::copyFallback() +{ + // Using a resource file to trigger QFile::copy's fallback handling + QFile file(":/copy-fallback.qrc"); + QFile::remove("file-copy-destination.txt"); + + QVERIFY2(file.exists(), "test precondition"); + QVERIFY2(!QFile::exists("file-copy-destination.txt"), "test precondition"); + + // Fallback copy of closed file. + QVERIFY(file.copy("file-copy-destination.txt")); + QVERIFY(QFile::exists("file-copy-destination.txt")); + QVERIFY(!file.isOpen()); + + QVERIFY(QFile::remove("file-copy-destination.txt")); + + // Fallback copy of open file. + QVERIFY(file.open(QIODevice::ReadOnly)); + QVERIFY(file.copy("file-copy-destination.txt")); + QVERIFY(QFile::exists("file-copy-destination.txt")); + QVERIFY(!file.isOpen()); + + QFile::remove("file-copy-destination.txt"); +} + #ifdef Q_OS_WIN #include #include @@ -2081,6 +2110,7 @@ void tst_QFile::renameFallback() QVERIFY(!file.rename("file-rename-destination.txt")); QVERIFY(!QFile::exists("file-rename-destination.txt")); + QVERIFY(!file.isOpen()); } void tst_QFile::renameMultiple() -- cgit v0.12 From 3580f5b4d002cca714d443054f8cdd6aefca3287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:30:47 +0200 Subject: QFile::rename fallback: reset permissions and error state on success Fallback implementation for rename operation should try to copy permissions from the original file to the destination file. Note that failures at this point are not treated as errors. Errors previously set by the native fileEngine are also reset before returning. Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index a0bd8b4..10b812b 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -748,8 +748,11 @@ QFile::rename(const QString &newName) } if (error) out.remove(); - else + else { + setPermissions(permissions()); + unsetError(); setFileName(newName); + } close(); return !error; } -- cgit v0.12 From 3672deb3b35fc0660c58a8ecc741b989dd0bfc8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Tue, 19 May 2009 14:02:12 +0200 Subject: Fix auto test When copying a resource file to the native file system the (read-only) permissions also get copied. On Windows platforms, this was preventing a test file from being deleted. Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- tests/auto/qfile/tst_qfile.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/auto/qfile/tst_qfile.cpp b/tests/auto/qfile/tst_qfile.cpp index 7e28d12..9ee4d7c 100644 --- a/tests/auto/qfile/tst_qfile.cpp +++ b/tests/auto/qfile/tst_qfile.cpp @@ -215,7 +215,11 @@ void tst_QFile::cleanup() // This will be executed immediately after each test is run. // for copyFallback() - QFile::remove("file-copy-destination.txt"); + if (QFile::exists("file-copy-destination.txt")) { + QFile::setPermissions("file-copy-destination.txt", + QFile::ReadOwner | QFile::WriteOwner); + QFile::remove("file-copy-destination.txt"); + } // for renameFallback() QFile::remove("file-rename-destination.txt"); @@ -925,6 +929,9 @@ void tst_QFile::copyFallback() QVERIFY(QFile::exists("file-copy-destination.txt")); QVERIFY(!file.isOpen()); + // Need to reset permissions on Windows to be able to delete + QVERIFY(QFile::setPermissions("file-copy-destination.txt", + QFile::ReadOwner | QFile::WriteOwner)); QVERIFY(QFile::remove("file-copy-destination.txt")); // Fallback copy of open file. -- cgit v0.12 From 662e8997e9777c6661dde2134e43e35963a12cb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:34:57 +0200 Subject: QTemporaryFile: don't clear filePath if remove fails Reviewed-by: MariusSO Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 6a9125c..b0809c6 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -364,9 +364,11 @@ bool QTemporaryFileEngine::remove() // Since the QTemporaryFileEngine::close() does not really close the file, // we must explicitly call QFSFileEngine::close() before we remove it. QFSFileEngine::close(); - bool removed = QFSFileEngine::remove(); - d->filePath.clear(); - return removed; + if (QFSFileEngine::remove()) { + d->filePath.clear(); + return true; + } + return false; } bool QTemporaryFileEngine::close() -- cgit v0.12 From cfa01206e38d120c0ddb17aec7358aadff30b6f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 12:40:01 +0200 Subject: QTemporaryFile would forget fileName while file was "closed" Note: this showed even if the file descriptor was kept open. Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 3 ++- tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index b0809c6..11e88e2 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -603,7 +603,8 @@ void QTemporaryFile::setAutoRemove(bool b) QString QTemporaryFile::fileName() const { - if(!isOpen()) + Q_D(const QTemporaryFile); + if(d->fileName.isEmpty()) return QString(); return fileEngine()->fileName(QAbstractFileEngine::DefaultName); } diff --git a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp index 2daa0f6..c6a43ff 100644 --- a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp +++ b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp @@ -77,6 +77,7 @@ private slots: void fileTemplate_data(); void getSetCheck(); void fileName(); + void fileNameIsEmpty(); void autoRemove(); void write(); void openCloseOpenClose(); @@ -189,6 +190,27 @@ void tst_QTemporaryFile::fileName() QCOMPARE(absoluteFilePath, absoluteTempPath); } +void tst_QTemporaryFile::fileNameIsEmpty() +{ + QString filename; + { + QTemporaryFile file; + QVERIFY(file.fileName().isEmpty()); + + QVERIFY(file.open()); + QVERIFY(!file.fileName().isEmpty()); + + filename = file.fileName(); + QVERIFY(QFile::exists(filename)); + + file.close(); + QVERIFY(!file.isOpen()); + QVERIFY(QFile::exists(filename)); + QVERIFY(!file.fileName().isEmpty()); + } + QVERIFY(!QFile::exists(filename)); +} + void tst_QTemporaryFile::autoRemove() { // Test auto remove @@ -358,6 +380,7 @@ void tst_QTemporaryFile::rename() QVERIFY(file.rename("temporary-file.txt")); QVERIFY(!dir.exists(tempname)); QVERIFY(dir.exists("temporary-file.txt")); + QCOMPARE(file.fileName(), QString("temporary-file.txt")); } QVERIFY(!dir.exists(tempname)); -- cgit v0.12 From 70f616238e77d866420f2c6e12afe04b529fe808 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 20 May 2009 20:13:51 +0200 Subject: Documentation fix We souldn't be returning an empty string for the fileName, just because the file is closed. E.g., after a rename, the file will be closed, but should still have a name. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 11e88e2..e83d7e9 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -432,8 +432,8 @@ QTemporaryFilePrivate::~QTemporaryFilePrivate() file will exist and be kept open internally by QTemporaryFile. The file name of the temporary file can be found by calling fileName(). - Note that this is only defined while the file is open; the function returns - an empty string before the file is opened and after it is closed. + Note that this is only defined after the file is first opened; the function + returns an empty string before this. A temporary file will have some static part of the name and some part that is calculated to be unique. The default filename \c -- cgit v0.12 From 5cb1ed45ba55dbc9752e0f6f47cc6d1525464646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 13:01:52 +0200 Subject: QTemporaryFile: handle failures from QFSFileEngine::open(mode, fd) For now, this only happens if Append mode is requested and we're unable to seek to the end of the file. Theoretically, this could change in the future so it's better to err on the safe side. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index e83d7e9..b6eff94 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -322,7 +322,6 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) qfilename += QLatin1String(".XXXXXX"); int suffixLength = qfilename.length() - (qfilename.lastIndexOf(QLatin1String("XXXXXX"), -1, Qt::CaseSensitive) + 6); - d->closeFileHandle = true; char *filename = qstrdup(qfilename.toLocal8Bit()); #ifndef Q_WS_WIN @@ -330,16 +329,19 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) if (fd != -1) { // First open the fd as an external file descriptor to // initialize the engine properly. - QFSFileEngine::open(openMode, fd); + if (QFSFileEngine::open(openMode, fd)) { - // Allow the engine to close the handle even if it's "external". - d->closeFileHandle = true; + // Allow the engine to close the handle even if it's "external". + d->closeFileHandle = true; - // Restore the file names (open() resets them). - d->filePath = QString::fromLocal8Bit(filename); //changed now! - d->nativeInitFileName(); - delete [] filename; - return true; + // Restore the file names (open() resets them). + d->filePath = QString::fromLocal8Bit(filename); //changed now! + d->nativeInitFileName(); + delete [] filename; + return true; + } + + QT_CLOSE(fd); } delete [] filename; setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(errno)); -- cgit v0.12 From f1793cbff8aa9b4adcb5fd511e495f7e96811e2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 14:58:44 +0200 Subject: Unconditionally open temporary files in ReadWrite mode Although QTemporaryFile hides QFile::open(OpenMode), this function is still available when accessing instance methods through the base class. Unconditionally setting ReadWrite allows the temporary file to be re-opened with different flags. Task-number: 248223 Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 1 + tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index b6eff94..3f8f978 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -720,6 +720,7 @@ bool QTemporaryFile::open(OpenMode flags) return true; } + flags |= QIODevice::ReadWrite; if (QFile::open(flags)) { d->fileName = d->fileEngine->fileName(QAbstractFileEngine::DefaultName); return true; diff --git a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp index c6a43ff..26f5f40 100644 --- a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp +++ b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp @@ -87,6 +87,8 @@ private slots: void stressTest(); void rename(); void renameFdLeak(); + void reOpenThroughQFile(); + public: }; @@ -424,5 +426,18 @@ void tst_QTemporaryFile::renameFdLeak() #endif } +void tst_QTemporaryFile::reOpenThroughQFile() +{ + QByteArray data("abcdefghij"); + + QTemporaryFile file; + QVERIFY(((QFile &)file).open(QIODevice::WriteOnly)); + QCOMPARE(file.write(data), (qint64)data.size()); + + file.close(); + QVERIFY(file.open()); + QCOMPARE(file.readAll(), data); +} + QTEST_MAIN(tst_QTemporaryFile) #include "tst_qtemporaryfile.moc" -- cgit v0.12 From 27369e563263e82a9c5747da54370eb0a225b3d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 18:40:03 +0200 Subject: QTemporaryFile: really (re)open file if it has been really closed... In some circumstances, the file descriptor in QTemporaryFile is actually closed and setOpenMode alone won't give us reOpen semantics. Added function to QTemporaryFileEngine that checks if we have open file handles. On open, if we currently hold no handles, re-open the file. Trying to open a new file while we hold open handles would lead to leaks, so added an assert there, to be on the safe side. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 3f8f978..5e08ed8 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -294,6 +294,7 @@ public: QTemporaryFileEngine(const QString &file) : QFSFileEngine(file) { } ~QTemporaryFileEngine(); + bool isReallyOpen(); void setFileName(const QString &file); bool open(QIODevice::OpenMode flags); @@ -306,6 +307,21 @@ QTemporaryFileEngine::~QTemporaryFileEngine() QFSFileEngine::close(); } +bool QTemporaryFileEngine::isReallyOpen() +{ + Q_D(QFSFileEngine); + + if (!((0 == d->fh) && (-1 == d->fd) +#if defined Q_OS_WIN + && (INVALID_HANDLE_VALUE == d->fileHandle) +#endif + )) + return true; + + return false; + +} + void QTemporaryFileEngine::setFileName(const QString &file) { // Really close the file, so we don't leak @@ -316,6 +332,7 @@ void QTemporaryFileEngine::setFileName(const QString &file) bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) { Q_D(QFSFileEngine); + Q_ASSERT(!isReallyOpen()); QString qfilename = d->filePath; if(!qfilename.contains(QLatin1String("XXXXXX"))) @@ -716,8 +733,10 @@ bool QTemporaryFile::open(OpenMode flags) { Q_D(QTemporaryFile); if (!d->fileName.isEmpty()) { - setOpenMode(flags); - return true; + if (static_cast(fileEngine())->isReallyOpen()) { + setOpenMode(flags); + return true; + } } flags |= QIODevice::ReadWrite; -- cgit v0.12 From 84cbe8ffa4a7189c46efca9bb6387e80ab889c5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:37:35 +0200 Subject: QTemporaryFile: there's no need to keep another pointer to the engine here Lifetime of the engine is already handled by the native engine. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 5e08ed8..ec539d4 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -409,17 +409,14 @@ protected: bool autoRemove; QString templateName; - mutable QTemporaryFileEngine *fileEngine; }; -QTemporaryFilePrivate::QTemporaryFilePrivate() : autoRemove(true), fileEngine(0) +QTemporaryFilePrivate::QTemporaryFilePrivate() : autoRemove(true) { } QTemporaryFilePrivate::~QTemporaryFilePrivate() { - delete fileEngine; - fileEngine = 0; } //************* QTemporaryFile -- cgit v0.12 From 1044e75822270d702a3e9f14a87954321984c942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 20:24:20 +0200 Subject: QTemporaryFileEngine now tracks if a fileName has been generated With recent changes to QTemporaryFile, allowing the file to be closed, the engine has to keep track of whether a fileName has already been generated, so we don't generate new files after the first one. If the file is closed but we already have a name for it, then just forward the call to the base file engine. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index ec539d4..564ec59 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -291,7 +291,11 @@ class QTemporaryFileEngine : public QFSFileEngine { Q_DECLARE_PRIVATE(QFSFileEngine) public: - QTemporaryFileEngine(const QString &file) : QFSFileEngine(file) { } + QTemporaryFileEngine(const QString &file, bool fileIsTemplate = true) + : QFSFileEngine(file), filePathIsTemplate(fileIsTemplate) + { + } + ~QTemporaryFileEngine(); bool isReallyOpen(); @@ -300,6 +304,8 @@ public: bool open(QIODevice::OpenMode flags); bool remove(); bool close(); + + bool filePathIsTemplate; }; QTemporaryFileEngine::~QTemporaryFileEngine() @@ -334,6 +340,9 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) Q_D(QFSFileEngine); Q_ASSERT(!isReallyOpen()); + if (!filePathIsTemplate) + return QFSFileEngine::open(openMode); + QString qfilename = d->filePath; if(!qfilename.contains(QLatin1String("XXXXXX"))) qfilename += QLatin1String(".XXXXXX"); @@ -353,6 +362,7 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) // Restore the file names (open() resets them). d->filePath = QString::fromLocal8Bit(filename); //changed now! + filePathIsTemplate = false; d->nativeInitFileName(); delete [] filename; return true; @@ -370,6 +380,7 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) } d->filePath = QString::fromLocal8Bit(filename); + filePathIsTemplate = false; d->nativeInitFileName(); d->closeFileHandle = true; delete [] filename; @@ -714,8 +725,12 @@ QTemporaryFile *QTemporaryFile::createLocalFile(QFile &file) QAbstractFileEngine *QTemporaryFile::fileEngine() const { Q_D(const QTemporaryFile); - if(!d->fileEngine) - d->fileEngine = new QTemporaryFileEngine(d->templateName); + if(!d->fileEngine) { + if (d->fileName.isEmpty()) + d->fileEngine = new QTemporaryFileEngine(d->templateName); + else + d->fileEngine = new QTemporaryFileEngine(d->fileName, false); + } return d->fileEngine; } -- cgit v0.12 From ba706d2564f1181fa4cc596a46bb2a041c62c28f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 13:08:04 +0200 Subject: QTemporaryFile: really close files before renaming This gets temporary file renaming working on Windows, without requiring block-copying. While we could #ifdef this behavior for Windows, it's preferrable to maintain consistency in the exposed interface. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 564ec59..7c0b018 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -303,6 +303,7 @@ public: bool open(QIODevice::OpenMode flags); bool remove(); + bool rename(const QString &newName); bool close(); bool filePathIsTemplate; @@ -401,6 +402,12 @@ bool QTemporaryFileEngine::remove() return false; } +bool QTemporaryFileEngine::rename(const QString &newName) +{ + QFSFileEngine::close(); + return QFSFileEngine::rename(newName); +} + bool QTemporaryFileEngine::close() { // Don't close the file, just seek to the front. -- cgit v0.12 From a0396c8c68aca446e68434e516bd46d749093b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 11:51:12 +0200 Subject: Reset openMode to NotOpen when returning false from QFile::open() When connecting to an open file descriptor, set the openMode in the file system engine, as is done for file handles. Reviewed-by: Thiago --- src/corelib/io/qfsfileengine.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp index 61ea7cc..1c8f0e9 100644 --- a/src/corelib/io/qfsfileengine.cpp +++ b/src/corelib/io/qfsfileengine.cpp @@ -312,6 +312,10 @@ bool QFSFileEnginePrivate::openFh(QIODevice::OpenMode openMode, FILE *fh) if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); + + this->openMode = QIODevice::NotOpen; + this->fh = 0; + return false; } } @@ -335,6 +339,7 @@ bool QFSFileEngine::open(QIODevice::OpenMode openMode, int fd) if ((openMode & QFile::WriteOnly) && !(openMode & (QFile::ReadOnly | QFile::Append))) openMode |= QFile::Truncate; + d->openMode = openMode; d->lastFlushFailed = false; d->closeFileHandle = false; d->nativeFilePath.clear(); @@ -367,6 +372,10 @@ bool QFSFileEnginePrivate::openFd(QIODevice::OpenMode openMode, int fd) if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); + + this->openMode = QIODevice::NotOpen; + this->fd = -1; + return false; } } -- cgit v0.12 From 8b2a16bd7f434a159e34e93dbffc983927a0a143 Mon Sep 17 00:00:00 2001 From: Markus Goetz Date: Fri, 22 May 2009 13:20:10 +0200 Subject: Fixed compilation with -qtnamespace Task-number: 254333 Reviewed-by: Andy Shaw --- src/corelib/io/qtemporaryfile.cpp | 4 +++- src/corelib/kernel/qsharedmemory_unix.cpp | 4 ++-- src/corelib/kernel/qsystemsemaphore_p.h | 4 ++-- src/corelib/kernel/qtranslator.cpp | 4 ++-- src/network/access/qhttp.cpp | 4 ++-- src/network/kernel/qnetworkproxy.cpp | 4 ++-- src/network/kernel/qurlinfo.cpp | 4 ++-- src/network/socket/qhttpsocketengine.cpp | 4 ++-- src/scripttools/debugging/qscriptenginedebugger.cpp | 13 ++++++++++--- 9 files changed, 27 insertions(+), 18 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 7c0b018..b4d8a48 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -766,6 +766,8 @@ bool QTemporaryFile::open(OpenMode flags) return false; } +QT_END_NAMESPACE + #endif // QT_NO_TEMPORARYFILE -QT_END_NAMESPACE + diff --git a/src/corelib/kernel/qsharedmemory_unix.cpp b/src/corelib/kernel/qsharedmemory_unix.cpp index 487c653..61d56f4 100644 --- a/src/corelib/kernel/qsharedmemory_unix.cpp +++ b/src/corelib/kernel/qsharedmemory_unix.cpp @@ -49,10 +49,10 @@ #include -QT_BEGIN_NAMESPACE - #ifndef QT_NO_SHAREDMEMORY +QT_BEGIN_NAMESPACE + #include #include #include diff --git a/src/corelib/kernel/qsystemsemaphore_p.h b/src/corelib/kernel/qsystemsemaphore_p.h index 81d4f10..a4a7389 100644 --- a/src/corelib/kernel/qsystemsemaphore_p.h +++ b/src/corelib/kernel/qsystemsemaphore_p.h @@ -101,9 +101,9 @@ public: QSystemSemaphore::SystemSemaphoreError error; }; -#endif // QT_NO_SYSTEMSEMAPHORE +QT_END_NAMESPACE +#endif // QT_NO_SYSTEMSEMAPHORE -QT_END_NAMESPACE #endif // QSYSTEMSEMAPHORE_P_H diff --git a/src/corelib/kernel/qtranslator.cpp b/src/corelib/kernel/qtranslator.cpp index 77d6599..3e4b467 100644 --- a/src/corelib/kernel/qtranslator.cpp +++ b/src/corelib/kernel/qtranslator.cpp @@ -819,6 +819,6 @@ bool QTranslator::isEmpty() const Use translate(\a context, \a sourceText, \a comment) instead. */ -#endif // QT_NO_TRANSLATION - QT_END_NAMESPACE + +#endif // QT_NO_TRANSLATION diff --git a/src/network/access/qhttp.cpp b/src/network/access/qhttp.cpp index 7d14ab6..30befb3 100644 --- a/src/network/access/qhttp.cpp +++ b/src/network/access/qhttp.cpp @@ -64,10 +64,10 @@ # include "qtimer.h" #endif -QT_BEGIN_NAMESPACE - #ifndef QT_NO_HTTP +QT_BEGIN_NAMESPACE + class QHttpNormalRequest; class QHttpRequest { diff --git a/src/network/kernel/qnetworkproxy.cpp b/src/network/kernel/qnetworkproxy.cpp index 62bdfc7..fd3a85a 100644 --- a/src/network/kernel/qnetworkproxy.cpp +++ b/src/network/kernel/qnetworkproxy.cpp @@ -1258,6 +1258,6 @@ QList QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuer return globalNetworkProxy()->proxyForQuery(query); } -#endif // QT_NO_NETWORKPROXY - QT_END_NAMESPACE + +#endif // QT_NO_NETWORKPROXY diff --git a/src/network/kernel/qurlinfo.cpp b/src/network/kernel/qurlinfo.cpp index 255c9ea..d90c480 100644 --- a/src/network/kernel/qurlinfo.cpp +++ b/src/network/kernel/qurlinfo.cpp @@ -726,6 +726,6 @@ bool QUrlInfo::isValid() const return d != 0; } -#endif // QT_NO_URLINFO - QT_END_NAMESPACE + +#endif // QT_NO_URLINFO diff --git a/src/network/socket/qhttpsocketengine.cpp b/src/network/socket/qhttpsocketengine.cpp index 540c443..5a2a746 100644 --- a/src/network/socket/qhttpsocketengine.cpp +++ b/src/network/socket/qhttpsocketengine.cpp @@ -768,6 +768,6 @@ QAbstractSocketEngine *QHttpSocketEngineHandler::createSocketEngine(int, QObject return 0; } -#endif - QT_END_NAMESPACE + +#endif diff --git a/src/scripttools/debugging/qscriptenginedebugger.cpp b/src/scripttools/debugging/qscriptenginedebugger.cpp index e35bd1d..0f8b600 100644 --- a/src/scripttools/debugging/qscriptenginedebugger.cpp +++ b/src/scripttools/debugging/qscriptenginedebugger.cpp @@ -63,16 +63,23 @@ #include #include +// this has to be outside the namespace +static void initScriptEngineDebuggerResources() +{ + Q_INIT_RESOURCE(scripttools_debugging); +} + +QT_BEGIN_NAMESPACE + class QtScriptDebuggerResourceInitializer { public: QtScriptDebuggerResourceInitializer() { - Q_INIT_RESOURCE(scripttools_debugging); + // call outside-the-namespace function + initScriptEngineDebuggerResources(); } }; -QT_BEGIN_NAMESPACE - /*! \since 4.5 \class QScriptEngineDebugger -- cgit v0.12 From 751e0f1b70cb0c80e88f99e5137329d6f4b76562 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Fri, 22 May 2009 14:58:06 +0200 Subject: qdoc: Moved some qdoc comments into the .cpp file common to all packages. Task-number: 252494 --- src/corelib/io/qfsfileengine.cpp | 113 +++++++++++++++++++++++++++++++++++ src/corelib/io/qfsfileengine_win.cpp | 83 ------------------------- 2 files changed, 113 insertions(+), 83 deletions(-) diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp index 61ea7cc..99c1909 100644 --- a/src/corelib/io/qfsfileengine.cpp +++ b/src/corelib/io/qfsfileengine.cpp @@ -868,6 +868,119 @@ bool QFSFileEngine::supportsExtension(Extension extension) const return false; } +/*! \fn bool QFSFileEngine::caseSensitive() const + Returns true for Windows, false for Unix. +*/ + +/*! \fn bool QFSFileEngine::copy(const QString ©Name) + + For windows, copy the file to file \a copyName. + + Not implemented for Unix. +*/ + +/*! \fn QString QFSFileEngine::currentPath(const QString &fileName) + For Unix, returns the current working directory for the file + engine. + + For Windows, returns the canonicalized form of the current path used + by the file engine for the drive specified by \a fileName. On + Windows, each drive has its own current directory, so a different + path is returned for file names that include different drive names + (e.g. A: or C:). + + \sa setCurrentPath() +*/ + +/*! \fn QFileInfoList QFSFileEngine::drives() + For Windows, returns the list of drives in the file system as a list + of QFileInfo objects. On unix, Mac OS X and Windows CE, only the + root path is returned. On Windows, this function returns all drives + (A:\, C:\, D:\, etc.). + + For Unix, the list contains just the root path "/". +*/ + +/*! \fn QString QFSFileEngine::fileName(FileName file) const + \reimp +*/ + +/*! \fn QDateTime QFSFileEngine::fileTime(FileTime time) const + \reimp +*/ + +/*! \fn QString QFSFileEngine::homePath() + Returns the home path of the current user. + + \sa rootPath() +*/ + +/*! \fn bool QFSFileEngine::isRelativePath() const + \reimp +*/ + +/*! \fn bool QFSFileEngine::link(const QString &newName) + + Creates a link from the file currently specified by fileName() to + \a newName. What a link is depends on the underlying filesystem + (be it a shortcut on Windows or a symbolic link on Unix). Returns + true if successful; otherwise returns false. +*/ + +/*! \fn bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) const + \reimp +*/ + +/*! \fn uint QFSFileEngine::ownerId(FileOwner own) const + In Unix, if stat() is successful, the \c uid is returned if + \a own is the owner. Otherwise the \c gid is returned. If stat() + is unsuccessful, -2 is reuturned. + + For Windows, -2 is always returned. +*/ + +/*! \fn QString QFSFileEngine::owner() const + \reimp +*/ + +/*! \fn bool QFSFileEngine::remove() + \reimp +*/ + +/*! \fn bool QFSFileEngine::rename(const QString &newName) + \reimp +*/ + +/*! \fn bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) const + \reimp +*/ + +/*! \fn QString QFSFileEngine::rootPath() + Returns the root path. + + \sa homePath() +*/ + +/*! \fn bool QFSFileEngine::setCurrentPath(const QString &path) + Sets the current path (e.g., for QDir), to \a path. Returns true if the + new path exists; otherwise this function does nothing, and returns false. + + \sa currentPath() +*/ + +/*! \fn bool QFSFileEngine::setPermissions(uint perms) + \reimp +*/ + +/*! \fn bool QFSFileEngine::setSize(qint64 size) + \reimp +*/ + +/*! \fn QString QFSFileEngine::tempPath() + Returns the temporary path (i.e., a path in which it is safe + to store temporary files). +*/ + QT_END_NAMESPACE #endif // QT_NO_FSFILEENGINE diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp index 63506c2..b22d6c7 100644 --- a/src/corelib/io/qfsfileengine_win.cpp +++ b/src/corelib/io/qfsfileengine_win.cpp @@ -946,9 +946,6 @@ bool QFSFileEnginePrivate::nativeIsSequential() const return false; } -/*! - \reimp -*/ bool QFSFileEngine::remove() { Q_D(QFSFileEngine); @@ -959,9 +956,6 @@ bool QFSFileEngine::remove() }); } -/*! - \reimp -*/ bool QFSFileEngine::copy(const QString ©Name) { Q_D(QFSFileEngine); @@ -974,9 +968,6 @@ bool QFSFileEngine::copy(const QString ©Name) }); } -/*! - \reimp -*/ bool QFSFileEngine::rename(const QString &newName) { Q_D(QFSFileEngine); @@ -1017,9 +1008,6 @@ static inline bool mkDir(const QString &path) }); } -/*! - \reimp -*/ static inline bool rmDir(const QString &path) { QT_WA({ @@ -1029,9 +1017,6 @@ static inline bool rmDir(const QString &path) }); } -/*! - \reimp -*/ static inline bool isDirPath(const QString &dirPath, bool *existed) { QString path = dirPath; @@ -1054,9 +1039,6 @@ static inline bool isDirPath(const QString &dirPath, bool *existed) return fileAttrib & FILE_ATTRIBUTE_DIRECTORY; } -/*! - \reimp -*/ bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) const { QString dirName = name; @@ -1097,9 +1079,6 @@ bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) con return mkDir(name); } -/*! - \reimp -*/ bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) const { QString dirName = name; @@ -1120,20 +1099,11 @@ bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) co return rmDir(name); } -/*! - \reimp -*/ bool QFSFileEngine::caseSensitive() const { return false; } -/*! - Sets the current path (e.g., for QDir), to \a path. Returns true if the - new path exists; otherwise this function does nothing, and returns false. - - \sa currentPath() -*/ bool QFSFileEngine::setCurrentPath(const QString &path) { if (!QDir(path).exists()) @@ -1153,16 +1123,6 @@ bool QFSFileEngine::setCurrentPath(const QString &path) #endif } -/*! - Returns the canonicalized form of the current path used by the file - engine for the drive specified by \a fileName. - - On Windows, each drive has its own current directory, so a different - path is returned for file names that include different drive names - (e.g. A: or C:). - - \sa setCurrentPath() -*/ QString QFSFileEngine::currentPath(const QString &fileName) { #if !defined(Q_OS_WINCE) @@ -1219,11 +1179,6 @@ QString QFSFileEngine::currentPath(const QString &fileName) #endif } -/*! - Returns the home path of the current user. - - \sa rootPath() -*/ QString QFSFileEngine::homePath() { QString ret; @@ -1277,11 +1232,6 @@ QString QFSFileEngine::homePath() return QDir::fromNativeSeparators(ret); } -/*! - Returns the root path. - - \sa homePath() -*/ QString QFSFileEngine::rootPath() { #if defined(Q_OS_WINCE) @@ -1299,10 +1249,6 @@ QString QFSFileEngine::rootPath() return ret; } -/*! - Returns the temporary path (i.e., a path in which it is safe to store - temporary files). -*/ QString QFSFileEngine::tempPath() { QString ret; @@ -1330,11 +1276,6 @@ QString QFSFileEngine::tempPath() return ret; } -/*! - Returns the list of drives in the file system as a list of QFileInfo - objects. On unix, Mac OS X and Windows CE, only the root path is returned. - On Windows, this function returns all drives (A:\, C:\, D:\, etc.). -*/ QFileInfoList QFSFileEngine::drives() { QFileInfoList ret; @@ -1556,9 +1497,6 @@ QString QFSFileEnginePrivate::getLink() const return readLink(filePath); } -/*! - \reimp -*/ bool QFSFileEngine::link(const QString &newName) { #if !defined(Q_OS_WINCE) @@ -1816,9 +1754,6 @@ QAbstractFileEngine::FileFlags QFSFileEngine::fileFlags(QAbstractFileEngine::Fil return ret; } -/*! - \reimp -*/ QString QFSFileEngine::fileName(FileName file) const { Q_D(const QFSFileEngine); @@ -1912,9 +1847,6 @@ QString QFSFileEngine::fileName(FileName file) const return d->filePath; } -/*! - \reimp -*/ bool QFSFileEngine::isRelativePath() const { Q_D(const QFSFileEngine); @@ -1924,18 +1856,12 @@ bool QFSFileEngine::isRelativePath() const || (d->filePath.at(0) == QLatin1Char('/') && d->filePath.at(1) == QLatin1Char('/'))))); // drive, e.g. a: } -/*! - \reimp -*/ uint QFSFileEngine::ownerId(FileOwner /*own*/) const { static const uint nobodyID = (uint) -2; return nobodyID; } -/*! - \reimp -*/ QString QFSFileEngine::owner(FileOwner own) const { #if !defined(QT_NO_LIBRARY) @@ -1974,9 +1900,6 @@ QString QFSFileEngine::owner(FileOwner own) const return QString(QLatin1String("")); } -/*! - \reimp -*/ bool QFSFileEngine::setPermissions(uint perms) { Q_D(QFSFileEngine); @@ -2003,9 +1926,6 @@ bool QFSFileEngine::setPermissions(uint perms) return ret; } -/*! - \reimp -*/ bool QFSFileEngine::setSize(qint64 size) { Q_D(QFSFileEngine); @@ -2075,9 +1995,6 @@ static inline QDateTime fileTimeToQDateTime(const FILETIME *time) return ret; } -/*! - \reimp -*/ QDateTime QFSFileEngine::fileTime(FileTime time) const { Q_D(const QFSFileEngine); -- cgit v0.12 From 327d94ce8054718d0ce157604594e470e90d6cb4 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Fri, 22 May 2009 15:14:11 +0200 Subject: Fixes a potential crash when changing system palette with QGtkStyle The problem was that we installed an eventfilter regardless if the gtk symbols were defined or not. Instead we now initialize and check for the symbols before we install the filter. Task-number: 254342 Reviewed-by: ogoffart --- src/gui/styles/qgtkstyle.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index ca71da2..86653df 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -140,10 +140,7 @@ static const char * const dock_widget_restore_xpm[] = class QGtkStyleFilter : public QObject { public: - QGtkStyleFilter() { - qApp->installEventFilter(this); - } - + QGtkStyleFilter() {} private: bool eventFilter(QObject *obj, QEvent *e); }; @@ -167,7 +164,12 @@ class QGtkStylePrivate : public QCleanlooksStylePrivate public: QGtkStylePrivate() : QCleanlooksStylePrivate() - {} + { + QGtk::initGtkWidgets(); + if (QGtk::isThemeAvailable()) + qApp->installEventFilter(&filter); + + } QGtkStyleFilter filter; }; @@ -243,7 +245,6 @@ static QString uniqueName(const QString &key, const QStyleOption *option, const QGtkStyle::QGtkStyle() : QCleanlooksStyle(*new QGtkStylePrivate) { - QGtk::initGtkWidgets(); } /*! -- cgit v0.12 From 93106a55db7bd781cde889425912ebc4a277eb8f Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Wed, 22 Apr 2009 19:03:52 +0200 Subject: Fix syntax of the fcntl system call: this is not setsockopt Reviewed-By: Oswald Buddenhagen --- src/corelib/io/qfsfileengine_unix.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/corelib/io/qfsfileengine_unix.cpp b/src/corelib/io/qfsfileengine_unix.cpp index 18b92e2..459725c 100644 --- a/src/corelib/io/qfsfileengine_unix.cpp +++ b/src/corelib/io/qfsfileengine_unix.cpp @@ -273,9 +273,8 @@ qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len) int oldFlags = fcntl(QT_FILENO(fh), F_GETFL); for (int i = 0; i < 2; ++i) { // Unix: Make the underlying file descriptor non-blocking - int v = 1; if ((oldFlags & O_NONBLOCK) == 0) - fcntl(QT_FILENO(fh), F_SETFL, oldFlags | O_NONBLOCK, &v, sizeof(v)); + fcntl(QT_FILENO(fh), F_SETFL, oldFlags | O_NONBLOCK); // Cross platform stdlib read size_t read = 0; @@ -293,8 +292,7 @@ qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len) // Unix: Restore the blocking state of the underlying socket if ((oldFlags & O_NONBLOCK) == 0) { - int v = 1; - fcntl(QT_FILENO(fh), F_SETFL, oldFlags, &v, sizeof(v)); + fcntl(QT_FILENO(fh), F_SETFL, oldFlags); if (readBytes == 0) { int readByte = 0; do { @@ -311,8 +309,7 @@ qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len) } // Unix: Restore the blocking state of the underlying socket if ((oldFlags & O_NONBLOCK) == 0) { - int v = 1; - fcntl(QT_FILENO(fh), F_SETFL, oldFlags, &v, sizeof(v)); + fcntl(QT_FILENO(fh), F_SETFL, oldFlags); } if (readBytes == 0 && !feof(fh)) { // if we didn't read anything and we're not at EOF, it must be an error -- cgit v0.12 From 049135667302482af66eeaf9a2323d5ee1551132 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 22 May 2009 15:42:31 +0200 Subject: Doc - updating the screenshot Reviewed-By: TrustMe --- doc/src/images/inputdialogs.png | Bin 4244 -> 30369 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/doc/src/images/inputdialogs.png b/doc/src/images/inputdialogs.png index 135c2f6..8bda185 100644 Binary files a/doc/src/images/inputdialogs.png and b/doc/src/images/inputdialogs.png differ -- cgit v0.12 From fc7a43cceba63b79a40183334ab97527483113e3 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Fri, 22 May 2009 16:55:28 +0200 Subject: Fix compilation breakage on Windows caused by 6c1d7e57. On Windows, QT_NO_IPV6 isn't defined, but the necessary includes were missing. So #include winsock2.h and also use our own structures. Reviewed-By: Trust Me --- src/network/socket/qnativesocketengine_p.h | 36 +++++++++++++++++++++---- src/network/socket/qnativesocketengine_unix.cpp | 2 +- src/network/socket/qnativesocketengine_win.cpp | 35 ------------------------ 3 files changed, 32 insertions(+), 41 deletions(-) diff --git a/src/network/socket/qnativesocketengine_p.h b/src/network/socket/qnativesocketengine_p.h index 825c333..eb031d3 100644 --- a/src/network/socket/qnativesocketengine_p.h +++ b/src/network/socket/qnativesocketengine_p.h @@ -56,7 +56,9 @@ #include "QtNetwork/qhostaddress.h" #include "private/qabstractsocketengine_p.h" #ifndef Q_OS_WIN -#include "qplatformdefs.h" +# include "qplatformdefs.h" +#else +# include #endif QT_BEGIN_NAMESPACE @@ -90,13 +92,37 @@ static inline int qt_socket_socket(int domain, int type, int protocol) #endif +// Use our own defines and structs which we know are correct +# define QT_SS_MAXSIZE 128 +# define QT_SS_ALIGNSIZE (sizeof(qint64)) +# define QT_SS_PAD1SIZE (QT_SS_ALIGNSIZE - sizeof (short)) +# define QT_SS_PAD2SIZE (QT_SS_MAXSIZE - (sizeof (short) + QT_SS_PAD1SIZE + QT_SS_ALIGNSIZE)) +struct qt_sockaddr_storage { + short ss_family; + char __ss_pad1[QT_SS_PAD1SIZE]; + qint64 __ss_align; + char __ss_pad2[QT_SS_PAD2SIZE]; +}; + +// sockaddr_in6 size changed between old and new SDK +// Only the new version is the correct one, so always +// use this structure. +struct qt_in6_addr { + quint8 qt_s6_addr[16]; +}; +struct qt_sockaddr_in6 { + short sin6_family; /* AF_INET6 */ + quint16 sin6_port; /* Transport level port number */ + quint32 sin6_flowinfo; /* IPv6 flow information */ + struct qt_in6_addr sin6_addr; /* IPv6 address */ + quint32 sin6_scope_id; /* set of interfaces for a scope */ +}; + union qt_sockaddr { sockaddr a; sockaddr_in a4; -#if !defined(QT_NO_IPV6) - sockaddr_in6 a6; -#endif - sockaddr_storage storage; + qt_sockaddr_in6 a6; + qt_sockaddr_storage storage; }; class QNativeSocketEnginePrivate; diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp index 2b11e8e..75b5a64 100644 --- a/src/network/socket/qnativesocketengine_unix.cpp +++ b/src/network/socket/qnativesocketengine_unix.cpp @@ -119,7 +119,7 @@ static inline void qt_socket_getPortAndAddress(const qt_sockaddr *s, quint16 *po #if !defined(QT_NO_IPV6) if (s->a.sa_family == AF_INET6) { Q_IPV6ADDR tmp; - memcpy(&tmp, &s->a6.sin6_addr.s6_addr, sizeof(tmp)); + memcpy(&tmp, &s->a6.sin6_addr, sizeof(tmp)); if (addr) { QHostAddress tmpAddress; tmpAddress.setAddress(tmp); diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp index d140be2..b08d7b0 100644 --- a/src/network/socket/qnativesocketengine_win.cpp +++ b/src/network/socket/qnativesocketengine_win.cpp @@ -149,41 +149,6 @@ static QByteArray qt_prettyDebug(const char *data, int len, int maxLength) #endif -#if !defined (QT_NO_IPV6) - -// Use our own defines and structs which we know are correct -# define QT_SS_MAXSIZE 128 -# define QT_SS_ALIGNSIZE (sizeof(__int64)) -# define QT_SS_PAD1SIZE (QT_SS_ALIGNSIZE - sizeof (short)) -# define QT_SS_PAD2SIZE (QT_SS_MAXSIZE - (sizeof (short) + QT_SS_PAD1SIZE + QT_SS_ALIGNSIZE)) -struct qt_sockaddr_storage { - short ss_family; - char __ss_pad1[QT_SS_PAD1SIZE]; - __int64 __ss_align; - char __ss_pad2[QT_SS_PAD2SIZE]; -}; - -// sockaddr_in6 size changed between old and new SDK -// Only the new version is the correct one, so always -// use this structure. -struct qt_in6_addr { - u_char qt_s6_addr[16]; -}; -typedef struct { - short sin6_family; /* AF_INET6 */ - u_short sin6_port; /* Transport level port number */ - u_long sin6_flowinfo; /* IPv6 flow information */ - struct qt_in6_addr sin6_addr; /* IPv6 address */ - u_long sin6_scope_id; /* set of interfaces for a scope */ -} qt_sockaddr_in6; - -#else - -typedef void * qt_sockaddr_in6 ; - - -#endif - #ifndef AF_INET6 #define AF_INET6 23 /* Internetwork Version 6 */ #endif -- cgit v0.12 From 701bdcbc8b7751834f6d24844bcb91a23cbdc409 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Fri, 22 May 2009 15:48:23 +0200 Subject: Pressing enter in a QPlainTextEdit embedded on a itemview should insert a newline Do the same special case as for QTextEdit (yes, this is a pitty that we have special cases like that Reviewed-by: Thierry Task-number: 252532 --- src/gui/itemviews/qitemdelegate.cpp | 3 +- src/gui/itemviews/qstyleditemdelegate.cpp | 3 +- tests/auto/qitemdelegate/tst_qitemdelegate.cpp | 78 ++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 2 deletions(-) diff --git a/src/gui/itemviews/qitemdelegate.cpp b/src/gui/itemviews/qitemdelegate.cpp index 3b7eb2d..a748199 100644 --- a/src/gui/itemviews/qitemdelegate.cpp +++ b/src/gui/itemviews/qitemdelegate.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -1194,7 +1195,7 @@ bool QItemDelegate::eventFilter(QObject *object, QEvent *event) case Qt::Key_Enter: case Qt::Key_Return: #ifndef QT_NO_TEXTEDIT - if (qobject_cast(editor)) + if (qobject_cast(editor) || qobject_cast(editor)) return false; // don't filter enter key events for QTextEdit // We want the editor to be able to process the key press // before committing the data (e.g. so it can do diff --git a/src/gui/itemviews/qstyleditemdelegate.cpp b/src/gui/itemviews/qstyleditemdelegate.cpp index be0971b..7f2c8ed 100644 --- a/src/gui/itemviews/qstyleditemdelegate.cpp +++ b/src/gui/itemviews/qstyleditemdelegate.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -646,7 +647,7 @@ bool QStyledItemDelegate::eventFilter(QObject *object, QEvent *event) case Qt::Key_Enter: case Qt::Key_Return: #ifndef QT_NO_TEXTEDIT - if (qobject_cast(editor)) + if (qobject_cast(editor) || qobject_cast(editor)) return false; // don't filter enter key events for QTextEdit // We want the editor to be able to process the key press // before committing the data (e.g. so it can do diff --git a/tests/auto/qitemdelegate/tst_qitemdelegate.cpp b/tests/auto/qitemdelegate/tst_qitemdelegate.cpp index 27741e0..615ac01 100644 --- a/tests/auto/qitemdelegate/tst_qitemdelegate.cpp +++ b/tests/auto/qitemdelegate/tst_qitemdelegate.cpp @@ -59,6 +59,8 @@ #include #include +#include +#include Q_DECLARE_METATYPE(QAbstractItemDelegate::EndEditHint) @@ -226,6 +228,8 @@ private slots: void decoration(); void editorEvent_data(); void editorEvent(); + void enterKey_data(); + void enterKey(); }; @@ -1048,6 +1052,80 @@ void tst_QItemDelegate::editorEvent() QCOMPARE(index.data(Qt::CheckStateRole).toInt(), expectedCheckState); } +void tst_QItemDelegate::enterKey_data() +{ + QTest::addColumn("widget"); + QTest::addColumn("key"); + QTest::addColumn("expectedFocus"); + + QTest::newRow("lineedit enter") << 1 << int(Qt::Key_Enter) << false; + QTest::newRow("textedit enter") << 2 << int(Qt::Key_Enter) << true; + QTest::newRow("plaintextedit enter") << 3 << int(Qt::Key_Enter) << true; + QTest::newRow("plaintextedit return") << 3 << int(Qt::Key_Return) << true; + QTest::newRow("plaintextedit tab") << 3 << int(Qt::Key_Tab) << false; + QTest::newRow("lineedit tab") << 1 << int(Qt::Key_Tab) << false; +} + +void tst_QItemDelegate::enterKey() +{ + QFETCH(int, widget); + QFETCH(int, key); + QFETCH(bool, expectedFocus); + + QStandardItemModel model; + model.appendRow(new QStandardItem()); + + QListView view; + view.setModel(&model); + view.show(); + QApplication::setActiveWindow(&view); + view.setFocus(); + QTest::qWait(30); + + struct TestDelegate : public QItemDelegate + { + int widgetType; + virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/) const + { + QWidget *editor = 0; + switch(widgetType) { + case 1: + editor = new QLineEdit(parent); + break; + case 2: + editor = new QTextEdit(parent); + break; + case 3: + editor = new QPlainTextEdit(parent); + break; + } + editor->setObjectName(QString::fromLatin1("TheEditor")); + return editor; + } + } delegate; + + delegate.widgetType = widget; + + view.setItemDelegate(&delegate); + QModelIndex index = model.index(0, 0); + view.setCurrentIndex(index); // the editor will only selectAll on the current index + view.edit(index); + QTest::qWait(30); + + QList lineEditors = qFindChildren(view.viewport(), QString::fromLatin1("TheEditor")); + QCOMPARE(lineEditors.count(), 1); + + QWidget *editor = lineEditors.at(0); + QCOMPARE(editor->hasFocus(), true); + + QTest::keyClick(editor, Qt::Key(key)); + QApplication::processEvents(); + + QCOMPARE(editor->hasFocus(), expectedFocus); +} + + + // ### _not_ covered: // editing with a custom editor factory -- cgit v0.12 d='n1563' href='#n1563'>1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtScript module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "config.h"
#include "qscriptengine.h"
#include "qscriptsyntaxchecker_p.h"
#include "qnumeric.h"

#include "qscriptengine_p.h"
#include "qscriptengineagent_p.h"
#include "qscriptcontext_p.h"
#include "qscriptstring_p.h"
#include "qscriptvalue_p.h"
#include "qscriptvalueiterator.h"
#include "qscriptclass.h"
#include "qdebug.h"

#include <QtCore/qstringlist.h>
#include <QtCore/qmetaobject.h>

#include "Error.h"
#include "JSArray.h"
#include "JSLock.h"
#include "Interpreter.h"
#include "DateConstructor.h"
#include "RegExpConstructor.h"

#include "PrototypeFunction.h"
#include "InitializeThreading.h"
#include "ObjectPrototype.h"
#include "SourceCode.h"
#include "FunctionPrototype.h"
#include "TimeoutChecker.h"
#include "JSFunction.h"
#include "Parser.h"
#include "Operations.h"

#include "utils/qscriptdate_p.h"
#include "bridge/qscriptfunction_p.h"
#include "bridge/qscriptobject_p.h"
#include "bridge/qscriptclassobject_p.h"
#include "bridge/qscriptvariant_p.h"
#include "bridge/qscriptqobject_p.h"
#include "bridge/qscriptglobalobject_p.h"
#include "bridge/qscriptactivationobject_p.h"

#ifndef QT_NO_QOBJECT
#include <QtCore/qcoreapplication.h>
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qpluginloader.h>
#include <QtCore/qset.h>
#include <QtCore/qtextstream.h>
#include "qscriptextensioninterface.h"
#endif

Q_DECLARE_METATYPE(QScriptValue)
#ifndef QT_NO_QOBJECT
Q_DECLARE_METATYPE(QObjectList)
#endif
Q_DECLARE_METATYPE(QList<int>)

QT_BEGIN_NAMESPACE

/*!
  \since 4.3
  \class QScriptEngine
  \reentrant

  \brief The QScriptEngine class provides an environment for evaluating Qt Script code.

  \ingroup script
  \mainclass

  See the \l{QtScript} documentation for information about the Qt Script language,
  and how to get started with scripting your C++ application.

  \section1 Evaluating Scripts

  Use evaluate() to evaluate script code; this is the C++ equivalent
  of the built-in script function \c{eval()}.

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 0

  evaluate() returns a QScriptValue that holds the result of the
  evaluation. The QScriptValue class provides functions for converting
  the result to various C++ types (e.g. QScriptValue::toString()
  and QScriptValue::toNumber()).

  The following code snippet shows how a script function can be
  defined and then invoked from C++ using QScriptValue::call():

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 1

  As can be seen from the above snippets, a script is provided to the
  engine in the form of a string. One common way of loading scripts is
  by reading the contents of a file and passing it to evaluate():

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 2

  Here we pass the name of the file as the second argument to
  evaluate().  This does not affect evaluation in any way; the second
  argument is a general-purpose string that is used to identify the
  script for debugging purposes (for example, our filename will now
  show up in any uncaughtExceptionBacktrace() involving the script).

  \section1 Engine Configuration

  The globalObject() function returns the \bold {Global Object}
  associated with the script engine. Properties of the Global Object
  are accessible from any script code (i.e. they are global
  variables). Typically, before evaluating "user" scripts, you will
  want to configure a script engine by adding one or more properties
  to the Global Object:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 3

  Adding custom properties to the scripting environment is one of the
  standard means of providing a scripting API that is specific to your
  application. Usually these custom properties are objects created by
  the newQObject() or newObject() functions, or constructor functions
  created by newFunction().

  \section1 Script Exceptions

  evaluate() can throw a script exception (e.g. due to a syntax
  error); in that case, the return value is the value that was thrown
  (typically an \c{Error} object). You can check whether the
  evaluation caused an exception by calling hasUncaughtException(). In
  that case, you can call toString() on the error object to obtain an
  error message. The current uncaught exception is also available
  through uncaughtException(). You can obtain a human-readable
  backtrace of the exception with uncaughtExceptionBacktrace().
  Calling clearExceptions() will cause any uncaught exceptions to be
  cleared.

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 4

  The checkSyntax() function can be used to determine whether code can be
  usefully passed to evaluate().

  \section1 Script Object Creation

  Use newObject() to create a standard Qt Script object; this is the
  C++ equivalent of the script statement \c{new Object()}. You can use
  the object-specific functionality in QScriptValue to manipulate the
  script object (e.g. QScriptValue::setProperty()). Similarly, use
  newArray() to create a Qt Script array object. Use newDate() to
  create a \c{Date} object, and newRegExp() to create a \c{RegExp}
  object.

  \section1 QObject Integration

  Use newQObject() to wrap a QObject (or subclass)
  pointer. newQObject() returns a proxy script object; properties,
  children, and signals and slots of the QObject are available as
  properties of the proxy object. No binding code is needed because it
  is done dynamically using the Qt meta object system.

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 5

  Use qScriptConnect() to connect a C++ signal to a script function;
  this is the Qt Script equivalent of QObject::connect().  When a
  script function is invoked in response to a C++ signal, it can cause
  a script exception; you can connect to the signalHandlerException()
  signal to catch such an exception.

  Use newQMetaObject() to wrap a QMetaObject; this gives you a "script
  representation" of a QObject-based class. newQMetaObject() returns a
  proxy script object; enum values of the class are available as
  properties of the proxy object. You can also specify a function that
  will be used to construct objects of the class (e.g.  when the
  constructor is invoked from a script). For classes that have a
  "standard" Qt constructor, Qt Script can provide a default script
  constructor for you; see scriptValueFromQMetaObject().

  See the \l{QtScript} documentation for more information on
  the QObject integration.

  \section1 Support for Custom C++ Types

  Use newVariant() to wrap a QVariant. This can be used to store
  values of custom (non-QObject) C++ types that have been registered
  with the Qt meta-type system. To make such types scriptable, you
  typically associate a prototype (delegate) object with the C++ type
  by calling setDefaultPrototype(); the prototype object defines the
  scripting API for the C++ type. Unlike the QObject integration,
  there is no automatic binding possible here; i.e. you have to create
  the scripting API yourself, for example by using the QScriptable
  class.

  Use fromScriptValue() to cast from a QScriptValue to another type,
  and toScriptValue() to create a QScriptValue from another value.
  You can specify how the conversion of C++ types is to be performed
  with qScriptRegisterMetaType() and qScriptRegisterSequenceMetaType().
  By default, Qt Script will use QVariant to store values of custom
  types.

  \section1 Importing Extensions

  Use importExtension() to import plugin-based extensions into the
  engine. Call availableExtensions() to obtain a list naming all the
  available extensions, and importedExtensions() to obtain a list
  naming only those extensions that have been imported.

  Call pushContext() to open up a new variable scope, and popContext()
  to close the current scope. This is useful if you are implementing
  an extension that evaluates script code containing temporary
  variable definitions (e.g. \c{var foo = 123;}) that are safe to
  discard when evaluation has completed.

  \section1 Native Functions

  Use newFunction() to wrap native (C++) functions, including
  constructors for your own custom types, so that these can be invoked
  from script code. Such functions must have the signature
  QScriptEngine::FunctionSignature. You may then pass the function as
  argument to newFunction(). Here is an example of a function that
  returns the sum of its first two arguments:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 6

  To expose this function to script code, you can set it as a property
  of the Global Object:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 7

  Once this is done, script code can call your function in the exact
  same manner as a "normal" script function:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 8

  \section1 Long-running Scripts

  If you need to evaluate possibly long-running scripts from the main
  (GUI) thread, you should first call setProcessEventsInterval() to
  make sure that the GUI stays responsive. You can abort a currently
  running script by calling abortEvaluation(). You can determine
  whether an engine is currently running a script by calling
  isEvaluating().

  \section1 Core Debugging/Tracing Facilities

  Since Qt 4.4, you can be notified of events pertaining to script
  execution (e.g. script function calls and statement execution)
  through the QScriptEngineAgent interface; see the setAgent()
  function. This can be used to implement debugging and profiling of a
  QScriptEngine.

  \sa QScriptValue, QScriptContext, QScriptEngineAgent

*/

/*!
    \enum QScriptEngine::ValueOwnership

    This enum specifies the ownership when wrapping a C++ value, e.g. by using newQObject().

    \value QtOwnership The standard Qt ownership rules apply, i.e. the associated object will never be explicitly deleted by the script engine. This is the default. (QObject ownership is explained in \l{Object Trees and Object Ownership}.)
    \value ScriptOwnership The value is owned by the script environment. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value).
    \value AutoOwnership If the associated object has a parent, the Qt ownership rules apply (QtOwnership); otherwise, the object is owned by the script environment (ScriptOwnership).
*/

/*!
    \enum  QScriptEngine::QObjectWrapOption

    These flags specify options when wrapping a QObject pointer with newQObject().

    \value ExcludeChildObjects The script object will not expose child objects as properties.
    \value ExcludeSuperClassMethods The script object will not expose signals and slots inherited from the superclass.
    \value ExcludeSuperClassProperties The script object will not expose properties inherited from the superclass.
    \value ExcludeSuperClassContents Shorthand form for ExcludeSuperClassMethods | ExcludeSuperClassProperties
    \value ExcludeDeleteLater The script object will not expose the QObject::deleteLater() slot.
    \value AutoCreateDynamicProperties Properties that don't already exist in the QObject will be created as dynamic properties of that object, rather than as properties of the script object.
    \value PreferExistingWrapperObject If a wrapper object with the requested configuration already exists, return that object.
    \value SkipMethodsInEnumeration Don't include methods (signals and slots) when enumerating the object's properties.
*/

class QScriptSyntaxCheckResultPrivate
{
public:
    QScriptSyntaxCheckResultPrivate() { ref = 0; }
    ~QScriptSyntaxCheckResultPrivate() {}

    QScriptSyntaxCheckResult::State state;
    int errorColumnNumber;
    int errorLineNumber;
    QString errorMessage;
    QBasicAtomicInt ref;
};

class QScriptTypeInfo
{
public:
    QScriptTypeInfo() : signature(0, '\0'), marshal(0), demarshal(0)
    { }

    QByteArray signature;
    QScriptEngine::MarshalFunction marshal;
    QScriptEngine::DemarshalFunction demarshal;
    JSC::JSValue prototype;
};

namespace QScript
{

struct GlobalClientData : public JSC::JSGlobalData::ClientData
{
    GlobalClientData(QScriptEnginePrivate *e)
        : engine(e) {}
    virtual ~GlobalClientData() {}
    virtual void mark() { engine->mark(); }

    QScriptEnginePrivate *engine;
};

class TimeoutCheckerProxy : public JSC::TimeoutChecker
{
public:
    TimeoutCheckerProxy(const JSC::TimeoutChecker& originalChecker)
        : JSC::TimeoutChecker(originalChecker)
        , m_shouldProcessEvents(false)
        , m_shouldAbortEvaluation(false)
    {}

    void setShouldProcessEvents(bool shouldProcess) { m_shouldProcessEvents = shouldProcess; }
    void setShouldAbort(bool shouldAbort) { m_shouldAbortEvaluation = shouldAbort; }
    bool shouldAbort() { return m_shouldAbortEvaluation; }

    virtual bool didTimeOut(JSC::ExecState* exec)
    {
        if (JSC::TimeoutChecker::didTimeOut(exec))
            return true;

        if (m_shouldProcessEvents)
            QCoreApplication::processEvents();

        return m_shouldAbortEvaluation;
    }

private:
    bool m_shouldProcessEvents;
    bool m_shouldAbortEvaluation;
};

static int toDigit(char c)
{
    if ((c >= '0') && (c <= '9'))
        return c - '0';
    else if ((c >= 'a') && (c <= 'z'))
        return 10 + c - 'a';
    else if ((c >= 'A') && (c <= 'Z'))
        return 10 + c - 'A';
    return -1;
}

qsreal integerFromString(const char *buf, int size, int radix)
{
    if (size == 0)
        return qSNaN();

    qsreal sign = 1.0;
    int i = 0;
    if (buf[0] == '+') {
        ++i;
    } else if (buf[0] == '-') {
        sign = -1.0;
        ++i;
    }

    if (((size-i) >= 2) && (buf[i] == '0')) {
        if (((buf[i+1] == 'x') || (buf[i+1] == 'X'))
            && (radix < 34)) {
            if ((radix != 0) && (radix != 16))
                return 0;
            radix = 16;
            i += 2;
        } else {
            if (radix == 0) {
                radix = 8;
                ++i;
            }
        }
    } else if (radix == 0) {
        radix = 10;
    }

    int j = i;
    for ( ; i < size; ++i) {
        int d = toDigit(buf[i]);
        if ((d == -1) || (d >= radix))
            break;
    }
    qsreal result;
    if (j == i) {
        if (!qstrcmp(buf, "Infinity"))
            result = qInf();
        else
            result = qSNaN();
    } else {
        result = 0;
        qsreal multiplier = 1;
        for (--i ; i >= j; --i, multiplier *= radix)
            result += toDigit(buf[i]) * multiplier;
    }
    result *= sign;
    return result;
}

qsreal integerFromString(const QString &str, int radix)
{
    QByteArray ba = str.trimmed().toUtf8();
    return integerFromString(ba.constData(), ba.size(), radix);
}

QScriptEnginePrivate *scriptEngineFromExec(const JSC::ExecState *exec)
{
    return static_cast<GlobalClientData*>(exec->globalData().clientData)->engine;
}

bool isFunction(const JSC::JSValue &value)
{
    if (!value || !value.isObject())
        return false;
    JSC::CallData callData;
    return (JSC::asObject(value)->getCallData(callData) != JSC::CallTypeNone);
}

static JSC::JSValue JSC_HOST_CALL functionConnect(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);
static JSC::JSValue JSC_HOST_CALL functionDisconnect(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);

JSC::JSValue JSC_HOST_CALL functionDisconnect(JSC::ExecState *exec, JSC::JSObject */*callee*/, JSC::JSValue thisObject, const JSC::ArgList &args)
{
#ifndef QT_NO_QOBJECT
    if (args.size() == 0) {
        return JSC::throwError(exec, JSC::GeneralError, "Function.prototype.disconnect: no arguments given");
    }

    if (!JSC::asObject(thisObject)->inherits(&QScript::QtFunction::info)) {
        return JSC::throwError(exec, JSC::TypeError, "Function.prototype.disconnect: this object is not a signal");
    }

    QScript::QtFunction *qtSignal = static_cast<QScript::QtFunction*>(JSC::asObject(thisObject));

    const QMetaObject *meta = qtSignal->metaObject();
    if (!meta) {
        return JSC::throwError(exec, JSC::TypeError, "Function.prototype.discconnect: cannot disconnect from deleted QObject");
    }

    QMetaMethod sig = meta->method(qtSignal->initialIndex());
    if (sig.methodType() != QMetaMethod::Signal) {
        QString message = QString::fromLatin1("Function.prototype.disconnect: %0::%1 is not a signal")
                          .arg(QLatin1String(qtSignal->metaObject()->className()))
                          .arg(QLatin1String(sig.signature()));
        return JSC::throwError(exec, JSC::TypeError, message);
    }

    QScriptEnginePrivate *engine = scriptEngineFromExec(exec);

    JSC::JSValue receiver;
    JSC::JSValue slot;
    JSC::JSValue arg0 = args.at(0);
    if (args.size() < 2) {
        slot = arg0;
    } else {
        receiver = arg0;
        JSC::JSValue arg1 = args.at(1);
        if (isFunction(arg1))
            slot = arg1;
        else {
            // ### don't go via QScriptValue
            QScriptValue tmp = engine->scriptValueFromJSCValue(arg0);
            QString propertyName(arg1.toString(exec));
            slot = engine->scriptValueToJSCValue(tmp.property(propertyName, QScriptValue::ResolvePrototype));
        }
    }

    if (!isFunction(slot)) {
        return JSC::throwError(exec, JSC::TypeError, "Function.prototype.disconnect: target is not a function");
    }

    bool ok = engine->scriptDisconnect(thisObject, receiver, slot);
    if (!ok) {
        QString message = QString::fromLatin1("Function.prototype.disconnect: failed to disconnect from %0::%1")
                          .arg(QLatin1String(qtSignal->metaObject()->className()))
                          .arg(QLatin1String(sig.signature()));
        return JSC::throwError(exec, JSC::GeneralError, message);
    }
    return JSC::jsUndefined();
#else
    Q_UNUSED(eng);
    return context->throwError(QScriptContext::TypeError,
                               QLatin1String("Function.prototype.disconnect"));
#endif // QT_NO_QOBJECT
}

JSC::JSValue JSC_HOST_CALL functionConnect(JSC::ExecState *exec, JSC::JSObject */*callee*/, JSC::JSValue thisObject, const JSC::ArgList &args)
{
#ifndef QT_NO_QOBJECT
    if (args.size() == 0) {
        return JSC::throwError(exec, JSC::GeneralError,"Function.prototype.connect: no arguments given");
    }

    if (!JSC::asObject(thisObject)->inherits(&QScript::QtFunction::info)) {
        return JSC::throwError(exec, JSC::TypeError, "Function.prototype.connect: this object is not a signal");
    }

    QScript::QtFunction *qtSignal = static_cast<QScript::QtFunction*>(JSC::asObject(thisObject));

    const QMetaObject *meta = qtSignal->metaObject();
    if (!meta) {
        return JSC::throwError(exec, JSC::TypeError, "Function.prototype.connect: cannot connect to deleted QObject");
    }

    QMetaMethod sig = meta->method(qtSignal->initialIndex());
    if (sig.methodType() != QMetaMethod::Signal) {
        QString message = QString::fromLatin1("Function.prototype.connect: %0::%1 is not a signal")
                          .arg(QLatin1String(qtSignal->metaObject()->className()))
                          .arg(QLatin1String(sig.signature()));
        return JSC::throwError(exec, JSC::TypeError, message);
    }

    {
        QList<int> overloads = qtSignal->overloadedIndexes();
        if (!overloads.isEmpty()) {
            overloads.append(qtSignal->initialIndex());
            QByteArray signature = sig.signature();
            QString message = QString::fromLatin1("Function.prototype.connect: ambiguous connect to %0::%1(); candidates are\n")
                              .arg(QLatin1String(qtSignal->metaObject()->className()))
                              .arg(QLatin1String(signature.left(signature.indexOf('('))));
            for (int i = 0; i < overloads.size(); ++i) {
                QMetaMethod mtd = meta->method(overloads.at(i));
                message.append(QString::fromLatin1("    %0\n").arg(QString::fromLatin1(mtd.signature())));
            }
            message.append(QString::fromLatin1("Use e.g. object['%0'].connect() to connect to a particular overload")
                           .arg(QLatin1String(signature)));
            return JSC::throwError(exec, JSC::GeneralError, message);
        }
    }

    QScriptEnginePrivate *engine = scriptEngineFromExec(exec);

    JSC::JSValue receiver;
    JSC::JSValue slot;
    JSC::JSValue arg0 = args.at(0);
    if (args.size() < 2) {
        slot = arg0;
    } else {
        receiver = arg0;
        JSC::JSValue arg1 = args.at(1);
        if (isFunction(arg1))
            slot = arg1;
        else {
            // ### don't go via QScriptValue
            QScriptValue tmp = engine->scriptValueFromJSCValue(arg0);
            QString propertyName = arg1.toString(exec);
            slot = engine->scriptValueToJSCValue(tmp.property(propertyName, QScriptValue::ResolvePrototype));
        }
    }

    if (!isFunction(slot)) {
        return JSC::throwError(exec, JSC::TypeError, "Function.prototype.connect: target is not a function");
    }

    bool ok = engine->scriptConnect(thisObject, receiver, slot, Qt::AutoConnection);
    if (!ok) {
        QString message = QString::fromLatin1("Function.prototype.connect: failed to connect to %0::%1")
                          .arg(QLatin1String(qtSignal->metaObject()->className()))
                          .arg(QLatin1String(sig.signature()));
        return JSC::throwError(exec, JSC::GeneralError, message);
    }
    return JSC::jsUndefined();
#else
    Q_UNUSED(eng);
    Q_UNUSED(classInfo);
    return context->throwError(QScriptContext::TypeError,
                               QLatin1String("Function.prototype.connect"));
#endif // QT_NO_QOBJECT
}

static JSC::JSValue JSC_HOST_CALL functionPrint(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);
static JSC::JSValue JSC_HOST_CALL functionGC(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);
static JSC::JSValue JSC_HOST_CALL functionVersion(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);

JSC::JSValue JSC_HOST_CALL functionPrint(JSC::ExecState* exec, JSC::JSObject*, JSC::JSValue, const JSC::ArgList& args)
{
    QString result;
    for (unsigned i = 0; i < args.size(); ++i) {
        if (i != 0)
            result.append(QLatin1Char(' '));
        QString s(args.at(i).toString(exec));
        if (exec->hadException())
            break;
        result.append(s);
    }
    if (exec->hadException())
        return exec->exception();
    qDebug(qPrintable(result));
    return JSC::jsUndefined();
}

JSC::JSValue JSC_HOST_CALL functionGC(JSC::ExecState* exec, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&)
{
    QScriptEnginePrivate *engine = scriptEngineFromExec(exec);
    engine->collectGarbage();
    return JSC::jsUndefined();
}

JSC::JSValue JSC_HOST_CALL functionVersion(JSC::ExecState *exec, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&)
{
    return JSC::JSValue(exec, 1);
}

static JSC::JSValue JSC_HOST_CALL functionQsTranslate(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);
static JSC::JSValue JSC_HOST_CALL functionQsTranslateNoOp(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);
static JSC::JSValue JSC_HOST_CALL functionQsTr(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);
static JSC::JSValue JSC_HOST_CALL functionQsTrNoOp(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);

JSC::JSValue JSC_HOST_CALL functionQsTranslate(JSC::ExecState *exec, JSC::JSObject*, JSC::JSValue, const JSC::ArgList &args)
{
    if (args.size() < 2)
        return JSC::throwError(exec, JSC::GeneralError, "qsTranslate() requires at least two arguments");
    if (!args.at(0).isString())
        return JSC::throwError(exec, JSC::GeneralError, "qsTranslate(): first argument (context) must be a string");
    if (!args.at(1).isString())
        return JSC::throwError(exec, JSC::GeneralError, "qsTranslate(): second argument (text) must be a string");
    if ((args.size() > 2) && !args.at(2).isString())
        return JSC::throwError(exec, JSC::GeneralError, "qsTranslate(): third argument (comment) must be a string");
    if ((args.size() > 3) && !args.at(3).isString())
        return JSC::throwError(exec, JSC::GeneralError, "qsTranslate(): fourth argument (encoding) must be a string");
    if ((args.size() > 4) && !args.at(4).isNumber())
        return JSC::throwError(exec, JSC::GeneralError, "qsTranslate(): fifth argument (n) must be a number");
#ifndef QT_NO_QOBJECT
    QString context(args.at(0).toString(exec));
#endif
    QString text(args.at(1).toString(exec));
#ifndef QT_NO_QOBJECT
    QString comment;
    if (args.size() > 2)
        comment = args.at(2).toString(exec);
    QCoreApplication::Encoding encoding = QCoreApplication::CodecForTr;
    if (args.size() > 3) {
        QString encStr(args.at(3).toString(exec));
        if (encStr == QLatin1String("CodecForTr"))
            encoding = QCoreApplication::CodecForTr;
        else if (encStr == QLatin1String("UnicodeUTF8"))
            encoding = QCoreApplication::UnicodeUTF8;
        else
            return JSC::throwError(exec, JSC::GeneralError, QString::fromLatin1("qsTranslate(): invalid encoding '%s'").arg(encStr));
    }
    int n = -1;
    if (args.size() > 4)
        n = args.at(4).toInt32(exec);
#endif
    QString result;
#ifndef QT_NO_QOBJECT
    result = QCoreApplication::translate(context.toLatin1().constData(),
                                         text.toLatin1().constData(),
                                         comment.toLatin1().constData(),
                                         encoding, n);
#else
    result = text;
#endif
    return JSC::jsString(exec, result);
}

JSC::JSValue JSC_HOST_CALL functionQsTranslateNoOp(JSC::ExecState *, JSC::JSObject*, JSC::JSValue, const JSC::ArgList &args)
{
    if (args.size() < 2)
        return JSC::jsUndefined();
    return args.at(1);
}

JSC::JSValue JSC_HOST_CALL functionQsTr(JSC::ExecState *exec, JSC::JSObject*, JSC::JSValue, const JSC::ArgList &args)
{
    if (args.size() < 1)
        return JSC::throwError(exec, JSC::GeneralError, "qsTr() requires at least one argument");
    if (!args.at(0).isString())
        return JSC::throwError(exec, JSC::GeneralError, "qsTr(): first argument (text) must be a string");
    if ((args.size() > 1) && !args.at(1).isString())
        return JSC::throwError(exec, JSC::GeneralError, "qsTr(): second argument (comment) must be a string");
    if ((args.size() > 2) && !args.at(2).isNumber())
        return JSC::throwError(exec, JSC::GeneralError, "qsTranslate(): third argument (n) must be a number");
#ifndef QT_NO_QOBJECT
    QString context;
// ### implement context resolution
//    if (ctx->parentContext())
//        context = QFileInfo(ctx->parentContext()->fileName()).baseName();
#endif
    QString text(args.at(0).toString(exec));
#ifndef QT_NO_QOBJECT
    QString comment;
    if (args.size() > 1)
        comment = args.at(1).toString(exec);
    int n = -1;
    if (args.size() > 2)
        n = args.at(2).toInt32(exec);
#endif
    QString result;
#ifndef QT_NO_QOBJECT
    result = QCoreApplication::translate(context.toLatin1().constData(),
                                         text.toLatin1().constData(),
                                         comment.toLatin1().constData(),
                                         QCoreApplication::CodecForTr, n);
#else
    result = text;
#endif
    return JSC::jsString(exec, result);
}

JSC::JSValue JSC_HOST_CALL functionQsTrNoOp(JSC::ExecState *, JSC::JSObject*, JSC::JSValue, const JSC::ArgList &args)
{
    if (args.size() < 1)
        return JSC::jsUndefined();
    return args.at(0);
}

static JSC::JSValue JSC_HOST_CALL stringProtoFuncArg(JSC::ExecState*, JSC::JSObject*, JSC::JSValue, const JSC::ArgList&);

JSC::JSValue JSC_HOST_CALL stringProtoFuncArg(JSC::ExecState *exec, JSC::JSObject*, JSC::JSValue thisObject, const JSC::ArgList &args)
{
    QString value(thisObject.toString(exec));
    JSC::JSValue arg = (args.size() != 0) ? args.at(0) : JSC::jsUndefined();
    QString result;
    if (arg.isString())
        result = value.arg(arg.toString(exec));
    else if (arg.isNumber())
        result = value.arg(arg.toNumber(exec));
    return JSC::jsString(exec, result);
}


#if !defined(QT_NO_QOBJECT) && !defined(QT_NO_LIBRARY)
static QScriptValue __setupPackage__(QScriptContext *ctx, QScriptEngine *eng)
{
    QString path = ctx->argument(0).toString();
    QStringList components = path.split(QLatin1Char('.'));
    QScriptValue o = eng->globalObject();
    for (int i = 0; i < components.count(); ++i) {
        QString name = components.at(i);
        QScriptValue oo = o.property(name);
        if (!oo.isValid()) {
            oo = eng->newObject();
            o.setProperty(name, oo);
        }
        o = oo;
    }
    return o;
}
#endif

} // namespace QScript

QScriptEnginePrivate::QScriptEnginePrivate() : idGenerator(1)
{
    qMetaTypeId<QScriptValue>();

    JSC::initializeThreading(); // ### hmmm

    globalData = JSC::JSGlobalData::create().releaseRef();
    globalData->clientData = new QScript::GlobalClientData(this);
    JSC::JSGlobalObject *globalObject = new (globalData)QScript::GlobalObject();

    JSC::ExecState* exec = globalObject->globalExec();

    scriptObjectStructure = QScriptObject::createStructure(globalObject->objectPrototype());

    qobjectPrototype = new (exec) QScript::QObjectPrototype(exec, QScript::QObjectPrototype::createStructure(globalObject->objectPrototype()), globalObject->prototypeFunctionStructure());
    qobjectWrapperObjectStructure = QScriptObject::createStructure(qobjectPrototype);

    qmetaobjectPrototype = new (exec) QScript::QMetaObjectPrototype(exec, QScript::QMetaObjectPrototype::createStructure(globalObject->objectPrototype()), globalObject->prototypeFunctionStructure());
    qmetaobjectWrapperObjectStructure = QScript::QMetaObjectWrapperObject::createStructure(qmetaobjectPrototype);

    variantPrototype = new (exec) QScript::QVariantPrototype(exec, QScript::QVariantPrototype::createStructure(globalObject->objectPrototype()), globalObject->prototypeFunctionStructure());
    variantWrapperObjectStructure = QScriptObject::createStructure(variantPrototype);

    globalObject->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, globalObject->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "print"), QScript::functionPrint));
    globalObject->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, globalObject->prototypeFunctionStructure(), 0, JSC::Identifier(exec, "gc"), QScript::functionGC));
    globalObject->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, globalObject->prototypeFunctionStructure(), 0, JSC::Identifier(exec, "version"), QScript::functionVersion));

    // ### rather than extending Function.prototype, consider creating a QtSignal.prototype
    globalObject->functionPrototype()->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, globalObject->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "disconnect"), QScript::functionDisconnect));
    globalObject->functionPrototype()->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, globalObject->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "connect"), QScript::functionConnect));

    JSC::TimeoutChecker* originalChecker = globalData->timeoutChecker;
    globalData->timeoutChecker = new QScript::TimeoutCheckerProxy(*originalChecker);
    delete originalChecker;

    currentFrame = exec;

    originalGlobalObjectProxy = 0;
    activeAgent = 0;
    processEventsInterval = -1;
}

QScriptEnginePrivate::~QScriptEnginePrivate()
{
    while (!ownedAgents.isEmpty())
        delete ownedAgents.takeFirst();
    detachAllRegisteredScriptValues();
    qDeleteAll(m_qobjectData);
    qDeleteAll(m_typeInfos);
    JSC::JSLock lock(false);
    globalData->heap.destroy();
    globalData->deref();
}

QScriptValue QScriptEnginePrivate::scriptValueFromJSCValue(JSC::JSValue value)
{
    Q_Q(QScriptEngine);
    if (!value)
        return QScriptValue();

    QScriptValuePrivate *p_value = new QScriptValuePrivate();
    p_value->engine = q;
    p_value->initFrom(value);
    return QScriptValuePrivate::get(p_value);
}

JSC::JSValue QScriptEnginePrivate::scriptValueToJSCValue(const QScriptValue &value)
{
    QScriptValuePrivate *vv = QScriptValuePrivate::get(value);
    if (!vv)
        return JSC::JSValue();
    if (vv->type != QScriptValuePrivate::JSC) {
        Q_Q(QScriptEngine);
        Q_ASSERT(!vv->engine || vv->engine == q);
        vv->engine = q;
        if (vv->type == QScriptValuePrivate::Number) {
            vv->initFrom(JSC::jsNumber(currentFrame, vv->numberValue));
        } else { //QScriptValuePrivate::String
            vv->initFrom(JSC::jsString(currentFrame, vv->stringValue));
        }
    }
    return vv->jscValue;
}

void QScriptEnginePrivate::releaseJSCValue(JSC::JSValue value)
{
// ### Q_ASSERT(!JSC::JSImmediate::isImmediate(value));
    Q_ASSERT(value.isCell());
    JSC::JSCell *cell = value.asCell();
    if (!keepAliveValues.contains(cell))
        qWarning("QScriptEnginePrivate::releaseJSCValue(): cell %p doesn't need releasing", cell);
    if (!keepAliveValues[cell].deref())
        keepAliveValues.remove(cell);
}

QScriptValue QScriptEnginePrivate::scriptValueFromVariant(const QVariant &v)
{
    Q_Q(QScriptEngine);
    QScriptValue result = q->create(v.userType(), v.data());
    Q_ASSERT(result.isValid());
    return result;
}

QVariant QScriptEnginePrivate::scriptValueToVariant(const QScriptValue &value, int targetType)
{
    QVariant v(targetType, (void *)0);
    if (QScriptEnginePrivate::convert(value, targetType, v.data(), this))
        return v;
    if (uint(targetType) == QVariant::LastType)
        return value.toVariant();
    if (value.isVariant()) {
        v = value.toVariant();
        if (v.canConvert(QVariant::Type(targetType))) {
            v.convert(QVariant::Type(targetType));
            return v;
        }
        QByteArray typeName = v.typeName();
        if (typeName.endsWith('*')
            && (QMetaType::type(typeName.left(typeName.size()-1)) == targetType)) {
            return QVariant(targetType, *reinterpret_cast<void* *>(v.data()));
        }
    }

    return QVariant();
}

JSC::JSValue QScriptEnginePrivate::jscValueFromVariant(const QVariant &v)
{
    // ### it's inefficient to convert to QScriptValue and then to JSValue
    QScriptValue vv = scriptValueFromVariant(v);
    QScriptValuePrivate *p = QScriptValuePrivate::get(vv);
    switch (p->type) {
    case QScriptValuePrivate::JSC:
        return p->jscValue;
    case QScriptValuePrivate::Number:
        return JSC::jsNumber(currentFrame, p->numberValue);
    case QScriptValuePrivate::String: {
        JSC::UString str = p->stringValue;
        return JSC::jsString(currentFrame, str);
      }
    }
    return JSC::JSValue();
}

QVariant QScriptEnginePrivate::jscValueToVariant(JSC::JSValue value, int targetType)
{
    // ### it's inefficient to convert to QScriptValue and then to QVariant
    return scriptValueToVariant(scriptValueFromJSCValue(value), targetType);
}

QScriptValue QScriptEnginePrivate::arrayFromStringList(const QStringList &lst)
{
    Q_Q(QScriptEngine);
    QScriptValue arr = q->newArray(lst.size());
    for (int i = 0; i < lst.size(); ++i)
        arr.setProperty(i, QScriptValue(q, lst.at(i)));
    return arr;
}

QStringList QScriptEnginePrivate::stringListFromArray(const QScriptValue &arr)
{
    QStringList lst;
    uint len = arr.property(QLatin1String("length")).toUInt32();
    for (uint i = 0; i < len; ++i)
        lst.append(arr.property(i).toString());
    return lst;
}

QScriptValue QScriptEnginePrivate::arrayFromVariantList(const QVariantList &lst)
{
    Q_Q(QScriptEngine);
    QScriptValue arr = q->newArray(lst.size());
    for (int i = 0; i < lst.size(); ++i)
        arr.setProperty(i, scriptValueFromVariant(lst.at(i)));
    return arr;
}

QVariantList QScriptEnginePrivate::variantListFromArray(const QScriptValue &arr)
{
    QVariantList lst;
    uint len = arr.property(QLatin1String("length")).toUInt32();
    for (uint i = 0; i < len; ++i)
        lst.append(arr.property(i).toVariant());
    return lst;
}

QScriptValue QScriptEnginePrivate::objectFromVariantMap(const QVariantMap &vmap)
{
    Q_Q(QScriptEngine);
    QScriptValue obj = q->newObject();
    QVariantMap::const_iterator it;
    for (it = vmap.constBegin(); it != vmap.constEnd(); ++it)
        obj.setProperty(it.key(), scriptValueFromVariant(it.value()));
    return obj;
}

QVariantMap QScriptEnginePrivate::variantMapFromObject(const QScriptValue &obj)
{
    QVariantMap vmap;
    QScriptValueIterator it(obj);
    while (it.hasNext()) {
        it.next();
        vmap.insert(it.name(), it.value().toVariant());
    }
    return vmap;
}

JSC::JSValue QScriptEnginePrivate::defaultPrototype(int metaTypeId) const
{
    QScriptTypeInfo *info = m_typeInfos.value(metaTypeId);
    if (!info)
        return JSC::JSValue();
    return info->prototype;
}

void QScriptEnginePrivate::setDefaultPrototype(int metaTypeId, JSC::JSValue prototype)
{
    QScriptTypeInfo *info = m_typeInfos.value(metaTypeId);
    if (!info) {
        info = new QScriptTypeInfo();
        m_typeInfos.insert(metaTypeId, info);
    }
    info->prototype = prototype;
}

QScriptContext *QScriptEnginePrivate::contextForFrame(JSC::ExecState *frame)
{
    return reinterpret_cast<QScriptContext *>(frame);
}

JSC::ExecState *QScriptEnginePrivate::frameForContext(QScriptContext *context)
{
    return reinterpret_cast<JSC::ExecState*>(context);
}

const JSC::ExecState *QScriptEnginePrivate::frameForContext(const QScriptContext *context)
{
    return reinterpret_cast<const JSC::ExecState*>(context);
}

JSC::JSGlobalObject *QScriptEnginePrivate::originalGlobalObject() const
{
    return globalData->head;
}

JSC::JSObject *QScriptEnginePrivate::customGlobalObject() const
{
    QScript::GlobalObject *glob = static_cast<QScript::GlobalObject*>(originalGlobalObject());
    return glob->customGlobalObject;
}

JSC::JSObject *QScriptEnginePrivate::getOriginalGlobalObjectProxy()
{
    if (!originalGlobalObjectProxy) {
        JSC::ExecState* exec = currentFrame;
        originalGlobalObjectProxy = new (exec)QScript::OriginalGlobalObjectProxy(scriptObjectStructure, originalGlobalObject());
    }
    return originalGlobalObjectProxy;
}

JSC::JSObject *QScriptEnginePrivate::globalObject() const
{
    QScript::GlobalObject *glob = static_cast<QScript::GlobalObject*>(originalGlobalObject());
    if (glob->customGlobalObject)
        return glob->customGlobalObject;
    return glob;
}

void QScriptEnginePrivate::setGlobalObject(JSC::JSObject *object)
{
    if (object == globalObject())
        return;
    QScript::GlobalObject *glob = static_cast<QScript::GlobalObject*>(originalGlobalObject());
    if (object == originalGlobalObjectProxy)
        glob->customGlobalObject = 0;
    else {
        Q_ASSERT(object != originalGlobalObject());
        glob->customGlobalObject = object;
    }
}

JSC::ExecState *QScriptEnginePrivate::globalExec() const
{
    return originalGlobalObject()->globalExec();
}

/*!
  \internal

  If the given \a value is the original global object, returns the custom
  global object or a proxy to the original global object; otherwise returns \a
  value.
*/
JSC::JSValue QScriptEnginePrivate::toUsableValue(JSC::JSValue value)
{
    if (!value || !value.isObject() || !JSC::asObject(value)->isGlobalObject())
        return value;
    Q_ASSERT(JSC::asObject(value) == originalGlobalObject());
    if (customGlobalObject())
        return customGlobalObject();
    if (!originalGlobalObjectProxy)
        originalGlobalObjectProxy = new (currentFrame)QScript::OriginalGlobalObjectProxy(scriptObjectStructure, originalGlobalObject());
    return originalGlobalObjectProxy;
}
/*!
    \internal
    Return the 'this' value for a given context
    The result may be null for the global context
*/
JSC::JSValue QScriptEnginePrivate::thisForContext(JSC::ExecState *frame)
{
    if (frame->codeBlock() != 0) {
        return frame->thisValue();
    } else {
        JSC::Register* thisRegister = frame->registers() - JSC::RegisterFile::CallFrameHeaderSize - frame->argumentCount();
        return thisRegister->jsValue();
    }
}

/*! \internal
     For native context, we use the ReturnValueRegister entry in the stackframe header to store flags.
     We can do that because this header is not used as the native function return their value thought C++

     when setting flags, NativeContext should always be set

     contextFlags returns 0 for non native context
 */
uint QScriptEnginePrivate::contextFlags(JSC::ExecState *exec)
{
    if (exec->codeBlock())
        return 0; //js function doesn't have flags

    return exec->returnValueRegister();
}

void QScriptEnginePrivate::setContextFlags(JSC::ExecState *exec, uint flags)
{
    Q_ASSERT(!exec->codeBlock());
    quintptr flag_ptr = flags;
    exec->registers()[JSC::RegisterFile::ReturnValueRegister] = JSC::JSValue(reinterpret_cast<JSC::JSObject*>(flag_ptr));
}


void QScriptEnginePrivate::mark()
{
    if (!originalGlobalObject()->marked())
        originalGlobalObject()->mark();
    if (!globalObject()->marked())
        globalObject()->mark();
    if (originalGlobalObjectProxy && !originalGlobalObjectProxy->marked())
        originalGlobalObjectProxy->mark();

    if (qobjectPrototype && !qobjectPrototype->marked())
        qobjectPrototype->mark();
    if (qmetaobjectPrototype && !qmetaobjectPrototype->marked())
        qmetaobjectPrototype->mark();
    if (variantPrototype && !variantPrototype->marked())
        variantPrototype->mark();

    {
        QHash<JSC::JSCell*,QBasicAtomicInt>::const_iterator it;
        for (it = keepAliveValues.constBegin(); it != keepAliveValues.constEnd(); ++it) {
            JSC::JSCell *cell = it.key();
            if (!cell->marked())
                cell->mark();
        }
    }

#ifndef QT_NO_QOBJECT
    {
        QHash<QObject*, QScript::QObjectData*>::const_iterator it;
        for (it = m_qobjectData.constBegin(); it != m_qobjectData.constEnd(); ++it) {
            QScript::QObjectData *qdata = it.value();
            qdata->mark();
        }
    }
#endif

    {
        QHash<int, QScriptTypeInfo*>::const_iterator it;
        for (it = m_typeInfos.constBegin(); it != m_typeInfos.constEnd(); ++it) {
            if ((*it)->prototype && !(*it)->prototype.marked())
                (*it)->prototype.mark();
        }
    }
}

bool QScriptEnginePrivate::isCollecting() const
{
    return globalData->heap.isBusy();
}

void QScriptEnginePrivate::collectGarbage()
{
    JSC::JSLock lock(false);
    globalData->heap.collect();
}

QScript::TimeoutCheckerProxy *QScriptEnginePrivate::timeoutChecker() const
{
    return static_cast<QScript::TimeoutCheckerProxy*>(globalData->timeoutChecker);
}

void QScriptEnginePrivate::agentDeleted(QScriptEngineAgent *agent)
{
    ownedAgents.removeOne(agent);
    if (activeAgent == agent) {
        QScriptEngineAgentPrivate::get(agent)->detach();
        activeAgent = 0;
    }
}

#ifndef QT_NO_QOBJECT

JSC::JSValue QScriptEnginePrivate::newQObject(
    QObject *object, QScriptEngine::ValueOwnership ownership,
    const QScriptEngine::QObjectWrapOptions &options)
{
    if (!object)
        return JSC::jsNull();
    JSC::ExecState* exec = currentFrame;
    QScript::QObjectData *data = qobjectData(object);
    bool preferExisting = (options & QScriptEngine::PreferExistingWrapperObject) != 0;
    QScriptEngine::QObjectWrapOptions opt = options & ~QScriptEngine::PreferExistingWrapperObject;
    QScriptObject *result = 0;
    if (preferExisting)
        result = data->findWrapper(ownership, opt);
    if (!result) {
        result = new (exec) QScriptObject(qobjectWrapperObjectStructure);
        if (preferExisting)
            data->registerWrapper(result, ownership, opt);
    }
    Q_ASSERT(result != 0);
    result->setDelegate(new QScript::QObjectDelegate(object, ownership, options));
    /*if (setDefaultPrototype)*/ {
        const QMetaObject *meta = object->metaObject();
        while (meta) {
            QByteArray typeString = meta->className();
            typeString.append('*');
            int typeId = QMetaType::type(typeString);
            if (typeId != 0) {
                JSC::JSValue proto = defaultPrototype(typeId);
                if (proto) {
                    result->setPrototype(proto);
                    break;
                }
            }
            meta = meta->superClass();
        }
    }
    return result;
}

JSC::JSValue QScriptEnginePrivate::newQMetaObject(
    const QMetaObject *metaObject, JSC::JSValue ctor)
{
    if (!metaObject)
        return JSC::jsNull();
    JSC::ExecState* exec = currentFrame;
    QScript::QMetaObjectWrapperObject *result = new (exec) QScript::QMetaObjectWrapperObject(exec, metaObject, ctor, qmetaobjectWrapperObjectStructure);
    return result;
}

bool QScriptEnginePrivate::convertToNativeQObject(const QScriptValue &value,
                                                  const QByteArray &targetType,
                                                  void **result)
{
    if (!targetType.endsWith('*'))
        return false;
    if (QObject *qobject = value.toQObject()) {
        int start = targetType.startsWith("const ") ? 6 : 0;
        QByteArray className = targetType.mid(start, targetType.size()-start-1);
        if (void *instance = qobject->qt_metacast(className)) {
            *result = instance;
            return true;
        }
    }
    return false;
}

QScript::QObjectData *QScriptEnginePrivate::qobjectData(QObject *object)
{
    QHash<QObject*, QScript::QObjectData*>::const_iterator it;
    it = m_qobjectData.constFind(object);
    if (it != m_qobjectData.constEnd())
        return it.value();

    QScript::QObjectData *data = new QScript::QObjectData(this);
    m_qobjectData.insert(object, data);
    QObject::connect(object, SIGNAL(destroyed(QObject*)),
                     q_func(), SLOT(_q_objectDestroyed(QObject *)));
    return data;
}

void QScriptEnginePrivate::_q_objectDestroyed(QObject *object)
{
    QHash<QObject*, QScript::QObjectData*>::iterator it;
    it = m_qobjectData.find(object);
    Q_ASSERT(it != m_qobjectData.end());
    QScript::QObjectData *data = it.value();
    m_qobjectData.erase(it);
    delete data;
}

void QScriptEnginePrivate::disposeQObject(QObject *object)
{
    // TODO
/*    if (isCollecting()) {
        // wait until we're done with GC before deleting it
        int index = m_qobjectsToBeDeleted.indexOf(object);
        if (index == -1)
            m_qobjectsToBeDeleted.append(object);
            } else*/ {
        delete object;
    }
}

void QScriptEnginePrivate::emitSignalHandlerException()
{
    Q_Q(QScriptEngine);
    emit q->signalHandlerException(q->uncaughtException());
}

bool QScriptEnginePrivate::scriptConnect(QObject *sender, const char *signal,
                                         JSC::JSValue receiver, JSC::JSValue function,
                                         Qt::ConnectionType type)
{
    Q_ASSERT(sender);
    Q_ASSERT(signal);
    const QMetaObject *meta = sender->metaObject();
    int index = meta->indexOfSignal(QMetaObject::normalizedSignature(signal+1));
    if (index == -1)
        return false;
    return scriptConnect(sender, index, receiver, function, /*wrapper=*/JSC::JSValue(), type);
}

bool QScriptEnginePrivate::scriptDisconnect(QObject *sender, const char *signal,
                                            JSC::JSValue receiver, JSC::JSValue function)
{
    Q_ASSERT(sender);
    Q_ASSERT(signal);
    const QMetaObject *meta = sender->metaObject();
    int index = meta->indexOfSignal(QMetaObject::normalizedSignature(signal+1));
    if (index == -1)
        return false;
    return scriptDisconnect(sender, index, receiver, function);
}

bool QScriptEnginePrivate::scriptConnect(QObject *sender, int signalIndex,
                                         JSC::JSValue receiver, JSC::JSValue function,
                                         JSC::JSValue senderWrapper,
                                         Qt::ConnectionType type)
{
    QScript::QObjectData *data = qobjectData(sender);
    return data->addSignalHandler(sender, signalIndex, receiver, function, senderWrapper, type);
}

bool QScriptEnginePrivate::scriptDisconnect(QObject *sender, int signalIndex,
                                            JSC::JSValue receiver, JSC::JSValue function)
{
    QScript::QObjectData *data = qobjectData(sender);
    if (!data)
        return false;
    return data->removeSignalHandler(sender, signalIndex, receiver, function);
}

bool QScriptEnginePrivate::scriptConnect(JSC::JSValue signal, JSC::JSValue receiver,
                                         JSC::JSValue function, Qt::ConnectionType type)
{
    QScript::QtFunction *fun = static_cast<QScript::QtFunction*>(JSC::asObject(signal));
    int index = fun->mostGeneralMethod();
    return scriptConnect(fun->qobject(), index, receiver, function, fun->wrapperObject(), type);
}

bool QScriptEnginePrivate::scriptDisconnect(JSC::JSValue signal, JSC::JSValue receiver,
                                            JSC::JSValue function)
{
    QScript::QtFunction *fun = static_cast<QScript::QtFunction*>(JSC::asObject(signal));
    int index = fun->mostGeneralMethod();
    return scriptDisconnect(fun->qobject(), index, receiver, function);
}

#endif
void QScriptEnginePrivate::registerScriptValue(QScriptValuePrivate *value)
{
    value->id=idGenerator.fetchAndAddRelaxed(1);
    attachedScriptValues.insert(value);
}

void QScriptEnginePrivate::detachAllRegisteredScriptValues()
{
    //make copy of attachedScriptValues (orignal set will be modified)
    QSet<QScriptValuePrivate*> tmpSet(attachedScriptValues);
    QSet<QScriptValuePrivate*>::const_iterator i = tmpSet.begin();
    while (i != tmpSet.end()) {
        //this will autmagicly remove *i from attachedScriptValues
        (*i)->detachEngine();
        i++;
    }
}

#ifdef QT_NO_QOBJECT

QScriptEngine::QScriptEngine()
    : d_ptr(new QScriptEnginePrivate)
{
    d_ptr->q_ptr = this;
}

/*! \internal
*/
QScriptEngine::QScriptEngine(QScriptEnginePrivate &dd)
    : d_ptr(&dd)
{
    d_ptr->q_ptr = this;
}
#else

/*!
    Constructs a QScriptEngine object.

    The globalObject() is initialized to have properties as described in
    \l{ECMA-262}, Section 15.1.
*/
QScriptEngine::QScriptEngine()
    : QObject(*new QScriptEnginePrivate, 0)
{
}

/*!
    Constructs a QScriptEngine object with the given \a parent.

    The globalObject() is initialized to have properties as described in
    \l{ECMA-262}, Section 15.1.
*/

QScriptEngine::QScriptEngine(QObject *parent)
    : QObject(*new QScriptEnginePrivate, parent)
{
}

/*! \internal
*/
QScriptEngine::QScriptEngine(QScriptEnginePrivate &dd, QObject *parent)
    : QObject(dd, parent)
{
}
#endif

/*!
  Destroys this QScriptEngine.
*/
QScriptEngine::~QScriptEngine()
{
#ifdef QT_NO_QOBJECT
    delete d_ptr;
    d_ptr = 0;
#endif
}

/*!
  Returns this engine's Global Object.

  By default, the Global Object contains the built-in objects that are
  part of \l{ECMA-262}, such as Math, Date and String. Additionally,
  you can set properties of the Global Object to make your own
  extensions available to all script code. Non-local variables in
  script code will be created as properties of the Global Object, as
  well as local variables in global code.
*/
QScriptValue QScriptEngine::globalObject() const
{
    Q_D(const QScriptEngine);
    JSC::JSObject *result = d->globalObject();
    return const_cast<QScriptEnginePrivate*>(d)->scriptValueFromJSCValue(result);
}

/*!
  \since 4.5

  Sets this engine's Global Object to be the given \a object.
  If \a object is not a valid script object, this function does
  nothing.

  When setting a custom global object, you may want to use
  QScriptValueIterator to copy the properties of the standard Global
  Object; alternatively, you can set the internal prototype of your
  custom object to be the original Global Object.
*/
void QScriptEngine::setGlobalObject(const QScriptValue &object)
{
    Q_D(QScriptEngine);
    if (!object.isObject())
        return;
    JSC::JSObject *jscObject = JSC::asObject(d->scriptValueToJSCValue(object));
    d->setGlobalObject(jscObject);
}

/*!
  Returns a QScriptValue of the primitive type Null.

  \sa undefinedValue()
*/
QScriptValue QScriptEngine::nullValue()
{
    Q_D(QScriptEngine);
    return d->scriptValueFromJSCValue(JSC::jsNull());
}

/*!
  Returns a QScriptValue of the primitive type Undefined.

  \sa nullValue()
*/
QScriptValue QScriptEngine::undefinedValue()
{
    Q_D(QScriptEngine);
    return d->scriptValueFromJSCValue(JSC::jsUndefined());
}

/*!
  Creates a constructor function from \a fun, with the given \a length.
  The \c{prototype} property of the resulting function is set to be the
  given \a prototype. The \c{constructor} property of \a prototype is
  set to be the resulting function.

  When a function is called as a constructor (e.g. \c{new Foo()}), the
  `this' object associated with the function call is the new object
  that the function is expected to initialize; the prototype of this
  default constructed object will be the function's public
  \c{prototype} property. If you always want the function to behave as
  a constructor (e.g. \c{Foo()} should also create a new object), or
  if you need to create your own object rather than using the default
  `this' object, you should make sure that the prototype of your
  object is set correctly; either by setting it manually, or, when
  wrapping a custom type, by having registered the defaultPrototype()
  of that type. Example:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 9

  To wrap a custom type and provide a constructor for it, you'd typically
  do something like this:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 10
*/
QScriptValue QScriptEngine::newFunction(QScriptEngine::FunctionSignature fun,
                                        const QScriptValue &prototype,
                                        int length)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue function = new (exec)QScript::FunctionWrapper(exec, length, JSC::Identifier(exec, ""), fun);
    QScriptValue result = d->scriptValueFromJSCValue(function);
    result.setProperty(QLatin1String("prototype"), prototype, QScriptValue::Undeletable);
    const_cast<QScriptValue&>(prototype)
        .setProperty(QLatin1String("constructor"), result,
                     QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
    return result;
}

#ifndef QT_NO_REGEXP
/*!
  Creates a QtScript object of class RegExp with the given
  \a regexp.

  \sa QScriptValue::toRegExp()
*/
QScriptValue QScriptEngine::newRegExp(const QRegExp &regexp)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue buf[2];
    JSC::ArgList args(buf, sizeof(buf));

    //convert the pattern to a ECMAScript pattern
    extern QString qt_regexp_toCanonical(const QString &, QRegExp::PatternSyntax);
    QString pattern = qt_regexp_toCanonical(regexp.pattern(), regexp.patternSyntax());
    if (regexp.isMinimal()) {
        QString ecmaPattern;
        int len = pattern.length();
        ecmaPattern.reserve(len);
        int i = 0;
        const QChar *wc = pattern.unicode();
        bool inBracket = false;
        while (i < len) {
            QChar c = wc[i++];
            ecmaPattern += c;
            switch (c.unicode()) {
            case '?':
            case '+':
            case '*':
            case '}':
                if (!inBracket)
                    ecmaPattern += QLatin1Char('?');
                break;
            case '\\':
                if (i < len)
                    ecmaPattern += wc[i++];
                break;
            case '[':
                inBracket = true;
                break;
            case ']':
                inBracket = false;
                break;
            default:
                break;
            }
        }
        pattern = ecmaPattern;
    }

    JSC::UString jscPattern = pattern;
    QString flags;
    if (regexp.caseSensitivity() == Qt::CaseInsensitive)
        flags.append(QLatin1Char('i'));
    JSC::UString jscFlags = flags;
    buf[0] = JSC::jsString(exec, jscPattern);
    buf[1] = JSC::jsString(exec, jscFlags);
    JSC::JSObject* result = JSC::constructRegExp(exec, args);
    return d->scriptValueFromJSCValue(result);
}

#endif // QT_NO_REGEXP

/*!
  Creates a QtScript object holding the given variant \a value.

  If a default prototype has been registered with the meta type id of
  \a value, then the prototype of the created object will be that
  prototype; otherwise, the prototype will be the Object prototype
  object.

  \sa setDefaultPrototype(), QScriptValue::toVariant()
*/
QScriptValue QScriptEngine::newVariant(const QVariant &value)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    QScriptObject *obj = new (exec) QScriptObject(d->variantWrapperObjectStructure);
    obj->setDelegate(new QScript::QVariantDelegate(value));
    QScriptValue result = d->scriptValueFromJSCValue(obj);
    QScriptValue proto = defaultPrototype(value.userType());
    if (proto.isValid())
        result.setPrototype(proto);
    return result;
}

/*!
  \since 4.4
  \overload

  Initializes the given Qt Script \a object to hold the given variant
  \a value, and returns the \a object.

  This function enables you to "promote" a plain Qt Script object
  (created by the newObject() function) to a variant, or to replace
  the variant contained inside an object previously created by the
  newVariant() function.

  The prototype() of the \a object will remain unchanged.

  If \a object is not an object, this function behaves like the normal
  newVariant(), i.e. it creates a new script object and returns it.

  This function is useful when you want to provide a script
  constructor for a C++ type. If your constructor is invoked in a
  \c{new} expression (QScriptContext::isCalledAsConstructor() returns
  true), you can pass QScriptContext::thisObject() (the default
  constructed script object) to this function to initialize the new
  object.
*/
QScriptValue QScriptEngine::newVariant(const QScriptValue &object,
                                       const QVariant &value)
{
    if (!object.isObject())
        return newVariant(value);
    JSC::JSObject *jscObject = JSC::asObject(QScriptValuePrivate::get(object)->jscValue);
    if (!jscObject->isObject(&QScriptObject::info)) {
        qWarning("QScriptEngine::newVariant(): changing class of non-QScriptObject not supported");
        return QScriptValue();
    }
    QScriptObject *jscScriptObject = static_cast<QScriptObject*>(jscObject);
    if (!object.isVariant()) {
        delete jscScriptObject->delegate();
        jscScriptObject->setDelegate(new QScript::QVariantDelegate(value));
    } else {
        QScriptValuePrivate::get(object)->setVariantValue(value);
    }
    return object;
}

#ifndef QT_NO_QOBJECT
/*!
  Creates a QtScript object that wraps the given QObject \a
  object, using the given \a ownership. The given \a options control
  various aspects of the interaction with the resulting script object.

  Signals and slots, properties and children of \a object are
  available as properties of the created QScriptValue. For more
  information, see the \l{QtScript} documentation.

  If \a object is a null pointer, this function returns nullValue().

  If a default prototype has been registered for the \a object's class
  (or its superclass, recursively), the prototype of the new script
  object will be set to be that default prototype.

  If the given \a object is deleted outside of QtScript's control, any
  attempt to access the deleted QObject's members through the QtScript
  wrapper object (either by script code or C++) will result in a
  script exception.

  \sa QScriptValue::toQObject()
*/
QScriptValue QScriptEngine::newQObject(QObject *object, ValueOwnership ownership,
                                       const QObjectWrapOptions &options)
{
    Q_D(QScriptEngine);
    JSC::JSValue jscQObject = d->newQObject(object, ownership, options);
    return d->scriptValueFromJSCValue(jscQObject);
}

/*!
  \since 4.4
  \overload

  Initializes the given \a scriptObject to hold the given \a qtObject,
  and returns the \a scriptObject.

  This function enables you to "promote" a plain Qt Script object
  (created by the newObject() function) to a QObject proxy, or to
  replace the QObject contained inside an object previously created by
  the newQObject() function.

  The prototype() of the \a scriptObject will remain unchanged.

  If \a scriptObject is not an object, this function behaves like the
  normal newQObject(), i.e. it creates a new script object and returns
  it.

  This function is useful when you want to provide a script
  constructor for a QObject-based class. If your constructor is
  invoked in a \c{new} expression
  (QScriptContext::isCalledAsConstructor() returns true), you can pass
  QScriptContext::thisObject() (the default constructed script object)
  to this function to initialize the new object.
*/
QScriptValue QScriptEngine::newQObject(const QScriptValue &scriptObject,
                                       QObject *qtObject,
                                       ValueOwnership ownership,
                                       const QObjectWrapOptions &options)
{
    if (!scriptObject.isObject())
        return newQObject(qtObject, ownership, options);
    JSC::JSObject *jscObject = JSC::asObject(QScriptValuePrivate::get(scriptObject)->jscValue);
    if (!jscObject->isObject(&QScriptObject::info)) {
        qWarning("QScriptEngine::newQObject(): changing class of non-QScriptObject not supported");
        return QScriptValue();
    }
    QScriptObject *jscScriptObject = static_cast<QScriptObject*>(jscObject);
    if (!scriptObject.isQObject()) {
        delete jscScriptObject->delegate();
        jscScriptObject->setDelegate(new QScript::QObjectDelegate(qtObject, ownership, options));
    } else {
        QScript::QObjectDelegate *delegate = static_cast<QScript::QObjectDelegate*>(jscScriptObject->delegate());
        delegate->setValue(qtObject);
        delegate->setOwnership(ownership);
        delegate->setOptions(options);
    }
    return scriptObject;
}

#endif // QT_NO_QOBJECT

/*!
  Creates a QtScript object of class Object.

  The prototype of the created object will be the Object
  prototype object.

  \sa newArray(), QScriptValue::setProperty()
*/
QScriptValue QScriptEngine::newObject()
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSObject *result = new (exec)QScriptObject(d->scriptObjectStructure);
    return d->scriptValueFromJSCValue(result);
}

/*!
  \since 4.4
  \overload

  Creates a QtScript Object of the given class, \a scriptClass.

  The prototype of the created object will be the Object
  prototype object.

  \a data, if specified, is set as the internal data of the
  new object (using QScriptValue::setData()).

  \sa QScriptValue::scriptClass()
*/
QScriptValue QScriptEngine::newObject(QScriptClass *scriptClass,
                                      const QScriptValue &data)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    QScriptObject *result = new (exec) QScriptObject(d->scriptObjectStructure);
    result->setDelegate(new QScript::ClassObjectDelegate(scriptClass));
    QScriptValue scriptObject = d->scriptValueFromJSCValue(result);
    scriptObject.setData(data);
    QScriptValue proto = scriptClass->prototype();
    if (proto.isValid())
        scriptObject.setPrototype(proto);
    return scriptObject;
}

/*!
  \internal
*/
QScriptValue QScriptEngine::newActivationObject()
{
    qWarning("QScriptEngine::newActivationObject() not implemented");
    // ### JSActivation or JSVariableObject?
    return QScriptValue();
}

/*!
  Creates a QScriptValue that wraps a native (C++) function. \a fun
  must be a C++ function with signature QScriptEngine::FunctionSignature.  \a
  length is the number of arguments that \a fun expects; this becomes
  the \c{length} property of the created QScriptValue.

  Note that \a length only gives an indication of the number of
  arguments that the function expects; an actual invocation of a
  function can include any number of arguments. You can check the
  \l{QScriptContext::argumentCount()}{argumentCount()} of the
  QScriptContext associated with the invocation to determine the
  actual number of arguments passed.

  A \c{prototype} property is automatically created for the resulting
  function object, to provide for the possibility that the function
  will be used as a constructor.

  By combining newFunction() and the property flags
  QScriptValue::PropertyGetter and QScriptValue::PropertySetter, you
  can create script object properties that behave like normal
  properties in script code, but are in fact accessed through
  functions (analogous to how properties work in \l{Qt's Property
  System}). Example:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 11

  When the property \c{foo} of the script object is subsequently
  accessed in script code, \c{getSetFoo()} will be invoked to handle
  the access.  In this particular case, we chose to store the "real"
  value of \c{foo} as a property of the accessor function itself; you
  are of course free to do whatever you like in this function.

  In the above example, a single native function was used to handle
  both reads and writes to the property; the argument count is used to
  determine if we are handling a read or write. You can also use two
  separate functions; just specify the relevant flag
  (QScriptValue::PropertyGetter or QScriptValue::PropertySetter) when
  setting the property, e.g.:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 12

  \sa QScriptValue::call()
*/
QScriptValue QScriptEngine::newFunction(QScriptEngine::FunctionSignature fun, int length)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue function = new (exec)QScript::FunctionWrapper(exec, length, JSC::Identifier(exec, ""), fun);
    QScriptValue result = d->scriptValueFromJSCValue(function);
    QScriptValue proto = newObject();
    result.setProperty(QLatin1String("prototype"), proto, QScriptValue::Undeletable);
    proto.setProperty(QLatin1String("constructor"), result,
                      QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
    return result;
}

/*!
  \internal
  \since 4.4
*/
QScriptValue QScriptEngine::newFunction(QScriptEngine::FunctionWithArgSignature fun, void *arg)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue function = new (exec)QScript::FunctionWithArgWrapper(exec, /*length=*/0, JSC::Identifier(exec, ""), fun, arg);
    QScriptValue result = d->scriptValueFromJSCValue(function);
    QScriptValue proto = newObject();
    result.setProperty(QLatin1String("prototype"), proto, QScriptValue::Undeletable);
    proto.setProperty(QLatin1String("constructor"), result,
                      QScriptValue::Undeletable | QScriptValue::SkipInEnumeration);
    return result;
}

/*!
  Creates a QtScript object of class Array with the given \a length.

  \sa newObject()
*/
QScriptValue QScriptEngine::newArray(uint length)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSArray* result = JSC::constructEmptyArray(exec, length);
    return d->scriptValueFromJSCValue(result);
}

/*!
  Creates a QtScript object of class RegExp with the given
  \a pattern and \a flags.

  The legal flags are 'g' (global), 'i' (ignore case), and 'm'
  (multiline).
*/
QScriptValue QScriptEngine::newRegExp(const QString &pattern, const QString &flags)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue buf[2];
    JSC::ArgList args(buf, sizeof(buf));
    JSC::UString jscPattern = pattern;
    QString strippedFlags;
    if (flags.contains(QLatin1Char('i')))
        strippedFlags += QLatin1Char('i');
    if (flags.contains(QLatin1Char('m')))
        strippedFlags += QLatin1Char('m');
    if (flags.contains(QLatin1Char('g')))
        strippedFlags += QLatin1Char('g');
    JSC::UString jscFlags = strippedFlags;
    buf[0] = JSC::jsString(exec, jscPattern);
    buf[1] = JSC::jsString(exec, jscFlags);
    JSC::JSObject* result = JSC::constructRegExp(exec, args);
    return d->scriptValueFromJSCValue(result);
}

/*!
  Creates a QtScript object of class Date with the given
  \a value (the number of milliseconds since 01 January 1970,
  UTC).
*/
QScriptValue QScriptEngine::newDate(qsreal value)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue val = JSC::jsNumber(exec, value);
    JSC::ArgList args(&val, 1);
    JSC::JSObject *result = JSC::constructDate(exec, args);
    return d->scriptValueFromJSCValue(result);
}

/*!
  Creates a QtScript object of class Date from the given \a value.

  \sa QScriptValue::toDateTime()
*/
QScriptValue QScriptEngine::newDate(const QDateTime &value)
{
    return newDate(QScript::FromDateTime(value));
}

#ifndef QT_NO_QOBJECT
/*!
  Creates a QtScript object that represents a QObject class, using the
  the given \a metaObject and constructor \a ctor.

  Enums of \a metaObject (declared with Q_ENUMS) are available as
  properties of the created QScriptValue. When the class is called as
  a function, \a ctor will be called to create a new instance of the
  class.

  Example:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 27

  \sa newQObject(), scriptValueFromQMetaObject()
*/
QScriptValue QScriptEngine::newQMetaObject(
    const QMetaObject *metaObject, const QScriptValue &ctor)
{
    Q_D(QScriptEngine);
    JSC::JSValue jscCtor = d->scriptValueToJSCValue(ctor);
    JSC::JSValue jscQMetaObject = d->newQMetaObject(metaObject, jscCtor);
    return d->scriptValueFromJSCValue(jscQMetaObject);
}

/*!
  \fn QScriptValue QScriptEngine::scriptValueFromQMetaObject()

  Creates a QScriptValue that represents the Qt class \c{T}.

  This function is used in combination with one of the
  Q_SCRIPT_DECLARE_QMETAOBJECT() macro. Example:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 13

  \warning This function is not available with MSVC 6. Use
  qScriptValueFromQMetaObject() instead if you need to support that version
  of the compiler.

  \sa QScriptEngine::newQMetaObject()
*/

/*!
  \fn QScriptValue qScriptValueFromQMetaObject(QScriptEngine *engine)
  \since 4.3
  \relates QScriptEngine

  Uses \a engine to create a QScriptValue that represents the Qt class
  \c{T}.

  This function is equivalent to
  QScriptEngine::scriptValueFromQMetaObject(). It is provided as a
  work-around for MSVC 6, which doesn't support member template
  functions.

  \sa QScriptEngine::newQMetaObject()
*/
#endif // QT_NO_QOBJECT

/*!
  \obsolete

  Returns true if \a program can be evaluated; i.e. the code is
  sufficient to determine whether it appears to be a syntactically
  correct program, or contains a syntax error.

  This function returns false if \a program is incomplete; i.e. the
  input is syntactically correct up to the point where the input is
  terminated.

  Note that this function only does a static check of \a program;
  e.g. it does not check whether references to variables are
  valid, and so on.

  A typical usage of canEvaluate() is to implement an interactive
  interpreter for QtScript. The user is repeatedly queried for
  individual lines of code; the lines are concatened internally, and
  only when canEvaluate() returns true for the resulting program is it
  passed to evaluate().

  The following are some examples to illustrate the behavior of
  canEvaluate(). (Note that all example inputs are assumed to have an
  explicit newline as their last character, since otherwise the
  QtScript parser would automatically insert a semi-colon character at
  the end of the input, and this could cause canEvaluate() to produce
  different results.)

  Given the input
  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 14
  canEvaluate() will return true, since the program appears to be complete.

  Given the input
  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 15
  canEvaluate() will return false, since the if-statement is not complete,
  but is syntactically correct so far.

  Given the input
  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 16
  canEvaluate() will return true, but evaluate() will throw a
  SyntaxError given the same input.

  Given the input
  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 17
  canEvaluate() will return true, even though the code is clearly not
  syntactically valid QtScript code. evaluate() will throw a
  SyntaxError when this code is evaluated.

  Given the input
  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 18
  canEvaluate() will return true, but evaluate() will throw a
  ReferenceError if \c{foo} is not defined in the script
  environment.

  \sa evaluate(), checkSyntax()
*/
bool QScriptEngine::canEvaluate(const QString &program) const
{
    return QScriptEnginePrivate::canEvaluate(program);
}


bool QScriptEnginePrivate::canEvaluate(const QString &program)
{
    QScript::SyntaxChecker checker;
    QScript::SyntaxChecker::Result result = checker.checkSyntax(program);
    return (result.state != QScript::SyntaxChecker::Intermediate);
}

/*!
  \since 4.5

  Checks the syntax of the given \a program. Returns a
  QScriptSyntaxCheckResult object that contains the result of the check.
*/
QScriptSyntaxCheckResult QScriptEngine::checkSyntax(const QString &program)
{
    return QScriptEnginePrivate::checkSyntax(program);
}

QScriptSyntaxCheckResult QScriptEnginePrivate::checkSyntax(const QString &program)
{
    QScript::SyntaxChecker checker;
    QScript::SyntaxChecker::Result result = checker.checkSyntax(program);
    QScriptSyntaxCheckResultPrivate *p = new QScriptSyntaxCheckResultPrivate();
    switch (result.state) {
    case QScript::SyntaxChecker::Error:
        p->state = QScriptSyntaxCheckResult::Error;
        break;
    case QScript::SyntaxChecker::Intermediate:
        p->state = QScriptSyntaxCheckResult::Intermediate;
        break;
    case QScript::SyntaxChecker::Valid:
        p->state = QScriptSyntaxCheckResult::Valid;
        break;
    }
    p->errorLineNumber = result.errorLineNumber;
    p->errorColumnNumber = result.errorColumnNumber;
    p->errorMessage = result.errorMessage;
    return QScriptSyntaxCheckResult(p);
}



/*!
  Evaluates \a program, using \a lineNumber as the base line number,
  and returns the result of the evaluation.

  The script code will be evaluated in the current context.

  The evaluation of \a program can cause an exception in the
  engine; in this case the return value will be the exception
  that was thrown (typically an \c{Error} object). You can call
  hasUncaughtException() to determine if an exception occurred in
  the last call to evaluate().

  \a lineNumber is used to specify a starting line number for \a
  program; line number information reported by the engine that pertain
  to this evaluation (e.g. uncaughtExceptionLineNumber()) will be
  based on this argument. For example, if \a program consists of two
  lines of code, and the statement on the second line causes a script
  exception, uncaughtExceptionLineNumber() would return the given \a
  lineNumber plus one. When no starting line number is specified, line
  numbers will be 1-based.

  \a fileName is used for error reporting. For example in error objects
  the file name is accessible through the "fileName" property if it's
  provided with this function.

  \sa canEvaluate(), hasUncaughtException(), isEvaluating(), abortEvaluation()
*/
QScriptValue QScriptEngine::evaluate(const QString &program, const QString &fileName, int lineNumber)
{
    Q_D(QScriptEngine);

    JSC::JSLock lock(false); // ### hmmm
    currentContext()->activationObject(); //force the creation of a context for native function;

    JSC::UString jscProgram = program;
    JSC::UString jscFileName = fileName;
    JSC::ExecState* exec = d->currentFrame;
    JSC::SourceCode source = JSC::makeSource(jscProgram, jscFileName, lineNumber);

    intptr_t sourceId = source.provider()->asID();
    JSC::Debugger* debugger = d->originalGlobalObject()->debugger();
    exec->globalData().scriptpool->startEvaluating(source);
    if (debugger)
        debugger->evaluateStart(sourceId);

    exec->clearException();
    JSC::DynamicGlobalObjectScope dynamicGlobalObjectScope(exec, exec->scopeChain()->globalObject());

    int errorLine;
    JSC::UString errorMessage;
    WTF::RefPtr<JSC::EvalNode> evalNode = exec->globalData().parser->parse<JSC::EvalNode>(exec, exec->dynamicGlobalObject()->debugger(), source, &errorLine, &errorMessage);
    if (!evalNode) {
        JSC::JSValue exceptionValue = JSC::Error::create(exec, JSC::SyntaxError, errorMessage, errorLine, source.provider()->asID(), 0);
        exec->setException(exceptionValue);

        if (debugger) {
            debugger->exceptionThrow(JSC::DebuggerCallFrame(exec, exceptionValue), sourceId, false);
            debugger->evaluateStop(exceptionValue, sourceId);
        }
        exec->globalData().scriptpool->stopEvaluating(source);

        return d->scriptValueFromJSCValue(exceptionValue);
    }

    JSC::JSValue thisValue = d->thisForContext(exec);
    JSC::JSObject* thisObject = (!thisValue || thisValue.isUndefinedOrNull()) ? exec->dynamicGlobalObject() : thisValue.toObject(exec);
    JSC::JSValue exceptionValue;
    d->timeoutChecker()->setShouldAbort(false);
    JSC::JSValue result = exec->interpreter()->execute(evalNode.get(), exec, thisObject, exec->scopeChain(), &exceptionValue);

    if (d->timeoutChecker()->shouldAbort()) {
        if (d->abortResult.isError())
            exec->setException(d->scriptValueToJSCValue(d->abortResult));

        if (debugger)
            debugger->evaluateStop(d->scriptValueToJSCValue(d->abortResult), sourceId);
        exec->globalData().scriptpool->stopEvaluating(source);

        return d->abortResult;
    }

    if (exceptionValue) {
        exec->setException(exceptionValue);

        if (debugger)
            debugger->evaluateStop(exceptionValue, sourceId);
        exec->globalData().scriptpool->stopEvaluating(source);

        return d->scriptValueFromJSCValue(exceptionValue);
    }

    if (debugger)
        debugger->evaluateStop(result, sourceId);
    exec->globalData().scriptpool->stopEvaluating(source);

    Q_ASSERT(!exec->hadException());
    return d->scriptValueFromJSCValue(result);
}


/*!
  Returns the current context.

  The current context is typically accessed to retrieve the arguments
  and `this' object in native functions; for convenience, it is
  available as the first argument in QScriptEngine::FunctionSignature.
*/
QScriptContext *QScriptEngine::currentContext() const
{
    Q_D(const QScriptEngine);
    return const_cast<QScriptEnginePrivate*>(d)->contextForFrame(d->currentFrame);
}

/*!
  Enters a new execution context and returns the associated
  QScriptContext object.

  Once you are done with the context, you should call popContext() to
  restore the old context.

  By default, the `this' object of the new context is the Global Object.
  The context's \l{QScriptContext::callee()}{callee}() will be invalid.

  This function is useful when you want to evaluate script code
  as if it were the body of a function. You can use the context's
  \l{QScriptContext::activationObject()}{activationObject}() to initialize
  local variables that will be available to scripts. Example:

  \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 19

  In the above example, the new variable "tmp" defined in the script
  will be local to the context; in other words, the script doesn't
  have any effect on the global environment.

  Returns 0 in case of stack overflow

  \sa popContext()
*/
QScriptContext *QScriptEngine::pushContext()
{
    Q_D(QScriptEngine);

    JSC::CallFrame* newFrame = d->pushContext(d->currentFrame, d->currentFrame->globalData().dynamicGlobalObject,
                                              JSC::ArgList(), /*callee = */0);

    if (agent())
        agent()->contextPush();

    return d->contextForFrame(newFrame);
}

/*! \internal
   push a context for a native function.
   JSC native function doesn't have different stackframe or context. so we need to create one.

   use popContext right after to go back to the previous context the context if no stack overflow has hapenned

   exec is the current top frame.

   return the new top frame. (might be the same as exec if a new stackframe was not needed) or 0 if stack overflow
*/
JSC::CallFrame *QScriptEnginePrivate::pushContext(JSC::CallFrame *exec, const JSC::JSValue &_thisObject,
                                                  const JSC::ArgList& args, JSC::JSObject *callee, bool calledAsConstructor)
{
    JSC::JSValue thisObject = _thisObject;
    if (calledAsConstructor) {
        //JSC doesn't create default created object for native functions. so we do it
        JSC::JSValue prototype = callee->get(exec, exec->propertyNames().prototype);
        JSC::Structure *structure = prototype.isObject() ? JSC::asObject(prototype)->inheritorID()
                                                         : originalGlobalObject()->emptyObjectStructure();
        thisObject = new (exec) QScriptObject(structure);
    }

    int flags = NativeContext;
    if (calledAsConstructor)
        flags |= CalledAsConstructorContext;

    JSC::CallFrame *newCallFrame = exec;
    if (callee == 0 || !(exec->callee() == callee && exec->returnPC() != 0)) {
        //We need to check if the Interpreter might have already created a frame for function called from JS.
        JSC::Interpreter *interp = exec->interpreter();
        JSC::Register *oldEnd = interp->registerFile().end();
        int argc = args.size() + 1; //add "this"
        JSC::Register *newEnd = oldEnd + argc + JSC::RegisterFile::CallFrameHeaderSize;
        if (!interp->registerFile().grow(newEnd))
            return 0; //### Stack overflow
        newCallFrame = JSC::CallFrame::create(oldEnd);
        newCallFrame[0] = thisObject;
        int dst = 0;
        JSC::ArgList::const_iterator it;
        for (it = args.begin(); it != args.end(); ++it)
            newCallFrame[++dst] = *it;
        newCallFrame += argc + JSC::RegisterFile::CallFrameHeaderSize;
        newCallFrame->init(0, /*vPC=*/0, exec->scopeChain(), exec, flags, argc, callee);
    } else {
        setContextFlags(newCallFrame, flags);
        if (calledAsConstructor) {
            //update the new created this
            JSC::Register* thisRegister = newCallFrame->registers() - JSC::RegisterFile::CallFrameHeaderSize - newCallFrame->argumentCount();
            *thisRegister = thisObject;
        }
    }
    currentFrame = newCallFrame;
    return newCallFrame;
}


/*!
  Pops the current execution context and restores the previous one.
  This function must be used in conjunction with pushContext().

  \sa pushContext()
*/
void QScriptEngine::popContext()
{
    if (agent())
        agent()->contextPop();
    Q_D(QScriptEngine);
    if (d->currentFrame->returnPC() != 0 || d->currentFrame->codeBlock() != 0
        || !currentContext()->parentContext()) {
        qWarning("QScriptEngine::popContext() doesn't match with pushContext()");
        return;
    }

    d->popContext();
}

/*! \internal
    counter part of QScriptEnginePrivate::pushContext
 */
void QScriptEnginePrivate::popContext()
{
    bool hasScope = contextFlags(currentFrame) & HasScopeContext;
    if (currentFrame->returnPC() == 0) { //normal case
        JSC::RegisterFile &registerFile = currentFrame->interpreter()->registerFile();
        JSC::Register *const newEnd = currentFrame->registers() - JSC::RegisterFile::CallFrameHeaderSize - currentFrame->argumentCount();
        if (hasScope)
            currentFrame->scopeChain()->pop()->deref();
        currentFrame = currentFrame->callerFrame();
        registerFile.shrink(newEnd);
    } else if(hasScope) { //the stack frame was created by the Interpreter, we don't need to rewind it.
        currentFrame->setScopeChain(currentFrame->scopeChain()->pop());
        currentFrame->scopeChain()->deref();
    }
}

/*!
  Returns true if the last script evaluation resulted in an uncaught
  exception; otherwise returns false.

  The exception state is cleared when evaluate() is called.

  \sa uncaughtException(), uncaughtExceptionLineNumber(),
      uncaughtExceptionBacktrace()
*/
bool QScriptEngine::hasUncaughtException() const
{
    Q_D(const QScriptEngine);
    JSC::ExecState* exec = d->globalExec();
    return exec->hadException();
}

/*!
  Returns the current uncaught exception, or an invalid QScriptValue
  if there is no uncaught exception.

  The exception value is typically an \c{Error} object; in that case,
  you can call toString() on the return value to obtain an error
  message.

  \sa hasUncaughtException(), uncaughtExceptionLineNumber(),
      uncaughtExceptionBacktrace()
*/
QScriptValue QScriptEngine::uncaughtException() const
{
    Q_D(const QScriptEngine);
    JSC::ExecState* exec = d->globalExec();
    return const_cast<QScriptEnginePrivate*>(d)->scriptValueFromJSCValue(exec->exception());
}

/*!
  Returns the line number where the last uncaught exception occurred.

  Line numbers are 1-based, unless a different base was specified as
  the second argument to evaluate().

  \sa hasUncaughtException(), uncaughtExceptionBacktrace()
*/
int QScriptEngine::uncaughtExceptionLineNumber() const
{
    if (!hasUncaughtException())
        return -1;
    return uncaughtException().property(QLatin1String("lineNumber")).toInt32();
}

/*!
  Returns a human-readable backtrace of the last uncaught exception.

  Each line is of the form \c{<function-name>(<arguments>)@<file-name>:<line-number>}.

  \sa uncaughtException()
*/
QStringList QScriptEngine::uncaughtExceptionBacktrace() const
{
    if (!hasUncaughtException())
        return QStringList();
// ### currently no way to get a full backtrace from JSC without installing a
// debugger that reimplements exception() and store the backtrace there.
    QScriptValue value = uncaughtException();
    if (!value.isError())
        return QStringList();
    QStringList result;
    result.append(QString::fromLatin1("<anonymous>()@%0:%1")
                  .arg(value.property(QLatin1String("fileName")).toString())
                  .arg(value.property(QLatin1String("lineNumber")).toInt32()));
    return result;
}

/*!
  \since 4.4

  Clears any uncaught exceptions in this engine.

  \sa hasUncaughtException()
*/
void QScriptEngine::clearExceptions()
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    exec->clearException();
}

/*!
  Returns the default prototype associated with the given \a metaTypeId,
  or an invalid QScriptValue if no default prototype has been set.

  \sa setDefaultPrototype()
*/
QScriptValue QScriptEngine::defaultPrototype(int metaTypeId) const
{
    Q_D(const QScriptEngine);
    return const_cast<QScriptEnginePrivate*>(d)->scriptValueFromJSCValue(d->defaultPrototype(metaTypeId));
}

/*!
  Sets the default prototype of the C++ type identified by the given
  \a metaTypeId to \a prototype.

  The default prototype provides a script interface for values of
  type \a metaTypeId when a value of that type is accessed from script
  code.  Whenever the script engine (implicitly or explicitly) creates
  a QScriptValue from a value of type \a metaTypeId, the default
  prototype will be set as the QScriptValue's prototype.

  The \a prototype object itself may be constructed using one of two
  principal techniques; the simplest is to subclass QScriptable, which
  enables you to define the scripting API of the type through QObject
  properties and slots.  Another possibility is to create a script
  object by calling newObject(), and populate the object with the
  desired properties (e.g. native functions wrapped with
  newFunction()).

  \sa defaultPrototype(), qScriptRegisterMetaType(), QScriptable, {Default Prototypes Example}
*/
void QScriptEngine::setDefaultPrototype(int metaTypeId, const QScriptValue &prototype)
{
    Q_D(QScriptEngine);
    d->setDefaultPrototype(metaTypeId, d->scriptValueToJSCValue(prototype));
}

/*!
  \typedef QScriptEngine::FunctionSignature
  \relates QScriptEngine

  The function signature \c{QScriptValue f(QScriptContext *, QScriptEngine *)}.

  A function with such a signature can be passed to
  QScriptEngine::newFunction() to wrap the function.
*/

/*!
  \typedef QScriptEngine::FunctionWithArgSignature
  \relates QScriptEngine

  The function signature \c{QScriptValue f(QScriptContext *, QScriptEngine *, void *)}.

  A function with such a signature can be passed to
  QScriptEngine::newFunction() to wrap the function.
*/

/*!
    \typedef QScriptEngine::MarshalFunction
    \internal
*/

/*!
    \typedef QScriptEngine::DemarshalFunction
    \internal
*/

/*!
    \internal
*/
QScriptValue QScriptEngine::create(int type, const void *ptr)
{
    Q_D(QScriptEngine);
    return d->create(type, ptr);
}

QScriptValue QScriptEnginePrivate::create(int type, const void *ptr)
{
    Q_ASSERT(ptr != 0);
    QScriptValue result;
    QScriptTypeInfo *info = m_typeInfos.value(type);
    if (info && info->marshal) {
        result = info->marshal(q_func(), ptr);
    } else {
        // check if it's one of the types we know
        switch (QMetaType::Type(type)) {
        case QMetaType::Void:
            result = QScriptValue(QScriptValue::UndefinedValue);
            break;
        case QMetaType::Bool:
            result = QScriptValue(*reinterpret_cast<const bool*>(ptr));
            break;
        case QMetaType::Int:
            result = QScriptValue(*reinterpret_cast<const int*>(ptr));
            break;
        case QMetaType::UInt:
            result = QScriptValue(*reinterpret_cast<const uint*>(ptr));
            break;
        case QMetaType::LongLong:
            result = QScriptValue(qsreal(*reinterpret_cast<const qlonglong*>(ptr)));
            break;
        case QMetaType::ULongLong:
#if defined(Q_OS_WIN) && defined(_MSC_FULL_VER) && _MSC_FULL_VER <= 12008804
#pragma message("** NOTE: You need the Visual Studio Processor Pack to compile support for 64bit unsigned integers.")
            result = QScriptValue(qsreal((qlonglong)*reinterpret_cast<const qulonglong*>(ptr)));
#elif defined(Q_CC_MSVC) && !defined(Q_CC_MSVC_NET)
            result = QScriptValue(qsreal((qlonglong)*reinterpret_cast<const qulonglong*>(ptr)));
#else
            result = QScriptValue(qsreal(*reinterpret_cast<const qulonglong*>(ptr)));
#endif
            break;
        case QMetaType::Double:
            result = QScriptValue(*reinterpret_cast<const double*>(ptr));
            break;
        case QMetaType::QString:
            result = QScriptValue(q_func(), *reinterpret_cast<const QString*>(ptr));
            break;
        case QMetaType::Float:
            result = QScriptValue(*reinterpret_cast<const float*>(ptr));
            break;
        case QMetaType::Short:
            result = QScriptValue(*reinterpret_cast<const short*>(ptr));
            break;
        case QMetaType::UShort:
            result = QScriptValue(*reinterpret_cast<const unsigned short*>(ptr));
            break;
        case QMetaType::Char:
            result = QScriptValue(*reinterpret_cast<const char*>(ptr));
            break;
        case QMetaType::UChar:
            result = QScriptValue(*reinterpret_cast<const unsigned char*>(ptr));
            break;
        case QMetaType::QChar:
            result = QScriptValue((*reinterpret_cast<const QChar*>(ptr)).unicode());
            break;
        case QMetaType::QStringList:
            result = arrayFromStringList(*reinterpret_cast<const QStringList *>(ptr));
            break;
        case QMetaType::QVariantList:
            result = arrayFromVariantList(*reinterpret_cast<const QVariantList *>(ptr));
            break;
        case QMetaType::QVariantMap:
            result = objectFromVariantMap(*reinterpret_cast<const QVariantMap *>(ptr));
            break;
        case QMetaType::QDateTime:
            result = q_func()->newDate(*reinterpret_cast<const QDateTime *>(ptr));
            break;
        case QMetaType::QDate:
            result = q_func()->newDate(QDateTime(*reinterpret_cast<const QDate *>(ptr)));
            break;
#ifndef QT_NO_REGEXP
        case QMetaType::QRegExp:
            result = q_func()->newRegExp(*reinterpret_cast<const QRegExp *>(ptr));
            break;
#endif
#ifndef QT_NO_QOBJECT
        case QMetaType::QObjectStar:
        case QMetaType::QWidgetStar:
            result = q_func()->newQObject(*reinterpret_cast<QObject* const *>(ptr));
            break;
#endif
        default:
            if (type == qMetaTypeId<QScriptValue>()) {
                result = *reinterpret_cast<const QScriptValue*>(ptr);
                if (!result.isValid())
                    result = QScriptValue(QScriptValue::UndefinedValue);
            }

#ifndef QT_NO_QOBJECT
            // lazy registration of some common list types
            else if (type == qMetaTypeId<QObjectList>()) {
                qScriptRegisterSequenceMetaType<QObjectList>(q_func());
                return create(type, ptr);
            }
#endif
            else if (type == qMetaTypeId<QList<int> >()) {
                qScriptRegisterSequenceMetaType<QList<int> >(q_func());
                return create(type, ptr);
            }

            else {
                QByteArray typeName = QMetaType::typeName(type);
                if (typeName == "QVariant")
                    result = scriptValueFromVariant(*reinterpret_cast<const QVariant*>(ptr));
                if (typeName.endsWith('*') && !*reinterpret_cast<void* const *>(ptr))
                    result = QScriptValue(QScriptValue::NullValue);
                else
                    result = q_func()->newVariant(QVariant(type, ptr));
            }
        }
    }
    if (result.isObject() && info && info->prototype
        && JSC::JSValue::strictEqual(scriptValueToJSCValue(result.prototype()), originalGlobalObject()->objectPrototype())) {
        result.setPrototype(scriptValueFromJSCValue(info->prototype));
    }
    return result;
}

bool QScriptEnginePrivate::convert(const QScriptValue &value,
                                   int type, void *ptr,
                                   QScriptEnginePrivate *eng)
{
    if (!eng && value.engine())
        eng = QScriptEnginePrivate::get(value.engine());
    if (eng) {
        QScriptTypeInfo *info = eng->m_typeInfos.value(type);
        if (info && info->demarshal) {
            info->demarshal(value, ptr);
            return true;
        }
    }

    // check if it's one of the types we know
    switch (QMetaType::Type(type)) {
    case QMetaType::Bool:
        *reinterpret_cast<bool*>(ptr) = value.toBoolean();
        return true;
    case QMetaType::Int:
        *reinterpret_cast<int*>(ptr) = value.toInt32();
        return true;
    case QMetaType::UInt:
        *reinterpret_cast<uint*>(ptr) = value.toUInt32();
        return true;
    case QMetaType::LongLong:
        *reinterpret_cast<qlonglong*>(ptr) = qlonglong(value.toInteger());
        return true;
    case QMetaType::ULongLong:
        *reinterpret_cast<qulonglong*>(ptr) = qulonglong(value.toInteger());
        return true;
    case QMetaType::Double:
        *reinterpret_cast<double*>(ptr) = value.toNumber();
        return true;
    case QMetaType::QString:
        if (value.isUndefined() || value.isNull())
            *reinterpret_cast<QString*>(ptr) = QString();
        else
            *reinterpret_cast<QString*>(ptr) = value.toString();
        return true;
    case QMetaType::Float:
        *reinterpret_cast<float*>(ptr) = value.toNumber();
        return true;
    case QMetaType::Short:
        *reinterpret_cast<short*>(ptr) = short(value.toInt32());
        return true;
    case QMetaType::UShort:
        *reinterpret_cast<unsigned short*>(ptr) = value.toUInt16();
        return true;
    case QMetaType::Char:
        *reinterpret_cast<char*>(ptr) = char(value.toInt32());
        return true;
    case QMetaType::UChar:
        *reinterpret_cast<unsigned char*>(ptr) = (unsigned char)(value.toInt32());
        return true;
    case QMetaType::QChar:
        if (value.isString()) {
            QString str = value.toString();
            *reinterpret_cast<QChar*>(ptr) = str.isEmpty() ? QChar() : str.at(0);
        } else {
            *reinterpret_cast<QChar*>(ptr) = QChar(value.toUInt16());
        }
        return true;
    case QMetaType::QDateTime:
        if (value.isDate()) {
            *reinterpret_cast<QDateTime *>(ptr) = value.toDateTime();
            return true;
        } break;
    case QMetaType::QDate:
        if (value.isDate()) {
            *reinterpret_cast<QDate *>(ptr) = value.toDateTime().date();
            return true;
        } break;
#ifndef QT_NO_REGEXP
    case QMetaType::QRegExp:
        if (value.isRegExp()) {
            *reinterpret_cast<QRegExp *>(ptr) = value.toRegExp();
            return true;
        } break;
#endif
#ifndef QT_NO_QOBJECT
    case QMetaType::QObjectStar:
        if (value.isQObject() || value.isNull()) {
            *reinterpret_cast<QObject* *>(ptr) = value.toQObject();
            return true;
        } break;
    case QMetaType::QWidgetStar:
        if (value.isQObject() || value.isNull()) {
            QObject *qo = value.toQObject();
            if (!qo || qo->isWidgetType()) {
                *reinterpret_cast<QWidget* *>(ptr) = reinterpret_cast<QWidget*>(qo);
                return true;
            }
        } break;
#endif
    case QMetaType::QStringList:
        if (value.isArray()) {
            *reinterpret_cast<QStringList *>(ptr) = stringListFromArray(value);
            return true;
        } break;
    case QMetaType::QVariantList:
        if (value.isArray()) {
            *reinterpret_cast<QVariantList *>(ptr) = variantListFromArray(value);
            return true;
        } break;
    case QMetaType::QVariantMap:
        if (value.isObject()) {
            *reinterpret_cast<QVariantMap *>(ptr) = variantMapFromObject(value);
            return true;
        } break;
    default:
    ;
    }

    QByteArray name = QMetaType::typeName(type);
#ifndef QT_NO_QOBJECT
    if (convertToNativeQObject(value, name, reinterpret_cast<void* *>(ptr)))
        return true;
#endif
    if (value.isVariant() && name.endsWith('*')) {
        int valueType = QMetaType::type(name.left(name.size()-1));
        QVariant &var = QScriptValuePrivate::get(value)->variantValue();
        if (valueType == var.userType()) {
            *reinterpret_cast<void* *>(ptr) = var.data();
            return true;
        } else {
            // look in the prototype chain
            QScriptValue proto = value.prototype();
            while (proto.isObject()) {
                bool canCast = false;
                if (proto.isVariant()) {
                    canCast = (type == proto.toVariant().userType())
                              || (valueType && (valueType == proto.toVariant().userType()));
                }
#ifndef QT_NO_QOBJECT
                else if (proto.isQObject()) {
                    QByteArray className = name.left(name.size()-1);
                    if (QObject *qobject = proto.toQObject())
                        canCast = qobject->qt_metacast(className) != 0;
                }
#endif
                if (canCast) {
                    QByteArray varTypeName = QMetaType::typeName(var.userType());
                    if (varTypeName.endsWith('*'))
                        *reinterpret_cast<void* *>(ptr) = *reinterpret_cast<void* *>(var.data());
                    else
                        *reinterpret_cast<void* *>(ptr) = var.data();
                    return true;
                }
                proto = proto.prototype();
            }
        }
    } else if (value.isNull() && name.endsWith('*')) {
        *reinterpret_cast<void* *>(ptr) = 0;
        return true;
    } else if (type == qMetaTypeId<QScriptValue>()) {
        if (!eng)
            return false;
        *reinterpret_cast<QScriptValue*>(ptr) = value;
        return true;
    } else if (name == "QVariant") {
        *reinterpret_cast<QVariant*>(ptr) = value.toVariant();
        return true;
    }

    // lazy registration of some common list types
#ifndef QT_NO_QOBJECT
    else if (type == qMetaTypeId<QObjectList>()) {
        if (!eng)
            return false;
        qScriptRegisterSequenceMetaType<QObjectList>(eng->q_func());
        return convert(value, type, ptr, eng);
    }
#endif
    else if (type == qMetaTypeId<QList<int> >()) {
        if (!eng)
            return false;
        qScriptRegisterSequenceMetaType<QList<int> >(eng->q_func());
        return convert(value, type, ptr, eng);
    }

#if 0
    if (!name.isEmpty()) {
        qWarning("QScriptEngine::convert: unable to convert value to type `%s'",
                 name.constData());
    }
#endif
    return false;
}

bool QScriptEnginePrivate::hasDemarshalFunction(int type) const
{
    QScriptTypeInfo *info = m_typeInfos.value(type);
    return info && (info->demarshal != 0);
}

/*!
    \internal
*/
bool QScriptEngine::convert(const QScriptValue &value, int type, void *ptr)
{
    Q_D(QScriptEngine);
    return QScriptEnginePrivate::convert(value, type, ptr, d);
}

/*!
    \internal
*/
bool QScriptEngine::convertV2(const QScriptValue &value, int type, void *ptr)
{
    return QScriptEnginePrivate::convert(value, type, ptr, /*engine=*/0);
}

/*!
    \internal
*/
void QScriptEngine::registerCustomType(int type, MarshalFunction mf,
                                       DemarshalFunction df,
                                       const QScriptValue &prototype)
{
    Q_D(QScriptEngine);
    QScriptTypeInfo *info = d->m_typeInfos.value(type);
    if (!info) {
        info = new QScriptTypeInfo();
        d->m_typeInfos.insert(type, info);
    }
    info->marshal = mf;
    info->demarshal = df;
    info->prototype = d->scriptValueToJSCValue(prototype);
}

/*!
  \since 4.5

  Installs translator functions on the given \a object, or on the Global
  Object if no object is specified.

  The relation between Qt Script translator functions and C++ translator
  functions is described in the following table:

    \table
    \header \o Script Function \o Corresponding C++ Function
    \row    \o qsTr()       \o QObject::tr()
    \row    \o QT_TR_NOOP() \o QT_TR_NOOP()
    \row    \o qsTranslate() \o QCoreApplication::translate()
    \row    \o QT_TRANSLATE_NOOP() \o QT_TRANSLATE_NOOP()
    \endtable

  \sa {Internationalization with Qt}
*/
void QScriptEngine::installTranslatorFunctions(const QScriptValue &object)
{
    Q_D(QScriptEngine);
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue jscObject = d->scriptValueToJSCValue(object);
    JSC::JSGlobalObject *glob = d->originalGlobalObject();
    if (!jscObject || !jscObject.isObject())
        jscObject = glob;
//    unsigned attribs = JSC::DontEnum;
    JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 5, JSC::Identifier(exec, "qsTranslate"), QScript::functionQsTranslate));
    JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 2, JSC::Identifier(exec, "QT_TRANSLATE_NOOP"), QScript::functionQsTranslateNoOp));
    JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 3, JSC::Identifier(exec, "qsTr"), QScript::functionQsTr));
    JSC::asObject(jscObject)->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "QT_TR_NOOP"), QScript::functionQsTrNoOp));

    glob->stringPrototype()->putDirectFunction(exec, new (exec)JSC::NativeFunctionWrapper(exec, glob->prototypeFunctionStructure(), 1, JSC::Identifier(exec, "arg"), QScript::stringProtoFuncArg));
}

/*!
    Imports the given \a extension into this QScriptEngine.  Returns
    undefinedValue() if the extension was successfully imported. You
    can call hasUncaughtException() to check if an error occurred; in
    that case, the return value is the value that was thrown by the
    exception (usually an \c{Error} object).

    QScriptEngine ensures that a particular extension is only imported
    once; subsequent calls to importExtension() with the same extension
    name will do nothing and return undefinedValue().

    \sa availableExtensions(), QScriptExtensionPlugin, {Creating QtScript Extensions}
*/
QScriptValue QScriptEngine::importExtension(const QString &extension)
{
#if defined(QT_NO_QOBJECT) || defined(QT_NO_LIBRARY) || defined(QT_NO_SETTINGS)
    Q_UNUSED(extension);
#else
    Q_D(QScriptEngine);
    if (d->importedExtensions.contains(extension))
        return undefinedValue(); // already imported

    QScriptContext *context = currentContext();
    QCoreApplication *app = QCoreApplication::instance();
    if (!app)
        return context->throwError(QLatin1String("No application object"));

    QObjectList staticPlugins = QPluginLoader::staticInstances();
    QStringList libraryPaths = app->libraryPaths();
    QString dot = QLatin1String(".");
    QStringList pathComponents = extension.split(dot);
    QString initDotJs = QLatin1String("__init__.js");

    QString ext;
    for (int i = 0; i < pathComponents.count(); ++i) {
        if (!ext.isEmpty())
            ext.append(dot);
        ext.append(pathComponents.at(i));
        if (d->importedExtensions.contains(ext))
            continue; // already imported

        if (d->extensionsBeingImported.contains(ext)) {
            return context->throwError(QString::fromLatin1("recursive import of %0")
                                       .arg(extension));
        }
        d->extensionsBeingImported.insert(ext);

        QScriptExtensionInterface *iface = 0;
        QString initjsContents;
        QString initjsFileName;

        // look for the extension in static plugins
        for (int j = 0; j < staticPlugins.size(); ++j) {
            iface = qobject_cast<QScriptExtensionInterface*>(staticPlugins.at(j));
            if (!iface)
                continue;
            if (iface->keys().contains(ext))
                break; // use this one
            else
                iface = 0; // keep looking
        }

        {
            // look for __init__.js resource
            QString path = QString::fromLatin1(":/qtscriptextension");
            for (int j = 0; j <= i; ++j) {
                path.append(QLatin1Char('/'));
                path.append(pathComponents.at(j));
            }
            path.append(QLatin1Char('/'));
            path.append(initDotJs);
            QFile file(path);
            if (file.open(QIODevice::ReadOnly)) {
                QTextStream ts(&file);
                initjsContents = ts.readAll();
                initjsFileName = path;
                file.close();
            }
        }

        if (!iface && initjsContents.isEmpty()) {
            // look for the extension in library paths
            for (int j = 0; j < libraryPaths.count(); ++j) {
                QString libPath = libraryPaths.at(j) + QDir::separator() + QLatin1String("script");
                QDir dir(libPath);
                if (!dir.exists(dot))
                    continue;

                // look for C++ plugin
                QFileInfoList files = dir.entryInfoList(QDir::Files);
                for (int k = 0; k < files.count(); ++k) {
                    QFileInfo entry = files.at(k);
                    QString filePath = entry.canonicalFilePath();
                    QPluginLoader loader(filePath);
                    iface = qobject_cast<QScriptExtensionInterface*>(loader.instance());
                    if (iface) {
                        if (iface->keys().contains(ext))
                            break; // use this one
                        else
                            iface = 0; // keep looking
                    }
                }

                // look for __init__.js in the corresponding dir
                QDir dirdir(libPath);
                bool dirExists = dirdir.exists();
                for (int k = 0; dirExists && (k <= i); ++k)
                    dirExists = dirdir.cd(pathComponents.at(k));
                if (dirExists && dirdir.exists(initDotJs)) {
                    QFile file(dirdir.canonicalPath()
                               + QDir::separator() + initDotJs);
                    if (file.open(QIODevice::ReadOnly)) {
                        QTextStream ts(&file);
                        initjsContents = ts.readAll();
                        initjsFileName = file.fileName();
                        file.close();
                    }
                }

                if (iface || !initjsContents.isEmpty())
                    break;
            }
        }

        if (!iface && initjsContents.isEmpty()) {
            d->extensionsBeingImported.remove(ext);
            return context->throwError(
                QString::fromLatin1("Unable to import %0: no such extension")
                .arg(extension));
        }

        // initialize the extension in a new context
        QScriptContext *ctx = pushContext();
        ctx->setThisObject(globalObject());
        ctx->activationObject().setProperty(QLatin1String("__extension__"), ext,
                                            QScriptValue::ReadOnly | QScriptValue::Undeletable);
        ctx->activationObject().setProperty(QLatin1String("__setupPackage__"),
                                            newFunction(QScript::__setupPackage__));
        ctx->activationObject().setProperty(QLatin1String("__postInit__"), QScriptValue(QScriptValue::UndefinedValue));

        // the script is evaluated first
        if (!initjsContents.isEmpty()) {
            QScriptValue ret = evaluate(initjsContents, initjsFileName);
            if (hasUncaughtException()) {
                popContext();
                d->extensionsBeingImported.remove(ext);
                return ret;
            }
        }

        // next, the C++ plugin is called
        if (iface) {
            iface->initialize(ext, this);
            if (hasUncaughtException()) {
                QScriptValue ret = uncaughtException(); // ctx_p->returnValue();
                popContext();
                d->extensionsBeingImported.remove(ext);
                return ret;
            }
        }

        // if the __postInit__ function has been set, we call it
        QScriptValue postInit = ctx->activationObject().property(QLatin1String("__postInit__"));
        if (postInit.isFunction()) {
            postInit.call(globalObject());
            if (hasUncaughtException()) {
                QScriptValue ret = uncaughtException(); // ctx_p->returnValue();
                popContext();
                d->extensionsBeingImported.remove(ext);
                return ret;
            }
        }

        popContext();

        d->importedExtensions.insert(ext);
        d->extensionsBeingImported.remove(ext);
    } // for (i)
#endif // QT_NO_QOBJECT
    return undefinedValue();
}

/*!
    \since 4.4

    Returns a list naming the available extensions that can be
    imported using the importExtension() function. This list includes
    extensions that have been imported.

    \sa importExtension(), importedExtensions()
*/
QStringList QScriptEngine::availableExtensions() const
{
#if defined(QT_NO_QOBJECT) || defined(QT_NO_LIBRARY) || defined(QT_NO_SETTINGS)
    return QStringList();
#else
    QCoreApplication *app = QCoreApplication::instance();
    if (!app)
        return QStringList();

    QSet<QString> result;

    QObjectList staticPlugins = QPluginLoader::staticInstances();
    for (int i = 0; i < staticPlugins.size(); ++i) {
        QScriptExtensionInterface *iface;
        iface = qobject_cast<QScriptExtensionInterface*>(staticPlugins.at(i));
        if (iface) {
            QStringList keys = iface->keys();
            for (int j = 0; j < keys.count(); ++j)
                result << keys.at(j);
        }
    }

    QStringList libraryPaths = app->libraryPaths();
    for (int i = 0; i < libraryPaths.count(); ++i) {
        QString libPath = libraryPaths.at(i) + QDir::separator() + QLatin1String("script");
        QDir dir(libPath);
        if (!dir.exists())
            continue;

        // look for C++ plugins
        QFileInfoList files = dir.entryInfoList(QDir::Files);
        for (int j = 0; j < files.count(); ++j) {
            QFileInfo entry = files.at(j);
            QString filePath = entry.canonicalFilePath();
            QPluginLoader loader(filePath);
            QScriptExtensionInterface *iface;
            iface = qobject_cast<QScriptExtensionInterface*>(loader.instance());
            if (iface) {
                QStringList keys = iface->keys();
                for (int k = 0; k < keys.count(); ++k)
                    result << keys.at(k);
            }
        }

        // look for scripts
        QString initDotJs = QLatin1String("__init__.js");
        QList<QFileInfo> stack;
        stack << dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
        while (!stack.isEmpty()) {
            QFileInfo entry = stack.takeLast();
            QDir dd(entry.canonicalFilePath());
            if (dd.exists(initDotJs)) {
                QString rpath = dir.relativeFilePath(dd.canonicalPath());
                QStringList components = rpath.split(QLatin1Char('/'));
                result << components.join(QLatin1String("."));
                stack << dd.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
            }
        }
    }

    QStringList lst = result.toList();
    qSort(lst);
    return lst;
#endif
}

/*!
    \since 4.4

    Returns a list naming the extensions that have been imported
    using the importExtension() function.

    \sa availableExtensions()
*/
QStringList QScriptEngine::importedExtensions() const
{
    Q_D(const QScriptEngine);
    QStringList lst = d->importedExtensions.toList();
    qSort(lst);
    return lst;
}

/*! \fn QScriptValue QScriptEngine::toScriptValue(const T &value)

    Creates a QScriptValue with the given \a value.

    Note that the template type \c{T} must be known to QMetaType.

    See \l{Conversion Between QtScript and C++ Types} for a
    description of the built-in type conversion provided by
    QtScript. By default, the types that are not specially handled by
    QtScript are represented as QVariants (e.g. the \a value is passed
    to newVariant()); you can change this behavior by installing your
    own type conversion functions with qScriptRegisterMetaType().

    \warning This function is not available with MSVC 6. Use
    qScriptValueFromValue() instead if you need to support that
    version of the compiler.

    \sa fromScriptValue(), qScriptRegisterMetaType()
*/

/*! \fn T QScriptEngine::fromScriptValue(const QScriptValue &value)

    Returns the given \a value converted to the template type \c{T}.

    Note that \c{T} must be known to QMetaType.

    See \l{Conversion Between QtScript and C++ Types} for a
    description of the built-in type conversion provided by
    QtScript.

    \warning This function is not available with MSVC 6. Use
    qScriptValueToValue() or qscriptvalue_cast() instead if you need
    to support that version of the compiler.

    \sa toScriptValue(), qScriptRegisterMetaType()
*/

/*!
    \fn QScriptValue qScriptValueFromValue(QScriptEngine *engine, const T &value)
    \since 4.3
    \relates QScriptEngine

    Creates a QScriptValue using the given \a engine with the given \a
    value of template type \c{T}.

    This function is equivalent to QScriptEngine::toScriptValue().
    It is provided as a work-around for MSVC 6, which doesn't support
    member template functions.

    \sa qScriptValueToValue()
*/

/*!
    \fn T qScriptValueToValue(const QScriptValue &value)
    \since 4.3
    \relates QScriptEngine

    Returns the given \a value converted to the template type \c{T}.

    This function is equivalent to QScriptEngine::fromScriptValue().
    It is provided as a work-around for MSVC 6, which doesn't
    support member template functions.

    \sa qScriptValueFromValue()
*/

/*!
    \fn QScriptValue qScriptValueFromSequence(QScriptEngine *engine, const Container &container)
    \since 4.3
    \relates QScriptEngine

    Creates an array in the form of a QScriptValue using the given \a engine
    with the given \a container of template type \c{Container}.

    The \c Container type must provide a \c const_iterator class to enable the
    contents of the container to be copied into the array.

    Additionally, the type of each element in the sequence should be suitable
    for conversion to a QScriptValue.
    See \l{QtScript Module#Conversion Between QtScript and C++ Types}
    {Conversion Between QtScript and C++ Types} for more information about the
    restrictions on types that can be used with QScriptValue.

    \sa qScriptValueFromValue()
*/

/*!
    \fn void qScriptValueToSequence(const QScriptValue &value, Container &container)
    \since 4.3
    \relates QScriptEngine

    Copies the elements in the sequence specified by \a value to the given
    \a container of template type \c{Container}.

    The \a value used is typically an array, but any container can be copied
    as long as it provides a \c length property describing how many elements
    it contains.

    Additionally, the type of each element in the sequence must be suitable
    for conversion to a C++ type from a QScriptValue.
    See \l{QtScript Module#Conversion Between QtScript and C++ Types}
    {Conversion Between QtScript and C++ Types} for more information about the
    restrictions on types that can be used with QScriptValue.

    \sa qscriptvalue_cast()
*/

/*!
    \fn T qscriptvalue_cast(const QScriptValue &value)
    \since 4.3
    \relates QScriptValue

    Returns the given \a value converted to the template type \c{T}.

    \sa qScriptRegisterMetaType(), QScriptEngine::toScriptValue()
*/

/*! \fn int qScriptRegisterMetaType(
            QScriptEngine *engine,
            QScriptValue (*toScriptValue)(QScriptEngine *, const T &t),
            void (*fromScriptValue)(const QScriptValue &, T &t),
            const QScriptValue &prototype = QScriptValue())
    \relates QScriptEngine

    Registers the type \c{T} in the given \a engine. \a toScriptValue must
    be a function that will convert from a value of type \c{T} to a
    QScriptValue, and \a fromScriptValue a function that does the
    opposite. \a prototype, if valid, is the prototype that's set on
    QScriptValues returned by \a toScriptValue.

    Returns the internal ID used by QMetaType.

    You only need to call this function if you want to provide custom
    conversion of values of type \c{T}, i.e. if the default
    QVariant-based representation and conversion is not
    appropriate. (Note that custom QObject-derived types also fall in
    this category; e.g. for a QObject-derived class called MyObject,
    you probably want to define conversion functions for MyObject*
    that utilize QScriptEngine::newQObject() and
    QScriptValue::toQObject().)

    If you only want to define a common script interface for values of
    type \c{T}, and don't care how those values are represented
    (i.e. storing them in QVariants is fine), use
    \l{QScriptEngine::setDefaultPrototype()}{setDefaultPrototype}()
    instead; this will minimize conversion costs.

    You need to declare the custom type first with
    Q_DECLARE_METATYPE().

    After a type has been registered, you can convert from a
    QScriptValue to that type using
    \l{QScriptEngine::fromScriptValue()}{fromScriptValue}(), and
    create a QScriptValue from a value of that type using
    \l{QScriptEngine::toScriptValue()}{toScriptValue}(). The engine
    will take care of calling the proper conversion function when
    calling C++ slots, and when getting or setting a C++ property;
    i.e. the custom type may be used seamlessly on both the C++ side
    and the script side.

    The following is an example of how to use this function. We will
    specify custom conversion of our type \c{MyStruct}. Here's the C++
    type:

    \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 20

    We must declare it so that the type will be known to QMetaType:

    \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 21

    Next, the \c{MyStruct} conversion functions. We represent the
    \c{MyStruct} value as a script object and just copy the properties:

    \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 22

    Now we can register \c{MyStruct} with the engine:
    \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 23

    Working with \c{MyStruct} values is now easy:
    \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 24

    If you want to be able to construct values of your custom type
    from script code, you have to register a constructor function for
    the type. For example:

    \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 25

    \sa qScriptRegisterSequenceMetaType(), qRegisterMetaType()
*/

/*!
    \macro Q_SCRIPT_DECLARE_QMETAOBJECT(QMetaObject, ArgType)
    \since 4.3
    \relates QScriptEngine

    Declares the given \a QMetaObject. Used in combination with
    QScriptEngine::scriptValueFromQMetaObject() to make enums and
    instantiation of \a QMetaObject available to script code. The
    constructor generated by this macro takes a single argument of
    type \a ArgType; typically the argument is the parent type of the
    new instance, in which case \a ArgType is \c{QWidget*} or
    \c{QObject*}. Objects created by the constructor will have
    QScriptEngine::AutoOwnership ownership.
*/

/*! \fn int qScriptRegisterSequenceMetaType(
            QScriptEngine *engine,
            const QScriptValue &prototype = QScriptValue())
    \relates QScriptEngine

    Registers the sequence type \c{T} in the given \a engine. This
    function provides conversion functions that convert between \c{T}
    and Qt Script \c{Array} objects. \c{T} must provide a
    const_iterator class and begin(), end() and push_back()
    functions. If \a prototype is valid, it will be set as the
    prototype of \c{Array} objects due to conversion from \c{T};
    otherwise, the standard \c{Array} prototype will be used.

    Returns the internal ID used by QMetaType.

    You need to declare the container type first with
    Q_DECLARE_METATYPE(). If the element type isn't a standard Qt/C++
    type, it must be declared using Q_DECLARE_METATYPE() as well.
    Example:

    \snippet doc/src/snippets/code/src_script_qscriptengine.cpp 26

    \sa qScriptRegisterMetaType()
*/

/*!
  Runs the garbage collector.

  The garbage collector will attempt to reclaim memory by locating and
  disposing of objects that are no longer reachable in the script
  environment.

  Normally you don't need to call this function; the garbage collector
  will automatically be invoked when the QScriptEngine decides that
  it's wise to do so (i.e. when a certain number of new objects have
  been created). However, you can call this function to explicitly
  request that garbage collection should be performed as soon as
  possible.
*/
void QScriptEngine::collectGarbage()
{
    Q_D(QScriptEngine);
    d->collectGarbage();
}

/*!

  Sets the interval between calls to QCoreApplication::processEvents
  to \a interval milliseconds.

  While the interpreter is running, all event processing is by default
  blocked. This means for instance that the gui will not be updated
  and timers will not be fired. To allow event processing during
  interpreter execution one can specify the processing interval to be
  a positive value, indicating the number of milliseconds between each
  time QCoreApplication::processEvents() is called.

  The default value is -1, which disables event processing during
  interpreter execution.

  You can use QCoreApplication::postEvent() to post an event that
  performs custom processing at the next interval. For example, you
  could keep track of the total running time of the script and call
  abortEvaluation() when you detect that the script has been running
  for a long time without completing.

  \sa processEventsInterval()
*/
void QScriptEngine::setProcessEventsInterval(int interval)
{
    Q_D(QScriptEngine);
    d->processEventsInterval = interval;

    if (interval > 0)
        d->globalData->timeoutChecker->setCheckInterval(interval);

    d->timeoutChecker()->setShouldProcessEvents(interval > 0);
}

/*!

  Returns the interval in milliseconds between calls to
  QCoreApplication::processEvents() while the interpreter is running.

  \sa setProcessEventsInterval()
*/
int QScriptEngine::processEventsInterval() const
{
    Q_D(const QScriptEngine);
    return d->processEventsInterval;
}

/*!
  \since 4.4

  Returns true if this engine is currently evaluating a script,
  otherwise returns false.

  \sa evaluate(), abortEvaluation()
*/
bool QScriptEngine::isEvaluating() const
{
    Q_D(const QScriptEngine);
    return (d->currentFrame != d->globalExec());
}

/*!
  \since 4.4

  Aborts any script evaluation currently taking place in this engine.
  The given \a result is passed back as the result of the evaluation
  (i.e. it is returned from the call to evaluate() being aborted).

  If the engine isn't evaluating a script (i.e. isEvaluating() returns
  false), this function does nothing.

  Call this function if you need to abort a running script for some
  reason, e.g.  when you have detected that the script has been
  running for several seconds without completing.

  \sa evaluate(), isEvaluating(), setProcessEventsInterval()
*/
void QScriptEngine::abortEvaluation(const QScriptValue &result)
{
    Q_D(QScriptEngine);

    d->timeoutChecker()->setShouldAbort(true);
    d->abortResult = result;
}

#ifndef QT_NO_QOBJECT

/*!
  \since 4.4
  \relates QScriptEngine

  Creates a connection from the \a signal in the \a sender to the
  given \a function. If \a receiver is an object, it will act as the
  `this' object when the signal handler function is invoked. Returns
  true if the connection succeeds; otherwise returns false.

  \sa qScriptDisconnect(), QScriptEngine::signalHandlerException()
*/
bool qScriptConnect(QObject *sender, const char *signal,
                    const QScriptValue &receiver, const QScriptValue &function)
{
    if (!sender || !signal)
        return false;
    if (!function.isFunction())
        return false;
    if (receiver.isObject() && (receiver.engine() != function.engine()))
        return false;
    QScriptEnginePrivate *engine = QScriptEnginePrivate::get(function.engine());
    JSC::JSValue jscReceiver = engine->scriptValueToJSCValue(receiver);
    JSC::JSValue jscFunction = engine->scriptValueToJSCValue(function);
    return engine->scriptConnect(sender, signal, jscReceiver, jscFunction,
                                 Qt::AutoConnection);
}

/*!
  \since 4.4
  \relates QScriptEngine

  Disconnects the \a signal in the \a sender from the given (\a
  receiver, \a function) pair. Returns true if the connection is
  successfully broken; otherwise returns false.

  \sa qScriptConnect()
*/
bool qScriptDisconnect(QObject *sender, const char *signal,
                       const QScriptValue &receiver, const QScriptValue &function)
{
    if (!sender || !signal)
        return false;
    if (!function.isFunction())
        return false;
    if (receiver.isObject() && (receiver.engine() != function.engine()))
        return false;
    QScriptEnginePrivate *engine = QScriptEnginePrivate::get(function.engine());
    JSC::JSValue jscReceiver = engine->scriptValueToJSCValue(receiver);
    JSC::JSValue jscFunction = engine->scriptValueToJSCValue(function);
    return engine->scriptDisconnect(sender, signal, jscReceiver, jscFunction);
}

/*!
    \since 4.4
    \fn void QScriptEngine::signalHandlerException(const QScriptValue &exception)

    This signal is emitted when a script function connected to a signal causes
    an \a exception.

    \sa qScriptConnect()
*/

QT_BEGIN_INCLUDE_NAMESPACE
#include "moc_qscriptengine.cpp"
QT_END_INCLUDE_NAMESPACE

#endif // QT_NO_QOBJECT

/*!
  \since 4.4

  Installs the given \a agent on this engine. The agent will be
  notified of various events pertaining to script execution. This is
  useful when you want to find out exactly what the engine is doing,
  e.g. when evaluate() is called. The agent interface is the basis of
  tools like debuggers and profilers.

  The engine maintains ownership of the \a agent.

  Calling this function will replace the existing agent, if any.

  \sa agent()
*/
void QScriptEngine::setAgent(QScriptEngineAgent *agent)
{
    Q_D(QScriptEngine);
    if (agent && (agent->engine() != this)) {
        qWarning("QScriptEngine::setAgent(): "
                 "cannot set agent belonging to different engine");
        return;
    }
    if (d->activeAgent)
        QScriptEngineAgentPrivate::get(d->activeAgent)->detach();
    d->activeAgent = agent;
    if (agent) {
        int index = d->ownedAgents.indexOf(agent);
        if (index == -1)
            d->ownedAgents.append(agent);
        QScriptEngineAgentPrivate::get(agent)->attach();
    }
}

/*!
  \since 4.4

  Returns the agent currently installed on this engine, or 0 if no
  agent is installed.

  \sa setAgent()
*/
QScriptEngineAgent *QScriptEngine::agent() const
{
    Q_D(const QScriptEngine);
    return d->activeAgent;
}

/*!
  \since 4.4

  Returns a handle that represents the given string, \a str.

  QScriptString can be used to quickly look up properties, and
  compare property names, of script objects.

  \sa QScriptValue::property()
*/
QScriptString QScriptEngine::toStringHandle(const QString &str)
{
    Q_D(QScriptEngine);
    QScriptString ss;
    QScriptStringPrivate::init(ss, this, JSC::Identifier(d->currentFrame, str));
    return ss;
}

/*!
  \since 4.5

  Converts the given \a value to an object, if such a conversion is
  possible; otherwise returns an invalid QScriptValue. The conversion
  is performed according to the following table:

    \table
    \header \o Input Type \o Result
    \row    \o Undefined  \o An invalid QScriptValue.
    \row    \o Null       \o An invalid QScriptValue.
    \row    \o Boolean    \o A new Boolean object whose internal value is set to the value of the boolean.
    \row    \o Number     \o A new Number object whose internal value is set to the value of the number.
    \row    \o String     \o A new String object whose internal value is set to the value of the string.
    \row    \o Object     \o The result is the object itself (no conversion).
    \endtable

    \sa newObject()
*/
QScriptValue QScriptEngine::toObject(const QScriptValue &value)
{
    Q_D(QScriptEngine);
    JSC::JSValue jscValue = d->scriptValueToJSCValue(value);
    if (!jscValue || jscValue.isUndefined() || jscValue.isNull())
        return QScriptValue();
    JSC::ExecState* exec = d->currentFrame;
    JSC::JSValue result = jscValue.toObject(exec);
    return d->scriptValueFromJSCValue(result);
}

/*!
  \internal

  Returns the object with the given \a id, or an invalid
  QScriptValue if there is no object with that id.

  \sa QScriptValue::objectId()
*/
QScriptValue QScriptEngine::objectById(qint64 id) const
{
    Q_D(const QScriptEngine);
    QSet<QScriptValuePrivate*>::const_iterator i = d->attachedScriptValues.constBegin();
    while(i != d->attachedScriptValues.constEnd()) {
        if ( (*i)->id == id )
            return QScriptValuePrivate::get(*i);
        i++;
    }
    return QScriptValue();
}

/*!
  \since 4.5
  \class QScriptSyntaxCheckResult

  \brief The QScriptSyntaxCheckResult class provides the result of a script syntax check.

  \ingroup script
  \mainclass

  QScriptSyntaxCheckResult is returned by QScriptEngine::checkSyntax() to
  provide information about the syntactical (in)correctness of a script.
*/

/*!
    \enum QScriptSyntaxCheckResult::State

    This enum specifies the state of a syntax check.

    \value Error The program contains a syntax error.
    \value Intermediate The program is incomplete.
    \value Valid The program is a syntactically correct Qt Script program.
*/

/*!
  Constructs a new QScriptSyntaxCheckResult from the \a other result.
*/
QScriptSyntaxCheckResult::QScriptSyntaxCheckResult(const QScriptSyntaxCheckResult &other)
    : d_ptr(other.d_ptr)
{
    if (d_ptr)
        d_ptr->ref.ref();
}

/*!
  \internal
*/
QScriptSyntaxCheckResult::QScriptSyntaxCheckResult(QScriptSyntaxCheckResultPrivate *d)
    : d_ptr(d)
{
    if (d_ptr)
        d_ptr->ref.ref();
}

/*!
  \internal
*/
QScriptSyntaxCheckResult::QScriptSyntaxCheckResult()
    : d_ptr(0)
{
}

/*!
  Destroys this QScriptSyntaxCheckResult.
*/
QScriptSyntaxCheckResult::~QScriptSyntaxCheckResult()
{
    if (d_ptr && !d_ptr->ref.deref()) {
        delete d_ptr;
        d_ptr = 0;
    }
}

/*!
  Returns the state of this QScriptSyntaxCheckResult.
*/
QScriptSyntaxCheckResult::State QScriptSyntaxCheckResult::state() const
{
    Q_D(const QScriptSyntaxCheckResult);
    if (!d)
        return Valid;
    return d->state;
}

/*!
  Returns the error line number of this QScriptSyntaxCheckResult, or -1 if
  there is no error.

  \sa state(), errorMessage()
*/
int QScriptSyntaxCheckResult::errorLineNumber() const
{
    Q_D(const QScriptSyntaxCheckResult);
    if (!d)
        return -1;
    return d->errorLineNumber;
}

/*!
  Returns the error column number of this QScriptSyntaxCheckResult, or -1 if
  there is no error.

  \sa state(), errorLineNumber()
*/
int QScriptSyntaxCheckResult::errorColumnNumber() const
{
    Q_D(const QScriptSyntaxCheckResult);
    if (!d)
        return -1;
    return d->errorColumnNumber;
}

/*!
  Returns the error message of this QScriptSyntaxCheckResult, or an empty
  string if there is no error.

  \sa state(), errorLineNumber()
*/
QString QScriptSyntaxCheckResult::errorMessage() const
{
    Q_D(const QScriptSyntaxCheckResult);
    if (!d)
        return QString();
    return d->errorMessage;
}

/*!
  Assigns the \a other result to this QScriptSyntaxCheckResult, and returns a
  reference to this QScriptSyntaxCheckResult.
*/
QScriptSyntaxCheckResult &QScriptSyntaxCheckResult::operator=(const QScriptSyntaxCheckResult &other)
{
    if (d_ptr == other.d_ptr)
        return *this;
    if (d_ptr && !d_ptr->ref.deref()) {
        delete d_ptr;
        d_ptr = 0;
    }
    d_ptr = other.d_ptr;
    if (d_ptr)
        d_ptr->ref.ref();
    return *this;
}

QT_END_NAMESPACE