Example #1
0
void TestController::initialize(int argc, const char* argv[])
{
    platformInitialize();

    if (argc < 2) {
        fputs("Usage: WebKitTestRunner [options] filename [filename2..n]\n", stderr);
        // FIXME: Refactor option parsing to allow us to print
        // an auto-generated list of options.
        exit(1);
    }

    bool printSupportedFeatures = false;

    for (int i = 1; i < argc; ++i) {
        std::string argument(argv[i]);

        if (argument == "--timeout" && i + 1 < argc) {
            m_longTimeout = atoi(argv[++i]);
            // Scale up the short timeout to match.
            m_shortTimeout = defaultShortTimeout * m_longTimeout / defaultLongTimeout;
            continue;
        }

        if (argument == "--no-timeout") {
            m_useWaitToDumpWatchdogTimer = false;
            continue;
        }

        if (argument == "--no-timeout-at-all") {
            m_useWaitToDumpWatchdogTimer = false;
            m_forceNoTimeout = true;
            continue;
        }

        if (argument == "--verbose") {
            m_verbose = true;
            continue;
        }
        if (argument == "--gc-between-tests") {
            m_gcBetweenTests = true;
            continue;
        }
        if (argument == "--pixel-tests" || argument == "-p") {
            m_shouldDumpPixelsForAllTests = true;
            continue;
        }
        if (argument == "--print-supported-features") {
            printSupportedFeatures = true;
            break;
        }


        // Skip any other arguments that begin with '--'.
        if (argument.length() >= 2 && argument[0] == '-' && argument[1] == '-')
            continue;

        m_paths.push_back(argument);
    }

    if (printSupportedFeatures) {
        // FIXME: On Windows, DumpRenderTree uses this to expose whether it supports 3d
        // transforms and accelerated compositing. When we support those features, we
        // should match DRT's behavior.
        exit(0);
    }

    m_usingServerMode = (m_paths.size() == 1 && m_paths[0] == "-");
    if (m_usingServerMode)
        m_printSeparators = true;
    else
        m_printSeparators = m_paths.size() > 1;

    initializeInjectedBundlePath();
    initializeTestPluginDirectory();

    WKRetainPtr<WKStringRef> pageGroupIdentifier(AdoptWK, WKStringCreateWithUTF8CString("WebKitTestRunnerPageGroup"));
    m_pageGroup.adopt(WKPageGroupCreateWithIdentifier(pageGroupIdentifier.get()));

    m_context.adopt(WKContextCreateWithInjectedBundlePath(injectedBundlePath()));
    m_geolocationProvider = adoptPtr(new GeolocationProviderMock(m_context.get()));

#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED > 1080
    WKContextSetUsesNetworkProcess(m_context.get(), true);
    WKContextSetProcessModel(m_context.get(), kWKProcessModelMultipleSecondaryProcesses);
#endif

    if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
        String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);

        // WebCore::pathByAppendingComponent is not used here because of the namespace,
        // which leads us to this ugly #ifdef and file path concatenation.
#if OS(WINDOWS)
        const char separator = '\\';
#else
        const char separator = '/';
#endif

        WKContextSetApplicationCacheDirectory(m_context.get(), toWK(temporaryFolder + separator + "ApplicationCache").get());
        WKContextSetDatabaseDirectory(m_context.get(), toWK(temporaryFolder + separator + "Databases").get());
        WKContextSetLocalStorageDirectory(m_context.get(), toWK(temporaryFolder + separator + "LocalStorage").get());
        WKContextSetDiskCacheDirectory(m_context.get(), toWK(temporaryFolder + separator + "Cache").get());
        WKContextSetCookieStorageDirectory(m_context.get(), toWK(temporaryFolder + separator + "Cookies").get());
        WKContextSetIconDatabasePath(m_context.get(), toWK(temporaryFolder + separator + "IconDatabase" + separator + "WebpageIcons.db").get());
    }

    WKContextUseTestingNetworkSession(m_context.get());
    WKContextSetCacheModel(m_context.get(), kWKCacheModelDocumentBrowser);

    platformInitializeContext();

    WKContextInjectedBundleClient injectedBundleClient = {
        kWKContextInjectedBundleClientCurrentVersion,
        this,
        didReceiveMessageFromInjectedBundle,
        didReceiveSynchronousMessageFromInjectedBundle,
        0 // getInjectedBundleInitializationUserData
    };
    WKContextSetInjectedBundleClient(m_context.get(), &injectedBundleClient);

    WKNotificationManagerRef notificationManager = WKContextGetNotificationManager(m_context.get());
    WKNotificationProvider notificationKit = m_webNotificationProvider.provider();
    WKNotificationManagerSetProvider(notificationManager, &notificationKit);

    if (testPluginDirectory())
        WKContextSetAdditionalPluginsDirectory(m_context.get(), testPluginDirectory());

    createWebViewWithOptions(0);
}
Example #2
0
File: jit.cpp Project: Bigot/factor
/* Allocates memory */
void jit::emit_with_parameter(cell code_template_, cell argument_) {
  data_root<array> code_template(code_template_, parent);
  data_root<object> argument(argument_, parent);
  parameter(argument.value());
  emit(code_template.value());
}
Example #3
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;

#ifdef XQ_WS_WIN
  WSADATA wsaData;
  if (WSAStartup(MAKEWORD(1, 1), &wsaData))
  {
    qDebug("Error starting up Windows Socket system... Database services are not avalable.");
    exit(-1);
  }
#endif

  QApplication app(argc, argv);
  app.addLibraryPath(".");

#ifdef Q_WS_WIN
  if (app.winVersion() == QSysInfo::WV_XP)
    app.setStyle(QStyleFactory::create("windowsxpstyle"));
#if QT_VERSION >= 0x040300 
  else if (app.winVersion() == QSysInfo::WV_VISTA)
    app.setStyle(QStyleFactory::create("windowsvistastyle"));
#endif
  else
    app.setStyle(new QWindowsStyle);
#elif defined Q_WS_MACX
  app.setStyle(new QMacStyle);
#elif defined Q_WS_X11
  app.setStyle(new QWindowsStyle);
#endif

  // Try and load a default translation file and install it
  QTranslator defaultTranslator(0);
  if (defaultTranslator.load("default.qm", app.applicationDirPath()))
    app.installTranslator(&defaultTranslator);

  app.processEvents();

  if (argc > 1)
  {
    bool    havePasswd          = FALSE;
    bool    interactive         = TRUE;
    bool    createCountTags     = FALSE;
    QString passwd;

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL="))
      {
        haveDatabaseURL = TRUE;
        databaseURL = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd="))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth"))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 

      else if (argument.contains("-createCountTags"))
      {
        interactive = FALSE;
        createCountTags = TRUE;
      }
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db.isValid())
      {
        qDebug("Cannot load Database Driver.  Contact your Systems Administrator.");
        exit(-1);
      }

      QString protocol;
      parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);
      db.setDatabaseName(dbName);
      db.setUserName(username);
      db.setPassword(passwd);
      db.setHostName(hostName);
      bool valport = false;
      int iport = port.toInt(&valport);
      if(!valport) iport = 5432;
      db.setPort(iport);

      if (!db.open())
      {
        qDebug( QObject::tr( "Cannot log onto the database with the supplied username/password!\n"
                             "Host = %1\n"
                             "Database = %2\n"
                             "Username = %3\n" )
                .arg(hostName)
                .arg(dbName)
                .arg(username) );
        exit(-1);
      }
      else
        loggedIn = TRUE;
    }

    if (!interactive)
      return 0;
  }

  _splash = new QSplashScreen();
  _splash->setPixmap(QPixmap(":/images/splashEmpty.png"));

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
//    params.append("name", _Name);  -- We can't tell now until were logged in what the app is.
    params.append("copyright", _Copyright);
    params.append("version", _Version);
    params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__));

    if (haveUsername)
      params.append("username", username);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    if (_evaluation)
      params.append("evaluation");

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, _splash);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
    else
    {
      databaseURL = newdlg._databaseURL;
      username = newdlg.username();
    }
  }

  XSqlQuery metric;
  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'Application')" );
  if(!metric.first() || (metric.value("metric_value").toString() == "OpenMFG"))
  {
    _splash->setPixmap(QPixmap(":/images/splashOpenMFG.png"));
    _Name = _Name.arg("OpenMFG");
  }
  else if(!metric.first() || (metric.value("metric_value").toString() == "xTupleERP"))
  {
    _splash->setPixmap(QPixmap(":/images/splashxTupleERP.png"));
    _Name = _Name.arg("Standard");
  }
  else
  {
    _splash->setPixmap(QPixmap(":/images/splashPostBooks.png"));
    _Name = _Name.arg("PostBooks");
  }

  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'OpenMFGServerVersion')" );
  if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion))
  {
    _splash->hide();
    int result;
    result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
      QObject::tr("The version of the database you are connecting to is not the version\n"
                  "this client was designed to work against.\n\n"
                  "This client was designed to work against the database version %1.\n"
                  "If you continue some or all functionality may not work properly\n"
                  "or at all. You may also cause other problems on the database.\n\n"
                  "Do you want to continue anyway?").arg(_dbVersion),
               QMessageBox::Yes,
               QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
    if(result != QMessageBox::Yes)
      return 0;
    _splash->show();
  }

  _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _metrics = new Metrics();

  _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _preferences = new Preferences(username);

  _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _privileges = new Privileges();

  // Load the translator and set the locale from the User's preferences
  QTranslator translator(0);
  _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList paths;
    paths << "dict";
    paths << "";
    paths << "../dict";
    paths << app.applicationDirPath() + "/dict";
    paths << app.applicationDirPath();
    paths << app.applicationDirPath() + "/../dict";
