Ejemplo n.º 1
0
KJS::Value KstBindKst::loadScript(KJS::ExecState *exec, const KJS::List& args) {
  if (args.size() != 1) {
    KJS::Object eobj = KJS::Error::create(exec, KJS::SyntaxError);
    exec->setException(eobj);
    return KJS::Undefined();
  }

  if (args[0].type() != KJS::StringType) {
    KJS::Object eobj = KJS::Error::create(exec, KJS::TypeError);
    exec->setException(eobj);
    return KJS::Undefined();
  }

  QString fn = args[0].toString(exec).qstring();
  if (!QFile::exists(fn)) { // One day make this support KIO FIXME
    return KJS::Boolean(false);
  }

  if (_ext->part()->runFile(fn)) {
    // FIXME: add to the script registry
  } else {
    KJS::Completion c = _ext->part()->completion();
    if (!c.isNull()) {
      QString err = c.toString(_ext->part()->globalExec()).qstring();
      KstDebug::self()->log(i18n("Error running script %1: %2").arg(fn).arg(err), KstDebug::Error);
    } else {
      KstDebug::self()->log(i18n("Unknown error running script %1.").arg(fn), KstDebug::Error);
    }
    return KJS::Boolean(false);
  }

  return KJS::Boolean(true);
}
Ejemplo n.º 2
0
void KstJS::loadScript() {
  QString fn = KFileDialog::getOpenFileName("::<kstfiledir>",
      i18n("*.js|JavaScript (*.js)\n*|All Files"),
      app(), i18n("Open Script"));

  if (!fn.isEmpty()) {
    if (_jsPart->runFile(fn)) {
      if (!_scripts.contains(fn)) {
        _scripts.append(fn);
      }
    } else {
      KJS::Completion c = _jsPart->completion();
      QString err = c.toString(_jsPart->globalExec()).qstring();
      KMessageBox::error(app(), i18n("Error running script %1: %2").arg(fn).arg(err));
    }
  }
}
bool JSConsoleWidget::execute( const QString &cmd, const KJS::Value &self )
{
    KJS::Completion jsres;
    bool ok = js->execute( jsres, cmd, self );

    // Executed ok
    if ( ok ) {

	// No return value
	if ( !jsres.isValueCompletion() )
	    return ok;

	// Return value
	KJS::Value ret = jsres.value();
	KJS::UString s = ret.toString( js->globalExec() );

	if ( s.isNull() ) {
	    warn( i18n("Success, but return value cannot be displayed") );
	    return ok;
	}

	QString txt = s.qstring();
	txt = txt.replace( QChar('\n'), "<br>" );
	println( txt );

	return ok;
    }

    // Handle errors
    KJS::ComplType ct = jsres.complType();
    if ( (ct == KJS::Throw) || (ct == KJS::Break) || ct == KJS::Continue ) {

	KJS::UString s = jsres.value().toString( js->globalExec() );
	if ( !s.isNull() )
	    warn( s.qstring() );
	else
	    warn( i18n("Unspecified error") );
    }
    else {
	kdDebug(80001) << "jsconsolewidget: Unknown completion error, " << ct << endl;
	warn( i18n("Unknown error returned, completion type %1").arg(ct) );
    }

    return ok;
}
Ejemplo n.º 4
0
void SVGScriptElement::executeScript(Document *document, StringImpl *jsCode)
{
    if(!document || !jsCode)
        return;
#if 0
    Ecma *ecmaEngine = document->ecmaEngine();
    if(!ecmaEngine)
        return;
                
    KJS::Interpreter::lock();

    // Run script
    KJS::Completion comp = ecmaEngine->evaluate(jsCode.deprecatedString(), ecmaEngine->globalObject());
    if(comp.complType() == KJS::Throw)
    {
        KJS::ExecState *exec = ecmaEngine->globalExec();
        KJS::JSValue *exVal = comp.value();

        int lineno = -1;
        if(exVal->isObject())
        {
            KJS::JSValue *lineVal = static_cast<KJS::JSObject *>(exVal)->get(exec, "line");
            if(lineVal->type() == KJS::NumberType)
                lineno = int(lineVal->toNumber(exec));
        }

        // Fire ERROR_EVENT upon errors...
        SVGDocument *svgDocument = static_cast<SVGDocument *>(document);
        if(svgDocument && document->hasListenerType(ERROR_EVENT))
        {
            RefPtr<Event> event = svgDocument->createEvent("SVGEvents");
            event->initEvent(EventNames::errorEvent, false, false);
            svgDocument->dispatchRecursiveEvent(event.get(), svgDocument->lastChild());
        }

        kdDebug() << "[SVGScriptElement] Evaluation error, line " << (lineno != -1 ? DeprecatedString::number(lineno) : DeprecatedString::fromLatin1("N/A"))  << " " << exVal->toString(exec).deprecatedString() << endl;
    }
    else if(comp.complType() == KJS::ReturnValue)
        kdDebug() << "[SVGScriptElement] Return value: " << comp.value()->toString(ecmaEngine->globalExec()).deprecatedString() << endl;
    else if(comp.complType() == KJS::Normal)
        kdDebug() << "[SVGScriptElement] Evaluated ecma script!" << endl;
    
    KJS::Interpreter::unlock();
#else
    if (jsCode)
        // Hack to close memory leak due to #if 0
        String(jsCode);
#endif
}
Ejemplo n.º 5
0
int main( int argc, char **argv )
{
    QTime time;
    time.start();

#ifdef _WIN32
#   ifdef CONSOLEIO
    RedirectIOToConsole();
#   endif
#endif

    // Handle arguments
    QString appName = argv[0];
    QStringList args;
    for (int i = 1; i < argc; i++ )
    {
        args << argv[i];
    }

    QString script;
    KJS::List scriptArgs;
    bool gui = true;
#ifndef QT_ONLY
    /*
    #ifdef __GNUC__
        #warning "KDE Support enabled"
    #endif
    */
    bool kde = true;
#else
    /*
    #ifdef __GNUC__
        #warning "KDE Support disabled"
    #endif
    */
#endif

    if (argc > 1)
    {
        while (!args.isEmpty())
        {
            QString arg = args.takeFirst();
            if (arg.contains('-'))
            {
                if ((arg == "--version") || (arg == "-v"))
		{
		    printf("Qt: %s\n", qVersion()); 
#ifndef QT_ONLY
		    printf("KDE: %s\n", KDE_VERSION_STRING); 
#endif
		     return 0;
		}
                if ((arg == "--exec") || (arg == "-e"))
		{
                    gui = false;
		}
                else if ((arg == "--interactive") || (arg == "-i"))
                    (*KJSEmbed::conout()) << "Interactive";
#ifndef QT_ONLY
                else if ((arg == "-n") || (arg == "--no-kde"))
		{
		    kde = false;
		}
#endif
		else
                {
                    printUsage(appName);
                    return 0;
                }
            }
            else
            {
                if (!script.isEmpty())
                    scriptArgs.append(KJS::jsString(arg));
                else
                    script = arg;
            }
        }
    }
    else
    {
        printUsage(appName);
        return 0;
    }

    // Setup QApplication
    QCoreApplication *app;

#ifndef QT_ONLY
    if (kde)
    {
        KAboutData aboutData( "kjscmd", 0, ki18n("KJSCmd"), "0.2",
            ki18n(""
            "Utility for running KJSEmbed scripts \n" ),
            KAboutData::License_LGPL,
            ki18n("(C) 2005-2006 The KJSEmbed Authors") );

        KCmdLineOptions options;
        options.add("e", ki18n("Execute script without gui support"));
        options.add("exec", ki18n("Execute script without gui support"));
        options.add("i", ki18n("start interactive kjs interpreter"));
        options.add("interactive", ki18n("start interactive kjs interpreter"));
        options.add("n", ki18n("start without KDE KApplication support."));
        options.add("no-kde", ki18n("start without KDE KApplication support."));
        options.add("!+command", ki18n("Script to execute"));

        KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
        KCmdLineArgs::init( argc, argv, &aboutData );

        app = new KApplication(gui);
    }
    else
#endif
    if (gui)
    {
	qDebug("no KDE");
        app = new QApplication( argc, argv );
        dynamic_cast<QApplication*>(app)->connect( app, SIGNAL(lastWindowClosed()), SLOT(quit()) );
    }
    else
    {
	qDebug("no GUI");
        app = new QCoreApplication(argc, argv);
    }
    qDebug(" New %s %dms", app->metaObject()->className(), time.elapsed());

    app->setApplicationName( appName );
    
    // Setup Interpreter
    time.restart();
    Engine kernel;
    qDebug(" New engine %dms", time.elapsed());
    time.restart();

    KJS::Interpreter *js = kernel.interpreter();
    js->setShouldPrintExceptions(true);
    KJS::ExecState *exec = js->globalExec();

    // Publish bindings
    KJS::JSObject *appObject = kernel.addObject( app, "Application" );
    KJS::JSObject *argObject = js->builtinArray()->construct( exec, scriptArgs );
    appObject->put( exec, "args", argObject );
    Engine::ExitStatus result = Engine::Failure;

    if (!script.isEmpty())
    {
        result = kernel.runFile(toUString(script));
    }
    else // exec shell
    {
        result = kernel.runFile( ":/console.js" );
    }

    if ( result != Engine::Success )
    {
        KJS::Completion jsres = kernel.completion();
       (*KJSEmbed::conerr()) << toQString(jsres.value()->toString(exec)) << endl;
    }
    return (int)result;
}
Ejemplo n.º 6
0
void ECMAscriptTest::runAllTests()
{
    static const QByteArray include = "$INCLUDE(\"";

    QFETCH(QString, filename);
    QByteArray expectedError;

    QFile input( filename );

    foreach ( const QByteArray &skip, skips.keys() ) {
        if ( skip == QTest::currentDataTag() )
            QSKIP( skips[ skip ], SkipSingle );
    }

    QVERIFY( input.open( QIODevice::ReadOnly ) );

    const QByteArray testdata = input.readAll();

    QVERIFY( ! testdata.isEmpty() );

    RefPtr<KJS::Interpreter> interp = new KJS::Interpreter(global);

    KJS::Interpreter::setShouldPrintExceptions(true);

    QByteArray testscript;

    // test is expected to fail
    if ( testdata.indexOf( "@negative" ) >= 0 ) {
        expectedError = getTextProperty( "@negative", testdata );
        if ( expectedError.isEmpty() )
            expectedError = ".";
    }

    int from = 0;
    while ( ( from = testdata.indexOf( include, from ) ) >= 0 ) {
        int endq = testdata.indexOf( "\"", from + include.length() );
        QVERIFY( endq >= 0 );

        const QByteArray includeFile = testdata.mid( from + include.length(), endq - from - include.length() );

        if ( ! includes.contains( includeFile ) )
            QVERIFY( loadInclude( includeFile ) );

        testscript += includes[ includeFile ];
        from = endq;
    }

    testscript += testrunner;

    testscript += testdata;

    const QFileInfo info( input );

    const QString scriptutf = QString::fromUtf8( testscript.constData() );

    KJS::Completion completion = interp->evaluate(info.fileName().toAscii().constData(), 0, scriptutf);

    const bool knownBroken = expectedBroken.contains( QString::fromAscii( QTest::currentDataTag() ) );

    if ( expectedError.isEmpty() ) {
        ECMATEST_VERIFY( completion.complType() != KJS::Throw );
    } else {
        if ( knownBroken && completion.complType() != KJS::Throw ) {
            QEXPECT_FAIL(QTest::currentDataTag(), "It is known that KJS doesn't pass this test", Abort);
            m_failed++;
        }

        QCOMPARE( completion.complType(), KJS::Throw );
        QVERIFY( completion.value() != NULL );

        const QString eMsg = exceptionToString( interp->execState(), completion.value() );

        if ( expectedError == "^((?!NotEarlyError).)*$" ) {
            ECMATEST_VERIFY( eMsg.indexOf( "NotEarlyError" ) == -1 );
        } else if ( expectedError == "." ) {
            // means "every exception passes
        } else {
            ECMATEST_VERIFY( eMsg.indexOf( expectedError ) >= 0 );
        }
    }
}
bool KJSEmbedPart::execute( KJS::Completion &result, const QString &script, const KJS::Value &self )
{
    KJS::Value val( self );
    result = js->evaluate( script, self.isNull() ? partobj : val );
    return (result.complType() == KJS::Normal) || (result.complType() == KJS::ReturnValue);
}