Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
    KAboutData aboutData("kappfinder", I18N_NOOP("KAppfinder"), "1.0", description, KAboutData::License_GPL,
                         "(c) 1998-2000, Matthias Hoelzer-Kluepfel");
    aboutData.addAuthor("Matthias Hoelzer-Kluepfel", 0, "*****@*****.**");
    aboutData.addAuthor("Tobias Koenig", 0, "*****@*****.**");

    KCmdLineArgs::init(argc, argv, &aboutData);
    KCmdLineArgs::addCmdLineOptions(options);
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication app;

    TopLevel *dlg = new TopLevel(args->getOption("dir"));
    app.setMainWidget(dlg);

    return dlg->exec();
}
Ejemplo n.º 2
0
int main(int argc, char** argv)
{
    qInstallMsgHandler(messageOutput);
    KAboutData aboutData( "duchaintokross", 0, ki18n( "duchaintokross" ),
                          "33", ki18n("Wrapper generator from C++ to Kross"), KAboutData::License_GPL,
                          ki18n( "(c) 2008, The KDevelop developers" ), KLocalizedString(), "http://www.kdevelop.org" );
    KCmdLineArgs::init( argc, argv, &aboutData );
    KCmdLineOptions options;
    options.add("+file", ki18n("input .cpp file"), QByteArray());
    options.add("I <includes>", ki18n("include directories for the parser (colon separated)"), QByteArray());
    options.add("i <includes>", ki18n("include directories that the generated implementation file will have (colon separated)"), QByteArray());
    options.add("b <builddir>", ki18n("build dir where the Makefile for the input is added"), QByteArray());
    options.add("F <filename>", ki18n("filename to be used for the .moc and the .h file"), QByteArray());
    options.add("D <directory>", ki18n("directory where to put the .h output"), QByteArray());
    options.add("o <output>", ki18n("directory where to put the code output"), QByteArray());
    options.add("impl", ki18n("create implementation"), QByteArray());
    options.add("verbose", ki18n("Verbose output"), QByteArray());
    KCmdLineArgs::addCmdLineOptions( options );
    
    KApplication app;
    ConsoleIDEExtension::init();
    Core::initialize(0, Core::NoUi);
    
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    KUrl::List includes;
    KUrl input;
    
    for(int i=0; i<args->count(); i++)
    {
        QString arg=args->arg(i);
        input=KUrl(arg);
    }
    
    foreach(const QString& inc, args->getOption("I").split(':'))
        includes << KUrl(inc);
    KUrl builddir(args->getOption("b"));
    QString filename(args->getOption("F"));
    QString directory(args->getOption("D"));
    QStringList toinclude(args->getOption("i").split(':'));
    QString output(args->getOption("o"));
    verbose=args->isSet("verbose");
    bool createImpl=args->isSet("impl");
    args->clear();
    
    DUChainExtractor e;
    kDebug() << input << builddir << includes << toinclude;
    e.setWriteImpl(createImpl);
    e.start(input, builddir, includes, filename, directory, toinclude, output);
    
    return app.exec();
}
Ejemplo n.º 3
0
void Widgets::handleXGeometry(QWidget * dlg)
{
#ifdef Q_WS_X11
	QString geometry;
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
	if (args && args->isSet("geometry"))
		geometry = args->getOption("geometry");
    if ( ! geometry.isEmpty()) {
	int x, y;
	int w, h;
	int m = XParseGeometry( geometry.toLatin1(), &x, &y, (unsigned int*)&w, (unsigned int*)&h);
	if ( (m & XNegative) )
	    x = KApplication::desktop()->width()  + x - w;
	if ( (m & YNegative) )
	    y = KApplication::desktop()->height() + y - h;
	dlg->setGeometry(x, y, w, h);
	// kDebug() << "x: " << x << "  y: " << y << "  w: " << w << "  h: " << h;
    }
#endif
}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
    KAboutData about("khotnewstuff", "KHotNewStuff", "0.2");
    KCmdLineArgs *args;

    KCmdLineArgs::init(argc, argv, &about);
    KCmdLineArgs::addCmdLineOptions(op);
    args = KCmdLineArgs::parsedArgs();

    KApplication i;

    KNS::DownloadDialog d;
    if(args->isSet("type"))
        d.setType(args->getOption("type"));
    if(args->count() == 1)
        d.setProviderList(args->arg(0));
    d.load();
    d.exec();

    return 0;
}
Ejemplo n.º 5
0
int main(int argc, char *argv[])
{
    KAboutData about("reviewboardtest", 0, ki18n(("ReviewBoard Test")), "0.10", ki18n("Test ReviewBoard support"),
            KAboutData::License_GPL, ki18n("(C) 2010 Aleix Pol Gonzalez"));
    about.addAuthor( ki18n("Aleix Pol Gonzalez"), KLocalizedString(), "*****@*****.**" );
    
    KCmdLineArgs::init( argc, argv, &about );
    KCmdLineOptions options;
    options.add("+patch", ki18n( "Patch" ));
    options.add("basedir <dir>", ki18n( "Base Directory" ));
    KCmdLineArgs::addCmdLineOptions( options );
    KApplication app;
    
    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    
    ReviewPatchDialog d;
    
    KUrl patch(args->arg(0));
    QString basedir=args->getOption("basedir");
    
    qDebug() << "patch:" << patch << ", basedir:" << basedir;
    d.setServer(KUrl("https://git.reviewboard.kde.org"));
    d.setBaseDir(basedir);
    int ret=d.exec();
    if(ret==QDialog::Accepted) {
        KUrl url=d.server();
        ReviewBoard::NewRequest* job=new ReviewBoard::NewRequest(d.server(), patch, d.repository(), d.baseDir());
        bool corr = job->exec();
        if(corr) {
            url.setUserInfo(QString());
            QString requrl = QString("%1/r/%2/").arg(url.prettyUrl()).arg(job->requestId());
            
            KMessageBox::information(0, i18n("<qt>You can find the new request at:<br /><a href='%1'>%1</a> </qt>", requrl));
        } else {
            KMessageBox::error(0, job->errorText());
        }
    }
    
    return ret!=QDialog::Accepted;
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
  global_debug=0;
  KAboutData aboutData( "kwin4", I18N_NOOP("KWin4"),
                        KWIN4_VERSION,
                        I18N_NOOP("KWin4: Two player network game"),
                        KAboutData::License_GPL,
                        "(c) 1995-2000, Martin Heni");
  aboutData.addAuthor("Martin Heni",0, "*****@*****.**");
  aboutData.addCredit("Laura", I18N_NOOP("Beta testing"), 0);
  aboutData.addAuthor("Benjamin Meyer", I18N_NOOP("Code Improvements"), 0);
  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.

  /* command line handling */
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  if (args->isSet("debug"))
  {
    global_debug=QString(args->getOption("debug")).toInt();
    kdDebug(12010) << "Debug level set to " << global_debug << endl;
  }
  args->clear(); 
  KApplication app(argc, argv);
  KGlobal::locale()->insertCatalogue("libkdegames");

  if (app.isRestored())
  {
    RESTORE(Kwin4App);
  }
  else
  {
    Kwin4App *kwin4 = new Kwin4App();
    app.setMainWidget(kwin4);
    kwin4->show();
  }

  return app.exec();
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
    KAboutData aboutData("testdistlist", I18N_NOOP("Test Distribution Lists"), "0.1");
    KCmdLineArgs::init(argc, argv, &aboutData);
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if(args->isSet("list"))
    {
        QString name = args->getOption("list");

        DistributionListManager *manager = new DistributionListManager(StdAddressBook::self());
        manager->load();
        DistributionList *list = manager->list(name);
        if(!list)
        {
            kdDebug() << "No list with name '" << name << "'" << endl;
            return 1;
        }
        else
        {
            kdDebug() << "RESULT: " << list->emails().join(", ") << endl;
            return 0;
        }
    }

    DistributionListEditor *editor = new DistributionListEditor(StdAddressBook::self(), 0);

    editor->show();
    app.setMainWidget(editor);

    QObject::connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));

    app.exec();

    delete editor;
}
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{

  global_debug=0;
  KAboutData aboutData( "lskat", I18N_NOOP("Lieutenant Skat"),
                        "1.0",
                        I18N_NOOP("Card Game"),
                        KAboutData::License_GPL,
                        "(c) 2000, Martin Heni");
  aboutData.addAuthor("Martin Heni",0, "*****@*****.**");
  aboutData.addCredit("Laura", I18N_NOOP("Beta testing"), 0);
  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.

  /* command line handling */
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  if (args->isSet("debug"))
  {
    QString s = args->getOption("debug");
    global_debug = s.toInt();
    qDebug("Debug level set to %d\n", global_debug);
  }
  args->clear();

  KApplication app;

  if (app.isRestored())
  {
    RESTORE(LSkatApp);
  }
  else
  {
    LSkatApp *lskat = new LSkatApp();
    lskat->show();
  }

  return app.exec();
}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{
    KAboutData about("propertytest2", 0, ki18n("KoProperty Test"), version, ki18n(description),
                     KAboutData::License_GPL, ki18n("(C) 2005 Cedric Pasteur"), KLocalizedString(), 0, "*****@*****.**");
    about.addAuthor(ki18n("Cedric Pasteur"), KLocalizedString(), "*****@*****.**");
    KCmdLineArgs::init(argc, argv, &about);

    KCmdLineOptions options;
    options.add("flat",
        ki18n("Flat display: do not display groups\n"
              "(useful for testing)"));
    options.add("font-size <size>",
        ki18n("Set font size to <size> (in points)\n"
              "(useful for testing whether editors keep the font settings)"));
    options.add("property <name>",
        ki18n("Display only specified property\n"
              "(useful when we want to focus on testing a single\n"
              "property editor)"));
    options.add("ro",
        ki18n("Set all properties as read-only:\n"
              "(useful for testing read-only mode)"));
    KCmdLineArgs::addCmdLineOptions(options);
    KApplication app;

    TestWindow test;
    bool ok;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    const int fontSize = args->getOption("font-size").toInt(&ok);
    if (fontSize > 0 && ok) {
        QFont f(test.font());
        f.setPointSize(fontSize);
        test.setFont(f);
    }
    test.show();

    return app.exec();
}
Ejemplo n.º 10
0
int main(int argc, char **argv)
{
  KAboutData about("khello", I18N_NOOP("HelloWorld-KDE"), "1.0", 
                   I18N_NOOP("The Hello-World program for KDE"), KAboutData::License_GPL, 
		   "(c) 2000 Addison-Wesley", "http://www.addison.wesley.de", 
		   I18N_NOOP("Here is more text\neven more lines"), "*****@*****.**");
  about.addAuthor("Burkhard Lehner", I18N_NOOP("Source and Testing"), 
                  "*****@*****.**", "http://www.burkhardlehner.de");
  about.addCredit("My mother", I18N_NOOP("cooking coffee"), "*****@*****.**", "http://www.mother.de");
  
  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions(options);
  KApplication app;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if(args->isSet("b"))
    KApplication::beep();
    
  QLabel *l = new QLabel(args->getOption("message"), 0);

  l->show();
  app.setMainWidget(l);
  return app.exec();
}
Ejemplo n.º 11
0
extern "C" KDE_EXPORT int kdemain( int argc, char **argv )
{
  // here we go, construct the Kate version
  QString kateVersion = KateApp::kateVersion();

  KAboutData aboutData ("kate", I18N_NOOP("Kate"), kateVersion.latin1(),
                        I18N_NOOP( "Kate - Advanced Text Editor" ), KAboutData::License_LGPL_V2,
                        I18N_NOOP( "(c) 2000-2005 The Kate Authors" ), 0, "http://kate.kde.org");

  aboutData.addAuthor ("Christoph Cullmann", I18N_NOOP("Maintainer"), "*****@*****.**", "http://www.babylon2k.de");
  aboutData.addAuthor ("Anders Lund", I18N_NOOP("Core Developer"), "*****@*****.**", "http://www.alweb.dk");
  aboutData.addAuthor ("Joseph Wenninger", I18N_NOOP("Core Developer"), "*****@*****.**","http://stud3.tuwien.ac.at/~e9925371");
  aboutData.addAuthor ("Hamish Rodda",I18N_NOOP("Core Developer"), "*****@*****.**");
  aboutData.addAuthor ("Waldo Bastian", I18N_NOOP( "The cool buffersystem" ), "*****@*****.**" );
  aboutData.addAuthor ("Charles Samuels", I18N_NOOP("The Editing Commands"), "*****@*****.**");
  aboutData.addAuthor ("Matt Newell", I18N_NOOP("Testing, ..."), "*****@*****.**");
  aboutData.addAuthor ("Michael Bartl", I18N_NOOP("Former Core Developer"), "*****@*****.**");
  aboutData.addAuthor ("Michael McCallum", I18N_NOOP("Core Developer"), "*****@*****.**");
  aboutData.addAuthor ("Jochen Wilhemly", I18N_NOOP( "KWrite Author" ), "*****@*****.**" );
  aboutData.addAuthor ("Michael Koch",I18N_NOOP("KWrite port to KParts"), "*****@*****.**");
  aboutData.addAuthor ("Christian Gebauer", 0, "*****@*****.**" );
  aboutData.addAuthor ("Simon Hausmann", 0, "*****@*****.**" );
  aboutData.addAuthor ("Glen Parker",I18N_NOOP("KWrite Undo History, Kspell integration"), "*****@*****.**");
  aboutData.addAuthor ("Scott Manson",I18N_NOOP("KWrite XML Syntax highlighting support"), "*****@*****.**");
  aboutData.addAuthor ("John Firebaugh",I18N_NOOP("Patches and more"), "*****@*****.**");
  aboutData.addAuthor ("Dominik Haumann", I18N_NOOP("Developer & Highlight wizard"), "*****@*****.**");

  aboutData.addCredit ("Matteo Merli",I18N_NOOP("Highlighting for RPM Spec-Files, Perl, Diff and more"), "*****@*****.**");
  aboutData.addCredit ("Rocky Scaletta",I18N_NOOP("Highlighting for VHDL"), "*****@*****.**");
  aboutData.addCredit ("Yury Lebedev",I18N_NOOP("Highlighting for SQL"),"");
  aboutData.addCredit ("Chris Ross",I18N_NOOP("Highlighting for Ferite"),"");
  aboutData.addCredit ("Nick Roux",I18N_NOOP("Highlighting for ILERPG"),"");
  aboutData.addCredit ("Carsten Niehaus", I18N_NOOP("Highlighting for LaTeX"),"");
  aboutData.addCredit ("Per Wigren", I18N_NOOP("Highlighting for Makefiles, Python"),"");
  aboutData.addCredit ("Jan Fritz", I18N_NOOP("Highlighting for Python"),"");
  aboutData.addCredit ("Daniel Naber","","");
  aboutData.addCredit ("Roland Pabel",I18N_NOOP("Highlighting for Scheme"),"");
  aboutData.addCredit ("Cristi Dumitrescu",I18N_NOOP("PHP Keyword/Datatype list"),"");
  aboutData.addCredit ("Carsten Pfeiffer", I18N_NOOP("Very nice help"), "");
  aboutData.addCredit (I18N_NOOP("All people who have contributed and I have forgotten to mention"),"","");

  aboutData.setTranslator(I18N_NOOP2("NAME OF TRANSLATORS","Your names"), I18N_NOOP2("EMAIL OF TRANSLATORS","Your emails"));

  // command line args init and co
  KCmdLineArgs::init (argc, argv, &aboutData);
  KCmdLineArgs::addCmdLineOptions (options);
  KCmdLineArgs::addTempFileOption();
  KateApp::addCmdLineOptions ();

  // get our command line args ;)
  KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

  // now, first try to contact running kate instance if needed
  if ( args->isSet("use") || (::getenv("KATE_PID")!=0) )
  {
    DCOPClient client;
    client.attach ();

    // get all attached clients ;)
    QCStringList allClients = client.registeredApplications();

    // search for a kate app client, use the first found
    QCString kateApp;

    if ( args->isSet("start") )
    {
      for (unsigned int i=0; i < allClients.count(); i++)
      {
        if (allClients[i] == "kate" || allClients[i].left(5) == "kate-")
        {
          DCOPRef ref( allClients[i], "KateApplication" );
          QString s = ref.call( "session" );
          if ( QString(args->getOption("start")) == s )
          {
            kateApp = allClients[i];
            break;
          }
        }
      }
    }
    else if ( (args->isSet("pid")) || (::getenv("KATE_PID") !=0 ) )
    {
      QCString tryApp;
      if ( args->isSet("pid") )
        tryApp = args->getOption("pid");
      else
        tryApp = ::getenv("KATE_PID");

      if ( client.isApplicationRegistered( tryApp.prepend("kate-") ) )
        kateApp = tryApp;
    }
    else
    {
      for (unsigned int i=0; i < allClients.count(); ++i)
      {
        if (allClients[i] == "kate" || allClients[i].left(5) == "kate-")
        {
          kateApp = allClients[i];
          break;
        }
      }
    }

    // found a matching kate client ;)
    if (!kateApp.isEmpty())
    {
      kdDebug () << "kate app: " << kateApp << endl;
      // make kdeinit happy
      client.registerAs( "kate" );

      DCOPRef kRef (kateApp, "KateApplication");

      if (args->isSet ("start"))
        kRef.call( "activateSession", QString (args->getOption("start")) );

      QString enc = args->isSet("encoding") ? args->getOption("encoding") : QCString("");

      bool tempfileSet = KCmdLineArgs::isTempFileSet();

      for (int z=0; z<args->count(); z++)
        kRef.call( "openURL", args->url(z), enc, tempfileSet );

      if( args->isSet( "stdin" ) )
      {
        QTextIStream input(stdin);

        // set chosen codec
        QTextCodec *codec = args->isSet("encoding") ? QTextCodec::codecForName(args->getOption("encoding")) : 0;

        if (codec)
          input.setCodec (codec);

        QString line;
        QString text;

        do
        {
          line = input.readLine();
          text.append( line + "\n" );
        } while( !line.isNull() );

        kRef.call( "openInput", text );
      }

      int line = 0;
      int column = 0;
      bool nav = false;

      if (args->isSet ("line"))
      {
        line = args->getOption ("line").toInt();
        nav = true;
      }

      if (args->isSet ("column"))
      {
        column = args->getOption ("column").toInt();
        nav = true;
      }

      if (nav)
         kRef.call( "setCursor", line, column );

      // since the user tried to open a document, let us assume [s]he
      // wants to see that document.
      // ### what to do about the infamous focus stealing prevention?
      uint mwn = kRef.call("activeMainWindowNumber");
      QCString smwn;
      DCOPRef wRef( kateApp, QCString( "__KateMainWindow#") + smwn.setNum(mwn) );
      if ( wRef.call("minimized") )
      {
        if ( wRef.call( "maximized" ) )
          wRef.call( "maximize" );
        else
          wRef.call("restore");
      }
      wRef.call( "raise" );

      // stop startup notification
      KStartupInfo::appStarted(  );

      return 0;
    }
  }

  // construct the real kate app object ;)
  KateApp app (args);

  // app execution should already end :)
  if (app.shouldExit())
  {
    return 0;
  }

  // execute ourself ;)
  return app.exec();
}
Ejemplo n.º 12
0
int
main (int argc, char **argv)
{
    KWD::Decorator  *app;
    KCmdLineArgs    *args;
    KCmdLineOptions options;
    int		    status;
    Time	    timestamp;
    QString         appname;

    options.add ("replace", ki18n ("Replace existing window decorator"));
    options.add ("sm-disable", ki18n ("Disable connection to session manager"));
    options.add ("blur <type>", ki18n ("Blur type (none/titlebar/all)"), "none");

    KAboutData about("kde-window-decorator", "kwin", ki18n ("KDE Window Decorator"),
                     "0.0.1", KLocalizedString(), KAboutData::License_GPL,
                     KLocalizedString(), KLocalizedString(), "http://www.compiz.org", 
		     "*****@*****.**");
    KCmdLineArgs::init (argc, argv,
			"kde-window-decorator",
			"kwin",
			ki18n ("KDE Window Decorator"),
			"0.0.1");
    KCmdLineArgs::addCmdLineOptions (options);
    args = KCmdLineArgs::parsedArgs ();

    if (args->isSet ("blur"))
    {
	QString blur = args->getOption ("blur");

	if (blur == QString ("titlebar"))
	    blurType = BLUR_TYPE_TITLEBAR;
	else if (blur == QString ("all"))
	    blurType = BLUR_TYPE_ALL;
    }

    app = new KWD::Decorator ();

    if (args->isSet ("sm-disable"))
	app->disableSessionManagement ();

    status = decor_acquire_dm_session (QX11Info::display(),
				       QX11Info::appScreen (),
				       "kwd", args->isSet ("replace"),
				       &timestamp);
    if (status != DECOR_ACQUIRE_STATUS_SUCCESS)
    {
	if (status == DECOR_ACQUIRE_STATUS_FAILED)
	{
	    fprintf (stderr,
		     "%s: Could not acquire decoration manager "
		     "selection on screen %d display \"%s\"\n",
		     argv[0], QX11Info::appScreen (),
		     DisplayString (QX11Info::display()));
	}
	else if (status == DECOR_ACQUIRE_STATUS_OTHER_DM_RUNNING)
	{
	    fprintf (stderr,
		     "%s: Screen %d on display \"%s\" already "
		     "has a decoration manager; try using the "
		     "--replace option to replace the current "
		     "decoration manager.\n",
		     argv[0], QX11Info::appScreen (),
		     DisplayString (QX11Info::display()));
	}

	return 1;
    }

    decor_set_dm_check_hint (QX11Info::display(), QX11Info::appScreen ());

    if (!app->enableDecorations (timestamp))
    {
	fprintf (stderr,
		 "%s: Could not enable decorations on display \"%s\"\n",
		 argv[0], DisplayString (QX11Info::display()));

	return 1;
    }

    if (QX11Info::appScreen () == 0)
        appname = "org.kde.kwin";
    else
        appname.sprintf("org.kde.kwin-screen-%d", QX11Info::appScreen ());

    QDBusConnection::sessionBus ().interface ()->registerService
	(appname, QDBusConnectionInterface::DontQueueService);

    status = app->exec ();

    delete app;

    return status;
}
Ejemplo n.º 13
0
void KopeteApplication::slotLoadPlugins()
{
	// we have to load the address book early, because calling this enters the Qt event loop when there are remote resources.
	// The plugin manager is written with the assumption that Kopete will not reenter the event loop during plugin load,
	// otherwise lots of things break as plugins are loaded, then contacts are added to incompletely initialised MCLVIs
	Kopete::KABCPersistence::self()->addressBook();

	//Create the command handler (looks silly)
	Kopete::CommandHandler::commandHandler();

	//Create the view manager
	KopeteViewManager::viewManager();

	Kopete::AccountManager::self()->load();
	Kopete::ContactList::self()->load();

	KConfig *config = KGlobal::config();

	// Parse command-line arguments
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	bool showConfigDialog = false;

	config->setGroup( "Plugins" );

	/* FIXME: This is crap, if something purged that groups but your accounts
	 * are still working kopete will load the necessary plugins but still show the
	 * stupid accounts dialog (of course empty at that time because account data
	 * gets loaded later on). [mETz - 29.05.2004]
	 */
	if ( !config->hasGroup( "Plugins" ) )
		showConfigDialog = true;

	// Listen to arguments
	/*
	// TODO: conflicts with emoticon installer and the general meaning
	// of %U in kopete.desktop
	if ( args->count() > 0 )
	{
		showConfigDialog = false;
		for ( int i = 0; i < args->count(); i++ )
			Kopete::PluginManager::self()->setPluginEnabled( args->arg( i ), true );
	}
	*/

	// Prevent plugins from loading? (--disable=foo,bar)
	QStringList disableArgs = QStringList::split( ',', args->getOption( "disable" ) );
	for ( QStringList::ConstIterator it = disableArgs.begin(); it != disableArgs.end(); ++it )
	{
		showConfigDialog = false;
		Kopete::PluginManager::self()->setPluginEnabled( *it, false );
	}

	// Load some plugins exclusively? (--load-plugins=foo,bar)
	if ( args->isSet( "load-plugins" ) )
	{
		config->deleteGroup( "Plugins", true );
		showConfigDialog = false;
		QStringList plugins = QStringList::split( ',', args->getOption( "load-plugins" ) );
		for ( QStringList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it )
			Kopete::PluginManager::self()->setPluginEnabled( *it, true );
	}

	config->sync();

	// Disable plugins altogether? (--noplugins)
	if ( !args->isSet( "plugins" ) )
	{
		// If anybody reenables this I'll get a sword and make a nice chop-suy out
		// of your body :P [mETz - 29.05.2004]
		// This screws up kopeterc because there is no way to get the Plugins group back!
		//config->deleteGroup( "Plugins", true );

		showConfigDialog = false;
		// pretend all plugins were loaded :)
		QTimer::singleShot(0, this, SLOT( slotAllPluginsLoaded() ));
	}
	else
	{
		Kopete::PluginManager::self()->loadAllPlugins();
	}

	connect( Kopete::PluginManager::self(), SIGNAL( allPluginsLoaded() ),
		this, SLOT( slotAllPluginsLoaded() ));

	if( showConfigDialog )
	{
		// No plugins specified. Show the config dialog.
		// FIXME: Although it's a bit stupid it is theoretically possible that a user
		//        explicitly configured Kopete to not load plugins on startup. In this
		//        case we don't want this dialog. We need some other config setting
		//        like a bool hasRunKopeteBefore or so to trigger the loading of the
		//        wizard. Maybe using the last run version number is more useful even
		//        as it also allows for other features. - Martijn
		// FIXME: Possibly we need to influence the showConfigDialog bool based on the
		//        command line arguments processed below. But how exactly? - Martijn
		// NB: the command line args are completely broken atm.  
		// I don't want to fix them for 3.5 as plugin loading will change for KDE4.	- Will
		AddAccountWizard *m_addwizard = new AddAccountWizard( Kopete::UI::Global::mainWidget(), "addAccountWizard", true, true );
		m_addwizard->exec();
		Kopete::AccountManager::self()->save();
	}
}
Ejemplo n.º 14
0
void PrintWrapper::slotPrint()
{
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
    struct sigaction action;
#endif /* HAVE_SIGACTION && !HAVE_SIGSET*/

    // read variables from command line
    QString printer = args->getOption("d");
    QString title = args->getOption("t");
    int ncopies = QString(args->getOption("n")).toInt();
    QString job_mode = args->getOption("j");
    QString system = args->getOption("system");
    KStringList optlist = args->getOptionList("o");
    QMap< QString, QString > opts;
    KURL::List files;
    QStringList filestoprint;
    force_stdin = args->isSet("stdin");
    docopy = args->isSet("c");
    bool nodialog = !(args->isSet("dialog"));

    if(isatty(0))
    {
        kdDebug(500) << "stdin is a terminal, disabling it" << endl;
        check_stdin = false;
    }

    // parse options
    for(KStringList::ConstIterator it = optlist.begin(); it != optlist.end(); ++it)
    {
        QStringList l = QStringList::split('=', QString(*it), false);
        if(l.count() >= 1)
            opts[l[0]] = (l.count() == 2 ? l[1] : QString::null);
    }

    // read file list
    for(int i = 0; i < args->count(); i++)
        files.append(args->url(i));

    // some clean-up
    args->clear();

    // set default values if necessary
    if(job_mode == "console")
        job_output = 1;
    else if(job_mode == "none")
        job_output = 2;
    else
        job_output = 0;

    // some checking
    if(files.count() > 0)
    {
        check_stdin = false;

        if(force_stdin)
        {
            showmsg(i18n("A file has been specified on the command line. Printing from STDIN will be disabled."), 1);
            force_stdin = false;
        }
    }
    if(nodialog && files.count() == 0 && !force_stdin && !check_stdin)
    {
        errormsg(i18n("When using '--nodialog', you must at least specify one file to print or use the '--stdin' flag."));
    }

    if(check_stdin)
    { // check if there's any input on stdin
        fd_set in;
        struct timeval tm;
        tm.tv_sec = 0;
        tm.tv_usec = 0;
        FD_ZERO(&in);
        FD_SET(0, &in);
        if(select(1, &in, NULL, NULL, &tm))
        { // we have data on stdin
            if(read(0, &readchar, 1) > 0)
            {
                force_stdin = true;
                check_stdin = false;
                dataread = true;
                kdDebug(500) << "input detected on stdin" << endl;
            }
            else
            {
                force_stdin = check_stdin = false;
                kdDebug(500) << "stdin closed and empty" << endl;
            }
        }
        else
            kdDebug(500) << "no input on stdin at startup" << endl;
    }

    // force_stdin ? or also check_stdin ?
    KPrinter::ApplicationType dialog_mode = (force_stdin || nodialog ? KPrinter::StandAlone : KPrinter::StandAlonePersistent);
    KPrinter::setApplicationType(dialog_mode);
    if(!force_stdin)
        KPrinter::addStandardPage(KPrinter::FilesPage);

    KPrinter kprinter;
    if(nodialog)
    {
        KMPrinter *prt(0);
        KMManager *mgr = KMManager::self();

        mgr->printerList(false);
        if(!printer.isEmpty())
            prt = mgr->findPrinter(printer);
        else
            prt = mgr->defaultPrinter();

        if(prt == 0)
            errormsg(i18n("The specified printer or the default printer could not be found."));
        else if(!prt->autoConfigure(&kprinter))
            errormsg(i18n("Operation aborted."));
    }
    else if(!printer.isEmpty())
        kprinter.setSearchName(printer);
    kprinter.setDocName(title);
    kprinter.initOptions(opts);
    kprinter.setOption("kde-filelist", files.toStringList().join("@@"));
    kdDebug(500) << kprinter.option("kde-filelist") << endl;
    if(ncopies > 0)
        kprinter.setNumCopies(ncopies);

    if(nodialog)
        slotPrintRequested(&kprinter);
    else
    {
        dlg = KPrintDialog::printerDialog(&kprinter, 0);
        if(dlg)
        {
            connect(dlg, SIGNAL(printRequested(KPrinter *)), SLOT(slotPrintRequested(KPrinter *)));
            if(check_stdin)
            {
                notif = new QSocketNotifier(0, QSocketNotifier::Read, this);
                connect(notif, SIGNAL(activated(int)), this, SLOT(slotGotStdin()));
                kdDebug(500) << "waiting for input on stdin" << endl;
            }
            dlg->exec();
            delete dlg;
        }
        else
            errormsg(i18n("Unable to construct the print dialog."));
    }
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    KCmdLineOptions options;
    options.add("c <digest>", ki18n("compare <digest> with the calculated digest for a string or file."));
    options.add("d", ki18n("decode the given string or file using base64"));
    options.add("e", ki18n("encode the given string or file using base64"));
    options.add("f", ki18n("the filename to be used as input"), "default");
    options.add("p", ki18n("encode the given string or file using quoted-printable"));
    options.add("q", ki18n("decode the given string or file using quoted-printable"));
    options.add("r", ki18n("calculate the raw md5 for the given string or file"));
    options.add("s", ki18n("the string to be used as input"));
    options.add("t", ki18n("perform a timed message-digest test"));
    options.add("u", ki18n("uuencode the given string or file"));
    options.add("x", ki18n("uudecode the given string or file"));
    options.add("z", ki18n("run a preset message-digest test"));
    options.add("+command", ki18n("[input1, input2,...]"));

    KCmdLineArgs::init(argc, argv, "kmdcodectest", 0,
                       ki18n("KMDCodecTest"), "1.0",
                       ki18n("Unit test for md5, base64 encode/decode "
                             "and uuencode/decode facilities"));
    KCmdLineArgs::addCmdLineOptions(options);
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    int count = args->count();

    //QCoreApplication app;

    if (!count) {
        if (args->isSet("t")) {
            MD5_timeTrial();
        } else if (args->isSet("z")) {
            MD5_testSuite();
        } else {
            args->usage();
        }
    } else {
        bool isVerify = args->isSet("c");
        bool isString = args->isSet("s");
        bool isFile = args->isSet("f");
        Codec type = Unspecified;
        if (args->isSet("d")) {
            type = Base64Decode;
        } else if (args->isSet("e")) {
            type = Base64Encode;
        } else if (args->isSet("u")) {
            type = UUEncode;
        } else if (args->isSet("x")) {
            type = UUDecode;
        } else if (args->isSet("p")) {
            type = QPEncode;
        } else if (args->isSet("q")) {
            type = QPDecode;
        }
        if (isVerify) {
            const char *opt = args->getOption("c").toLocal8Bit().data();
            for (int i = 0; i < count; i++) {
                MD5_verify(args->arg(i).toLocal8Bit().constData(), opt, (isString || !isFile));
            }
        } else {
            for (int i = 0; i < count; i++) {
                if (type != Unspecified) {
                    testCodec(args->arg(i).toLocal8Bit().constData(), type, isFile);
                } else {
                    if (isString) {
                        MD5_string(args->arg(i).toLocal8Bit().constData(), 0, args->isSet("r"));
                    } else {
                        MD5_file(args->arg(i).toLocal8Bit().constData(), args->isSet("r"));
                    }
                }
            }
        }
    }
    args->clear();
    return (0);
}
Ejemplo n.º 16
0
extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
{
    KLocale::setMainCatalogue("konqueror");
    KAboutData aboutData("keditbookmarks", I18N_NOOP("Bookmark Editor"), VERSION, I18N_NOOP("Konqueror Bookmarks Editor"), KAboutData::License_GPL,
                         I18N_NOOP("(c) 2000 - 2003, KDE developers"));
    aboutData.addAuthor("David Faure", I18N_NOOP("Initial author"), "*****@*****.**");
    aboutData.addAuthor("Alexander Kellett", I18N_NOOP("Author"), "*****@*****.**");

    KCmdLineArgs::init(argc, argv, &aboutData);
    KApplication::addCmdLineOptions();
    KCmdLineArgs::addCmdLineOptions(options);

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    bool isGui =
        !(args->isSet("exportmoz") || args->isSet("exportns") || args->isSet("exporthtml") || args->isSet("exportie") || args->isSet("exportopera")
          || args->isSet("importmoz") || args->isSet("importns") || args->isSet("importie") || args->isSet("importopera"));

    bool browser = args->isSet("browser");

    KApplication::disableAutoDcopRegistration();
    KApplication app(isGui, isGui);

    bool gotArg = (args->count() == 1);

    QString filename = gotArg ? QString::fromLatin1(args->arg(0)) : locateLocal("data", QString::fromLatin1("konqueror/bookmarks.xml"));

    if(!isGui)
    {
        CurrentMgr::self()->createManager(filename);
        CurrentMgr::ExportType exportType = CurrentMgr::MozillaExport; // uumm.. can i just set it to -1 ?
        int got = 0;
        const char *arg, *arg2 = 0, *importType = 0;
        if(arg = "exportmoz", args->isSet(arg))
        {
            exportType = CurrentMgr::MozillaExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exportns", args->isSet(arg))
        {
            exportType = CurrentMgr::NetscapeExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exporthtml", args->isSet(arg))
        {
            exportType = CurrentMgr::HTMLExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exportie", args->isSet(arg))
        {
            exportType = CurrentMgr::IEExport;
            arg2 = arg;
            got++;
        }
        if(arg = "exportopera", args->isSet(arg))
        {
            exportType = CurrentMgr::OperaExport;
            arg2 = arg;
            got++;
        }
        if(arg = "importmoz", args->isSet(arg))
        {
            importType = "Moz";
            arg2 = arg;
            got++;
        }
        if(arg = "importns", args->isSet(arg))
        {
            importType = "NS";
            arg2 = arg;
            got++;
        }
        if(arg = "importie", args->isSet(arg))
        {
            importType = "IE";
            arg2 = arg;
            got++;
        }
        if(arg = "importopera", args->isSet(arg))
        {
            importType = "Opera";
            arg2 = arg;
            got++;
        }
        if(!importType && arg2)
        {
            Q_ASSERT(arg2);
            // TODO - maybe an xbel export???
            if(got > 1) // got == 0 isn't possible as !isGui is dependant on "export.*"
                KCmdLineArgs::usage(I18N_NOOP("You may only specify a single --export option."));
            QString path = QString::fromLocal8Bit(args->getOption(arg2));
            CurrentMgr::self()->doExport(exportType, path);
        }
        else if(importType)
        {
            if(got > 1) // got == 0 isn't possible as !isGui is dependant on "import.*"
                KCmdLineArgs::usage(I18N_NOOP("You may only specify a single --import option."));
            QString path = QString::fromLocal8Bit(args->getOption(arg2));
            ImportCommand *importer = ImportCommand::importerFactory(importType);
            importer->import(path, true);
            importer->execute();
            CurrentMgr::self()->managerSave();
            CurrentMgr::self()->notifyManagers();
        }
        return 0; // error flag on exit?, 1?
    }

    QString address = args->isSet("address") ? QString::fromLocal8Bit(args->getOption("address")) : QString("/0");

    QString caption = args->isSet("customcaption") ? QString::fromLocal8Bit(args->getOption("customcaption")) : QString::null;

    args->clear();

    bool readonly = false; // passed by ref

    if(askUser(app, (gotArg ? filename : QString::null), readonly))
    {
        KEBApp *toplevel = new KEBApp(filename, readonly, address, browser, caption);
        toplevel->show();
        app.setMainWidget(toplevel);
        return app.exec();
    }

    return 0;
}
Ejemplo n.º 17
0
Archivo: main.cpp Proyecto: KDE/kdepim
int main(int argc, char *argv[])
{
    KLocalizedString::setApplicationDomain("konsolekalendar");
    K4AboutData aboutData(
        progName, 0,                 // internal program name
        ki18n(progDisplay),          // displayable program name.
        progVersion,                 // version string
        ki18n(progDesc),             // short program description
        K4AboutData::License_GPL,     // license type
        ki18n("(c) 2002-2009, Tuukka Pasanen and Allen Winter"),
        ki18n(0),                    // any free form text
        progURL,                     // program home page address
        "bugs.kde.org"               // bug report email address
    );

    aboutData.addAuthor(
        ki18n("Allen Winter"),       // developer's name
        ki18n("Maintainer"),         // task or role
        "*****@*****.**",            // email address
        0                            // home page or relevant link
    );
    aboutData.addAuthor(
        ki18n("Tuukka Pasanen"),     // developer's name
        ki18n("Author"),             // task or role
        "*****@*****.**",     // email address
        0                            // home page or relevant link
    );

    KCmdLineArgs::init(argc, argv, &aboutData, KCmdLineArgs::CmdLineArgNone);

    KCmdLineOptions options;
    options.add("verbose",
                ki18n("Print helpful runtime messages"));
    options.add("dry-run",
                ki18n("Print what would have been done, but do not execute"));
    options.add("allow-gui",
                ki18n("Allow calendars which might need an interactive user interface"));
    options.add(":",
                ki18n("Incidence types (these options can be combined):"));
    options.add("event",
                ki18n("  Operate for Events only (Default)"));
    options.add("todo",
                ki18n("  Operate for To-dos only [NOT WORKING YET]"));
    options.add("journal",
                ki18n("  Operate for Journals only [NOT WORKING YET]"));
    options.add(":",
                ki18n("Major operation modes:"));
    options.add("view",
                ki18n("  Print incidences in specified export format"));
    options.add("add",
                ki18n("  Insert an incidence into the calendar"));
    options.add("change",
                ki18n("  Modify an existing incidence"));
    options.add("delete",
                ki18n("  Remove an existing incidence"));
    options.add("create",
                ki18n("  Create new calendar file if one does not exist"));
    options.add("import <import-file>",
                ki18n("  Import this calendar to main calendar"));
    options.add("list-calendars",
                ki18n("  List available calendars"));
    options.add(":",
                ki18n("Operation modifiers:"));
    options.add("all",
                ki18n("  View all calendar entries, ignoring date/time options"));
    options.add("next",
                ki18n("  View next activity in calendar"));
    options.add("show-next <days>",
                ki18n("  From start date show next # days' activities"));
    options.add("uid <uid>",
                ki18n("  Incidence Unique-string identifier"));
    options.add("date <start-date>",
                ki18n("  Start from this day [YYYY-MM-DD]"));
    options.add("time <start-time>",
                ki18n("  Start from this time [HH:MM:SS]"));
    options.add("end-date <end-date>",
                ki18n("  End at this day [YYYY-MM-DD]"));
    options.add("end-time <end-time>",
                ki18n("  End at this time [HH:MM:SS]"));
    options.add("epoch-start <epoch-time>",
                ki18n(" Start from this time [secs since epoch]"));
    options.add("epoch-end <epoch-time>",
                ki18n("  End at this time [secs since epoch]"));
    options.add("summary <summary>",
                ki18n("  Add summary to incidence (for add/change modes)"));
    options.add("description <description>",
                ki18n("Add description to incidence (for add/change modes)"));
    options.add("location <location>",
                ki18n("  Add location to incidence (for add/change modes)"));
    options.add("calendar <calendar id>",
                ki18n("  Calendar to use when creating a new incidence"));
    options.add(":",
                ki18n("Export options:"));
    options.add("export-type <export-type>",
                ki18n("Export file type (Default: text)"));
    options.add("export-file <export-file>",
                ki18n("Export to file (Default: stdout)"));
    options.add("export-list",
                ki18n("  Print list of export types supported and exit"));
    options.add("",
                ki18n("Examples:\n"
                      "  konsolekalendar --view\n"
                      "  konsolekalendar --list-calendars\n"
                      "  konsolekalendar --add --collection 42 --date 2003-06-04 "
                      "--time 10:00 --end-time 12:00 \\\n"
                      "                  --summary \"Doctor Visit\" "
                      "--description \"Get My Head Examined\"\n"
                      "  konsolekalendar --delete --uid KOrganizer-1740326.803"));
    options.add("",
                ki18n("For more information visit the program home page at:\n"
                      "  http://pim.kde.org/components/konsolekalendar.php"));
    KCmdLineArgs::addCmdLineOptions(options);   // Add our own options.

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication app(
        // when not set (default) GUI is not enabled - disable all GUI stuff
        args->isSet("allow-gui")
    );

    // Default values for start date/time (today at 07:00)
    QDate startdate = QDate::currentDate();
    QTime starttime(7, 0);

    // Default values for end date/time (today at 17:00)
    QDate enddate = QDate::currentDate();
    QTime endtime(17, 0);

    // Default values for switches
    bool view = true;
    bool add = false;
    bool change = false;
    bool del = false;
    bool create = false;
    //bool calendarFile = false;
    bool importFile = false;

    QString option;

    KonsoleKalendarVariables variables;
    KonsoleKalendarEpoch epochs;

    variables.setFloating(false);   // by default, new events do NOT float

    if (args->isSet("verbose")) {
        variables.setVerbose(true);
    }

    if (args->isSet("dry-run")) {
        variables.setDryRun(true);
    }

    if (args->isSet("allow-gui")) {
        variables.setAllowGui(true);
    }

    /*
     * Switch on export list
     */
    if (args->isSet("export-list")) {
        cout << endl;
        cout << i18n("%1 supports these export formats:",
                     QString::fromLatin1(progDisplay)).toLocal8Bit().data()
             << endl;
        cout << i18nc("the default export format", "  %1 [Default]",
                      QStringLiteral("Text")).toLocal8Bit().data()
             << endl;
        cout << i18nc("short text export", "  %1 (like %2, but more compact)",
                      QStringLiteral("Short"), QStringLiteral("Text")).toLocal8Bit().data()
             << endl;
        cout << i18nc("HTML export", "  %1",
                      QStringLiteral("HTML")).toLocal8Bit().data()
             << endl;
        cout << i18nc("HTMLmonth export", "  %1 (like %2, but in a month view)",
                      QStringLiteral("HTMLmonth"), QStringLiteral("HTML")).toLocal8Bit().data()
             << endl;
        cout << i18nc("comma-separated values export", "  %1 (Comma-Separated Values)",
                      QStringLiteral("CSV")).toLocal8Bit().data()
             << endl;
        cout << endl;
        return 0;
    }

    /*
     * Set incidence type(s)
     */
    if (args->isSet("event")) {
        variables.setUseEvents(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use Events";
    }
    if (args->isSet("todo")) {
        variables.setUseTodos(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use To-dos";
        cout << i18n("Sorry, To-dos are not working yet.").toLocal8Bit().data()
             << endl;
        return 1;
    }
    if (args->isSet("journal")) {
        variables.setUseJournals(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use Journals";
        cout << i18n("Sorry, Journals are not working yet.").toLocal8Bit().data()
             << endl;
        return 1;
    }
    // Use Events if no incidence type is specified on the command line
    if (!args->isSet("event") &&
            !args->isSet("todo") &&
            !args->isSet("journal")) {
        variables.setUseEvents(true);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options | use Events (Default)";
    }

    /*
     * Switch on exporting
     */
    variables.setExportType(ExportTypeText);
    if (args->isSet("export-type")) {
        option = args->getOption("export-type");

        if (option.toUpper() == QLatin1String("HTML")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to HTML";
            variables.setExportType(ExportTypeHTML);
        } else if (option.toUpper() == QLatin1String("HTMLMONTH")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to HTML by Month";
            variables.setExportType(ExportTypeMonthHTML);
        } else if (option.toUpper() == QLatin1String("CSV")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to CSV";
            variables.setExportType(ExportTypeCSV);
        } else if (option.toUpper() == QLatin1String("TEXT")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to TEXT (default)";
            variables.setExportType(ExportTypeText);
        } else if (option.toUpper() == QLatin1String("SHORT")) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | export-type | Export to TEXT-SHORT";
            variables.setExportType(ExportTypeTextShort);
        } else {
            cout << i18n("Invalid Export Type Specified: %1", option).toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    /*
     * Switch on export file name
     */
    if (args->isSet("export-file")) {
        option = args->getOption("export-file");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Export File:"
                                     << "(" << option << ")";

        variables.setExportFile(option);
    }

    /*
     * Switch on View (Print Entries).  This is the default mode of operation.
     */
    if (args->isSet("view")) {
        view = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Print incidences)";
    }

    /*
     * Switch on Add (Insert Entry)
     */
    if (args->isSet("add")) {
        view = false;
        add = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Add incidence)";
    }

    /*
     * Switch on Change (Modify Entry)
     */
    if (args->isSet("change")) {
        view = false;
        change = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Change incidence)";
    }

    /*
     * Switch on Delete (Remove Entry)
     */
    if (args->isSet("delete")) {
        view = false;
        del = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Mode: (Delete incidence)";
    }

    /*
     * Switch on Create
     */
    if (args->isSet("create")) {
        view = false;
        create = true;

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Calendar File: (Create)";
    }

    /*
     * If there is summary attached.
     */
    if (args->isSet("summary")) {
        option = args->getOption("summary");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Summary:"
                                     << "(" << option << ")";

        variables.setSummary(option);
    }

    /*
     * If there is description attached.
     */
    if (args->isSet("description")) {
        option = args->getOption("description");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Description:"
                                     << "(" << option << ")";

        variables.setDescription(option);
    }

    if (args->isSet("calendar")) {
        option = args->getOption("calendar");
        bool ok = false;
        int colId = option.toInt(&ok);
        if (ok) {
            variables.setCollectionId(colId);
        }
    }

    /*
     * If there is location information
     */
    if (args->isSet("location")) {
        option = args->getOption("location");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Location:"
                                     << "(" << option << ")";

        variables.setLocation(option);
    }

    /*
     * Show next happening and exit
     */
    if (args->isSet("next")) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Show next incidence only";

        variables.setNext(true);
    }

    /*
     * Set incidence unique string identifier
     */
    if (args->isSet("uid")) {
        option = args->getOption("uid");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "incidence UID:"
                                     << "(" << option << ")";

        variables.setUID(option);
    }

    /*
     * Set starting date for calendar
     */
    if (args->isSet("date")) {
        option = args->getOption("date");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Start date before conversion:"
                                     << "(" << option << ")";

        startdate = QDate::fromString(option, Qt::ISODate);
        if (!startdate.isValid()) {
            cout << i18n("Invalid Start Date Specified: %1",
                         option).toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Start date after conversion:"
                                     << "(" << startdate.toString() << ")";
    }

    /*
     * Set starting time
     */
    if (args->isSet("time")) {
        option = args->getOption("time");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Start time before conversion :"
                                     << "(" << option << ")";

        if (option.toUpper() != QLatin1String("FLOAT")) {
            if (option.count(QLatin1Char(':')) < 2) {
                // need to append seconds
                option.append(QLatin1String(":00"));
            }
            starttime = QTime::fromString(option, Qt::ISODate);
            if (!starttime.isValid()) {
                cout << i18n("Invalid Start Time Specified: %1", option).toLocal8Bit().data()
                     << endl;
                return 1;
            }
            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "Start time after conversion:"
                                         << "(" << starttime.toString() << ")";
        } else {
            variables.setFloating(true);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "Floating event time specified";
        }
    }

    /*
     * Set end date for calendar
     */
    if (args->isSet("end-date")) {
        option = args->getOption("end-date");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End date before conversion:"
                                     << "(" << option << ")";

        enddate = QDate::fromString(option, Qt::ISODate);
        if (!enddate.isValid()) {
            cout << i18n("Invalid End Date Specified: %1",
                         option).toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End date after conversion:"
                                     << "(" << enddate.toString() << ")";
    }

    /*
     * Show next # days and exit
     */
    if (args->isSet("show-next")) {
        bool ok;

        option = args->getOption("show-next");
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Show" << option << "days ahead";
        variables.setDaysCount(option.toInt(&ok, 10));

        if (!ok) {
            cout << i18n("Invalid Date Count Specified: %1", option).toLocal8Bit().data()
                 << endl;
            return 1;
        }

        enddate = startdate;
        enddate = enddate.addDays(variables.getDaysCount());
        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End date after conversion:"
                                     << "(" << enddate.toString() << ")";
    }

    /*
     * Set ending time
     */
    if (args->isSet("end-time")) {
        option = args->getOption("end-time");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "End time before conversion:"
                                     << "(" << option << ")";

        if (option.toUpper() != QLatin1String("FLOAT")) {
            if (option.count(QLatin1Char(':')) < 2) {
                // need to append seconds
                option.append(QLatin1String(":00"));
            }
            endtime = QTime::fromString(option, Qt::ISODate);
            if (!endtime.isValid()) {
                cout << i18n("Invalid End Time Specified: %1", option).toLocal8Bit().data()
                     << endl;
                return 1;
            }

            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "End time after conversion:"
                                         << "(" << endtime.toString() << ")";
        } else {
            variables.setFloating(true);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                         << "Floating event time specified";
        }
    }

    /*
     * Set start date/time from epoch
     */
    time_t epochstart = 0;
    if (args->isSet("epoch-start")) {
        option = args->getOption("epoch-start");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Epoch start:"
                                     << "(" << option << ")";

        epochstart = (time_t) option.toULong(0, 10);
    }

    /*
     * Set end date/time from epoch
     */
    time_t epochend = 0;
    if (args->isSet("epoch-end")) {
        option = args->getOption("epoch-end");

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "Epoch end:"
                                     << "(" << option << ")";

        epochend = (time_t) option.toULong(0, 10);
    }

    if (args->isSet("all")) {
        variables.setAll(true);
    } else {
        variables.setAll(false);
    }

    if (args->isSet("import")) {
        view = false;
        importFile = true;
        option = args->getOption("import");
        variables.setImportFile(option);

        qCDebug(KONSOLEKALENDAR_LOG) << "main | parse options |"
                                     << "importing file from:"
                                     << "(" << option << ")";
    }

    KonsoleKalendar *konsolekalendar = new KonsoleKalendar(&variables);

    if (args->isSet("list-calendars")) {
        konsolekalendar->printCalendarList();
        return 0;
    }

    QEventLoop loop;
    Akonadi::FetchJobCalendar::Ptr calendar = Akonadi::FetchJobCalendar::Ptr(new Akonadi::FetchJobCalendar());
    QObject::connect(calendar.data(), &Akonadi::FetchJobCalendar::loadFinished, &loop, &QEventLoop::quit);
    qCDebug(KONSOLEKALENDAR_LOG) << "Starting to load calendar";
    QElapsedTimer t;
    t.start();
    loop.exec();
    qCDebug(KONSOLEKALENDAR_LOG) << "Calendar loaded in" << t.elapsed() << "ms; success=" << calendar->isLoaded() << "; num incidences=" << calendar->incidences().count();

    if (!args->isSet("import")) {
        variables.setCalendar(calendar);
    }

    /***************************************************************************
     * Glorious date/time checking and setting code                            *
     ***************************************************************************/
    QDateTime startdatetime, enddatetime;

    // Handle case with either date or end-date unspecified
    if (!args->isSet("end-date") && !args->isSet("show-next") &&
            args->isSet("date")) {
        enddate = startdate;
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting enddate to startdate";
    } else if (args->isSet("end-date") && !args->isSet("date")) {
        startdate = enddate;
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting startdate to enddate";
    }

    // NOTE: If neither date nor end-date specified, then event will be today.

    // Case:
    //   End time (or epoch) unspecified, and start time (or epoch) IS specified.
    //   In this case, set the ending to 1 hour after starting.
    if (!args->isSet("end-time") && !args->isSet("epoch-end")) {
        if (args->isSet("time")) {
            endtime = starttime.addSecs(60 * 60);    // end is 1 hour after start
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting endtime 1 hour after starttime";
        } else if (args->isSet("epoch-start")) {
            startdatetime = epochs.epoch2QDateTime(epochstart);
            enddatetime = startdatetime.addSecs(60 * 60);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting endtime 1 hour after epochstart";
        }
    }

    // Case:
    //   Time (or epoch) unspecified, and end-time (or epoch) IS specified.
    //   In this case, set the starting to 1 hour before ending.
    if (!args->isSet("time") && !args->isSet("epoch-start")) {
        if (args->isSet("end-time")) {
            starttime = endtime.addSecs(-60 * 60);    // start is 1 hour before end
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting starttime 1 hour before endtime";
        } else if (args->isSet("epoch-end")) {
            enddatetime = epochs.epoch2QDateTime(epochend);
            startdatetime = enddatetime.addSecs(-60 * 60);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                         << "setting starttime 1 before after epochend";
        }
    }

    // Case:
    //   Time (or epoch) unspecified, and end-time (or epoch) unspecified.
    if (!args->isSet("time")     && !args->isSet("epoch-start") &&
            !args->isSet("end-time") && !args->isSet("epoch-end")) {
        // set default start date/time
        startdatetime = QDateTime(startdate, starttime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting startdatetime from"
                                     << "default startdate (today) and starttime";
        // set default end date/time
        enddatetime = QDateTime(enddate, endtime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting enddatetime from"
                                     << "default enddate (today) and endtime";
    }

    // Set startdatetime, enddatetime if still necessary
    if (startdatetime.isNull()) {
        startdatetime = QDateTime(startdate, starttime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting startdatetime from startdate and starttime";
    }
    if (enddatetime.isNull()) {
        enddatetime = QDateTime(enddate, endtime);
        qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp |"
                                     << "setting enddatetime from enddate and endtime";
    }

    // Float check for add mode:
    //   Events float if time AND end-time AND epoch times are UNspecified
    if (add) {
        if (!args->isSet("time")        && !args->isSet("end-time") &&
                !args->isSet("epoch-start") && !args->isSet("epoch-end")) {
            variables.setFloating(true);
            qCDebug(KONSOLEKALENDAR_LOG) << "main | floatingcheck |"
                                         << "turn-on floating event";
        }
    }

    // Finally! Set the start/end date times
    if (!change) {
        variables.setStartDateTime(startdatetime);
        variables.setEndDateTime(enddatetime);
    } else {
        // Do NOT set start/end datetimes in change mode,
        //   unless they were specified on commandline
        if (args->isSet("time")     || args->isSet("epoch-start") ||
                args->isSet("end-time") || args->isSet("epoch-end")) {
            variables.setStartDateTime(startdatetime);
            variables.setEndDateTime(enddatetime);
        }
    }

    // Some more debug prints
    qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp | StartDate="
                                 << startdatetime.toString(Qt::TextDate);
    qCDebug(KONSOLEKALENDAR_LOG) << "main | datetimestamp | EndDate="
                                 << enddatetime.toString(Qt::TextDate);

    /***************************************************************************
     * Sanity checks                                                           *
     ***************************************************************************/

    // Cannot combine modes
    if (create + view + add + change + del > 1) {
        cout << i18n("Only 1 operation mode "
                     "(view, add, change, delete, create) "
                     "permitted at any one time").toLocal8Bit().data() << endl;
        return 1;
    }

    // Cannot have a ending before starting
    if (startdatetime > enddatetime) {
        cout << i18n("Ending Date/Time occurs before the Starting Date/Time").toLocal8Bit().data()
             << endl;
        return 1;
    }

    /***************************************************************************
     * And away we go with the real work...                                    *
     ***************************************************************************/

    args->clear(); // Free up some memory.

    /*
     * Set our application name for use in unique IDs and error messages,
     * and product ID for incidence PRODID property
     */
    QString prodId = QStringLiteral("-//K Desktop Environment//NONSGML %1 %2//EN");
    CalFormat::setApplication(QLatin1String(progDisplay),
                              prodId.arg(QLatin1String(progDisplay)).arg(QLatin1String(progVersion)));

    if (importFile) {
        if (konsolekalendar->importCalendar()) {
            cout << i18n("Calendar %1 successfully imported",
                         variables.getImportFile()).toLocal8Bit().data()
                 << endl;
            return 0;
        } else {
            cout << i18n("Unable to import calendar: %1",
                         variables.getImportFile()).toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    if (add) {
        if (!konsolekalendar->isEvent(startdatetime, enddatetime,
                                      variables.getSummary())) {
            qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                         << "calling addEvent()";
            konsolekalendar->addEvent();
        } else {
            cout << i18n("Attempting to insert an event that already exists").toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    if (change) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "calling changeEvent()";
        if (!variables.isUID()) {
            cout << i18n("Missing event UID: "
                         "use --uid command line option").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        if (!konsolekalendar->changeEvent()) {
            cout << i18n("No such event UID: change event failed").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "successful changeEvent()";
    }

    if (del) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "calling deleteEvent()";
        if (!variables.isUID()) {
            cout << i18n("Missing event UID: "
                         "use --uid command line option").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        if (!konsolekalendar->deleteEvent()) {
            cout << i18n("No such event UID: delete event failed").toLocal8Bit().data()
                 << endl;
            return 1;
        }
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "successful deleteEvent()";
    }

    if (view) {
        qCDebug(KONSOLEKALENDAR_LOG) << "main | modework |"
                                     << "calling showInstance() to view events";
        if (!konsolekalendar->showInstance()) {
            cout << i18n("Cannot open specified export file: %1",
                         variables.getExportFile()).toLocal8Bit().data()
                 << endl;
            return 1;
        }
    }

    delete konsolekalendar;

    qCDebug(KONSOLEKALENDAR_LOG) << "main | exiting";

    return 0;
}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{
    KCmdLineArgs::init(argc, argv, "cstester", 0, KLocalizedString(), 0, KLocalizedString());

    KCmdLineOptions options;
    options.add("create", ki18n("create verification data for file"));
    options.add("indir <dir>", ki18n("directory to read the data from"));
    options.add("outdir <dir>", ki18n("directory to save the data to"));
    options.add("roundtrip", ki18n("load/save/load and check the document is the same after load and save/load"));
    options.add("verbose", ki18n("be verbose"));
    options.add("!verify", ki18n("verify the file"));
    options.add( "+file", ki18n("file to use"));
    KCmdLineArgs::addCmdLineOptions(options);

    QApplication app(argc, argv);

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    bool create = false;
    bool roundtrip = false;
    bool verify = false;
    int optionCount = 0;

    if (args->isSet("create")) {
        create = true;
        optionCount++;
    }
    if (args->isSet("roundtrip")) {
        roundtrip = true;
        optionCount++;
    }
    if (args->isSet("verify")) {
        verify = true;
        optionCount++;
    }

    if (optionCount > 1) {
        kError() << "create, roundtrip and verify cannot be used the same time";
        exit(1);
    }
    else if (optionCount < 1) {
        kError() << "one of the options create, roundtrip or verify needs to be specified";
        exit(1);
    }

    QString outDir;
    if (args->isSet("outdir")) {
        // check if it is a directory
        QDir dir(args->getOption("outdir"));
        if (!dir.exists()) {
            kError() << "outdir" << args->getOption("outdir") << "does not exist";
            exit(1);
        }
        outDir = dir.path();
    }

    QString inDir;
    if (args->isSet("indir")) {
        // check if it is a directory
        QDir dir(args->getOption("indir"));
        if (!dir.exists()) {
            kError() << "indir" << args->getOption("indir") << "does not exist";
            exit(1);
        }
        inDir = dir.path();
    }

    bool verbose = args->isSet("verbose");

    int exitValue = 0;

    int successful = 0;
    int failed = 0;
    for (int i=0; i < args->count(); ++i) {
        QString filename(args->arg(i));
        QFileInfo file(filename);
        QString checkDir;
        if (!args->isSet("indir")) {
            checkDir = filename + ".check";
        }
        else {
            checkDir = inDir + '/' + file.fileName() + ".check";
        }

        // this is wrong for multiple files in different dirs
        if (!args->isSet("outdir")) {
            outDir = file.path();
        }

        qDebug() << "filename" << filename << "path" << file.path() << file.completeBaseName() << checkDir << file.absoluteFilePath();
        qDebug() << "inDir" << inDir << "outDir" << outDir << "checkDir" << checkDir;

        // filename must be a absolute path
        KoDocument* document = openFile(file.absoluteFilePath());
        if (!document) {
            exit(2);
        }

        QList<QImage> thumbnails(createThumbnails(document, QSize(800,800)));

        qDebug() << "created" << thumbnails.size() << "thumbnails";
        if (create) {
            saveThumbnails(file, thumbnails, outDir);
        }
        else if (verify) {
            if (args->isSet("outdir")) {
                saveThumbnails(file, thumbnails, outDir);
            }
            if (checkThumbnails(thumbnails, checkDir, verbose)) {
                ++successful;
            }
            else {
                ++failed;
                exitValue = 2;
            }
        }
        else if (roundtrip) {
            QString rFilename = saveFile(document, filename, "cstester-roundtrip");
            delete document;
            QFileInfo rFile(rFilename);
            qDebug() << roundtrip << "rFilename" << rFilename << rFile.absoluteFilePath();
            document = openFile(rFile.absoluteFilePath());
            QList<QImage> others(createThumbnails(document, QSize(800,800)));
            if (args->isSet("outdir")) {
                saveThumbnails(file, others, outDir);
                saveThumbnails(file, thumbnails, outDir + "/before");
            }
            if (checkThumbnails(thumbnails, others, verbose)) {
                ++successful;
            }
            else {
                ++failed;
                exitValue = 2;
            }
        }
        delete document;
    }

    if (verify || roundtrip) {
        qDebug() << "Totals:" << successful << "passed" << failed << "failed";
    }

    QTimer::singleShot(1, &app, SLOT(quit()));
    app.exec();
    return exitValue;
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
    //KApplication::disableAutoDcopRegistration();
    KCmdLineArgs::init( argc, argv, "ktrash", "kio_trash",
                        ki18n( "ktrash" ),
                        KDE_VERSION_STRING ,
                        ki18n( "Helper program to handle the KDE trash can\n"
				   "Note: to move files to the trash, do not use ktrash, but \"kioclient move 'url' trash:/\"" ));

    KCmdLineOptions options;
    options.add("empty", ki18n( "Empty the contents of the trash" ));
    //{ "migrate", I18N_NOOP( "Migrate contents of old trash" ), 0 },
    options.add("restore <file>", ki18n( "Restore a trashed file to its original location" ));
    // This hack is for the servicemenu on trash.desktop which uses Exec=ktrash -empty. %f is implied...
    options.add("+[ignored]", ki18n( "Ignored" ));
    KCmdLineArgs::addCmdLineOptions( options );
    KApplication app;

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    if ( args->isSet( "empty" ) ) {
        // We use a kio job instead of linking to TrashImpl, for a smaller binary
        // (and the possibility of a central service at some point)
        QByteArray packedArgs;
        QDataStream stream( &packedArgs, QIODevice::WriteOnly );
        stream << (int)1;
        KIO::Job* job = KIO::special( KUrl("trash:/"), packedArgs );
        (void)KIO::NetAccess::synchronousRun( job, 0 );

        // Update konq windows opened on trash:/
        org::kde::KDirNotify::emitFilesAdded(QString::fromLatin1("trash:/")); // yeah, files were removed, but we don't know which ones...
        return 0;
    }

#if 0
    // This is only for testing. KDesktop handles it automatically.
    if ( args->isSet( "migrate" ) ) {
        QByteArray packedArgs;
        QDataStream stream( packedArgs, QIODevice::WriteOnly );
        stream << (int)2;
        KIO::Job* job = KIO::special( "trash:/", packedArgs );
        (void)KIO::NetAccess::synchronousRun( job, 0 );
        return 0;
    }
#endif

    QString restoreArg = args->getOption( "restore" );
    if ( !restoreArg.isEmpty() ) {

        if (restoreArg.indexOf(QLatin1String("system:/trash"))==0) {
            restoreArg.remove(0, 13);
            restoreArg.prepend(QString::fromLatin1("trash:"));
        }

        KUrl trashURL( restoreArg );
        if ( !trashURL.isValid() || trashURL.protocol() != QLatin1String("trash") ) {
            kError() << "Invalid URL for restoring a trashed file:" << trashURL << endl;
            return 1;
        }

        QByteArray packedArgs;
        QDataStream stream( &packedArgs, QIODevice::WriteOnly );
        stream << (int)3 << trashURL;
        KIO::Job* job = KIO::special( trashURL, packedArgs );
        bool ok = KIO::NetAccess::synchronousRun( job, 0 );
        if ( !ok )
            kError() << KIO::NetAccess::lastErrorString() << endl;
        return 0;
    }

    return 0;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    KAboutData aboutData( "kstars", 0, ki18n("KStars"),
                          KSTARS_VERSION, ki18n(description), KAboutData::License_GPL,
                          ki18n("(c) 2001-2012, The KStars Team"), ki18n(notice), "http://edu.kde.org/kstars");
    aboutData.addAuthor(ki18n("Jason Harris"),KLocalizedString(), "*****@*****.**", "http://www.30doradus.org");
    aboutData.addAuthor(ki18n("Jasem Mutlaq"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("James Bowlin"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Pablo de Vicente"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Thomas Kabelmann"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Heiko Evermann"),KLocalizedString(), "*****@*****.**", "http://www.evermann.de");
    aboutData.addAuthor(ki18n("Carsten Niehaus"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Mark Hollomon"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Alexey Khudyakov"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("M&eacute;d&eacute;ric Boquien"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Akarsh Simha"), KLocalizedString(), "*****@*****.**", "http://www.ph.utexas.edu/~asimha");
    aboutData.addAuthor(ki18n("J&eacute;r&ocirc;me Sonrier"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Prakash Mohan"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Victor Cărbune"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Henry de Valence"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Samikshan Bairagya"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Rafał Kułaga"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Rishab Arora"), KLocalizedString(), "*****@*****.**");

    aboutData.addCredit(ki18n("Valery Kharitonov"), ki18n("Converted labels containing technical terms to links to documentation") );
    aboutData.addCredit(ki18n("Ana-Maria Constantin"), ki18n("Technical documentation on Astronomy and KStars") );
    aboutData.addCredit(ki18n("Andrew Stepanenko"), ki18n("Guiding code based on lin_guider") );
    aboutData.addCredit(ki18n("Nuno Pinheiro"), ki18n("Artwork") );

    KCmdLineArgs::init( argc, argv, &aboutData );

    KCmdLineOptions options;
    options.add("!dump", ki18n( "Dump sky image to file" ));
    options.add("script ", ki18n( "Script to execute" ));
    options.add("width ", ki18n( "Width of sky image" ), "640");
    options.add("height ", ki18n( "Height of sky image" ), "480");
    options.add("filename ", ki18n( "Filename for sky image" ), "kstars.png");
    options.add("date ", ki18n( "Date and time" ));
    options.add("!paused", ki18n( "Start with clock paused" ));
    KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication a;

    if ( args->isSet( "dump" ) ) {
        kDebug() << i18n( "Dumping sky image" );

        //parse filename and image format
        const char* format = "PNG";
        QString fname = args->getOption( "filename" );
        QString ext = fname.mid( fname.lastIndexOf(".")+1 );
        if ( ext.toLower() == "png" ) { format = "PNG"; }
        else if ( ext.toLower() == "jpg" || ext.toLower() == "jpeg" ) { format = "JPG"; }
        else if ( ext.toLower() == "gif" ) { format = "GIF"; }
        else if ( ext.toLower() == "pnm" ) { format = "PNM"; }
        else if ( ext.toLower() == "bmp" ) { format = "BMP"; }
        else { kWarning() << i18n( "Could not parse image format of %1; assuming PNG.", fname ) ; }

        //parse width and height
        bool ok(false);
        int w(0), h(0);
        w = args->getOption( "width" ).toInt( &ok );
        if ( ok ) h =  args->getOption( "height" ).toInt( &ok );
        if ( !ok ) {
            kWarning() << "Unable to parse arguments: " ;
            kWarning() << "Width: " << args->getOption( "width" )
            << "  Height: " << args->getOption( "height" ) << endl;
            return 1;
        }

        KStarsData *dat = KStarsData::Create();
        QObject::connect( dat, SIGNAL( progressText(QString) ), dat, SLOT( slotConsoleMessage(QString) ) );
        dat->initialize();

        //Set Geographic Location
        dat->setLocationFromOptions();

        //Set color scheme
        dat->colorScheme()->loadFromConfig();

        //set clock now that we have a location:
        //Check to see if user provided a date/time string.  If not, use current CPU time
        QString datestring = args->getOption( "date" );
        KStarsDateTime kdt;
        if ( ! datestring.isEmpty() ) {
            if ( datestring.contains( "-" ) ) { //assume ISODate format
                if ( datestring.contains( ":" ) ) { //also includes time
                    kdt = KDateTime::fromString( datestring, KDateTime::ISODate );
                } else { //string probably contains date only
                    kdt.setDate( QDate::fromString( datestring, Qt::ISODate ) );
                    kdt.setTime( QTime( 0, 0, 0 ) );
                }
            } else { //assume Text format for date string
                kdt = dat->geo()->LTtoUT( KDateTime::fromString( datestring, KDateTime::QtTextDate ) );
            }

            if ( ! kdt.isValid() ) {
                kWarning() << i18n( "Using CPU date/time instead." ) ;

                kdt = KStarsDateTime::currentUtcDateTime();
            }
        } else {
            kdt = KStarsDateTime::currentUtcDateTime();
        }
        dat->clock()->setUTC( kdt );

        KSNumbers num( dat->ut().djd() );
        //		dat->initGuides(&num);

        SkyMap *map = SkyMap::Create();
        map->resize( w, h );
        QPixmap sky( w, h );

        dat->setFullTimeUpdate();
        dat->updateTime(dat->geo(), map );

        SkyPoint dest( Options::focusRA(), Options::focusDec() );
        map->setDestination( dest );
        map->destination()->EquatorialToHorizontal( dat->lst(), dat->geo()->lat() );
        map->setFocus( map->destination() );
        map->focus()->EquatorialToHorizontal( dat->lst(), dat->geo()->lat() );

        //Execute the specified script
        QString scriptfile = args->getOption( "script" );
        if ( ! scriptfile.isEmpty() ) {
            if ( dat->executeScript( scriptfile, map ) ) {
                std::cout << i18n( "Script executed." ).toUtf8().data() << std::endl;
            } else {
                kWarning() << i18n( "Could not execute script." ) ;
            }
        }

        qApp->processEvents();
        map->setupProjector();
        map->exportSkyImage( &sky );
        qApp->processEvents();

        if ( ! sky.save( fname, format ) ) kWarning() << i18n( "Unable to save image: %1 ", fname ) ;
        else kDebug() << i18n( "Saved to file: %1", fname );

        delete map;
        delete dat;
        return 0;
    }

    //start up normally in GUI mode

    //Try to parse the given date string
    QString datestring = args->getOption( "date" );
    //DEBUG
    kDebug() << "Date string: " << datestring;

    if ( ! datestring.isEmpty() && ! KStarsDateTime::fromString( datestring ).isValid() ) {
        kWarning() << i18n( "Using CPU date/time instead." ) ;
        datestring.clear();
    }

    KStars::createInstance( true, ! args->isSet( "paused" ), datestring );
    args->clear();
    QObject::connect(kapp, SIGNAL(lastWindowClosed()), kapp, SLOT(quit()));
    return a.exec();

}
Ejemplo n.º 21
0
KdeSudo::KdeSudo(QWidget *parent, const char *name,const QString& icon, const QString& generic, bool withIgnoreButton)
	: KPasswordDialog(KPasswordDialog::Password, false, (withIgnoreButton ? User1: false), icon, parent, name)
{
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	QString defaultComment = i18n("<b>%1</b> needs administrative privileges. Please enter your password for verification.");
	p=NULL;
	bError=false;

	m_pCookie = new KCookie;

	// Set vars
	bool newDcop = args->isSet("newdcop");
	bool realtime = args->isSet("r");
	bool priority = args->isSet("p");
	bool showCommand = (!args->isSet("d"));
	bool changeUID = true;
	bool noExec = false;
	keepPwd = (!args->isSet("n"));
	emptyPwd = args->isSet("s");
	QString runas = args->getOption("u");
	QString cmd;

	if (!args->isSet("c") && !args->count() && (!args->isSet("s")))
	{
		KMessageBox::information(NULL, i18n("No command arguments supplied!\nUsage: kdesudo [-u <runas>] <command>\nKdeSudo will now exit..."));
		noExec = true;
	}

	p = new KProcess;
	p->clearArguments();

	// Parsins args

	/* Get the comment out of cli args */
	QByteArray commentBytes = args->getOption("comment");
	QTextCodec* tCodecConv = QTextCodec::codecForLocale();
	QString comment = tCodecConv->toUnicode(commentBytes, commentBytes.size());

	if (args->isSet("f"))
	{
		// If file is writeable, do not change uid
		QString filename = QFile::decodeName(args->getOption("f"));
		QString file = filename;
		if (!file.isEmpty())
		{
			if (file.at(0) != '/')
			{
				KStandardDirs dirs;
				dirs.addKDEDefaults();
				file = dirs.findResource("config", file);
				if (file.isEmpty())
				{
					kdError(1206) << "Config file not found: " << file << "\n";
					exit(1);
				}
			}
			QFileInfo fi(file);
			if (!fi.exists())
			{
				kdError(1206) << "File does not exist: " << file << "\n";
				exit(1);
			}
			if (fi.isWritable())
			{
				changeUID = false;
			}
		}
	}

	if (withIgnoreButton)
	{
		setButtonText(User1, i18n("&Ignore"));
	}

	// Apologies for the C code, taken from kdelibs/kdesu/kdesu_stub.c
	// KControl and other places need to use the user's existing DCOP server
	// For that we set DCOPSERVER.  Create a file in /tmp and use iceauth to add magic cookies
	// from the existing server and set ICEAUTHORITY to point to the file
	if (!newDcop) {
		dcopServer = m_pCookie->dcopServer();
		QCString dcopAuth = m_pCookie->dcopAuth();
		QCString iceAuth = m_pCookie->iceAuth();

		FILE *fout;
		char iceauthority[200];
		char *host, *auth;
		host = qstrdup(dcopServer);
		auth = qstrdup(iceAuth);
		int tempfile;
		int oldumask = umask(077);

		strcpy(iceauthority, "/tmp/iceauth.XXXXXXXXXX");
		tempfile = mkstemp(iceauthority);
		umask(oldumask);
		if (tempfile == -1) {
			kdError() << "error in kdesudo mkstemp" << endl;
			exit(1);
		} else {
			// close(tempfile); //FIXME why does this make the connect() call later crash?
		}
		iceauthorityFile = iceauthority;
		//FIXME we should change owner of iceauthority file, but don't have permissions
		setenv("ICEAUTHORITY", iceauthorityFile, 1);
	
		fout = popen("iceauth >/dev/null 2>&1", "w");
		if (!fout) {
			kdError() << "error in kdesudo running iceauth" << endl;
			exit(1);
		}
		fprintf(fout, "add ICE \"\" %s %s\n", host, auth);
		auth = qstrdup(dcopAuth);
		//auth = xstrsep(params[P_DCOP_AUTH].value);
		fprintf(fout, "add DCOP \"\" %s %s\n", host, auth);
		unsetenv("ICEAUTHORITY");
		pclose(fout);
	}

	connect( p, SIGNAL(receivedStdout(KProcess*, char*, int)), this, SLOT(receivedOut(KProcess*, char*, int)) );
	connect( p, SIGNAL(receivedStderr(KProcess*, char*, int)), this, SLOT(receivedOut(KProcess*, char*, int)) );
	connect( p, SIGNAL(processExited (KProcess *)), this, SLOT(procExited(KProcess*)));

	QString xauthenv = QString(getenv("HOME")) + "/.Xauthority";
	p->setEnvironment("XAUTHORITY", xauthenv);

	// Generate the xauth cookie and put it in a tempfile
	// set the environment variables to reflect that.
	// Default cookie-timeout is 60 sec. .
	// 'man xauth' for more info on xauth cookies.
	
	KTempFile temp = KTempFile("/tmp/kdesudo-","-xauth");
	m_tmpname = temp.name();
	
	FILE *f;
	char buf[1024];
	
	QCString disp = m_pCookie->display();
	// command: xauth -q -f m_tmpname generate $DISPLAy . trusted timeout 60
	QString c = "/usr/bin/xauth -q -f " + m_tmpname + " generate " 
		+ QString::fromLocal8Bit(disp) + " . trusted timeout 60";
	blockSigChild(); // pclose uses waitpid()
	
	if (!(f = popen(c, "r"))) {
		kdWarning() << k_lineinfo << "Cannot run: " << c << "\n";
		unblockSigChild();
		return;
	}
	
	// non root users need to be able to read the xauth file.
	// the xauth file is deleted when kdesudo exits. security?
	QFile tf(m_tmpname);
	if (!runas.isEmpty() && runas != "root" && tf.exists())
		chmod(m_tmpname.ascii(),0644);
	
	QCStringList output;
	while (fgets(buf, 1024, f) > 0)
		output += buf; 
	if (pclose(f) < 0) {
		kdError() << k_lineinfo << "Could not run xauth.\n";
		unblockSigChild();
		return;
	}
	unblockSigChild();
	
	p->setEnvironment("DISPLAY", disp); 
	p->setEnvironment("XAUTHORITY", m_tmpname);

	if (emptyPwd)
		*p << "sudo" << "-k";
	else
	{
		if (changeUID)
		{
			*p << "sudo" << "-H" << "-S" << "-p" << "passprompt";

			if (!runas.isEmpty())
				*p << "-u" << runas;
		}

		if (!dcopServer.isEmpty())
			*p << "DCOPSERVER=" + dcopServer;

		if (!iceauthorityFile.isEmpty())
			*p << "ICEAUTHORITY=" + iceauthorityFile;

		if (realtime)
		{
			*p << "nice" << "-n" << "10";
			addLine(i18n("Priority:"), i18n("realtime:") + QChar(' ') + QString("50/100"));
		}
		else if (priority)
		{
			QString n = args->getOption("p");
			int intn = atoi(n);
			intn =  (intn * 40 / 100) - (20 + 0.5);
		
			QString strn;
			strn.sprintf("%d",intn);

			*p << "nice" << "-n" << strn;
			addLine(i18n("Priority:"), n + QString("/100"));
		}

		*p << "--";

		if (args->isSet("c"))
		{
			QString command = args->getOption("c");
			QStringList commandSplit = QStringList::split(" ", command);
			for (int i = 0; i < commandSplit.count(); i++)
			{
				QString toto = validArg(commandSplit[i]);
				*p << toto;
				cmd += validArg(commandSplit[i]) + QChar(' ');
			}
		}
		else if (args->count())
		{
			for (int i = 0; i < args->count(); i++)
			{
				if (i==0)
				{
					QStringList argsSplit = QStringList::split(" ", args->arg(i));
					for (int i = 0; i < argsSplit.count(); i++)
					{
						*p << validArg(argsSplit[i]);
						cmd += validArg(argsSplit[i]) + QChar(' ');
					}
				}
				else
				{
					*p << validArg(args->arg(i));
					cmd += validArg(args->arg(i)) + QChar(' ');
				}
			}
		}
		// strcmd needs to be defined
		if (showCommand && !cmd.isEmpty())
			addLine(i18n("Command:"), cmd);
	}

	if (comment.isEmpty())
	{
		if (!generic.isEmpty())
			setPrompt(defaultComment.arg(generic));
		else
			setPrompt(defaultComment.arg(cmd));
	}
	else
		setPrompt(comment);

	if (noExec)
		exit(0);
	else
		p->start( KProcess::NotifyOnExit, KProcess::All );
}
Ejemplo n.º 22
0
/* --| main |------------------------------------------------------ */
extern "C" int KDE_EXPORT kdemain(int argc, char *argv[])
{
    setgid(getgid());
    setuid(getuid()); // drop privileges

    // deal with shell/command ////////////////////////////
    bool histon = true;
    bool menubaron = true;
    bool tabbaron = true;
    bool frameon = true;
    bool scrollbaron = true;
    bool showtip = true;

    KAboutData aboutData("konsole", I18N_NOOP("Konsole"), KONSOLE_VERSION, description, KAboutData::License_GPL_V2,
                         "Copyright (c) 1997-2006, Lars Doelle");
    aboutData.addAuthor("Robert Knight", I18N_NOOP("Maintainer"), "*****@*****.**");
    aboutData.addAuthor("Lars Doelle", I18N_NOOP("Author"), "*****@*****.**");
    aboutData.addCredit("Kurt V. Hindenburg", I18N_NOOP("bug fixing and improvements"), "*****@*****.**");
    aboutData.addCredit("Waldo Bastian", I18N_NOOP("bug fixing and improvements"), "*****@*****.**");
    aboutData.addCredit("Stephan Binner", I18N_NOOP("bug fixing and improvements"), "*****@*****.**");
    aboutData.addCredit("Chris Machemer", I18N_NOOP("bug fixing"), "*****@*****.**");
    aboutData.addCredit("Stephan Kulow", I18N_NOOP("Solaris support and work on history"), "*****@*****.**");
    aboutData.addCredit("Alexander Neundorf", I18N_NOOP("faster startup, bug fixing"), "*****@*****.**");
    aboutData.addCredit("Peter Silva", I18N_NOOP("decent marking"), "*****@*****.**");
    aboutData.addCredit("Lotzi Boloni", I18N_NOOP("partification\n"
                                                  "Toolbar and session names"),
                        "*****@*****.**");
    aboutData.addCredit("David Faure", I18N_NOOP("partification\n"
                                                 "overall improvements"),
                        "*****@*****.**");
    aboutData.addCredit("Antonio Larrosa", I18N_NOOP("transparency"), "*****@*****.**");
    aboutData.addCredit("Matthias Ettrich", I18N_NOOP("most of main.C donated via kvt\n"
                                                      "overall improvements"),
                        "*****@*****.**");
    aboutData.addCredit("Warwick Allison", I18N_NOOP("schema and selection improvements"), "*****@*****.**");
    aboutData.addCredit("Dan Pilone", I18N_NOOP("SGI Port"), "*****@*****.**");
    aboutData.addCredit("Kevin Street", I18N_NOOP("FreeBSD port"), "*****@*****.**");
    aboutData.addCredit("Sven Fischer", I18N_NOOP("bug fixing"), "*****@*****.**");
    aboutData.addCredit("Dale M. Flaven", I18N_NOOP("bug fixing"), "*****@*****.**");
    aboutData.addCredit("Martin Jones", I18N_NOOP("bug fixing"), "*****@*****.**");
    aboutData.addCredit("Lars Knoll", I18N_NOOP("bug fixing"), "*****@*****.**");
    aboutData.addCredit("", I18N_NOOP("Thanks to many others.\n"
                                      "The above list only reflects the contributors\n"
                                      "I managed to keep track of."));

    KCmdLineArgs::init(argc, argv, &aboutData);
    KCmdLineArgs::addCmdLineOptions(options); // Add our own options.
    // 1.53 sec
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    KCmdLineArgs *qtargs = KCmdLineArgs::parsedArgs("qt");
    has_noxft = !args->isSet("xft");
    TEWidget::setAntialias(!has_noxft);
    TEWidget::setStandalone(true);

    // The following Qt options have no effect; warn users.
    if(qtargs->isSet("background"))
        kdWarning() << "The Qt option -bg, --background has no effect." << endl;
    if(qtargs->isSet("foreground"))
        kdWarning() << "The Qt option -fg, --foreground has no effect." << endl;
    if(qtargs->isSet("button"))
        kdWarning() << "The Qt option -btn, --button has no effect." << endl;
    if(qtargs->isSet("font"))
        kdWarning() << "The Qt option -fn, --font has no effect." << endl;

    KApplication *a = NULL;
#ifdef COMPOSITE
    if(args->isSet("real-transparency"))
    {
        char *display = 0;
        if(qtargs->isSet("display"))
            display = qtargs->getOption("display").data();

        Display *dpy = XOpenDisplay(display);
        if(!dpy)
        {
            kdError() << "cannot connect to X server " << display << endl;
            exit(1);
        }

        int screen = DefaultScreen(dpy);
        Colormap colormap = 0;
        Visual *visual = 0;
        int event_base, error_base;

        if(XRenderQueryExtension(dpy, &event_base, &error_base))
        {
            int nvi;
            XVisualInfo templ;
            templ.screen = screen;
            templ.depth = 32;
            templ.c_class = TrueColor;
            XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask | VisualDepthMask | VisualClassMask, &templ, &nvi);

            for(int i = 0; i < nvi; i++)
            {
                XRenderPictFormat *format = XRenderFindVisualFormat(dpy, xvi[i].visual);
                if(format->type == PictTypeDirect && format->direct.alphaMask)
                {
                    visual = xvi[i].visual;
                    colormap = XCreateColormap(dpy, RootWindow(dpy, screen), visual, AllocNone);
                    kdDebug() << "found visual with alpha support" << endl;
                    argb_visual = true;
                    break;
                }
            }
        }
        // The QApplication ctor used is normally intended for applications not using Qt
        // as the primary toolkit (e.g. Motif apps also using Qt), with some slightly
        // unpleasant side effects (e.g. #83974). This code checks if qt-copy patch #0078
        // is applied, which allows turning this off.
        bool *qt_no_foreign_hack = static_cast< bool * >(dlsym(RTLD_DEFAULT, "qt_no_foreign_hack"));
        if(qt_no_foreign_hack)
            *qt_no_foreign_hack = true;
        // else argb_visual = false ... ? *shrug*

        if(argb_visual)
            a = new KApplication(dpy, Qt::HANDLE(visual), Qt::HANDLE(colormap));
        else
            XCloseDisplay(dpy);
    }
    if(a == NULL)
        a = new KApplication;
#else
    KApplication *a = new KApplication;
#endif

    QString dataPathBase = KStandardDirs::kde_default("data").append("konsole/");
    KGlobal::dirs()->addResourceType("wallpaper", dataPathBase + "wallpapers");

    KImageIO::registerFormats(); // add io for additional image formats
    // 2.1 secs

    QString title;
    if(args->isSet("T"))
    {
        title = QFile::decodeName(args->getOption("T"));
    }
    if(qtargs->isSet("title"))
    {
        title = QFile::decodeName(qtargs->getOption("title"));
    }

    QString term = "";
    if(args->isSet("tn"))
    {
        term = QString::fromLatin1(args->getOption("tn"));
    }
    login_shell = args->isSet("ls");

    QStrList eargs;

    const char *shell = 0;
    if(!args->getOption("e").isEmpty())
    {
        if(args->isSet("ls"))
            KCmdLineArgs::usage(i18n("You can't use BOTH -ls and -e.\n"));
        shell = strdup(args->getOption("e"));
        eargs.append(shell);
        for(int i = 0; i < args->count(); i++)
            eargs.append(args->arg(i));

        if(title.isEmpty() && (kapp->caption() == kapp->aboutData()->programName()))
        {
            title = QFile::decodeName(shell); // program executed in the title bar
        }
        showtip = false;
    }

    QCString sz = "";
    sz = args->getOption("vt_sz");
    histon = args->isSet("hist");
    menubaron = args->isSet("menubar");
    tabbaron = args->isSet("tabbar") && args->isSet("toolbar");
    frameon = args->isSet("frame");
    scrollbaron = args->isSet("scrollbar");
    QCString wname = qtargs->getOption("name");
    full_script = args->isSet("script");
    auto_close = args->isSet("close");
    fixed_size = !args->isSet("resize");

    if(!full_script)
        a->dcopClient()->setQtBridgeEnabled(false);

    QCString type = "";

    if(args->isSet("type"))
    {
        type = args->getOption("type");
    }
    if(args->isSet("types"))
    {
        QStringList types = KGlobal::dirs()->findAllResources("appdata", "*.desktop", false, true);
        types.sort();
        for(QStringList::ConstIterator it = types.begin(); it != types.end(); ++it)
        {
            QString file = *it;
            file = file.mid(file.findRev('/') + 1);
            if(file.endsWith(".desktop"))
                file = file.left(file.length() - 8);
            printf("%s\n", QFile::encodeName(file).data());
        }
        return 0;
    }
    if(args->isSet("schemas") || args->isSet("schemata"))
    {
        ColorSchemaList colors;
        colors.checkSchemas();
        for(int i = 0; i < (int)colors.count(); i++)
        {
            ColorSchema *schema = colors.find(i);
            QString relPath = schema->relPath();
            if(!relPath.isEmpty())
                printf("%s\n", QFile::encodeName(relPath).data());
        }
        return 0;
    }

    if(args->isSet("keytabs"))
    {
        QStringList lst = KGlobal::dirs()->findAllResources("data", "konsole/*.keytab");

        printf("default\n"); // 'buildin' keytab
        lst.sort();
        for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it)
        {
            QFileInfo fi(*it);
            QString file = fi.baseName();
            printf("%s\n", QFile::encodeName(file).data());
        }
        return 0;
    }

    QString workDir = QFile::decodeName(args->getOption("workdir"));

    QString keytab = "";
    if(args->isSet("keytab"))
        keytab = QFile::decodeName(args->getOption("keytab"));

    QString schema = "";
    if(args->isSet("schema"))
        schema = args->getOption("schema");

    KConfig *sessionconfig = 0;
    QString profile = "";
    if(args->isSet("profile"))
    {
        profile = args->getOption("profile");
        QString path = locate("data", "konsole/profiles/" + profile);
        if(QFile::exists(path))
            sessionconfig = new KConfig(path, true);
        else
            profile = "";
    }
    if(args->isSet("profiles"))
    {
        QStringList profiles = KGlobal::dirs()->findAllResources("data", "konsole/profiles/*", false, true);
        profiles.sort();
        for(QStringList::ConstIterator it = profiles.begin(); it != profiles.end(); ++it)
        {
            QString file = *it;
            file = file.mid(file.findRev('/') + 1);
            printf("%s\n", QFile::encodeName(file).data());
        }
        return 0;
    }


    // FIXME: more: font

    args->clear();

    int c = 0, l = 0;
    if(!sz.isEmpty())
    {
        char *ls = (char *)strchr(sz.data(), 'x');
        if(ls != NULL)
        {
            *ls = '\0';
            ls++;
            c = atoi(sz.data());
            l = atoi(ls);
        }
        else
        {
            KCmdLineArgs::usage(i18n("expected --vt_sz <#columns>x<#lines> e.g. 80x40\n"));
        }
    }

    if(!kapp->authorizeKAction("size"))
        fixed_size = true;

    // ///////////////////////////////////////////////

    // Ignore SIGHUP so that we don't get killed when
    // our parent-shell gets closed.
    signal(SIGHUP, SIG_IGN);

    putenv((char *)"COLORTERM="); // to trigger mc's color detection
    KonsoleSessionManaged ksm;

    if(a->isRestored() || !profile.isEmpty())
    {
        if(!shell)
            shell = konsole_shell(eargs);

        if(profile.isEmpty())
            sessionconfig = a->sessionConfig();
        sessionconfig->setDesktopGroup();
        int n = 1;

        QString key;
        QString sTitle;
        QString sPgm;
        QString sTerm;
        QString sIcon;
        QString sCwd;
        int n_tabbar;

        // TODO: Session management stores everything in same group,
        // should use one group / mainwindow
        while(KMainWindow::canBeRestored(n) || !profile.isEmpty())
        {
            sessionconfig->setGroup(QString("%1").arg(n));
            if(!sessionconfig->hasKey("Pgm0"))
                sessionconfig->setDesktopGroup(); // Backwards compatible

            int session_count = sessionconfig->readNumEntry("numSes");
            int counter = 0;

            wname = sessionconfig->readEntry("class", wname).latin1();

            sPgm = sessionconfig->readEntry("Pgm0", shell);
            sessionconfig->readListEntry("Args0", eargs);
            sTitle = sessionconfig->readEntry("Title0", title);
            sTerm = sessionconfig->readEntry("Term0");
            sIcon = sessionconfig->readEntry("Icon0", "konsole");
            sCwd = sessionconfig->readPathEntry("Cwd0");
            workDir = sessionconfig->readPathEntry("workdir");
            n_tabbar = QMIN(sessionconfig->readUnsignedNumEntry("tabbar", Konsole::TabBottom), 2);
            Konsole *m = new Konsole(wname, histon, menubaron, tabbaron, frameon, scrollbaron, 0 /*type*/, true, n_tabbar, workDir);

            m->newSession(sPgm, eargs, sTerm, sIcon, sTitle, sCwd);

            m->enableFullScripting(full_script);
            m->enableFixedSize(fixed_size);
            m->restore(n);
            sessionconfig->setGroup(QString("%1").arg(n));
            if(!sessionconfig->hasKey("Pgm0"))
                sessionconfig->setDesktopGroup(); // Backwards compatible
            m->makeGUI();
            m->setEncoding(sessionconfig->readNumEntry("Encoding0"));
            m->setSchema(sessionconfig->readEntry("Schema0"));
            // Use konsolerc default as tmpFont instead?
            QFont tmpFont = KGlobalSettings::fixedFont();
            m->initSessionFont(sessionconfig->readFontEntry("SessionFont0", &tmpFont));
            m->initSessionKeyTab(sessionconfig->readEntry("KeyTab0"));
            m->initMonitorActivity(sessionconfig->readBoolEntry("MonitorActivity0", false));
            m->initMonitorSilence(sessionconfig->readBoolEntry("MonitorSilence0", false));
            m->initMasterMode(sessionconfig->readBoolEntry("MasterMode0", false));
            m->initTabColor(sessionconfig->readColorEntry("TabColor0"));
            // -1 will be changed to the default history in konsolerc
            m->initHistory(sessionconfig->readNumEntry("History0", -1), sessionconfig->readBoolEntry("HistoryEnabled0", true));
            counter++;

            // show() before 2nd+ sessions are created allows --profile to
            //  initialize the TE size correctly.
            m->show();

            while(counter < session_count)
            {
                key = QString("Title%1").arg(counter);
                sTitle = sessionconfig->readEntry(key, title);
                key = QString("Args%1").arg(counter);
                sessionconfig->readListEntry(key, eargs);

                key = QString("Pgm%1").arg(counter);

                // if the -e option is passed on the command line, this overrides the program specified
                // in the profile file
                if(args->isSet("e"))
                    sPgm = (shell ? QFile::decodeName(shell) : QString::null);
                else
                    sPgm = sessionconfig->readEntry(key, shell);

                key = QString("Term%1").arg(counter);
                sTerm = sessionconfig->readEntry(key);
                key = QString("Icon%1").arg(counter);
                sIcon = sessionconfig->readEntry(key, "konsole");
                key = QString("Cwd%1").arg(counter);
                sCwd = sessionconfig->readPathEntry(key);
                m->newSession(sPgm, eargs, sTerm, sIcon, sTitle, sCwd);
                m->setSessionTitle(sTitle); // Use title as is
                key = QString("Schema%1").arg(counter);
                m->setSchema(sessionconfig->readEntry(key));
                key = QString("Encoding%1").arg(counter);
                m->setEncoding(sessionconfig->readNumEntry(key));
                key = QString("SessionFont%1").arg(counter);
                QFont tmpFont = KGlobalSettings::fixedFont();
                m->initSessionFont(sessionconfig->readFontEntry(key, &tmpFont));
                key = QString("KeyTab%1").arg(counter);
                m->initSessionKeyTab(sessionconfig->readEntry(key));
                key = QString("MonitorActivity%1").arg(counter);
                m->initMonitorActivity(sessionconfig->readBoolEntry(key, false));
                key = QString("MonitorSilence%1").arg(counter);
                m->initMonitorSilence(sessionconfig->readBoolEntry(key, false));
                key = QString("MasterMode%1").arg(counter);
                m->initMasterMode(sessionconfig->readBoolEntry(key, false));
                key = QString("TabColor%1").arg(counter);
                m->initTabColor(sessionconfig->readColorEntry(key));
                // -1 will be changed to the default history in konsolerc
                key = QString("History%1").arg(counter);
                QString key2 = QString("HistoryEnabled%1").arg(counter);
                m->initHistory(sessionconfig->readNumEntry(key, -1), sessionconfig->readBoolEntry(key2, true));
                counter++;
            }
            m->setDefaultSession(sessionconfig->readEntry("DefaultSession", "shell.desktop"));

            m->initFullScreen();
            if(!profile.isEmpty())
            {
                m->callReadPropertiesInternal(sessionconfig, 1);
                profile = "";
                // Hack to work-around sessions initialized with minimum size
                for(int i = 0; i < counter; i++)
                    m->activateSession(i);
                m->setColLin(c, l); // will use default height and width if called with (0,0)
            }
            // works only for the first one, but there won't be more.
            n++;
            m->activateSession(sessionconfig->readNumEntry("ActiveSession", 0));
            m->setAutoClose(auto_close);
        }
    }
    else
    {
        Konsole *m = new Konsole(wname, histon, menubaron, tabbaron, frameon, scrollbaron, type, false, 0, workDir);
        m->newSession((shell ? QFile::decodeName(shell) : QString::null), eargs, term, QString::null, title, workDir);
        m->enableFullScripting(full_script);
        m->enableFixedSize(fixed_size);
        // 3.8 :-(
        // exit(0);

        if(!keytab.isEmpty())
            m->initSessionKeyTab(keytab);

        if(!schema.isEmpty())
        {
            if(schema.right(7) != ".schema")
                schema += ".schema";
            m->setSchema(schema);
            m->activateSession(0); // Fixes BR83162, transp. schema + notabbar
        }

        m->setColLin(c, l); // will use default height and width if called with (0,0)

        m->initFullScreen();
        m->show();
        if(showtip)
            m->showTipOnStart();
        m->setAutoClose(auto_close);
    }

    int ret = a->exec();

    //// Temporary code, waiting for Qt to do this properly

    // Delete all toplevel widgets that have WDestructiveClose
    QWidgetList *list = QApplication::topLevelWidgets();
    // remove all toplevel widgets that have a parent (i.e. they
    // got WTopLevel explicitly), they'll be deleted by the parent
    list->first();
    while(list->current())
    {
        if(list->current()->parentWidget() != NULL || !list->current()->testWFlags(Qt::WDestructiveClose))
        {
            list->remove();
            continue;
        }
        list->next();
    }
    QWidgetListIt it(*list);
    QWidget *w;
    while((w = it.current()) != 0)
    {
        ++it;
        delete w;
    }
    delete list;

    delete a;

    return ret;
}
Ejemplo n.º 23
0
int main(int argc, char** argv)
{
    KAboutData aboutData("CCSGraph",
                         0,
                         ki18n("CCSGraph"),
                         "1.0",
                         ki18n("Output the graph of color conversion of pigment's Color Conversion"),
                         KAboutData::License_LGPL,
                         ki18n("(c) 2007 Cyrille Berger"),
                         KLocalizedString(),
                         "www.koffice.org",
                         "*****@*****.**");
    KCmdLineArgs::init( argc, argv, &aboutData );
    // Initialize the list of options
    KCmdLineOptions options;
    options.add("graphs", ki18n("return the list of available graphs"));
    options.add("graph <type>", ki18n("specify the type of graph (see --graphs to get the full list, the default is full)"), "full");
    options.add("src-key <key>", ki18n("specify the key of the source color space"), "");
    options.add("dst-key <key>", ki18n("specify the key of the destination color space"), "");
    options.add("output <type>", ki18n("specify the output (can be ps or dot, the default is ps)"), "ps");
    options.add("+outputfile", ki18n("name of the output file"));
    KCmdLineArgs::addCmdLineOptions( options );
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if( args->isSet("graphs"))
    {
        // Don't change those lines to use qDebug derivatives, they need to be outputed
        // to stdout not stderr.
        std::cout << "full : show all the connection on the graph" << std::endl;
        std::cout << "bestpath : show the best path for a given transformation" << std::endl;
        exit(EXIT_SUCCESS);
    }
    QString graphType = args->getOption("graph");
    QString outputType = args->getOption("output");
    if( args->count() != 1 )
    {
        kError() << "No output file name specified";
        args->usage();
        exit(EXIT_FAILURE);
    }
    QString outputFileName = args->arg(0);
    // Generate the graph
    KApplication app;
    QString dot;
    if(graphType == "full")
    {
        dot = KoColorSpaceRegistry::instance()->colorConversionSystem()->toDot();
    } else if(graphType == "bestpath") {
        QString srcKey = args->getOption("src-key");
        QString dstKey = args->getOption("dst-key");
        if (srcKey == "" or dstKey == "") {
            kError() << "src-key and dst-key must be specified for the graph bestpath";
            exit(EXIT_FAILURE);
        }
        else {
            dot = KoColorSpaceRegistry::instance()->colorConversionSystem()->bestPathToDot(srcKey, dstKey );
        }
    } else {
        kError() << "Unknow graph type : " << graphType.toLatin1();
        exit(EXIT_FAILURE);
    }

    if (outputType == "dot") {
        QFile file(outputFileName);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
            exit(EXIT_FAILURE);
        QTextStream out(&file);
        out << dot;
    }
    else if (outputType == "ps" or outputType == "svg" ) {
        QTemporaryFile file;
        if (!file.open()) {
            exit(EXIT_FAILURE);
        }
        QTextStream out(&file);
        out << dot;
        QString cmd = QString("dot -T%1 %2 -o %3").arg(outputType).arg(file.fileName()).arg(outputFileName);
        file.close();

        if (QProcess::execute(cmd) != 0)
        {
            kError() << "An error has occurred when executing : '" << cmd << "' the most likely cause is that 'dot' command is missing, and that you should install graphviz (from http://www.graphiz.org)";
        }
    }
    else {
        kError() << "Unknow output type : " << outputType;
        exit(EXIT_FAILURE);
    }
}
Ejemplo n.º 24
0
int main ( int argc, char *argv[] )
{
    KAboutData aboutData( "marble", 0,
                          ki18n( "Marble Virtual Globe" ),
                          ControlView::applicationVersion().toLatin1(),
                          ki18n( "A World Atlas." ),
                          KAboutData::License_LGPL,
                          ki18n( "(c) 2007-2012" ), // FIXME: use subs() here and replace 2012 by %1
                          KLocalizedString(),
                          "http://edu.kde.org/marble" );

    // Active Development Team of Marble
    aboutData.addAuthor( ki18n( "Torsten Rahn" ),
                         ki18n( "Developer and Original Author" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Bernhard Beschow" ),
                         ki18n( "WMS Support, Mobile, Performance" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Thibaut Gridel" ),
                         ki18n( "Geodata" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Jens-Michael Hoffmann" ),
                         ki18n( "OpenStreetMap Integration, OSM Namefinder, Download Management" ),
                         "*****@*****.**", "http://www.c-xx.com" );
    aboutData.addAuthor( ki18n( "Florian E&szlig;er" ),
                         ki18n( "Elevation Profile" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Wes Hardaker" ),
                         ki18n( "APRS Plugin" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Bastian Holst" ),
                         ki18n( "Online Services support" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Guillaume Martres" ),
                         ki18n( "Satellites" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Rene Kuettner" ),
                         ki18n( "Satellites, Eclipses" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Friedrich W. H. Kossebau" ),
                         ki18n( "Plasma Integration, Bugfixes" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Dennis Nienhüser" ),
                         ki18n( "Routing, Navigation, Mobile" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Niko Sams" ),
                         ki18n( "Routing, Elevation Profile" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Patrick Spendrin" ),
                         ki18n( "Core Developer: KML and Windows support" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Eckhart Wörner" ),
                         ki18n( "Bugfixes" ),
                         "*****@*****.**" );
    
    // Developers:    
    
    aboutData.addAuthor( ki18n( "Inge Wallin" ),
                         ki18n( "Core Developer and Co-Maintainer" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Henry de Valence" ),
                         ki18n( "Core Developer: Marble Runners, World-Clock Plasmoid" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Pino Toscano" ),
                         ki18n( "Network plugins" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Harshit Jain" ),
                         ki18n( "Planet filter" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Simon Edwards" ),
                         ki18n( "Marble Python Bindings" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Magnus Valle" ),
                         ki18n( "Historical Maps" ),
                         "" );
    aboutData.addAuthor( ki18n( "Médéric Boquien" ),
                         ki18n( "Astronomical Observatories" ),
                         "*****@*****.**" );

    // ESA Summer of Code in Space
    aboutData.addAuthor( ki18n( "Rene Kuettner" ),
                         ki18n( "ESA Summer of Code in Space 2012 Project:"
                                " Visualization of planetary satellites" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Guillaume Martres" ),
                         ki18n( "ESA Summer of Code in Space 2011 Project:"
                                " Visualisation of Satellite Orbits" ),
                         "*****@*****.**" );    
    
    // Google Summer of Code
    aboutData.addAuthor( ki18n( "Konstantin Oblaukhov" ),
                         ki18n( "Google Summer of Code 2011 Project:"
                                " OpenStreetMap Vector Rendering" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Daniel Marth" ),
                         ki18n( "Google Summer of Code 2011 Project:"
                                " Marble Touch on MeeGo" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Gaurav Gupta" ),
                         ki18n( "Google Summer of Code 2010 Project:"
                                " Bookmarks" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Harshit Jain " ),
                         ki18n( "Google Summer of Code 2010 Project:"
                                " Time Support" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Siddharth Srivastava" ),
                         ki18n( "Google Summer of Code 2010 Project:"
                                " Turn-by-turn Navigation" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Andrew Manson" ),
                         ki18n( "Google Summer of Code 2009 Project:"
                                " OSM Annotation" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Bastian Holst" ),
                         ki18n( "Google Summer of Code 2009 Project:"
                                " Online Services" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Patrick Spendrin" ),
                         ki18n( "Google Summer of Code 2008 Project:"
                                " Vector Tiles for Marble" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Shashank Singh" ),
                         ki18n( "Google Summer of Code 2008 Project:"
                                " Panoramio / Wikipedia -photo support for Marble" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Carlos Licea" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " Equirectangular Projection (\"Flat Map\")" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Andrew Manson" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " GPS Support for Marble" ),
                         "*****@*****.**" );
    aboutData.addAuthor( ki18n( "Murad Tagirov" ),
                         ki18n( "Google Summer of Code 2007 Project:"
                                " KML Support for Marble" ),
                         "*****@*****.**" );

    // Developers
    aboutData.addAuthor( ki18n( "Simon Schmeisser" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Claudiu Covaci" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "David Roberts" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Nikolas Zimmermann" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Jan Becker" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Stefan Asserhäll" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Laurent Montel" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Mayank Madan" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Prashanth Udupa" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Anne-Marie Mahfouf" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Josef Spillner" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Frerich Raabe" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Frederik Gladhorn" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Fredrik Höglund" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Albert Astals Cid" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Thomas Zander" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Joseph Wenninger" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Kris Thomsen" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Daniel Molkentin" ),
                         ki18n( "Development & Patches" ));
    aboutData.addAuthor( ki18n( "Christophe Leske" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Sebastian Wiedenroth" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Tim Sutton" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Christian Ehrlicher" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Ralf Habacker" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Steffen Joeris" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Marcus Czeslinski" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Marcus D. Hanwell" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Chitlesh Goorah" ),
                         ki18n( "Platforms & Distributions" ));
    aboutData.addAuthor( ki18n( "Nuno Pinheiro" ),
                         ki18n( "Artwork" ));
    aboutData.addAuthor( ki18n( "Torsten Rahn" ),
                         ki18n( "Artwork" ));

    // Credits
    aboutData.addCredit( ki18n( "Luis Silva" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Stefan Jordan" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Robert Scott" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Lubos Petrovic" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Benoit Sigoure" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Martin Konold" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Matthias Welwarsky" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Rainer Endres" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Ralf Gesellensetter" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "Tim Alder" ),
                         ki18n( "Various Suggestions & Testing" ));
    aboutData.addCredit( ki18n( "John Layt" ),
                         ki18n( "Special thanks for providing an"
                                " important source of inspiration by creating"
                                " Marble's predecessor \"Kartographer\"." ));

    QApplication::setGraphicsSystem( readGraphicsSystem( argc, argv, aboutData ) );

    KCmdLineArgs::init( argc, argv, &aboutData );

    // Autodetect profiles
    MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();

    KCmdLineOptions  options;
    options.add( "debug-info", ki18n( "Enable debug output" ) );
    options.add( "timedemo", ki18n( "Make a time measurement to check performance" ) );
    options.add( "fps", ki18n( "Show frame rate" ) );
    options.add( "tile-id", ki18n( "Show tile IDs" ) );
    options.add( "runtimeTrace", ki18n( "Show time spent in each layer" ) );
    options.add( "marbledatapath <data path>", ki18n( "Use a different directory which contains map data" ) );
    if( profiles & MarbleGlobal::SmallScreen ) {
        options.add( "nosmallscreen", ki18n( "Do not use the interface optimized for small screens" ) );
    }
    else {
        options.add( "smallscreen", ki18n( "Use the interface optimized for small screens" ) );
    }
    if( profiles & MarbleGlobal::HighResolution ) {
        options.add( "nohighresolution", ki18n( "Do not use the interface optimized for high resolutions" ) );
    }
    else {
        options.add( "highresolution", ki18n( "Use the interface optimized for high resolutions" ) );
    }
    options.add( "latlon <coordinates>", ki18n( "Show map at given lat lon coordinates" ) );
    options.add( "distance <value>", ki18n( "Set the distance of the observer to the globe (in km)" ) );
    options.add( "map <id>", ki18n( "Use map id (e.g. \"earth/openstreetmap/openstreetmap.dgml\")" ) );
    options.add( "+[file]", ki18n( "One or more placemark files to be opened" ) );

    KCmdLineArgs::addCmdLineOptions( options );
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication app;
    KGlobal::locale()->insertCatalog( "marble_qt" );

    

    if ( args->isSet( "debug-info" ) ) {
        MarbleDebug::enable = true;
    } else {
        MarbleDebug::enable = false;
    }

    if ( args->isSet( "smallscreen" ) ) {
        profiles |= MarbleGlobal::SmallScreen;
    }
    else {
        profiles &= ~MarbleGlobal::SmallScreen;
    }

    if ( args->isSet( "highresolution" ) ) {
        profiles |= MarbleGlobal::HighResolution;
    }
    else {
        profiles &= ~MarbleGlobal::HighResolution;
    }

    MarbleGlobal::getInstance()->setProfiles( profiles );

    QString marbleDataPath = args->getOption( "marbledatapath" );
    if( marbleDataPath.isEmpty() ) {
        marbleDataPath.clear(); /** @todo: why is this done? */
    }
    MainWindow *window = new MainWindow( marbleDataPath );
    window->setAttribute( Qt::WA_DeleteOnClose, true );
    window->show();

    if ( args->isSet( "timedemo" ) ) {
        window->resize(900, 640);
        MarbleTest test( window->marbleWidget() );
        test.timeDemo();
        return 0;
    }

    if ( args->isSet( "fps" ) ) {
        window->marbleControl()->marbleWidget()->setShowFrameRate( true );
    }

    if ( args->isSet( "tile-id" ) ) {
	window->marbleControl()->marbleWidget()->setShowTileId( true );
    }

    const QString map = args->getOption( "map" );
    if ( !map.isEmpty() ) {
        window->marbleWidget()->setMapThemeId(map);
    }

    const QString coordinatesString = args->getOption( "latlon" );
    if ( !coordinatesString.isEmpty() ) {
        bool success = false;
        const GeoDataCoordinates coordinates = GeoDataCoordinates::fromString(coordinatesString, success);
        if ( success ) {
            const qreal longitude = coordinates.longitude(GeoDataCoordinates::Degree);
            const qreal latitude = coordinates.latitude(GeoDataCoordinates::Degree);
            window->marbleWidget()->centerOn(longitude, latitude);
        }
    }

    const QString distance = args->getOption( "distance" );
    if ( !distance.isEmpty() ) {
        bool success = false;
        const qreal distanceValue = distance.toDouble(&success);
        if ( success )
            window->marbleWidget()->setDistance(distanceValue);
    }

    // Read the files that are given on the command line.
    for ( int i = 0; i < args->count(); ++i ) {

        // FIXME: Use openUrl( args->url(i) ) instead?
        if ( QFile::exists( args->arg( i ) ) )
            window->marbleControl()->addGeoDataFile( args->arg( i ) );
    }

    return app.exec();
}
Ejemplo n.º 25
0
int main(int argc, char **argv)
{
    KAboutData about("lokalize", 0, ki18nc("@title", "Lokalize"), version, ki18n(description),
                     KAboutData::License_GPL, ki18nc("@info:credit", "(c) 2007-2011 Nick Shaforostoff\n(c) 1999-2006 The KBabel developers") /*, KLocalizedString(), 0, "*****@*****.**"*/);
    about.addAuthor( ki18n("Nick Shaforostoff"), KLocalizedString(), "*****@*****.**" );
    about.addCredit (ki18n("Google Inc."), ki18n("sponsored development as part of Google Summer Of Code program"), QByteArray(), "http://google.com");
    about.addCredit (ki18n("Translate-toolkit"), ki18n("provided excellent cross-format converting scripts"), QByteArray(), "http://translate.sourceforge.net");
    about.addCredit (ki18n("Viesturs Zarins"), ki18n("project tree merging translation+templates"), "*****@*****.**", QByteArray());
    about.addCredit (ki18n("Stephan Johach"), ki18n("bug fixing patches"), "*****@*****.**");
    about.addCredit (ki18n("Chusslove Illich"), ki18n("bug fixing patches"), "*****@*****.**");
    about.addCredit (ki18n("Jure Repinc"), ki18n("testing and bug fixing"), "*****@*****.**");
    about.addCredit (ki18n("Stefan Asserhall"), ki18n("patches"), "*****@*****.**");
    about.addCredit (ki18n("Papp Laszlo"), ki18n("bug fixing patches"), "*****@*****.**");

    KCmdLineArgs::init(argc, argv, &about);

    KCmdLineOptions options;
    //options.add("merge-source <URL>", ki18n( "Source for the merge mode" ));
    options.add("noprojectscan", ki18n( "Do not scan files of the project."));
    options.add("project <filename>", ki18n( "Load specified project."));
    options.add("+[URL]", ki18n( "Document to open" ));
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    //qDebug() is important as it aviods compile 'optimization'.
    qDebug()<<qRegisterMetaType<DocPosition>();
    qDebug()<<qRegisterMetaType<InlineTag>();
    qDebug()<<qRegisterMetaType<CatalogString>();
    qRegisterMetaTypeStreamOperators<InlineTag>("InlineTag");
    qRegisterMetaTypeStreamOperators<CatalogString>("CatalogString");
    qAddPostRoutine(&cleanupSpellers);

    // see if we are starting with session management
    if (app.isSessionRestored())
        kRestoreMainWindows<LokalizeMainWindow>();
    else
    {
        // no session.. just start up normally
        KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

        if (!args->getOption("project").isEmpty())
        {
            // load needs an absolute path
            // FIXME: I do not know how to handle urls here
            // bug 245546 regarding symlinks
            QFileInfo projectFileInfo(args->getOption("project").toUtf8());
            QString projectFilePath=projectFileInfo.canonicalFilePath();
            if (projectFilePath.isEmpty())
                projectFilePath=projectFileInfo.absoluteFilePath();
            Project::instance()->load( projectFilePath );
        }
        LokalizeMainWindow* lmw=new LokalizeMainWindow;
        SettingsController::instance()->setMainWindowPtr(lmw);
        kWarning()<<"showing LokalizeMainWindow";
        lmw->show();
        kWarning()<<"LokalizeMainWindow shown";
        int j=args->count();
        while (--j>=0)
            lmw->fileOpen(args->url(j));

        Project::instance()->model()->setCompleteScan(args->isSet("projectscan"));
        args->clear();
    }

    int code=app.exec();

    ThreadWeaver::Weaver::instance()->dequeue();
    Project::instance()->model()->weaver()->dequeue();

    if (SettingsController::instance()->dirty) //for config changes done w/o config dialog
        Settings::self()->writeConfig();

    if (Project::instance()->isLoaded())
        Project::instance()->save();

    qWarning()<<"QCoreApplication::processEvents()...";
    QCoreApplication::processEvents();
    QCoreApplication::sendPostedEvents(0,0);

    qWarning()<<"Finishing Project jobs...";
    //Project::instance()->model()->weaver()->finish();
    // HACK due to deadlock with libstreamanalyzer.so.0 -> libxml2.so.2 -> etree.so -> libpython2.5.so.1.0 -> PyThread_acquire_lock
    while (!Project::instance()->model()->weaver()->isIdle())
    {
        QCoreApplication::processEvents();
        QCoreApplication::sendPostedEvents(0,0);
    }

    qWarning()<<"Finishing TM jobs...";
    ThreadWeaver::Weaver::instance()->finish();

    return code;
}
Ejemplo n.º 26
0
int main(int argc, char *argv[])
{
	KCmdLineArgs::init(argc, argv, appName, "kscreensaver", ki18n("Random screen saver"), 
                KDE_VERSION_STRING, ki18n(description));


	KCmdLineOptions options;

	options.add("setup", ki18n("Setup screen saver"));

	options.add("window-id wid", ki18n("Run in the specified XWindow"));

	options.add("root", ki18n("Run in the root XWindow"));

	KCmdLineArgs::addCmdLineOptions(options);

	KApplication app;

	WId windowId = 0;

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	if (args->isSet("setup"))
	{
		KRandomSetup setup;
		setup.exec();
		exit(0);
	}

	if (args->isSet("window-id"))
	{
		windowId = args->getOption("window-id").toInt();
	}

#ifdef Q_WS_X11
	if (args->isSet("root"))
	{
		QX11Info info;
		windowId = RootWindow(QX11Info::display(), info.screen());
	}
#endif
	args->clear();
	const KService::List lst = KServiceTypeTrader::self()->query( "ScreenSaver");
        KService::List availableSavers;

	KConfig type("krandom.kssrc", KConfig::NoGlobals);
        const KConfigGroup configGroup = type.group("Settings");
	const bool opengl = configGroup.readEntry("OpenGL", false);
	const bool manipulatescreen = configGroup.readEntry("ManipulateScreen", false);
        // TODO replace this with TryExec=fortune in the desktop files
        const bool fortune = !KStandardDirs::findExe("fortune").isEmpty();
        foreach( const KService::Ptr& service, lst ) {
            //QString file = KStandardDirs::locate("services", service->entryPath());
            //kDebug() << "Looking at " << file;
            const QString saverType = service->property("X-KDE-Type").toString();
            foreach (const QString &type, saverType.split(QLatin1Char(';'))) {
                //kDebug() << "saverTypes is "<< type;
                if (type == QLatin1String("ManipulateScreen")) {
                    if (!manipulatescreen)
                        goto fail;
                } else if (type == QLatin1String("OpenGL")) {
                    if (!opengl)
                        goto fail;
                } else if (type == QLatin1String("Fortune")) {
                    if (!fortune)
                        goto fail;
                }
            }
            availableSavers.append(service);
          fail: ;
        }

	KRandomSequence rnd;
	const int indx = rnd.getLong(availableSavers.count());
        const KService::Ptr service = availableSavers.at(indx);
        const QList<KServiceAction> actions = service->actions();

	QString cmd;
	if (windowId)
            cmd = exeFromActionGroup(actions, "InWindow");
        if (cmd.isEmpty() && windowId == 0)
            cmd = exeFromActionGroup(actions, "Root");
        if (cmd.isEmpty())
            cmd = service->exec();

    QHash<QChar, QString> keyMap;
    keyMap.insert('w', QString::number(windowId));
    const QStringList words = KShell::splitArgs(KMacroExpander::expandMacrosShellQuote(cmd, keyMap));
    if (!words.isEmpty()) {
        QString exeFile = KStandardDirs::findExe(words.first());
        if (!exeFile.isEmpty()) {
            char **sargs = new char *[words.size() + 1];
            int i = 0;
            for (; i < words.size(); i++)
                sargs[i] = qstrdup(words[i].toLocal8Bit().constData());
            sargs[i] = 0;

            execv(exeFile.toLocal8Bit(), sargs);
        }
    }

	// If we end up here then we couldn't start a saver.
	// If we have been supplied a window id or root window then blank it.
#ifdef Q_WS_X11
	QX11Info info;
	Window win = windowId ? windowId : RootWindow(QX11Info::display(), info.screen());
	XSetWindowBackground(QX11Info::display(), win,
			BlackPixel(QX11Info::display(), info.screen()));
	XClearWindow(QX11Info::display(), win);
#endif
}
Ejemplo n.º 27
0
int main( int argc, char** argv )
{
#ifdef Q_OS_WIN
    SetErrorMode(SEM_NOGPFAULTERRORBOX); 
#endif

    QString version = CalligraVersionWrapper::versionString(true);

    K4AboutData aboutData("calligrageminithumbnailer",
                         "calligrawords",
                         ki18n("Calligra Gemini Thumbnailer"),
                         version.toLatin1(),
                         ki18n("Calligra Gemini: Writing and Presenting at Home and on the Go"),
                         K4AboutData::License_GPL,
                         ki18n("(c) 1999-%1 The Calligra team and KO GmbH.\n").subs(CalligraVersionWrapper::versionYear()),
                         KLocalizedString(),
                         "http://www.calligra.org",
                         "*****@*****.**");

    KCmdLineArgs::init (argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add( "in <local-url>", ki18n( "Document to thumbnail" ) );
    options.add( "out <local-url>", ki18n( "The full path for the thumbnail file" ) );
    options.add( "width <pixels>", ki18n( "The width in pixels of the thumbnail" ) );
    options.add( "height <pixels>", ki18n( "The height in pixels of the thumbnail" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

    KApplication app;
    app.setApplicationName("calligrageminithumbnailer");

#ifdef Q_OS_WIN
    QDir appdir(app.applicationDirPath());
    appdir.cdUp();

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    if (!env.contains("KDESYCOCA")) {
        _putenv_s("KDESYCOCA", QString(appdir.absolutePath() + "/sycoca").toLocal8Bit());
    }
    if (!env.contains("XDG_DATA_DIRS")) {
        _putenv_s("XDG_DATA_DIRS", QString(appdir.absolutePath() + "/share").toLocal8Bit());
    }
    _putenv_s("PATH", QString(appdir.absolutePath() + "/bin" + ";"
              + appdir.absolutePath() + "/lib" + ";"
              + appdir.absolutePath() + "/lib"  +  "/kde4" + ";"
              + appdir.absolutePath()).toLocal8Bit());

    app.addLibraryPath(appdir.absolutePath());
    app.addLibraryPath(appdir.absolutePath() + "/bin");
    app.addLibraryPath(appdir.absolutePath() + "/lib");
    app.addLibraryPath(appdir.absolutePath() + "/lib/kde4");
#endif

#if defined HAVE_X11
    QApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

    QString inFile = args->getOption("in");
    QString outFile = args->getOption("out");
    // Only create the thunbnail if:
    // 1) The infile exists and
    // 2) The outfile does /not/ exist
    if(!QFile::exists(inFile)) {
        qDebug() << "The document you are attempting to create a thumbnail of does not exist on disk:" << inFile;
    }
    else if(QFile::exists(outFile)) {
        qDebug() << "The thumbnail file you are asking to have used already exists on disk. We will refuse to overwrite it." << outFile;
    }
    else {
        ThumbnailHelperImpl helper;
        helper.convert(inFile, outFile, args->getOption("width").toInt(), args->getOption("height").toInt());
    }
    QTimer::singleShot(0, &app, SLOT(quit()));

    return app.exec();
}
Ejemplo n.º 28
0
int main( int argc, char **argv )
{
  KAboutData aboutData( "soapdebug", 0, ki18n("Groupwise Soap Debug"), "0.1" );
  aboutData.addAuthor( ki18n("Cornelius Schumacher"), KLocalizedString(), "*****@*****.**" );

  KCmdLineArgs::init( argc, argv, &aboutData );

  KCmdLineOptions options;
  options.add("s");
  options.add("server <hostname>", ki18n("Server"));
  options.add("u");
  options.add("user <string>", ki18n("User"));
  options.add("p");
  options.add("password <string>", ki18n("Password"));
  options.add("f");
  options.add("freebusy-user <string>", ki18n("Free/Busy user name"));
  options.add("addressbook-id <string>", ki18n("Address book identifier"));
  KCmdLineArgs::addCmdLineOptions( options );

  KApplication app;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  QString user = args->getOption( "user" );
  QString pass = args->getOption( "password" );
  QString url = args->getOption( "server" );

#if 1
  if ( user.isEmpty() ) {
    kError() <<"Need user.";
    return 1; 
  }
  if ( pass.isEmpty() ) {
    kError() <<"Need password.";
    return 1; 
  }
  if ( url.isEmpty() ) {
    kError() <<"Need server.";
    return 1; 
  }
#endif
  KDateTime::Spec spec = KDateTime::Spec::LocalZone();
  GroupwiseServer server( url, user, pass, spec, 0 );

#if 1
  if ( !server.login() ) {
    kError() <<"Unable to login to server" << url;
    return 1;
  }
#endif

#if 0
  server.dumpData();
#endif

#if 0
  server.getCategoryList();
#endif

#if 0
  server.dumpFolderList();
#endif

#if 0
  QString fbUser = args->getOption( "freebusy-user" );
  if ( fbUser.isEmpty() ) {
    kError() <<"Need user for which the freebusy data should be retrieved.";
  } else {
    KCal::FreeBusy *fb = new KCal::FreeBusy;

    server.readFreeBusy( "user1",
      QDate( 2004, 9, 1 ), QDate( 2004, 10, 31 ), fb );
  }
#endif

#if 0
  KTemporaryFile temp;
  temp.setautoRemove(false);
  temp.open();
  KCal::ResourceLocal resource( temp.fileName() );
  resource.setActive( true );
  KCal::CalendarResources calendar;
  calendar.resourceManager()->add( &resource );
  kDebug() <<"Login";

  if ( !server.login() ) {
    kDebug() <<"Unable to login.";
  } else {
    kDebug() <<"Read calendar";
    if ( !server.readCalendarSynchronous( &resource ) ) {
      kDebug() <<"Unable to read calendar data.";
    }
    kDebug() <<"Logout";
    server.logout();
  }
  KCal::ICalFormat format;

  QString ical = format.toString( &calendar );

  kDebug() <<"ICALENDAR:" << ical;
#endif

#if 0
  QString id = args->getOption( "addressbook-id" );

  kDebug() <<"ADDRESSBOOK ID:" << id;

  QStringList ids;
  ids.append( id );

  KABC::ResourceMemory resource;

  kDebug() <<"Login";
  if ( !server.login() ) {
    kError() <<"Unable to login.";
  } else {
    kDebug() <<"Read Addressbook";
    if ( !server.readAddressBooksSynchronous( ids, &resource ) ) {
      kError() <<"Unable to read addressbook data.";
    }
    kDebug() <<"Logout";
    server.logout();
  }

  KABC::Addressee::List addressees;
  KABC::Resource::Iterator it2;
  for( it2 = resource.begin(); it2 != resource.end(); ++it2 ) {
    kDebug() <<"ADDRESSEE:" << (*it2).fullEmail();
    addressees.append( *it2 );
  }
#endif

#if 0    
  server.getDelta();
#endif

  server.logout();

  return 0;
}
Ejemplo n.º 29
0
Archivo: main.cpp Proyecto: KDE/rkward
int main(int argc, char *argv[]) {
	options.add ("evaluate <Rcode>", ki18n ("After starting (and after loading the specified workspace, if applicable), evaluate the given R code."), 0);
	options.add ("debug-level <level>", ki18n ("Verbosity of debug messages (0-5)"), "2");
	options.add ("debug-flags <flags>", ki18n ("Mask for components to debug (see debug.h)"), QString::number (DEBUG_ALL).toLocal8Bit ());
	options.add ("debugger <command and arguments>", ki18n ("Debugger for the frontend. Specify last, or add '--' after all debugger arguments"), "");
	options.add ("backend-debugger <command>", ki18n ("Debugger for the backend. (Enclose any debugger arguments in single quotes ('') together with the command. Make sure to re-direct stdout!)"), "");
	options.add ("r-executable <command>", ki18n ("Use specified R installation, instead of the one configured at compile time (note: rkward R library must be installed to that installation of R)"), "");
	options.add ("reuse", ki18n ("Reuse a running RKWard instance (if available). If a running instance is reused, only the file arguments will be interpreted, all other options will be ignored."), 0);
	options.add ("nowarn-external", ki18n ("When used in conjunction with rkward://runplugin/-URLs specified on the command line, suppresses the warning about application-external (untrusted) links."));
	options.add ("+[Files]", ki18n ("File or files to open, typically a workspace, or an R script file. When loading several things, you should specify the workspace, first."), 0);

	KAboutData aboutData("rkward", QByteArray (), ki18n ("RKWard"), RKWARD_VERSION, ki18n ("Frontend to the R statistics language"), KAboutData::License_GPL, ki18n ("(c) 2002, 2004 - 2016"), KLocalizedString (), "http://rkward.kde.org", "*****@*****.**");
	aboutData.addAuthor (ki18n ("Thomas Friedrichsmeier"), ki18n ("Project leader / main developer"));
	aboutData.addAuthor (ki18n ("Pierre Ecochard"), ki18n ("C++ developer between 2004 and 2007"));
	aboutData.addAuthor (ki18n ("Prasenjit Kapat"), ki18n ("Many plugins, suggestions, plot history feature"));
	aboutData.addAuthor (ki18n ("Meik Michalke"), ki18n ("Many plugins, suggestions, rkwarddev package"));
	aboutData.addAuthor (ki18n ("Stefan Roediger"), ki18n ("Many plugins, suggestions, marketing, translations"));
	aboutData.addCredit (ki18n ("Contributors in alphabetical order"));
	aboutData.addCredit (ki18n ("Björn Balazs"), ki18n ("Extensive usability feedback"));
	aboutData.addCredit (ki18n ("Aaron Batty"), ki18n ("Whealth of feedback, hardware donations"));
	aboutData.addCredit (ki18n ("Jan Dittrich"), ki18n ("Extensive usability feedback"));
	aboutData.addCredit (ki18n ("Philippe Grosjean"), ki18n ("Several helpful comments and discussions"));
	aboutData.addCredit (ki18n ("Adrien d'Hardemare"), ki18n ("Plugins and patches"));
	aboutData.addCredit (ki18n ("Yves Jacolin"), ki18n ("New website"));
	aboutData.addCredit (ki18n ("Germán Márquez Mejía"), ki18n ("HP filter plugin, spanish translation"), 0);
	aboutData.addCredit (ki18n ("Marco Martin"), ki18n ("A cool icon"));
	aboutData.addCredit (ki18n ("Daniele Medri"), ki18n ("RKWard logo, many suggestions, help on wording"));
	aboutData.addCredit (ki18n ("David Sibai"), ki18n ("Several valuable comments, hints and patches"));
	aboutData.addCredit (ki18n ("Ilias Soumpasis"), ki18n ("Translation, Suggestions, plugins"));
	aboutData.addCredit (ki18n ("Ralf Tautenhahn"), ki18n ("Many comments, useful suggestions, and bug reports"));
	aboutData.addCredit (ki18n ("Jannis Vajen"), ki18n ("German Translation, bug reports"));
	aboutData.addCredit (ki18n ("Roland Vollgraf"), ki18n ("Some patches"));
	aboutData.addCredit (ki18n ("Roy Qu"), ki18n ("patches and helpful comments"));
	aboutData.addCredit (ki18n ("Many more people on [email protected]"), ki18n ("Sorry, if we forgot to list you. Please contact us to get added"));

	// before initializing the commandline args, remove the ".bin" from "rkward.bin".
	// This is so it prints "Usage rkward..." instead of "Usage rkward.bin...", etc.
	// it seems safest to keep a copy, since the shell still owns argv
	char *argv_copy[argc];
	argv_copy[0] = qstrdup (QString (argv[0]).remove (".frontend").replace (".exe", ".bat").toLocal8Bit ());
	for (int i = 1; i < argc; ++i) {
		argv_copy[i] = argv[i];
	}
	KCmdLineArgs::init (argc, argv_copy, &aboutData);
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
	RK_Debug_Level = DL_FATAL - QString (args->getOption ("debug-level")).toInt ();
	RK_Debug_Flags = QString (args->getOption ("debug-flags")).toInt ();
	if (!args->getOption ("debugger").isEmpty ()) {
		RK_DEBUG (DEBUG_ALL, DL_ERROR, "--debugger option should have been handled by wrapper script. Ignoring.");
	}

	if (args->count ()) {
		QStringList urls_to_open;
		for (int i = 0; i < args->count (); ++i) {
			urls_to_open.append (KCmdLineArgs::makeURL (decodeArgument (args->arg (i)).toUtf8 ()).url ());
		}
		RKGlobals::startup_options["initial_urls"] = urls_to_open;
		RKGlobals::startup_options["warn_external"] = args->isSet ("warn-external");
	}
	RKGlobals::startup_options["evaluate"] = decodeArgument (args->getOption ("evaluate"));
	RKGlobals::startup_options["backend-debugger"] = decodeArgument (args->getOption ("backend-debugger"));

	RKWardApplication app;
	// No, I do not really understand the point of separating KDE_LANG from LANGUAGE. We do honor it in so far as not
	// forcing LANGUAGE on the backend, though. Having language as LANGUAGE makes code in RKMessageCatalog much easier compared to KCatalog.
	qputenv ("LANGUAGE", QFile::encodeName (KGlobal::locale ()->language ()));
	// install message handler *after* the componentData has been initialized
	RKSettingsModuleDebug::debug_file = new QTemporaryFile (QDir::tempPath () + "/rkward.frontend");
	RKSettingsModuleDebug::debug_file->setAutoRemove (false);
	if (RKSettingsModuleDebug::debug_file->open ()) {
		RK_DEBUG (APP, DL_INFO, "Full debug output is at %s", qPrintable (RKSettingsModuleDebug::debug_file->fileName ()));
		qInstallMsgHandler (RKDebugMessageOutput);
	}

	if (app.isSessionRestored ()) {
		RESTORE(RKWardMainWindow);	// well, whatever this is supposed to do -> TODO
	} else {
		new RKWardMainWindow ();
	}
	args->clear();

	// Usually, KDE always adds the current directory to the list of prefixes.
	// However, since RKWard 0.5.6, the main binary is in KDE's libexec dir, which defies this mechanism. Therefore, RKWARD_ENSURE_PREFIX is set from the wrapper script.
	char *add_path = getenv ("RKWARD_ENSURE_PREFIX");
	if (add_path) KGlobal::dirs ()->addPrefix (QString::fromLocal8Bit (add_path));

	// do it!
	int status = app.exec ();

	qInstallMsgHandler (0);
	RKSettingsModuleDebug::debug_file->close ();

	return status;
}
Ejemplo n.º 30
0
int main( int argc, char ** argv )
{
    //disable qt module support for skim itself; xim will be disabled latter
    setenv("QT_IM_SWITCHER", "imsw-none", 1);
    setenv("QT_IM_MODULE", "xim", 1);
    setenv("XMODIFIER", "@im=none", 1);

    KAboutData about(PACKAGE, "SKIM",
        VERSION " (compiled with libscim " SCIM_VERSION ")",
        description, KAboutData::License_GPL_V2, "(C) 2004 - 2006 LiuCougar",
        I18N_NOOP("IRC:\nserver: irc.freenode.net / channel: #scim\n\nFeedback:\[email protected]"),
        "http://www.scim-im.org");
    about.addAuthor( "LiuCougar (liuspider)", I18N_NOOP("Core Developer"),
      "*****@*****.**" );
    about.addCredit ( "JamesSu", I18N_NOOP("SCIM Core Author"), "*****@*****.**" );
    about.addAuthor ( "JanHefti", I18N_NOOP("Doc writer and German translator"),
      "*****@*****.**" );
    about.addAuthor ( "KitaeKim", I18N_NOOP("Art designer and Korean translator"),
      "*****@*****.**" );
    about.addAuthor ( "YukikoBando", I18N_NOOP("Japanese translator"),
      "*****@*****.**" );
    about.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names")
        ,I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails"));

    QString curarg;

    QStringList otherArgs;

    for(int i = 1; i < argc ; i++)
    {
        curarg = argv[i];
        if( curarg == "--no-stay")
            otherArgs.push_back("no-stay");
        else if (curarg == "-c" ) {
            otherArgs.push_back("c");
            //FIXME
            otherArgs.push_back(argv[++i]);
        } else if( curarg == "-f")
            otherArgs.push_back("force");
    }

    //FIXME: noxim is necessary to disable xim support in qt for this app
    const char* fake_arg1 =  "--noxim";
    char* fake_argv[10] = {argv[0], const_cast<char *>(fake_arg1), 0, 0, 0, 0, 0};
    for(int i = 1; i < argc; i++)
    {
      fake_argv[i+1] = argv[i];
    }
    KCmdLineArgs::init(argc+1, fake_argv, &about);

    KCmdLineArgs::addCmdLineOptions( options );

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    scim::uint32 verbose_level = 0;
    QString verbose_raw = args->getOption("verbose");
    if( verbose_raw.length() && verbose_raw.toInt())
        verbose_level = verbose_raw.toInt();

    scim::DebugOutput::set_verbose_level( verbose_level );
    scim::DebugOutput::enable_debug (SCIM_DEBUG_AllMask);
//     scim::DebugOutput::enable_debug (SCIM_DEBUG_MainMask | SCIM_DEBUG_SocketMask);

    if( args->isSet("l") ) {
      new KInstance(PACKAGE);
      QValueList<SkimPluginInfo *> info = SkimPluginManager::allAvailablePlugins();
      std::cout << I18N_NOOP("Installed skim Plugins:") << "\n" << I18N_NOOP("Name") << "\t\t\t\t" << I18N_NOOP("Comment") << "\n";
      for(uint i = 0; i < info.size(); i++) {
          printf("%-26s\t%s", (const char *)info[i]->pluginName().local8Bit(), (const char *)info[i]->comment().local8Bit());
          if(info[i]->isNoDisplay())
              std::cout << I18N_NOOP(" (Hidden)");
          std::cout << "\n";
      }
      std::cout << "\n" << I18N_NOOP("Note: Hidden plugins can not be disabled.") << "\n";
      return 0;
    }

    QCString p = args->getOption("p"), np = args->getOption("np");
    QStringList enabledPlugins, disabledPlugins;
    if( p.length() )
      enabledPlugins = QStringList::split(",", p);

    if( np.length() )
      disabledPlugins = QStringList::split(",", np);

    if( args->isSet("d") )
        scim::scim_daemon ();

    KApplication * kAppMainThread = new KApplication();
    if( kAppMainThread->isRestored() && !ScimKdeSettings::autoStart() )
      return 127; //when skim should not auto start, restore from session is not permitted

    if (signal(SIGTERM, sighandler) == SIG_IGN)
        signal(SIGTERM, SIG_IGN);
    if (signal(SIGINT, sighandler) == SIG_IGN)
        signal(SIGINT, SIG_IGN);
    if (signal(SIGHUP, sighandler) == SIG_IGN)
        signal(SIGHUP, SIG_IGN);

    new SkimPluginManager(enabledPlugins, disabledPlugins, otherArgs);
    return kAppMainThread->exec();
}