#if defined Q_WS_MACX
    paths << app.applicationDirPath() + "/../../../dict";
    paths << app.applicationDirPath() + "/../../..";
#endif
    
    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    if (!langq.value("lang_abbr2").toString().isEmpty() && 
        !langq.value("country_abbr").toString().isEmpty())
    {
      files << "xTuple." + langq.value("lang_abbr2").toString() + "_" +
               langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      files << "xTuple." + langq.value("lang_abbr2").toString();
    }

    if (files.size() > 0)
    {
      bool langFound = false;

      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit)
        {
          qDebug("looking for %s in %s",
                   (*fit).toAscii().data(), (*pit).toAscii().data());
          if (translator.load(*fit, *pit))
          {
            app.installTranslator(&translator);
            langFound = true;
            break;
          }
        }
      }

      if (!langFound && !_preferences->boolean("IngoreMissingTranslationFiles"))
        QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"),
                              QObject::tr("<p>The Translation Dictionaries %1 "
                                          "cannot be loaded. Reverting "
                                          "to the default dictionary." )
                                       .arg(files.join(QObject::tr(", "))));
    }

    /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or
       lang#, depending on what information is available
     */
    QString langAbbr = langq.value("lang_abbr2").toString();
    QString cntryAbbr = langq.value("country_abbr").toString().toUpper();
    if(cntryAbbr == "UK")
      cntryAbbr = "GB";
    if (! langAbbr.isEmpty() &&
        ! cntryAbbr.isEmpty())
      QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr));
    else if (! langAbbr.isEmpty())
      QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString()));
    else if (langq.value("lang_qt_number").toInt() &&
             langq.value("country_qt_number").toInt())
      QLocale::setDefault(
          QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()),
                  QLocale::Country(langq.value("country_qt_number").toInt())));
    else
      QLocale::setDefault(QLocale::system());

    qDebug("Locale set to language %s and country %s",
           QLocale().languageToString(QLocale().language()).toAscii().data(),
           QLocale().countryToString(QLocale().country()).toAscii().data());

  }
  else if (langq.lastError().type() != QSqlError::None)
  {
    systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__);
  }

  qApp->processEvents();
  QString key;

  // TODO: Add code to check a few locations - Hopefully done

  QString keypath;
  QString keyname;
  QString keytogether;
  
  keytogether = app.applicationDirPath() + "/OpenMFG.key";
#ifdef Q_WS_WIN
  keypath = _metrics->value("CCWinEncKey");
#elif defined Q_WS_MACX
  keypath = _metrics->value("CCMacEncKey");
#elif defined Q_WS_X11
  keypath = _metrics->value("CCLinEncKey");
#endif
  
  if (keypath.isEmpty())
    keypath = app.applicationDirPath();

  if (! keypath.endsWith(QDir::separator()))
    keypath += QDir::separator();

  keyname = _metrics->value("CCEncKeyName");
  if (keyname.isEmpty())
    keyname = "OpenMFG.key";
  
  keytogether = keypath + keyname;
  
  // qDebug("keytogether: %s", keytogether.toAscii().data());
  QFile keyFile(keytogether);

  if(keyFile.exists())
  {
    if(keyFile.open(QIODevice::ReadOnly))
    {
      key = keyFile.readLine(1024);
      // strip off any newline characters
      key = key.stripWhiteSpace();
    }
  }

  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;

// qDebug("Encryption Key: %s", key.toAscii().data() );
  
  if (key.length() > 0) {
	_splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor);
	qApp->processEvents();
	_metricsenc = new Metricsenc(key);
  }
  
  initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace());

  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->show();
    app.setMainWidget(omfgThis);
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    woTimeClock* newdlg = new woTimeClock();
    ParameterList params;
    params.append("captive");
    newdlg->set(params);
    newdlg->show();
    app.setMainWidget(newdlg);
  }

  if(!omfgThis->singleCurrency())
  {
    // Check for the gain/loss and discrep accounts
    q.prepare("SELECT COALESCE((SELECT TRUE"
              "                   FROM accnt, metric"
              "                  WHERE ((CAST(accnt_id AS text)=metric_value)"
              "                    AND  (metric_name='CurrencyGainLossAccount'))), FALSE)"
              "   AND COALESCE((SELECT TRUE"
              "                   FROM accnt, metric"
              "                  WHERE ((CAST(accnt_id AS text)=metric_value)"
              "                    AND  (metric_name='GLSeriesDiscrepancyAccount'))), FALSE) AS result; ");
    q.exec();
    if(q.first() && q.value("result").toBool() != true)
      QMessageBox::warning( omfgThis, QObject::tr("Additional Configuration Required"),
        QObject::tr("Your system is configured to use multiple Currencies, but the\n"
                    "Currency Gain/Loss Account and/or the G/L Series Discrepancy Account\n"
                    "does not appear to be configured correctly. You should define these\n"
                    "Accounts in 'System | Configure Modules | Configure G/L...' before\n"
                    "posting any transactions in the system.") );
  }

  app.exec();

//  Clean up
  delete _metrics;
  delete _preferences;
  delete _privileges;
  if (0 != _metricsenc)
    delete _metricsenc;

#ifdef XQ_WS_WIN
  WSACleanup();
#endif

  return 0;
}
/**
 *
 * Main testing loop.
 * Read a script file, parse it and execute each test step in turn.
 *
 * @param "const TDesC& aCmdLine"
 *			The command line
 * 
 * @xxxx
 *
 */
void CTestFrameworkMain::RunTestScriptL(const TDesC& aCmdLine)
	{
	// use TLex to decode the cmd line
	TLex lex(aCmdLine);
	TPtrC token=lex.NextToken();
	
	// if there is no input filename on the cmd line, panic
	if (token.Length() == 0) 
		UsageL();
	else
		{
		// Process any options
		while(token.Length() > 1 && token[0] == '-')
			{
			switch(token[1])
				{
				case 'C':
				case 'c':
					// log to console ONLY
					iLogMode = ELogToConsole;
					break;
				case 'A':
				case 'a':
					iLogMode |= ELogConsoleFull;
					break;
				case 'F':
				case 'f':
					// log to file ONLY
					iLogMode = ELogToFile; 
					break;
				case 'P':
				case 'p':
					// log to port AS WELL AS to console / file
					iLogMode |= ELogToPort;
					break;
				//This stops the emulator from thowing int 3 if a panic occurs in debug builds
				case 'T':
				case 't':
					User::SetJustInTime(EFalse);
				// -S flag removed - was for old Unit Test mode only
				// -A 'automated mode' removed - it's always automated
					break;
				case 'G':
				case 'g':
					{
					// ** guard timer override - get numeric value that follows
					TPtrC val = &token[2];
					TLex lexTimeOut(val);
					if (lexTimeOut.Val(iGuardTimer) != KErrNone)
						UsageL();
					}
					break;
				case 'm':
				case 'M':
					{
					if (token.Length()<=2)
						{
						// only -m found. must be -m<arg> with no space
						UsageL();
						}
					TPtrC restOfLine = &token[2]; // this will be rest of command line
					TLex argument(restOfLine);
					TPtrC matchString = argument.NextToken(); // will be the argument itself
					ASSERT(matchString.Length()>1);
					iTestMatchString = matchString;
					}
					break;
				case 'Q':
				case 'q':
					{
					// This flag has been removed.  This block is just to ensure that if used it wont panic
					}
					break;

				default:
					UsageL();
					return;
				}

			token.Set(lex.NextToken());
			}

		// save the input filename
		CFileName* scriptFileName = CFileName::NewLC();
		*scriptFileName = token;

		// make the log file name from the script file name
		CFileName* logFileName = CFileName::NewLC();
		*logFileName = token;
		RDebug::Print(_L("TestFrameWorkMain.cpp: RunTestScriptL 1"));
		// open the log file
		iLogClient->OpenLogFileL(logFileName->FileName(), iLogMode);
		RDebug::Print(_L("TestFrameWorkMain.cpp: RunTestScriptL 2"));	
		iLogClient->LogExtra(__FILE8__, __LINE__, ESevrInfo,
				KTxtFrameworkStarting, &KTxtVersion(), &KTxtTarget(), &KTxtBuild());
		RDebug::Print(_L("TestFrameWorkMain.cpp: RunTestScriptL 3"));
		// create a ParseScript object
		CScript* parseScript = CScript::NewLC(iTestUtils, 
											  iLogClient, 
											  iGuardTimer,
											  iTestMatchString);
		RDebug::Print(_L("TestFrameWorkMain.cpp: RunTestScriptL 4"));
		// parse all scripts
		do
			{
			// get the next file
			*scriptFileName = token;
				
			// read in the script file
			if ( parseScript->OpenScriptFile(scriptFileName))
				{
				// process it
				parseScript->ExecuteScriptL();
				// display results summary
				parseScript->DisplayResults();
				}
			// get the next
			token.Set(lex.NextToken());
			} while ( token.Length()!=0 );
		RDebug::Print(_L("TestFrameWorkMain.cpp: RunTestScriptL 5"));
		CleanupStack::PopAndDestroy(parseScript);

		// close the logging system
		iLogClient->CloseLogFile();

		CleanupStack::PopAndDestroy(logFileName);
		CleanupStack::PopAndDestroy(scriptFileName);
		}
	}
Example #5
0
int main (int inArgc, char * const inArgv[])
{
	// set pattern matching wild char asap
	VCollator::SetDefaultWildChar( '*');	
	
	// First, create the application. So, everything is initialized and ready to use
	VRIAServerApplication application;
	VProcess::InitOptions initOptions = VProcess::Init_Default & ~VProcess::Init_WithQuickTime;

#if VERSION_LINUX
	XBOX::VString versionString;
	versionString.FromCString (STRPRODUCTVER); // 	YT 18-May-2012 - WAK0076647
    VRIAServerApplication::Get()->SetProductVersion (versionString);
#endif
	
    //jmo - We may want to quit after parsing the command line
    bool shouldQuit=false;

	if (application.Init( initOptions))
	{
		// Parse the command line argument
		VError err = VE_OK;

		// remote admin: feature development in progress
		//VRIAServerSupervisor*	srvSup = VRIAServerSupervisor::Get();

		VRIAServerStartupParameters *startupParameters = new VRIAServerStartupParameters();
		if (startupParameters != NULL)
		{
			// skip first argument (executable path)
			if (inArgc > 1)
			{
				int curArg = 1;

				while (curArg < inArgc && err == VE_OK)
				{
					VString argument( inArgv[curArg]);

					if (argument.BeginsWith( kARG_ADMINISTRATOR_PORT))
					{
						++curArg;
						argument.Remove( 1, kARG_ADMINISTRATOR_PORT.GetLength());
						if (!argument.IsEmpty() && argument.GetUniChar(1) == '=')
						{
							argument.Remove( 1, 1);
							if (!argument.IsEmpty())
							{
								sLONG port = argument.GetLong();
								if (port > 0)
									startupParameters->SetAdministratorHttpPort( port);
								else
									err = VE_RIA_INVALID_COMMAND_LINE_ARGUMENTS;
							}
							else
							{
								err = VE_RIA_INVALID_COMMAND_LINE_ARGUMENTS;
							}
						}
						else
						{
							err = VE_RIA_INVALID_COMMAND_LINE_ARGUMENTS;
						}
					}
					else if (argument.BeginsWith( kARG_ADMINISTRATOR_SSL_PORT))
					{
						++curArg;
						argument.Remove( 1, kARG_ADMINISTRATOR_SSL_PORT.GetLength());
						if (!argument.IsEmpty() && argument.GetUniChar(1) == '=')
						{
							argument.Remove( 1, 1);
							if (!argument.IsEmpty())
							{
								sLONG port = argument.GetLong();
								if (port > 0)
									startupParameters->SetAdministratorSSLPort( port);
								else
									err = VE_RIA_INVALID_COMMAND_LINE_ARGUMENTS;
							}
							else
							{
								err = VE_RIA_INVALID_COMMAND_LINE_ARGUMENTS;
							}
						}
						else
						{
							err = VE_RIA_INVALID_COMMAND_LINE_ARGUMENTS;
						}
					}
                    else if (argument.BeginsWith( kVERSION_NUMBER))
					{
						++curArg;
						argument.Remove(1, kVERSION_NUMBER.GetLength());

						VString version;
						
						VRIAServerApplication::Get()->GetProductVersion(version);
						
						char buf[100];
						
						version.ToCString(buf, sizeof(buf));
						
                        printf("Wakanda Server %s\n", buf);

                        shouldQuit=true;
					}
					else if (argument.BeginsWith( kLOG_DUMP))
					{
						++curArg;
						argument.Remove(1, kLOG_DUMP.GetLength());
						
						startupParameters->SetNetDump(true);
					}
					else if (argument.EqualToString( kARG_DEBUG_OFF))
					{
						++curArg;
						startupParameters->SetDebuggingAuthorized( false);
					}
					else if (argument.EqualToString( kARG_SYSLOG))
					{
						++curArg;

					#if VERSIONMAC || VERSION_LINUX
						VSysLogOutput *syslogOutput = new VSysLogOutput( L"Wakanda Server");
						application.GetLogger()->AddLogListener( syslogOutput);
						syslogOutput->Release();
					#endif
					}
					else
					{
						++curArg;

						// check whether it's a solution file path
						VFilePath fullPath;
					#if VERSIONWIN
						fullPath.FromFullPath( argument, FPS_SYSTEM);
					#else // VERSIONMAC
						VURL::Decode( argument);
						fullPath.FromFullPath( argument, FPS_POSIX);
					#endif

						if (fullPath.IsValid())
						{
							VFile *file = new VFile( fullPath);
							if (file != NULL)
							{
								if (file->Exists())
								{
									if (file->ConformsTo( RIAFileKind::kSolutionFileKind) && (startupParameters->GetSolutionToLaunch() == NULL))
									{
										startupParameters->SetSolutionToLaunch( file);
									}
									else if (file->ConformsTo( L"com.netscape.javascript-source") && (startupParameters->GetJavaScriptFileToExecute() == NULL))
									{
										startupParameters->SetJavaScriptFileToExecute( file);
									}
								}
							}
							else
							{
								err = VE_MEMORY_FULL;
							}
							ReleaseRefCountable( &file);
						}
						
						// Skip unknown argument without generate an error
					}
				}
			}

			if (err == VE_OK && shouldQuit == false)
			{
				VRIAServerStartupMessage *msg = new VRIAServerStartupMessage( &application, startupParameters);
				if (msg != NULL)
				{
					msg->PostTo( VTaskMgr::Get()->GetMainTask());
					msg->Release();
				}
				ReleaseRefCountable( &startupParameters);
				
				application.Run();
			}
			else
			{
				ReleaseRefCountable( &startupParameters);
			}
		}
	}
	return 0;
}
Example #6
0
int main(int argc, char *argv[])
{
#if defined Q_WS_WIN
  OpenRPT::name = QObject::tr("Report Import Tool for Windows");
#elif defined Q_WS_X11
  OpenRPT::name = QObject::tr("Report Import Tool for Linux");
#elif defined Q_WS_MAC
  OpenRPT::name = QObject::tr("Report Import Tool for OS X");
#else
  OpenRPT::name = QObject::tr("Report Import Tool");
#endif

  QString username  = "";
  bool    haveUsername    = false;
  bool    haveDatabaseURL = false;
  bool    loggedIn        = false;

  QString databaseURL = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");

  if (argc > 1)
  {
    haveUsername        = false;
    bool    havePasswd  = false;
    QString passwd      = "";

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL=")) {
        haveDatabaseURL = true;
        databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd="))
      {
        havePasswd = true;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth"))
      {
        haveUsername = true;
        havePasswd   = true;
      }

    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the database driver. Please contact your systems administrator."));
        QApplication::exit(-1);
      }

      db.setUserName(username);
      db.setPassword(passwd);

      if (!db.open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        loggedIn = true;
    }

  }

  if(!loggedIn)
  {
    ParameterList params;
    params.append("name",      OpenRPT::name);
    params.append("copyright", OpenRPT::copyright);
    params.append("version",   OpenRPT::version);
    params.append("build",     OpenRPT::build);

    if (haveUsername)
      params.append("username", username);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    login newdlg(0, "", true);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
  }

  ImportWindow mainwin;
  mainwin.show();

  return app.exec();
}
Example #7
0
int main(int argc, char* argv[])
{
  QString username  = "";
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  _loggedIn        = FALSE;
  bool multitrans = false;
  bool debugpkg   = false;
  bool autoRunArg   = false;
  bool autoRunCheck = false;
  QString pkgfile = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");
#ifndef Q_WS_MACX
  app.setWindowIcon(QIcon(":/images/updater-32x32.png"));
#endif

  if (argc > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd          = FALSE;
    QString passwd              = "";

    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.startsWith("-help", Qt::CaseInsensitive))
      {
        qWarning("%s [ -databaseURL=PSQL7://hostname:port/databasename |"
                 " -username=databaseUserName -passwd=databasePassword |"
                 " -noauth ]"
                 " [ -multitrans ]"
                 " [ -debug ]"
                 " [ -file=updaterFile.gz ]"
                 " [ -autorun ]",
                 argv[0]);
        return 0;
      }
      else if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive))
      {
        haveDatabaseURL = TRUE;
        _databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-noauth")
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      }
      else if (argument.toLower() == "-multitrans")
        multitrans = true;
      else if (argument.toLower() == "-debug")
        debugpkg = true;
      else if (argument.startsWith("-file=", Qt::CaseInsensitive))
        pkgfile = argument.right(argument.size() - argument.indexOf("=") - 1);
      else if (argument.toLower() == "-autorun")
        autoRunArg = true;
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db.isValid())
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the databse driver. Please contact your systems adminstrator."));
        QApplication::exit(-1);
      }

      parseDatabaseURL(_databaseURL, protocol, hostName, dbName, port);
      db.setDatabaseName(dbName);
      db.setUserName(username);
      db.setPassword(passwd);
      db.setHostName(hostName);
      db.setPort(port.toInt());

      if (!db.open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        _loggedIn = TRUE;
    }

  }

  if(!_loggedIn)
  {
    ParameterList params;
    params.append("name", _name);
    params.append("copyright", _copyright.toAscii().data());
    params.append("version",   _version.toAscii().data());
    params.append("build", __DATE__ " " __TIME__); // use C++ string concat

    if (haveUsername)
      params.append("username", _user);

    if (haveDatabaseURL)
      params.append("databaseURL", _databaseURL.toAscii().data());

    if (_evaluation)
      params.append("evaluation");

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
    else
    {
      _databaseURL = newdlg._databaseURL;
      _user = newdlg._user;
      _loggedIn = TRUE;
    }

    QSqlQuery su;
    su.prepare("SELECT rolsuper FROM pg_roles WHERE (rolname=:user);");
    su.bindValue(":user", _user);
    su.exec();
    if (su.first())
    {
      if (! su.value(0).toBool() &&
          QMessageBox::question(0, QObject::tr("Not Super User"),
                                QObject::tr("You are not logged in as a "
                                            "database super user. The update "
                                            "may fail. Are you sure you want "
                                            "to continue?"),
                                QMessageBox::Yes,
                                QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
        return -2;
    }
    else if (su.lastError().type() != QSqlError::NoError &&
             QMessageBox::question(0, QObject::tr("System Error"),
                            QObject::tr("<p>The application received a database "
                                        "error while trying to check the user "
                                        "status of %1. Would you like to try to "
                                        "update anyway?<br><pre>%2")
                            .arg(_user)
                            .arg(su.lastError().databaseText()),
                            QMessageBox::Yes,
                            QMessageBox::No | QMessageBox::Default) == QMessageBox::No)
      return -3;
  }

  LoaderWindow * mainwin = new LoaderWindow();
  mainwin->setMultipleTransactions(multitrans);
  mainwin->setDebugPkg(debugpkg);
  if (! pkgfile.isEmpty())
  {
    autoRunCheck = mainwin->openFile(pkgfile);
  }

  // Start the upgrade if the -autoRun argument is used and file prereqs pass.
  if (autoRunArg)
  {
    bool successful = autoRunCheck && ! pkgfile.isEmpty();
    if (successful)
    {
      _autoRun = true;
      successful = mainwin->sStart();
    }
    if (successful)     // not else if
      return 0;
    else
    {
#ifdef Q_OS_WIN32
      mainwin->show();
#else
      qWarning("%s", qPrintable(mainwin->_text->toPlainText()));
      return 1;
#endif
    }
  }
  else
    mainwin->show();

  return app.exec();
}
///
/// Returns the type of decoding for selective decompilation.
///
std::string DecompilationArguments::selDecompDecoding() const {
	return argument(SelDecompDecodingId);
}
///
/// Returns a copy of the arguments with a differing argument of the given ID.
///
DecompilationArguments DecompilationArguments::withArgument(
		const std::string &id, const std::string &value) const {
	auto copy = *this;
	copy.argument(id, value);
	return copy;
}
///
/// Returns the ranges for selective decompilation.
///
std::string DecompilationArguments::selDecompRanges() const {
	return argument(SelDecompRangesId);
}
///
/// Sets type of decoding for selective decompilation.
///
DecompilationArguments &DecompilationArguments::selDecompDecoding(
		const std::string &decoding) {
	return argument(SelDecompDecodingId, decoding);
}
///
/// Sets ranges for selective decompilation.
///
/// Each range is of the form <tt>ADDRESS-ADDRESS</tt>, where <tt>ADDRESS</tt>
/// is a non-negative hexadecimal number. The ranges have to be divided by
/// commas. The addresses are case-insensitive, so <tt>0xFF</tt> is the same as
/// <tt>0xff</tt>. The addresses can be surrounded by spaces.
///
/// @par Examples
/// @code
/// args.selDecompRanges("0x0-0xffff")
/// args.selDecompRanges("0x0-0x2eef,0x3000-0x4fff")
/// args.selDecompRanges(" 0x0 - 0xfa, 0xFC - 0xFF ")
/// @endcode
///
DecompilationArguments &DecompilationArguments::selDecompRanges(
		const std::string &ranges) {
	return argument(SelDecompRangesId, ranges);
}
Example #13
0
int main(int argc, char *argv[])
{
  QMap<QString,ParamPair> paramList;
  QString username  = "";
  QString filename;
  QString printerName;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    print           = FALSE;
  bool    printPreview    = FALSE;
  bool    close           = FALSE;
  int     numCopies       = 1;
  // BVI::Sednacom
  // new options
  bool    pdfOutput = FALSE;
  QString pdfFileName;
  // BVI::Sednacom

  QString databaseURL = "";
  QString loadFromDB = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");

  OpenRPT::languages.addTranslationToDefault(":/common.qm");
  OpenRPT::languages.addTranslationToDefault(":/wrtembed.qm");
  OpenRPT::languages.addTranslationToDefault(":/renderer.qm");
  OpenRPT::languages.addTranslationToDefault(":/renderapp.qm");
  OpenRPT::languages.installSelected();

  if (app.argc() > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd          = FALSE;
    QString passwd              = "";

    QStringList arguments;
    QString firstArgument = QString( app.argv()[ 1 ] );

    if( firstArgument.startsWith("-fromStdin=", Qt::CaseInsensitive) ){
      QFile file;
      file.open(stdin, QIODevice::ReadOnly);
      QTextStream in(&file);
      in.setCodec( firstArgument.right( firstArgument.length() - 11 ).toAscii() ); 
      QString arg;
      while( arg.compare("-launch") !=0 ){
        arg = in.readLine();
        arguments << arg;
      }
      file.close();
    }
    else{
      for (int intCounter = 1; intCounter < app.argc(); intCounter++){
        arguments << QString (app.argv()[intCounter]);
      }
    }

    for ( QStringList::Iterator it = arguments.begin(); it != arguments.end(); ++it ) {
      QString argument( *it );

      if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive)) {
        haveDatabaseURL = TRUE;
        databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-noauth")
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      }
      else if (argument.startsWith("-numCopies=", Qt::CaseInsensitive)){
        numCopies = argument.right( argument.length() - 11).toInt();
      }
      else if (argument.toLower() == "-print")
        print = true;
      else if (argument.toLower() == "-printpreview")
        printPreview = true;
      else if (argument.toLower() == "-close")
        close = true;
      else if (argument.startsWith("-printerName=", Qt::CaseInsensitive))
        printerName = argument.right(argument.length() - 13);
      else if (argument.startsWith("-param=", Qt::CaseInsensitive))
      {
        QString str = argument.right(argument.length() - 7);
        bool active = true;
        QString name;
        QString type;
        QString value;
        QVariant var;
        int sep = str.indexOf('=');
        if(sep == -1)
          name = str;
        else
        {
          name = str.left(sep);
          value = str.right(str.length() - (sep + 1));
        }
        str = name;
        sep = str.indexOf(':');
        if(sep != -1)
        {
          name = str.left(sep);
          type = str.right(str.length() - (sep + 1));
        }
        if(name.startsWith("-"))
        {
          name = name.right(name.length() - 1);
          active = false;
        }
        else if(name.startsWith("+"))
          name = name.right(name.length() - 1);
        if(!value.isEmpty())
          var = XVariant::decode(type, value);
        paramList[name] = ParamPair(active, var);
      }
      // BVI::Sednacom
      // manage new arguments for CLI
      else if (argument.startsWith("-pdf", Qt::CaseInsensitive)) {
        pdfOutput = true ;
      }
      else if (argument.startsWith("-outpdf=", Qt::CaseInsensitive)) {
        pdfFileName = argument.right(argument.length() - 8 ) ;
      }
      // BVI::Sednacom
      else if (argument.startsWith("-loadfromdb=", Qt::CaseInsensitive))
        loadFromDB = argument.right(argument.length() - 12);
      else if (argument.toLower() == "-e")
        XSqlQuery::setNameErrorValue("Missing");
      else if(!argument.startsWith("-"))
        filename = argument;
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the database driver. Please contact your systems administrator."));
        QApplication::exit(-1);
      }

      db.setUserName(username);
      db.setPassword(passwd);

      if (!db.open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        loggedIn = TRUE;
    }

  }

  if(!loggedIn)
  {
    ParameterList params;
    params.append("name",      RenderWindow::name());
    params.append("copyright", OpenRPT::copyright);
    params.append("version",   OpenRPT::version);
    params.append("build",     OpenRPT::build);

    if (haveUsername)
      params.append("username", username);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    login newdlg(0, "", TRUE);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
  }

  // The following is code that works specifically with the xTuple ERP database
  // This should be expanded to be usefull when not connecting to an xTuple ERP
  // database as well. Command line option maybe?
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList paths;
    paths << "dict";
    paths << "";
    paths << "../dict";
    paths << app.applicationDirPath() + "/dict";
    paths << app.applicationDirPath();
    paths << app.applicationDirPath() + "/../dict";
#if defined Q_WS_MACX
    paths << app.applicationDirPath() + "/../../../dict";
    paths << app.applicationDirPath() + "/../../..";
#endif

    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    QString langext;
    if (!langq.value("lang_abbr2").toString().isEmpty() &&
        !langq.value("country_abbr").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString() + "_" +
                langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString();
    }

    if(!langext.isEmpty())
    {
      files << "reports." + langext;

      XSqlQuery pkglist("SELECT pkghead_name FROM pkghead WHERE packageIsEnabled(pkghead_name);");
      while(pkglist.next())
      {
        files << pkglist.value("pkghead_name").toString() + "." + langext;
      }
    }

    if (files.size() > 0)
    {
      QTranslator *translator = new QTranslator(&app);
      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit)
        {
          qDebug("looking for %s in %s", (*fit).toAscii().data(), (*pit).toAscii().data());
          if (translator->load(*fit, *pit))
          {
            app.installTranslator(translator);
            qDebug("installed %s/%s", (*pit).toAscii().data(), (*fit).toAscii().data());
            translator = new QTranslator(&app);
            break;
          }
        }
      }
    }
  }
  // END language loading code

  RenderWindow mainwin;

  mainwin._printerName = printerName;

  if(!filename.isEmpty())
    mainwin.fileOpen(filename);
  if(!loadFromDB.isEmpty())
    mainwin.fileLoad(loadFromDB);

  QMap<QString,ParamPair>::Iterator it;
  for ( it = paramList.begin(); it != paramList.end(); ++it ) {
    mainwin.updateParam(it.key(), it.value().second, it.value().first);
  }

  // BVI::Sednacom
  // do not display window for PDF output
  if (!pdfOutput)
    mainwin.show();
  // BVI::Sednacom

  if(print)
    mainwin.filePrint( numCopies );

  if(printPreview)
    mainwin.filePreview( numCopies );

  // BVI::Sednacom
  // generate the PDF
  if (pdfOutput)
    mainwin.filePrintToPDF(pdfFileName);  
  // BVI::Sednacom

  if(close)
  {
    mainwin.fileExit();
    return 0;
  }

  return app.exec();
}
Example #14
0
void TestController::initialize(int argc, const char* argv[])
{
    platformInitialize();

    bool printSupportedFeatures = false;

    for (int i = 1; i < argc; ++i) {
        std::string argument(argv[i]);

        if (argument == "--timeout" && i + 1 < argc) {
            m_longTimeout = atoi(argv[++i]);
            // Scale up the short timeout to match.
            m_shortTimeout = defaultShortTimeout * m_longTimeout / defaultLongTimeout;
            continue;
        }
        if (argument == "--pixel-tests") {
            m_dumpPixels = true;
            continue;
        }
        if (argument == "--verbose") {
            m_verbose = true;
            continue;
        }
        if (argument == "--gc-between-tests") {
            m_gcBetweenTests = true;
            continue;
        }
        if (argument == "--print-supported-features") {
            printSupportedFeatures = true;
            break;
        }

        // Skip any other arguments that begin with '--'.
        if (argument.length() >= 2 && argument[0] == '-' && argument[1] == '-')
            continue;

        m_paths.push_back(argument);
    }

    if (printSupportedFeatures) {
        // FIXME: On Windows, DumpRenderTree uses this to expose whether it supports 3d
        // transforms and accelerated compositing. When we support those features, we
        // should match DRT's behavior.
        exit(0);
    }

    m_usingServerMode = (m_paths.size() == 1 && m_paths[0] == "-");
    if (m_usingServerMode)
        m_printSeparators = true;
    else
        m_printSeparators = m_paths.size() > 1;

    initializeInjectedBundlePath();
    initializeTestPluginDirectory();

    WKRetainPtr<WKStringRef> pageGroupIdentifier(AdoptWK, WKStringCreateWithUTF8CString("WebKitTestRunnerPageGroup"));
    m_pageGroup.adopt(WKPageGroupCreateWithIdentifier(pageGroupIdentifier.get()));

    m_context.adopt(WKContextCreateWithInjectedBundlePath(injectedBundlePath()));

    const char* path = libraryPathForTesting();
    if (path) {
        Vector<char> databaseDirectory(strlen(path) + strlen("/Databases") + 1);
        sprintf(databaseDirectory.data(), "%s%s", path, "/Databases");
        WKRetainPtr<WKStringRef> databaseDirectoryWK(AdoptWK, WKStringCreateWithUTF8CString(databaseDirectory.data()));
        WKContextSetDatabaseDirectory(m_context.get(), databaseDirectoryWK.get());
    }

    platformInitializeContext();

    WKContextInjectedBundleClient injectedBundleClient = {
        0,
        this,
        didReceiveMessageFromInjectedBundle,
        didReceiveSynchronousMessageFromInjectedBundle
    };
    WKContextSetInjectedBundleClient(m_context.get(), &injectedBundleClient);

    _WKContextSetAdditionalPluginsDirectory(m_context.get(), testPluginDirectory());

    m_mainWebView = adoptPtr(new PlatformWebView(m_context.get(), m_pageGroup.get()));

    WKPageUIClient pageUIClient = {
        0,
        this,
        createOtherPage,
        0, // showPage
        0, // close
        0, // takeFocus
        0, // focus
        0, // unfocus
        0, // runJavaScriptAlert        
        0, // runJavaScriptConfirm
        0, // runJavaScriptPrompt
        0, // setStatusText
        0, // mouseDidMoveOverElement
        0, // missingPluginButtonClicked
        0, // didNotHandleKeyEvent
        0, // toolbarsAreVisible
        0, // setToolbarsAreVisible
        0, // menuBarIsVisible
        0, // setMenuBarIsVisible
        0, // statusBarIsVisible
        0, // setStatusBarIsVisible
        0, // isResizable
        0, // setIsResizable
        getWindowFrameMainPage,
        setWindowFrameMainPage,
        runBeforeUnloadConfirmPanel,
        0, // didDraw
        0, // pageDidScroll
        exceededDatabaseQuota,
        0, // runOpenPanel
        0, // decidePolicyForGeolocationPermissionRequest
        0, // headerHeight
        0, // footerHeight
        0, // drawHeader
        0, // drawFooter
        0, // printFrame
        0, // runModal
        0, // didCompleteRubberBandForMainFrame
        0, // saveDataToFileInDownloadsFolder
        0, // shouldInterruptJavaScript
    };
    WKPageSetPageUIClient(m_mainWebView->page(), &pageUIClient);

    WKPageLoaderClient pageLoaderClient = {
        0,
        this,
        0, // didStartProvisionalLoadForFrame
        0, // didReceiveServerRedirectForProvisionalLoadForFrame
        0, // didFailProvisionalLoadWithErrorForFrame
        0, // didCommitLoadForFrame
        0, // didFinishDocumentLoadForFrame
        didFinishLoadForFrame,
        0, // didFailLoadWithErrorForFrame
        0, // didSameDocumentNavigationForFrame
        0, // didReceiveTitleForFrame
        0, // didFirstLayoutForFrame
        0, // didFirstVisuallyNonEmptyLayoutForFrame
        0, // didRemoveFrameFromHierarchy
        0, // didDisplayInsecureContentForFrame
        0, // didRunInsecureContentForFrame
        0, // canAuthenticateAgainstProtectionSpaceInFrame
        0, // didReceiveAuthenticationChallengeInFrame
        0, // didStartProgress
        0, // didChangeProgress
        0, // didFinishProgress
        0, // didBecomeUnresponsive
        0, // didBecomeResponsive
        processDidCrash,
        0, // didChangeBackForwardList
        0, // shouldGoToBackForwardListItem
        0  // didFailToInitializePlugin
    };
    WKPageSetPageLoaderClient(m_mainWebView->page(), &pageLoaderClient);
}
//------------------------------do_call----------------------------------------
// Handle your basic call.  Inline if we can & want to, else just setup call.
void Parse::do_call() {
  // It's likely we are going to add debug info soon.
  // Also, if we inline a guy who eventually needs debug info for this JVMS,
  // our contribution to it is cleaned up right here.
  kill_dead_locals();

  // Set frequently used booleans
  bool is_virtual = bc() == Bytecodes::_invokevirtual;
  bool is_virtual_or_interface = is_virtual || bc() == Bytecodes::_invokeinterface;
  bool has_receiver = is_virtual_or_interface || bc() == Bytecodes::_invokespecial;

  // Find target being called
  bool             will_link;
  ciMethod*        dest_method   = iter().get_method(will_link);
  ciInstanceKlass* holder_klass  = dest_method->holder();
  ciKlass* holder = iter().get_declared_method_holder();
  ciInstanceKlass* klass = ciEnv::get_instance_klass_for_declared_method_holder(holder);

  int   nargs    = dest_method->arg_size();
  // See if the receiver (if any) is NULL, hence we always throw BEFORE
  // attempting to resolve the call or initialize the holder class.  Doing so
  // out of order opens a window where we can endlessly deopt because the call
  // holder is not initialized, but the call never actually happens (forcing
  // class initialization) because we only see NULL receivers.
  CPData_Invoke *caller_cpdi = cpdata()->as_Invoke(bc());
  debug_only( assert(caller_cpdi->is_Invoke(), "Not invoke!") );
  if( is_virtual_or_interface &&
      _gvn.type(stack(sp() - nargs))->higher_equal(TypePtr::NULL_PTR) ) {
    builtin_throw( Deoptimization::Reason_null_check, "null receiver", caller_cpdi, caller_cpdi->saw_null(), /*must_throw=*/true );
    return;
  }

  // uncommon-trap when callee is unloaded, uninitialized or will not link
  // bailout when too many arguments for register representation
  if (!will_link || can_not_compile_call_site(dest_method, klass)) {
    return;
  }
assert(FAM||holder_klass->is_loaded(),"");
  assert(dest_method->is_static() == !has_receiver, "must match bc");
  // Note: this takes into account invokeinterface of methods declared in java/lang/Object,
  // which should be invokevirtuals but according to the VM spec may be invokeinterfaces
  assert(holder_klass->is_interface() || holder_klass->super() == NULL || (bc() != Bytecodes::_invokeinterface), "must match bc");
  // Note:  In the absence of miranda methods, an abstract class K can perform
  // an invokevirtual directly on an interface method I.m if K implements I.

  // ---------------------
  // Does Class Hierarchy Analysis reveal only a single target of a v-call?
  // Then we may inline or make a static call, but become dependent on there being only 1 target.
  // Does the call-site type profile reveal only one receiver?
  // Then we may introduce a run-time check and inline on the path where it succeeds.
  // The other path may uncommon_trap, check for another receiver, or do a v-call.

  // Choose call strategy.
  bool call_is_virtual = is_virtual_or_interface;
  int vtable_index = methodOopDesc::invalid_vtable_index;
  ciMethod* call_method = dest_method;

  // Try to get the most accurate receiver type
  if (is_virtual_or_interface) {
    Node*             receiver_node = stack(sp() - nargs);
const TypeInstPtr*inst_type=_gvn.type(receiver_node)->isa_instptr();
    if( inst_type ) {
ciInstanceKlass*ikl=inst_type->klass()->as_instance_klass();
      // If the receiver is not yet linked then: (1) we never can make this
      // call because no objects can be created until linkage, and (2) CHA
      // reports incorrect answers... so do not bother with making the call
      // until after the klass gets linked.
      ciInstanceKlass *ikl2 = ikl->is_subtype_of(klass) ? ikl : klass;
if(!ikl->is_linked()){
        uncommon_trap(Deoptimization::Reason_uninitialized,klass,"call site where receiver is not linked",false);
        return;
      }
    }
    const TypeOopPtr* receiver_type = _gvn.type(receiver_node)->isa_oopptr();
    ciMethod* optimized_virtual_method = optimize_inlining(method(), bci(), klass, dest_method, receiver_type);

    // Have the call been sufficiently improved such that it is no longer a virtual?
    if (optimized_virtual_method != NULL) {
      call_method     = optimized_virtual_method;
      call_is_virtual = false;
    } else if (false) {
      // We can make a vtable call at this site
      vtable_index = call_method->resolve_vtable_index(method()->holder(), klass);
    }
  }

  // Note:  It's OK to try to inline a virtual call.
  // The call generator will not attempt to inline a polymorphic call
  // unless it knows how to optimize the receiver dispatch.
bool try_inline=(C->do_inlining()||InlineAccessors)&&
                    (!C->method()->should_disable_inlining()) &&
                    (call_method->number_of_breakpoints() == 0);

  // Get profile data for the *callee*.  First see if we have precise
  // CodeProfile for this exact inline because C1 inlined it already.
  CodeProfile *callee_cp;
  int callee_cp_inloff;

  if( caller_cpdi->inlined_method_oid() == call_method->objectId() ) {
    callee_cp = c1_cp();        // Use same CodeProfile as current
    callee_cp_inloff = caller_cpdi->cpd_offset(); // But use inlined portion
  } else {
    // If callee has a cp, clone it and use
    callee_cp = call_method->codeprofile(true);
    callee_cp_inloff = 0;

    if (callee_cp || FAM) {
      // The cloned cp needs to be freed later
      Compile* C = Compile::current();
      C->record_cloned_cp(callee_cp);
    } else { // Had profile info at top level, but not for this call site?
      // callee_cp will hold the just created cp, or whatever cp allocated by
      // other thread which wins the race in set_codeprofile
      callee_cp = call_method->set_codeprofile(CodeProfile::make(call_method));
    }
  }

  CPData_Invoke *c2_caller_cpdi = UseC1 ? c2cpdata()->as_Invoke(bc()) : NULL;

  // ---------------------
  inc_sp(- nargs);              // Temporarily pop args for JVM state of call
  JVMState* jvms = sync_jvms();

  // ---------------------
  // Decide call tactic.
  // This call checks with CHA, the interpreter profile, intrinsics table, etc.
  // It decides whether inlining is desirable or not.
CallGenerator*cg=C->call_generator(call_method,vtable_index,call_is_virtual,jvms,try_inline,prof_factor(),callee_cp,callee_cp_inloff,c2_caller_cpdi,caller_cpdi);

  // ---------------------
  // Round double arguments before call
  round_double_arguments(dest_method);

#ifndef PRODUCT
  // Record first part of parsing work for this call
  parse_histogram()->record_change();
#endif // not PRODUCT

  assert(jvms == this->jvms(), "still operating on the right JVMS");
  assert(jvms_in_sync(),       "jvms must carry full info into CG");

  // save across call, for a subsequent cast_not_null.
  Node* receiver = has_receiver ? argument(0) : NULL;

  JVMState* new_jvms = cg->generate(jvms, caller_cpdi, is_private_copy());
  if( new_jvms == NULL ) {      // Did it work?
    // When inlining attempt fails (e.g., too many arguments),
    // it may contaminate the current compile state, making it
    // impossible to pull back and try again.  Once we call
    // cg->generate(), we are committed.  If it fails, the whole
    // compilation task is compromised.
    if (failing())  return;
    if (PrintOpto || PrintInlining || PrintC2Inlining) {
      // Only one fall-back, so if an intrinsic fails, ignore any bytecodes.
      if (cg->is_intrinsic() && call_method->code_size() > 0) {
C2OUT->print("Bailed out of intrinsic, will not inline: ");
        call_method->print_name(C2OUT); C2OUT->cr();
      }
    }
    // This can happen if a library intrinsic is available, but refuses
    // the call site, perhaps because it did not match a pattern the
    // intrinsic was expecting to optimize.  The fallback position is
    // to call out-of-line.
    try_inline = false;  // Inline tactic bailed out.
cg=C->call_generator(call_method,vtable_index,call_is_virtual,jvms,try_inline,prof_factor(),c1_cp(),c1_cp_inloff(),c2_caller_cpdi,caller_cpdi);
new_jvms=cg->generate(jvms,caller_cpdi,is_private_copy());
assert(new_jvms!=NULL,"call failed to generate:  calls should work");
    if (c2_caller_cpdi) c2_caller_cpdi->_inlining_failure_id = IF_GENERALFAILURE;
  }

  if (cg->is_inline()) {
    C->env()->notice_inlined_method(call_method);
  }

  // Reset parser state from [new_]jvms, which now carries results of the call.
  // Return value (if any) is already pushed on the stack by the cg.
  add_exception_states_from(new_jvms);
  if (new_jvms->map()->control() == top()) {
    stop_and_kill_map();
  } else {
    assert(new_jvms->same_calls_as(jvms), "method/bci left unchanged");
    set_jvms(new_jvms);
  }

  if (!stopped()) {
    // This was some sort of virtual call, which did a null check for us.
    // Now we can assert receiver-not-null, on the normal return path.
    if (receiver != NULL && cg->is_virtual()) {
Node*cast=cast_not_null(receiver,true);
      // %%% assert(receiver == cast, "should already have cast the receiver");
    }

    // Round double result after a call from strict to non-strict code
    round_double_result(dest_method);

    // If the return type of the method is not loaded, assert that the
    // value we got is a null.  Otherwise, we need to recompile.
    if (!dest_method->return_type()->is_loaded()) {
      // If there is going to be a trap, put it at the next bytecode:
      set_bci(iter().next_bci());
      do_null_assert(peek(), T_OBJECT);
      set_bci(iter().cur_bci()); // put it back
    } else {
      assert0( call_method->return_type()->is_loaded() );
      BasicType result_type = dest_method->return_type()->basic_type();
if(result_type==T_OBJECT||result_type==T_ARRAY){
        const Type *t = peek()->bottom_type();
        assert0( t == TypePtr::NULL_PTR || t->is_oopptr()->klass()->is_loaded() );
      }
    }
  }

  // Restart record of parsing work after possible inlining of call
#ifndef PRODUCT
  parse_histogram()->set_initial_state(bc());
#endif
}
///
/// Sets the mode.
///
/// Available modes are:
/// - <tt>bin</tt>: %Decompilation of a binary file in the ELF or WinPE format.
/// - <tt>c</tt>: %Decompilation of a C file.
///
DecompilationArguments &DecompilationArguments::mode(const std::string &mode) {
	return argument(ModeId, mode);
}
Example #17
0
int option_parser::parse_option_value(int argc, char * argv[], int argi, int index, option * operand)
{
	std::string argument(argv[argi]);

	// parsing options of type --option=value (-o=value).
	if (index < static_cast<int>(argument.size())) {
		if (argument[index] != PARSE_OPTION_VALUE_DELIMITER) {
			print_error_header(argc, argv, argi, index, "option value expected");
			return PARSE_ERROR;
		}

		std::string option_value = argument.substr(index + 1);
		if (!operand->parse_value(option_value)) {
			print_error_header(argc,
				argv,
				argi,
				index + 1,
				"failed to parse value or restriction does not accept it");

			return PARSE_ERROR;
		}

		return argi + 1;
	}

	// parsing option of type --option value1 value2 ... (-o value1 value2 ...).
	++argi;
	size_type parsed = 0;
	const size_type max_values = operand->size();
	for (; argi < argc; ++argi, ++parsed) {

		// everything is already parsed.
		if (parsed == max_values) {
			break;
		}

		// we have another option or delimiter.
		if (type(argv[argi]) != ARGUMENT) {
			break;
		}

		// parse argument.
		if (!operand->parse_value(argv[argi])) {
			print_error_header(argc,
				argv,
				argi,
				0,
				"failed to parse value or restriction does not accept it");

			return PARSE_ERROR;
		}
	}

	if ((parsed == 0) && (operand->value_category() == REQUIRED)) {
		print_error_header(argc,
			argv,
			argi - 1,
			index,
			"option has required value");

			return PARSE_ERROR;
	}

	return argi;
}
///
/// Returns the mode.
///
std::string DecompilationArguments::mode() const {
	return argument(ModeId);
}
Example #19
0
FeatureFunction *ConstructKenLM(size_t startInd, const std::string &lineOrig)
{
  FactorType factorType = 0;
  string filePath;
  util::LoadMethod load_method = util::POPULATE_OR_READ;

  util::TokenIter<util::SingleCharacter, true> argument(lineOrig, ' ');
  ++argument; // KENLM

  util::StringStream line;
  line << "KENLM";

  for (; argument; ++argument) {
    const char *equals = std::find(argument->data(),
        argument->data() + argument->size(), '=');
    UTIL_THROW_IF2(equals == argument->data() + argument->size(),
        "Expected = in KenLM argument " << *argument);
    StringPiece name(argument->data(), equals - argument->data());
    StringPiece value(equals + 1,
        argument->data() + argument->size() - equals - 1);
    if (name == "factor") {
      factorType = boost::lexical_cast<FactorType>(value);
    }
    else if (name == "order") {
      // Ignored
    }
    else if (name == "path") {
      filePath.assign(value.data(), value.size());
    }
    else if (name == "lazyken") {
      // deprecated: use load instead.
      load_method =
          boost::lexical_cast<bool>(value) ?
              util::LAZY : util::POPULATE_OR_READ;
    }
    else if (name == "load") {
      if (value == "lazy") {
        load_method = util::LAZY;
      }
      else if (value == "populate_or_lazy") {
        load_method = util::POPULATE_OR_LAZY;
      }
      else if (value == "populate_or_read" || value == "populate") {
        load_method = util::POPULATE_OR_READ;
      }
      else if (value == "read") {
        load_method = util::READ;
      }
      else if (value == "parallel_read") {
        load_method = util::PARALLEL_READ;
      }
      else {
        UTIL_THROW2("Unknown KenLM load method " << value);
      }
    }
    else {
      // pass to base class to interpret
      line << " " << name << "=" << value;
    }
  }

  return ConstructKenLM(startInd, line.str(), filePath, factorType, load_method);
}
TEST(StanGmArgumentsConfiguration, TestRandomWithoutMethod) {
  
  // Prepare model
  std::vector<std::string> model_path;
  model_path.push_back("src");
  model_path.push_back("test");
  model_path.push_back("gm");
  model_path.push_back("arguments");
  model_path.push_back("test_model");
  
  // Prepare arguments
  std::stringstream s;
  
  std::vector<stan::gm::argument*> valid_arguments;
  valid_arguments.push_back(new stan::gm::arg_random());
  
  stan::gm::argument_probe probe(valid_arguments);
  probe.probe_args(s);
  
  // Check argument consistency
  bool expected_success = false;
  
  std::string l1;
  std::stringstream expected_output;
  std::stringstream output;
  
  while (s.good()) {
    
    std::getline(s, l1);
    if (!s.good()) continue;
    
    if      (l1 == "good") expected_success = true;
    else if (l1 == "bad") expected_success = false;
    else if (l1 != "") expected_output << l1 << std::endl;
    else {
      
      int n_output = 0;
      
      std::string l2;
      std::string argument("");
      
      while (expected_output.good()) {
        std::getline(expected_output, l2);
        if (!expected_output.good()) continue;
        clean_line(l2);
        argument += " " + l2;
        ++n_output;
      }
      
      if (argument.length() == 0) continue;
      
      remove_duplicates(argument);
      
      std::string command = convert_model_path(model_path) + argument;
      run_command_output out = run_command(command);
      
      expected_output.clear();
      expected_output.seekg(std::ios_base::beg);
      
      if (expected_success == false) {
        
        unsigned int c1 = out.output.find("is not");
        out.output.erase(0, c1);
        unsigned int c2 = out.output.find(" \"");
        unsigned int c3 = out.output.find("Failed to parse");
        out.output.replace(c2, c3 - c2, "\n");
        
        expected_output.str(std::string());
        expected_output << "is not a valid value for" << std::endl;
        expected_output << "Failed to parse arguments, terminating Stan" << std::endl;
        n_output = 2;
        
      }
      else {
        expected_output.str(std::string());
        expected_output << "A method must be specified!" << std::endl;
        expected_output << "Failed to parse arguments, terminating Stan" << std::endl;
        n_output = 2;
      }
      
      output.str(out.output);
      
      for (int i = 0; i < n_output; ++i) {
        
        std::string expected_line;
        std::getline(expected_output, expected_line);
        
        std::string actual_line;
        std::getline(output, actual_line);
        
        EXPECT_EQ(expected_line, actual_line);
        
      }
      
      expected_output.clear();
      expected_output.seekg(std::ios_base::beg);
      expected_output.str(std::string());
      
    }
    
  }
  
  for (size_t i = 0; i < valid_arguments.size(); ++i)
    delete valid_arguments.at(i);
  
}
Example #21
0
 void operator () (const T& argument)
 {
    static_assert(std::is_base_of<Dumpable, T>::value, "argument type is not derived from dumpable");
    argument();
 }
/**
 * \brief Main function for the snowfocus program
 */
int	main(int argc, char *argv[]) {
	debug_set_ident("snowfocus");
	snowstar::CommunicatorSingleton	cs(argc, argv);
	Ice::CommunicatorPtr	ic = cs.get();

	bool	remote = false;
	int	steps = 10;
	double	exposuretime = 1.0;
	double	temperature = std::numeric_limits<double>::quiet_NaN();
	std::string	binning;
	std::string	frame;
	std::string	filtername;
	astro::focusing::Focusing::method_type	method
		= astro::focusing::Focusing::BRENNER;

	int	c;
	int	longindex;
	while (EOF != (c = getopt_long(argc, argv, "b:c:de:f:hi:m:r:Rt:",
		longopts, &longindex)))
		switch (c) {
		case 'b':
			binning = optarg;
			break;
		case 'c':
			astro::config::Configuration::set_default(optarg);
			break;
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		case 'e':
			exposuretime = std::stod(optarg);
			break;
		case 'f':
			filtername = optarg;
			break;
		case 'h':
			usage(argv[0]);
			return EXIT_SUCCESS;
		case 'm':
			method = astro::focusing::Focusing::string2method(optarg);
			break;
		case 'r':
			frame = optarg;
			break;
		case 'R':
			remote = true;
			break;
		case 's':
			steps = std::stoi(optarg);
			break;
		case 't':
			temperature = std::stod(optarg);
			break;
		default:
			throw std::runtime_error("unknown option");
		}

	// the next argument is the command
	if (argc <= optind) {
		short_usage(argv[0]);
		throw std::runtime_error("missing service argument");
	}
	std::string	argument(argv[optind++]);
	if ("help" == argument) {
		usage(argv[0]);
		return EXIT_SUCCESS;
	}
	astro::ServerName	servername(argument);
	if (argc <= optind) {
		short_usage(argv[0]);
		throw std::runtime_error("missing instrument name argument");
	}

	// make sure the server offers instruments and guiding
	if (!remote) {
		astro::discover::ServiceDiscoveryPtr     sd
			= astro::discover::ServiceDiscovery::get();
		sd->start();
		astro::discover::ServiceObject  so
			= sd->find(sd->waitfor(argument));
		if (!so.has(astro::discover::ServiceSubset::INSTRUMENTS)) {
			std::cerr << "service '" << argument;
			std::cerr << "' does not offer focusing service";
			std::cerr << std::endl;
			return EXIT_FAILURE;
		}
		if (!so.has(astro::discover::ServiceSubset::FOCUSING)) {
			std::cerr << "service '" << argument;
			std::cerr << "' does not offer focusing service";
			std::cerr << std::endl;
			return EXIT_FAILURE;
		}
	}

	std::string	instrumentname(argv[optind++]);
	if (argc <= optind) {
		short_usage(argv[0]);
		throw std::runtime_error("missing command argument");
	}
	std::string	command = argv[optind++];
	debug(LOG_DEBUG, DEBUG_LOG, 0, "command: %s", command.c_str()); 

	// get a proxy for the instruments
	Ice::ObjectPrx	base = ic->stringToProxy(
				servername.connect("Instruments"));
	InstrumentsPrx	instruments = InstrumentsPrx::checkedCast(base);

	// get the configuration
	astro::config::ConfigurationPtr	config
		= astro::config::Configuration::get();

	// check whether we have an instrument
	if (0 == instrumentname.size()) {
		throw std::runtime_error("instrument name not set");
	}
	RemoteInstrument	instrument(instruments, instrumentname);

	// make sure the server names for focuser and ccd are identical
	astro::ServerName	targetserver
					= instrument.servername(InstrumentCCD);
	if (targetserver != instrument.servername(InstrumentFocuser)) {
		throw std::runtime_error("ccd and focuser are on different "
			"servers");
	}

	// get the device names
	CcdPrx	ccdprx = instrument.ccd();
	std::string	ccdname = ccdprx->getName();
	FocuserPrx	focuserprx = instrument.focuser();
	std::string	focusername = focuserprx->getName();
	debug(LOG_DEBUG, DEBUG_LOG, 0, "ccd: %s focuser: %s", ccdname.c_str(),
		focusername.c_str());

	// first get a connection to the server
	Ice::ObjectPrx	fbase = ic->stringToProxy(
				targetserver.connect("FocusingFactory"));
	FocusingFactoryPrx	focusingfactory
		= FocusingFactoryPrx::checkedCast(fbase);

	// get the focusing interface
	FocusingPrx	focusing = focusingfactory->get(ccdname, focusername);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "got a focusing proxy");

	// creating a callback
	Ice::ObjectPtr	callback = new FocusCallbackI();
	CallbackAdapter	adapter(ic);
	Ice::Identity	ident = adapter.add(callback);
	focusing->ice_getConnection()->setAdapter(adapter.adapter());
	debug(LOG_DEBUG, DEBUG_LOG, 0, "callback installed");

	// handle the simple commands
	if (command == "help") {
		short_usage(argv[0]);
		return EXIT_SUCCESS;
	}

	if (command == "status") {
		std::cout << "status: ";
		FocusState	state = focusing->status();
		std::cout << focusingstate2string(state);
		switch (state) {
		case FocusFOCUSED:
			std::cout << " ";
			std::cout << focusing->getFocuser()->current();
			break;
		default:
			break;
		}
		std::cout << std::endl;
		return EXIT_SUCCESS;
	}

	if (command == "history") {
		show_history(focusing->history());
		return EXIT_SUCCESS;
	}

	if (command == "monitor") {
		std::cout << "current status: ";
		std::cout << focusingstate2string(focusing->status());
		std::cout << std::endl;
		focusing->registerCallback(ident);
		signal(SIGINT, handler);
		while (!signal_received) {
			sleep(1);
		}
		focusing->unregisterCallback(ident);
		return EXIT_SUCCESS;
	}

	if (command == "cancel") {
		focusing->cancel();
		std::cout << "cancel command sent" << std::endl;
		return EXIT_SUCCESS;
	}

	if (command == "repository") {
		if (optind < argc) {
			std::string	reponame(argv[optind]);
			focusing->setRepositoryName(reponame);
		} else {
			std::string	reponame
				= focusing->getRepositoryName();
			if (reponame.size() > 0) {
				std::cout << "repository: " << reponame;
				std::cout << std::endl;
			} else {
				std::cout << "repository not set" << std::endl;
			}
		}
		return EXIT_SUCCESS;
	}

	// throw exception for unknown commands
	if (command != "start") {
		short_usage(argv[0]);
		throw std::runtime_error("unknown command");
	}
	debug(LOG_DEBUG, DEBUG_LOG, 0, "executing start command");

	// make sure temperature is set
	CoolerTask	coolertask(instrument, temperature);
	coolertask.stop_on_exit(true);
	coolertask.wait();

	// next two arguments are the interval boundaries
	if ((argc - optind) < 2) {
		short_usage(argv[0]);
		throw std::runtime_error("missing interval arguments");
	}
	int	min = std::stoi(argv[optind++]);
	int	max = std::stoi(argv[optind++]);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "interval [%d,%d]", min, max);
	if (min >= max) {
		short_usage(argv[0]);
		throw std::runtime_error("not an interval");
	}
	debug(LOG_DEBUG, DEBUG_LOG, 0, "focusing in interval [%d,%d]",
		min, max);

	// ensure that focuser is ready
	FocusState	state = focusing->status();
	debug(LOG_DEBUG, DEBUG_LOG, 0, "current state = %d", state);
	if ((state == FocusMOVING) && (state == FocusMEASURING)) {
		short_usage(argv[0]);
		throw std::runtime_error("already focusing");
	}
	debug(LOG_DEBUG, DEBUG_LOG, 0, "focuser available");

	// set up the exposure
	astro::camera::Exposure	exposure;
	exposure.purpose(astro::camera::Exposure::focus);
	exposure.exposuretime(exposuretime);
	if (binning.size() > 0) {
		exposure.mode(astro::image::Binning(binning));
	}
	exposure.shutter(astro::camera::Shutter::OPEN);
	if (frame.size() > 0) {
		exposure.frame(astro::image::ImageRectangle(frame));
	}

	// set up the focusing
	focusing->setSteps(steps);
	focusing->setMethod(convert(method));
	focusing->setExposure(convert(exposure));
	debug(LOG_DEBUG, DEBUG_LOG, 0, "focusing set up %d steps, method %s",
		steps,
		astro::focusing::Focusing::method2string(method).c_str());

	// start the focusing process
	debug(LOG_DEBUG, DEBUG_LOG, 0, "starting between %d and %d", min, max);
	focusing->start(min, max);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "focusing started, status: %d",
		focusing->status());

	// wait for the process to complete
	bool	completed = false;
	signal(SIGINT, handler);
	do {
		sleep(1);
		switch (focusing->status()) {
        	case FocusIDLE:
        	case FocusMOVING:
        	case FocusMEASURING:
			break;
        	case FocusFOCUSED:
        	case FocusFAILED:
			completed = true;
			break;
		}
	} while ((!completed) && (!signal_received));
	if (completed) {
		std::cout << "final focus position: " << focuserprx->current();
		std::cout << std::endl;

		// display the history
		show_history(focusing->history());
	} else {
		std::cout << "focusing incomplete" << std::endl;
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}