Example #1
0
int main(int argc, char **argv)
{
   KLocale::setMainCatalogue("kdelibs");
   const char *description = I18N_NOOP("KDE Menu query tool.\n"
   "This tool can be used to find in which menu a specific application is shown.\n"
   "The --highlight option can be used to visually indicate to the user where\n"
   "in the KDE menu a specific application is located.");
   
   KAboutData d(appName, I18N_NOOP("kde-menu"), appVersion,
                description,
                KAboutData::License_GPL, "(c) 2003 Waldo Bastian");
   d.addAuthor("Waldo Bastian", I18N_NOOP("Author"), "*****@*****.**");

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

//   KApplication k(false, false);
   KApplication k(false);
   k.disableSessionManagement();

   // this program is in kdelibs so it uses kdelibs as catalog
   KLocale::setMainCatalogue("kdelibs");

   KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
   if (args->count() != 1)
      KCmdLineArgs::usage(i18n("You must specify an application-id such as 'kde-konsole.desktop'"));

   utf8 = args->isSet("utf8");

   bPrintMenuId = args->isSet("print-menu-id");
   bPrintMenuName = args->isSet("print-menu-name");
   bHighlight = args->isSet("highlight");

   if (!bPrintMenuId && !bPrintMenuName && !bHighlight)
      KCmdLineArgs::usage(i18n("You must specify at least one of --print-menu-id, --print-menu-name or --highlight"));

   if (args->isSet("cache-update"))
   {
      QStringList args;
      args.append("--incremental");
      args.append("--checkstamps");
      QString command = "kbuildsycoca";
      QCString _launcher = KApplication::launcher();
      if (!DCOPRef(_launcher, _launcher).call("kdeinit_exec_wait", command, args).isValid())
      {
         qWarning("Can't talk to klauncher!");
         command = KGlobal::dirs()->findExe(command);
         command += " " + args.join(" ");
         system(command.local8Bit());
      }
   }

   QString menuId = QFile::decodeName(args->arg(0));
   KService::Ptr s = KService::serviceByMenuId(menuId);
   
   if (!s)
      error(1, i18n("No menu item '%1'.").arg(menuId));

   findMenuEntry(KServiceGroup::root(), "", menuId);

   error(2, i18n("Menu item '%1' not found in menu.").arg(menuId));
   return 2;
}
Example #2
0
/**
 * Setting up the KAboutData structure.
 * Parsing and handling of the given command line arguments.
 * @param argc   the number of arguments
 * @param argv   the array of arguments
 * @return exit status
 */
int main(int argc, char *argv[])
{
	KAboutData aboutData( "kompare", 0, ki18n("Kompare"), version, ki18n(description),
	                      KAboutData::License_GPL,
	                      ki18n("(c) 2001-2004 John Firebaugh, (c) 2001-2005,2009 Otto Bruggeman, (c) 2004-2005 Jeff Snyder, (c) 2007-2012 Kevin Kofler") );
	aboutData.addAuthor( ki18n("John Firebaugh"), ki18n("Author"), "*****@*****.**" );
	aboutData.addAuthor( ki18n("Otto Bruggeman"), ki18n("Author"), "*****@*****.**" );
	aboutData.addAuthor( ki18n("Jeff Snyder"), ki18n("Developer"), "*****@*****.**" );
	aboutData.addCredit( ki18n("Kevin Kofler"), ki18n("Maintainer"), "*****@*****.**" );
	aboutData.addCredit( ki18n("Chris Luetchford"), ki18n("Kompare icon artist"), "*****@*****.**" );
	aboutData.addCredit( ki18n("Malte Starostik"), ki18n("A lot of good advice"), "*****@*****.**" );
	aboutData.addCredit( ki18n("Bernd Gehrmann"), ki18n("Cervisia diff viewer"), "*****@*****.**" );

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

	KCmdLineOptions options;
	options.add("c", ki18n( "This will compare URL1 with URL2" ));
	options.add("o", ki18n( "This will open URL1 and expect it to be diff output. URL1 can also be a '-' and then it will read from standard input. Can be used for instance for cvs diff | kompare -o -. Kompare will do a check to see if it can find the original file(s) and then blend the original file(s) into the diffoutput and show that in the viewer. -n disables the check." ));
	options.add("b", ki18n( "This will blend URL2 into URL1, URL2 is expected to be diff output and URL1 the file or folder that the diffoutput needs to be blended into. " ));
	options.add("n", ki18n( "Disables the check for automatically finding the original file(s) when using '-' as URL with the -o option." ));
	options.add("e <encoding>", ki18n( "Use this to specify the encoding when calling it from the command line. It will default to the local encoding if not specified." ));
	options.add("+[URL1 [URL2]]");
	options.add("+-");
	KCmdLineArgs::addCmdLineOptions( options );
	KApplication kompare;
	bool difault = false;

	KompareShell* ks;

	// see if we are starting with session management
	if (kompare.isSessionRestored())
	{
		RESTORE(KompareShell)
	}
	else
	{
		KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

		ks = new KompareShell();
		ks->setObjectName( "FirstKompareShell" );

		kDebug( 8100 ) << "Arg Count = " << args->count() << endl;
		for ( int i=0; i < args->count(); i++ )
		{
			kDebug( 8100 ) << "Argument " << (i+1) << ": " << args->arg( i ) << endl;
		}

		if ( args->isSet( "e" ) )
		{
			// Encoding given...
			// FIXME: Need to implement this...
		}

		if ( args->isSet( "o" ) )
		{
			kDebug( 8100 ) << "Option -o is set" << endl;
			if ( args->count() != 1 )
			{
				difault = true;
			}
			else
			{
				ks->show();
				kDebug( 8100 ) << "OpenDiff..." << endl;
				if ( args->arg(0) == QLatin1String("-") )
					ks->openStdin();
				else
					ks->openDiff( args->url( 0 ) );
				difault = false;
			}
		}
		else if ( args->isSet( "c" ) )
		{
			kDebug( 8100 ) << "Option -c is set" << endl;
			if ( args->count() != 2 )
			{
				KCmdLineArgs::usage( "kompare" );
				difault = true;
			}
			else
			{
				ks->show();
				KUrl url0 = args->url( 0 );
				kDebug( 8100 ) << "URL0 = " << url0.url() << endl;
				KUrl url1 = args->url( 1 );
				kDebug( 8100 ) << "URL1 = " << url1.url() << endl;
				ks->compare( url0, url1 );
				difault = false;
			}
		}
		else if ( args->isSet( "b" ) )
		{
			kDebug( 8100 ) << "Option -b is set" << endl;
			if ( args->count() != 2 )
			{
				KCmdLineArgs::usage( "kompare" );
				difault = true;
			}
			else
			{
				ks->show();
				kDebug( 8100 ) << "blend..." << endl;
				KUrl url0 = args->url( 0 );
				kDebug( 8100 ) << "URL0 = " << url0.url() << endl;
				KUrl url1 = args->url( 1 );
				kDebug( 8100 ) << "URL1 = " << url1.url() << endl;
				ks->blend( url0, url1 );
				difault = false;
			}
		}
		else if ( args->count() == 1 )
		{
			ks->show();

			kDebug( 8100 ) << "Single file. so openDiff/openStdin is only possible..." << endl;
			if ( args->arg(0) == QLatin1String("-") )
				ks->openStdin();
			else
				ks->openDiff( args->url( 0 ) );

			difault = false;
		}
		else if ( args->count() == 2 )
		{
			// In this case we are assuming you want to compare files/dirs
			// and not blending because that is almost impossible to detect
			ks->show();
			kDebug( 8100 ) << "Dunno, we'll have to figure it out later, trying compare for now..." << endl;
			KUrl url0 = args->url( 0 );
			kDebug( 8100 ) << "URL0 = " << url0.url() << endl;
			KUrl url1 = args->url( 1 );
			kDebug( 8100 ) << "URL1 = " << url1.url() << endl;
			ks->compare( url0, url1 );
			difault = false;
		}
		else if ( args->count() == 0 ) // no options and no args
		{
			difault = true;
		}

		if ( difault )
		{
			KompareURLDialog dialog( 0 );

			dialog.setCaption( i18n("Compare Files or Folders") );
			dialog.setFirstGroupBoxTitle( i18n( "Source" ) );
			dialog.setSecondGroupBoxTitle( i18n( "Destination" ) );

			KGuiItem compareGuiItem( i18n( "Compare" ), QString(), i18n( "Compare these files or folder" ), i18n( "If you have entered 2 filenames or 2 folders in the fields in this dialog then this button will be enabled and pressing it will start a comparison of the entered files or folders. " ) );
			dialog.setButtonGuiItem( KDialog::Ok, compareGuiItem );

			dialog.setGroup( "Recent Compare Files" );

			dialog.setFirstURLRequesterMode( KFile::File|KFile::Directory|KFile::ExistingOnly );
			dialog.setSecondURLRequesterMode( KFile::File|KFile::Directory|KFile::ExistingOnly );

			if( dialog.exec() == QDialog::Accepted )
			{
				ks->show();
				ks->viewPart()->setEncoding( dialog.encoding() );
				ks->compare( dialog.getFirstURL(), dialog.getSecondURL() );
			}
			else
                        {
				return -1;
                        }
		}

		args->clear();
	}

	return kompare.exec();
}
Example #3
0
int main(int argc, char **argv)
{
    KAboutData aboutData("previewer", 0, ki18n("Plasma-Studio Previewer"),
                         "1.0", ki18n(description), KAboutData::License_BSD,
                         ki18n("XXXX"));
    aboutData.setProgramIconName("plasma");
    aboutData.addAuthor(ki18n("XXX"),
                         ki18n("Original author"),
                        "*****@*****.**");

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

    KCmdLineOptions options;
    options.add("list", ki18n("Displays a list of known applets"));
    options.add("f");
    options.add("formfactor <name>", ki18nc("Do not translate horizontal, vertical, mediacenter nor planar", "The formfactor to use (horizontal, vertical, mediacenter or planar)"), "planar");
    options.add("l");
    options.add("location <name>", ki18nc("Do not translate floating, desktop, fullscreen, top, bottom, left nor right", "The location constraint to start the Containment with (floating, desktop, fullscreen, top, bottom, left, right)"), "floating");
    options.add("c");
    options.add("containment <name>", ki18n("Name of the containment plugin"), "null");
    options.add("w");
    options.add("wallpaper <name>", ki18n("Name of the wallpaper plugin"), QByteArray());
    options.add("p");
    options.add("pixmapcache <size>", ki18n("The size in KB to set the pixmap cache to"));
    options.add("+applet", ki18n("Name of applet to add (required)"));
    options.add("+[args]", ki18n("Optional arguments of the applet to add"));
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs() ;

    if (args->isSet("list")) {
        int maxLen = 0;
        QMap<QString, QString> applets;
        foreach (const KPluginInfo &info, Plasma::Applet::listAppletInfo()) {
            if (info.property("NoDisplay").toBool())
                continue;

            int len = info.pluginName().length();
            if (len > maxLen)
                maxLen = len;

            QString name = info.pluginName();
            QString comment = info.comment();

            if(comment.isEmpty())
                comment = i18n("No description available");

            applets.insert(name, comment);
        }

        QMap<QString, QString>::const_iterator it;
        for(it = applets.constBegin(); it != applets.constEnd(); it++) {
            QString applet("%1 - %2");

            applet = applet.arg(it.key().leftJustified(maxLen, ' ')).arg(it.value());
            std::cout << applet.toLocal8Bit().data() << std::endl;
        }

        return 0;
    }
Example #4
0
int main(int argc, char *argv[])
{
	KLocale::setMainCatalogue("kscreensaver");
	KCmdLineArgs::init(argc, argv, appName, I18N_NOOP("Random screen saver"), description, version);

	KCmdLineArgs::addCmdLineOptions(options);

	KApplication app;

	Window windowId = 0;

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

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

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

	if (args->isSet("root"))
	{
		windowId = RootWindow(qt_xdisplay(), qt_xscreen());
	}

	KGlobal::dirs()->addResourceType("scrsav",
			KGlobal::dirs()->kde_default("apps") +
			"apps/ScreenSavers/");
	KGlobal::dirs()->addResourceType("scrsav",
			KGlobal::dirs()->kde_default("apps") +
			"System/ScreenSavers/");
	QStringList tempSaverFileList = KGlobal::dirs()->findAllResources("scrsav",
			"*.desktop", false, true);

	QStringList saverFileList;

	KConfig type("krandom.kssrc");
	type.setGroup("Settings");
	bool opengl = type.readBoolEntry("OpenGL");
	bool manipulatescreen = type.readBoolEntry("ManipulateScreen");
        bool fortune = !KStandardDirs::findExe("fortune").isEmpty();

	for (uint i = 0; i < tempSaverFileList.count(); i++)
	{
		kdDebug() << "Looking at " << tempSaverFileList[i] << endl;
		KDesktopFile saver(tempSaverFileList[i], true);
		if(!saver.tryExec())
			continue;
		kdDebug() << "read X-KDE-Type" << endl;
		QString saverType = saver.readEntry("X-KDE-Type");

		if (saverType.isEmpty()) // no X-KDE-Type defined so must be OK
		{
			saverFileList.append(tempSaverFileList[i]);
		}
		else
		{
			QStringList saverTypes = QStringList::split(";", saverType);
			for (QStringList::ConstIterator it =  saverTypes.begin(); it != saverTypes.end(); ++it )
			{
				kdDebug() << "saverTypes is "<< *it << endl;
				if (*it == "ManipulateScreen")
				{
					if (manipulatescreen)
					{
						saverFileList.append(tempSaverFileList[i]);
					}
				}
				else
				if (*it == "OpenGL")
				{
					if (opengl)
					{
						saverFileList.append(tempSaverFileList[i]);
					}
				}
				if (*it == "Fortune")
				{
					if (fortune)
					{
						saverFileList.append(tempSaverFileList[i]);
					}
				}

			}
		}
	}

	KRandomSequence rnd;
	int indx = rnd.getLong(saverFileList.count());
	QString filename = *(saverFileList.at(indx));

	KDesktopFile config(filename, true);

	QString cmd;
	if (windowId && config.hasActionGroup("InWindow"))
	{
		config.setActionGroup("InWindow");
	}
	else if ((windowId == 0) && config.hasActionGroup("Root"))
	{
		config.setActionGroup("Root");
	}
	cmd = config.readPathEntry("Exec");

	QTextStream ts(&cmd, IO_ReadOnly);
	QString word;
	ts >> word;
	QString exeFile = KStandardDirs::findExe(word);

	if (!exeFile.isEmpty())
	{
		char *sargs[MAX_ARGS];
		sargs[0] = new char [strlen(word.ascii())+1];
		strcpy(sargs[0], word.ascii());

		int i = 1;
		while (!ts.atEnd() && i < MAX_ARGS-1)
		{
			ts >> word;
			if (word == "%w")
			{
				word = word.setNum(windowId);
			}

			sargs[i] = new char [strlen(word.ascii())+1];
			strcpy(sargs[i], word.ascii());
			kdDebug() << "word is " << word.ascii() << endl;

			i++;
		}

		sargs[i] = 0;

		execv(exeFile.ascii(), sargs);
	}
int main( int argc, char *argv[] )
{
    QList<QByteArray> argvOrig;  //We copy the original argv here, as it seems that KCmdLineArgs changes the arguments ("--style" becomes "-style")

    for(int a = 0; a < argc; ++a)
        argvOrig << argv[a];

    static const char description[] = I18N_NOOP( "The KDevelop Integrated Development Environment" );
    KAboutData aboutData( "kdevelop", 0, ki18n( "KDevelop" ),
                          i18n("%1", QString(VERSION) ).toUtf8(), ki18n(description), KAboutData::License_GPL,
                          ki18n( "Copyright 1999-2010, The KDevelop developers" ), KLocalizedString(), "http://www.kdevelop.org/" );
    aboutData.addAuthor( ki18n("Andreas Pakulat"), ki18n( "Maintainer, Architecture, VCS Support, Project Management Support, QMake Projectmanager" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("Alexander Dymo"), ki18n( "Architecture, Sublime UI, Ruby support" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("David Nolden"), ki18n( "Definition-Use Chain, C++ Support, Code Navigation, Code Completion, Coding Assistance, Refactoring" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("Aleix Pol Gonzalez"), ki18n( "CMake Support, Run Support, Kross Support" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("Vladimir Prus"), ki18n( "GDB integration" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("Hamish Rodda"), ki18n( "Text editor integration, definition-use chain" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("Amilcar do Carmo Lucas"), ki18n( "Website admin, API documentation, Doxygen and autoproject patches" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("Niko Sams"), ki18n( "GDB integration, Webdevelopment Plugins" ), "*****@*****.**" );
    aboutData.addAuthor( ki18n("Milian Wolff"), ki18n( "Generic manager, Webdevelopment Plugins, Snippets, Performance" ), "*****@*****.**" );

    aboutData.addCredit( ki18n("Matt Rogers"), KLocalizedString(), "*****@*****.**");
    aboutData.addCredit( ki18n("Cédric Pasteur"), ki18n("astyle and indent support"), "*****@*****.**" );
    aboutData.addCredit( ki18n("Evgeniy Ivanov"), ki18n("Distributed VCS, Git, Mercurial"), "*****@*****.**" );
    // QTest integration is separate in playground currently.
    //aboutData.addCredit( ki18n("Manuel Breugelmanns"), ki18n( "Veritas, QTest integration"), "*****@*****.**" );
    aboutData.addCredit( ki18n("Robert Gruber") , ki18n( "SnippetPart, debugger and usability patches" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Dukju Ahn"), ki18n( "Subversion plugin, Custom Make Manager, Overall improvements" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Harald Fernengel"), ki18n( "Ported to Qt 3, patches, valgrind, diff and perforce support" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Roberto Raggi"), ki18n( "C++ parser" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("The KWrite authors"), ki18n( "Kate editor component" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Nokia Corporation/Qt Software"), ki18n( "Designer code" ), "*****@*****.**" );

    aboutData.addCredit( ki18n("Contributors to older versions:"), KLocalizedString(), "" );
    aboutData.addCredit( ki18n("The KHTML authors"), ki18n( "HTML documentation component" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Bernd Gehrmann"), ki18n( "Initial idea, basic architecture, much initial source code" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Caleb Tennis"), ki18n( "KTabBar, bugfixes" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Richard Dale"), ki18n( "Java & Objective C support" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("John Birch"), ki18n( "Debugger frontend" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Sandy Meier"), ki18n( "PHP support, context menu stuff" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Kurt Granroth"), ki18n( "KDE application templates" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Ian Reinhart Geiser"), ki18n( "Dist part, bash support, application templates" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Matthias Hoelzer-Kluepfel"), ki18n( "Several components, htdig indexing" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Victor Roeder"), ki18n( "Help with Automake manager and persistent class store" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Simon Hausmann"), ki18n( "Help with KParts infrastructure" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Oliver Kellogg"), ki18n( "Ada support" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Jakob Simon-Gaarde"), ki18n( "QMake projectmanager" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Falk Brettschneider"), ki18n( "MDI modes, QEditor, bugfixes" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Mario Scalas"), ki18n( "PartExplorer, redesign of CvsPart, patches, bugs(fixes)" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Jens Dagerbo"), ki18n( "Replace, Bookmarks, FileList and CTags2 plugins. Overall improvements and patches" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Julian Rockey"), ki18n( "Filecreate part and other bits and patches" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Ajay Guleria"), ki18n( "ClearCase support" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Marek Janukowicz"), ki18n( "Ruby support" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Robert Moniot"), ki18n( "Fortran documentation" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Ka-Ping Yee"), ki18n( "Python documentation utility" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Dimitri van Heesch"), ki18n( "Doxygen wizard" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Hugo Varotto"), ki18n( "Fileselector component" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Matt Newell"), ki18n( "Fileselector component" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Daniel Engelschalt"), ki18n( "C++ code completion, persistent class store" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Stephane Ancelot"), ki18n( "Patches" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Jens Zurheide"), ki18n( "Patches" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Luc Willems"), ki18n( "Help with Perl support" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Marcel Turino"), ki18n( "Documentation index view" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Yann Hodique"), ki18n( "Patches" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Tobias Gl\303\244\303\237er") , ki18n( "Documentation Finder,  qmake projectmanager patches, usability improvements, bugfixes ... " ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Andreas Koepfle") , ki18n( "QMake project manager patches" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Sascha Cunz") , ki18n( "Cleanup and bugfixes for qEditor, AutoMake and much other stuff" ), "*****@*****.**" );
    aboutData.addCredit( ki18n("Zoran Karavla"), ki18n( "Artwork for the ruby language" ), "*****@*****.**", "http://the-error.net" );

    //we can't use KCmdLineArgs as it doesn't allow arguments for the debugee
    //so lookup the --debug switch and eat everything behind by decrementing argc
    //debugArgs is filled with args after --debug <debuger>
    QStringList debugArgs;
    {
        bool debugFound = false;
        int c = argc;
        for (int i=0; i < c; ++i) {
            if (debugFound) {
                debugArgs << argv[i];
            } else if (QString(argv[i]) == "--debug") {
                if (argc <= i+1) {
                    argc = i + 1;
                } else {
                    i++;
                    argc = i + 1;
                }
                debugFound = true;
            } else if (QString(argv[i]).startsWith("--debug=")) {
                argc = i + 1;
                debugFound = true;
            }
        }
    }

    KCmdLineArgs::init( argc, argv, &aboutData );
    KCmdLineOptions options;
    options.add("project <project>", ki18n( "Url to project to load" ));
    options.add("+files", ki18n( "Files to load" ));
    options.add("debug <debugger>", ki18n( "Start debugger, for example gdb. The binary that should be debugged must follow - including arguments." ));
    options.add("cs <name>", ki18n("Create new session with given name."));
    options.add("s <session>", ki18n("Session to load. You can pass either hash or the name of the session." ));
    options.add("sessions", ki18n( "List available sessions and quit" ));

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

    if(args->isSet("sessions"))
    {
        QTextStream qout(stdout);
        qout << endl << ki18n("Available sessions (use '-s HASH' or '-s NAME' to open a specific one):").toString() << endl << endl;
        qout << QString("%1").arg(ki18n("Hash").toString(), -38) << '\t' << ki18n("Name: Opened Projects").toString() << endl;
        foreach(const KDevelop::SessionInfo& si, KDevelop::SessionController::availableSessionInfo())
        {
            if ( si.name.isEmpty() && si.projects.isEmpty() ) {
                continue;
            }
            qout << si.uuid.toString() << '\t' << si.description;

            if(!KDevelop::SessionController::tryLockSession(si.uuid.toString()))
                qout << "     " << i18n("[running]");

            qout << endl;
        }
        return 0;
    }
Example #6
0
int KGpgApp::newInstance()
{
	if (!running) {
		running = true;

		const QString gpgPath(KGpgSettings::gpgConfigPath());

		const QString gpgError = GPGProc::getGpgStartupError(KGpgSettings::gpgBinaryPath());
		if (!gpgError.isEmpty()) {
			KMessageBox::detailedError(0, i18n("GnuPG failed to start.<br />You must fix the GnuPG error first before running KGpg."), gpgError, i18n("GnuPG error"));
			KApplication::quit();
		}

		s_keyManager = new KeysManager();

		w = new KGpgExternalActions(s_keyManager, s_keyManager->getModel());

		connect(s_keyManager, SIGNAL(readAgainOptions()), w, SLOT(readOptions()));
		connect(w, SIGNAL(updateDefault(QString)), SLOT(assistantOver(QString)));
		connect(w, SIGNAL(createNewKey()), s_keyManager, SLOT(slotGenerateKey()));

		if (!gpgPath.isEmpty()) {
			if ((KgpgInterface::getGpgBoolSetting(QLatin1String( "use-agent" ), gpgPath)) && (qgetenv("GPG_AGENT_INFO").isEmpty()))
				KMessageBox::sorry(0, i18n("<qt>The use of <b>GnuPG Agent</b> is enabled in GnuPG's configuration file (%1).<br />"
					"However, the agent does not seem to be running. This could result in problems with signing/decryption.<br />"
					"Please disable GnuPG Agent from KGpg settings, or fix the agent.</qt>", gpgPath));
		}
	}

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	// parsing of command line args
	if (args->isSet("k") || (!KGpgSettings::showSystray() && (args->count() == 0) && !args->isSet("d"))) {
		s_keyManager->show();
		KWindowSystem::setOnDesktop(s_keyManager->winId(), KWindowSystem::currentDesktop());  //set on the current desktop
		KWindowSystem::unminimizeWindow(s_keyManager->winId());  //de-iconify window
		s_keyManager->raise();  // set on top
	} else if (args->isSet("d")) {
		s_keyManager->slotOpenEditor();
		s_keyManager->hide();
	} else {
		KUrl::List urlList;

		for (int ct = 0; ct < args->count(); ct++)
			urlList.append(args->url(ct));

		bool directoryInside = false;
		foreach (const KUrl &url, urlList)
			if (KMimeType::findByUrl(url)->name() == QLatin1String( "inode/directory" )) {
				directoryInside = true;
				break;
			}

		if (args->isSet("e")) {
			if (urlList.isEmpty())
				KMessageBox::sorry(0, i18n("No files given."));
			else if (!directoryInside)
				KGpgExternalActions::encryptFiles(s_keyManager, urlList);
			else
				KGpgExternalActions::encryptFolders(s_keyManager, urlList);
		} else if (args->isSet("s")) {
			if (urlList.isEmpty())
				KMessageBox::sorry(0, i18n("No files given."));
			else if (!directoryInside)
				w->showDroppedFile(urlList.first());
			else
				KMessageBox::sorry(0, i18n("Cannot decrypt and show folder."));
		} else if (args->isSet("S")) {
			if (urlList.isEmpty())
				KMessageBox::sorry(0, i18n("No files given."));
			else if (!directoryInside)
				KGpgExternalActions::signFiles(s_keyManager, urlList);
			else
				KMessageBox::sorry(0, i18n("Cannot sign folder."));
		} else if (args->isSet("V") != 0) {
			if (urlList.isEmpty())
				KMessageBox::sorry(0, i18n("No files given."));
			else if (!directoryInside)
				w->verifyFile(urlList.first());
			else
				KMessageBox::sorry(0, i18n("Cannot verify folder."));
		} else {
			if (directoryInside && (urlList.count() > 1)) {
				KMessageBox::sorry(0, i18n("Unable to perform requested operation.\nPlease select only one folder, or several files, but do not mix files and folders."));
				return 0;
			}

			if (urlList.isEmpty()) {
				/* do nothing */
			} else if (urlList.first().fileName().endsWith(QLatin1String(".sig"))) {
				w->verifyFile(urlList.first());
			} else {
				bool haskeys = false;
				bool hastext = false;
				foreach (const KUrl &url, urlList) {
					QFile qfile(url.path());
					if (qfile.open(QIODevice::ReadOnly)) {
						const int probelen = 4096;
						QTextStream t(&qfile);
						QString probetext(t.read(probelen));
						qfile.close();

						if (KGpgImport::isKey(probetext, probetext.length() == probelen))
							haskeys = true;
						else
							hastext = true;
					}
				}

				if (hastext) {
					KGpgExternalActions::decryptFiles(s_keyManager, urlList);
				} else if (haskeys) {
					s_keyManager->slotImport(urlList);
				}
			}
		}
	}
Example #7
0
int main(int argc, char **argv) {
    k9batch batch;
    if (batch.exec(argc,argv)) 
      return 1;
    
    KAboutData about("k9copy", 0, ki18n("k9copy"), version, ki18n(description),
                     KAboutData::License_GPL, ki18n("(C) 2004-2011 Jean-Michel PETIT"), KLocalizedString(), 0, "*****@*****.**");
    about.addAuthor( ki18n("Jean-Michel PETIT"), KLocalizedString(), "*****@*****.**" );
    about.setTranslator(ki18n("_: NAME OF TRANSLATORS\\nYour names")
                        ,ki18n("_: EMAIL OF TRANSLATORS\\nYour emails"));

    KCmdLineArgs::init(argc, argv, &about);
    KCmdLineOptions options;
    options.add( "input <device>", ki18n("input device"));
    options.add("output <device>", ki18n("output device"));
    options.add("dvdtitle <number>", ki18n("title to play"));
    options.add("assistant", ki18n("the k9copy backup assistant"));


    KCmdLineArgs::addCmdLineOptions( options );

    //    KCmdLineOptions options;
    //    options.add("+[URL]", ki18n( "Document to open" ));
    KCmdLineArgs::addCmdLineOptions(options);
    KApplication app;

    k9Tools::setMainThread();

    if (app.isSessionRestored()) {
        RESTORE(k9Copy);
    } else {
        // no session.. just start up normally
        KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
        QString InputOptionArg( args->getOption("input"));
        QString OutputOptionArg( args->getOption("output"));
        k9Config::checkCodecs();
        if (!args->isSet("assistant")) {
            k9Copy  *widget = new k9Copy;
            if (InputOptionArg !="") {
		widget->setInput( InputOptionArg);
		widget->fileOpen();
            }
            if (OutputOptionArg !="")
		widget->setOutput( OutputOptionArg);

            if ((InputOptionArg !="") && (OutputOptionArg!=""))
		widget->clone( InputOptionArg,OutputOptionArg);
            widget->show();
        } else {
            k9Assistant *ast=k9Assistant::createAssistant();
            if (InputOptionArg !="")
                ast->setPath(InputOptionArg);
            k9Dialogs::setMainWidget(ast);
            QTimer::singleShot (10, ast, SLOT (run ()));

	}	

        int res=app.exec();
        k9Config config;
        if (config.getPrefDelTmpFiles())
            k9Tools::clearOutput();

        return res;
    }
}
Example #8
0
int main (int argc, char *argv[])
{
    const char *version = "1.0";
    const char *description = "Unit test for md5, base64 encode/decode and uuencode/decode facilities";
    KCmdLineOptions options[] =
    {
        { "c <digest>", "compare <digest> with the calculated digest for a string or file.", 0 },
        { "d", "decode the given string or file using base64", 0 },
        { "e", "encode the given string or file using base64", 0 },
        { "f", "the filename to be used as input", "default" },
        { "p", "encode the given string or file using quoted-printable", 0},
        { "q", "decode the given string or file using quoted-printable", 0},
        { "r", "calculate the raw md5 for the given string or file", 0 },
        { "s", "the string to be used as input", 0 },
        { "t", "perform a timed message-digest test", 0 },
        { "u", "uuencode the given string or file", 0 },
        { "x", "uudecode the given string or file", 0 },
        { "z", "run a preset message-digest test", 0 },
        { "+command", "[input1, input2,...]", 0 },
        KCmdLineLastOption
    };

    KCmdLineArgs::init( argc, argv, "kmdcodectest", description, version );
    KCmdLineArgs::addCmdLineOptions( options );
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    int count = args->count();

    KApplication 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" ).data();
          for ( int i=0 ; i < count; i++ )
            MD5_verify ( QCString(args->arg(i)), opt, (isString || !isFile) );
       }
       else
       {
          for ( int i=0 ; i < count; i++ )
          {
            if ( type != Unspecified )
              testCodec( args->arg(i), type, isFile );
            else
            {
              if ( isString )
                MD5_string( args->arg( i ), 0, args->isSet("r") );
              else
                MD5_file( args->arg( i ), args->isSet("r") );
            }
          }
       }
    }
    args->clear();
    return (0);
}
Example #9
0
int main(int argc, char *argv[]) {
    int i_file, i_v, i_curve;
    int i_plot;
    QString fullPath;

    KAboutData aboutData("kst", I18N_NOOP("Kst"),
                         KSTVERSION, description, KAboutData::License_GPL,
                         I18N_NOOP("(c) 2000-2007 Barth Netterfield"),
                         0,
                         "http://kst.kde.org/");
    aboutData.addAuthor("Barth Netterfield",
                        I18N_NOOP("Original author and maintainer."),
                        "*****@*****.**",
                        "http://omega.astro.utoronto.ca/");
    aboutData.addAuthor("Staikos Computing Services Inc.",
                        I18N_NOOP("Developed for the University of Toronto."),
                        "*****@*****.**",
                        "http://www.staikos.net/");
    aboutData.addAuthor("Sumus Technology Limited",
                        I18N_NOOP("Developed for the University of British Columbia"),
                        "*****@*****.**",
                        "http://www.sumusltd.com/");
    aboutData.addAuthor("Rick Chern",
                        I18N_NOOP("University of British Columbia"),
                        "",
                        "");
    aboutData.addAuthor("Duncan Hanson",
                        I18N_NOOP("University of British Columbia"),
                        "",
                        "");
    aboutData.addAuthor("Nicolas Brisset",
                        "",
                        "",
                        "");
    aboutData.addAuthor("Matthew Truch",
                        "",
                        "http://matt.truch.net/",
                        "*****@*****.**");
    aboutData.addAuthor("Theodore Kisner",
                        "",
                        "*****@*****.**",
                        "");
    aboutData.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"),
                            I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails"));

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

    KApplication app;
    KImageIO::registerFormats();

    KstDialogs::replaceSelf(new KstGuiDialogs);
    KstData::replaceSelf(new KstGuiData);
    KstApp::initialize();

    atexit(exitHelper);

    if (app.isRestored()) {
        RESTORE(KstApp)
    } else {
        KstApp *kst = new KstApp;
        InType in;
        QColor color;
        QCStringList ycolList;
        QCStringList matrixList;
        QCStringList yEqList;
        QCStringList psdList;
        QCStringList hsList;
        QCStringList errorList;
        unsigned int i_ycol;
        QCStringList::Iterator hs_string;
        QCStringList::Iterator eq_i;
        QCStringList::Iterator mat_i;
        bool showQuickStart = false;
        bool showDataWizard = false;
        bool nOK;
        int n_y = 0;
        KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

        CheckForCMDErrors(args);

        QString wizardfile = args->getOption("w");
        QString printfile = args->getOption("print");
        QString pngfile = args->getOption("png");
        bool print_and_exit = false;

        if (printfile != "<none>") {
            print_and_exit = true;
        }
        if (pngfile != "<none>") {
            print_and_exit = true;
        }

        if (!print_and_exit) {
            app.setMainWidget(kst);
            QRect rect = KGlobalSettings::desktopGeometry(kst);
            kst->resize(5 * rect.width() / 6, 5 * rect.height() / 6);
            kst->show();
        }

        // get Y axis columns
        ycolList = args->getOptionList("y");
        matrixList = args->getOptionList("z");
        yEqList = args->getOptionList("ye");
        psdList = args->getOptionList("p");
        hsList = args->getOptionList("h");
        errorList = args->getOptionList("e");

        // y axis or PSD specified, so the files are data files, not kst files.
        n_y = ycolList.count() + psdList.count() + hsList.count() + yEqList.count() + matrixList.count();
        if (n_y > 0) {
            QString creatingEquations = i18n("Creating equations");
            QString creatingCurves = i18n("Creating curves");
            QString creatingPlots = i18n("Creating plots");
            int count;
            int handled;

            kst->slotUpdateProgress( 0, 0, QString::null );

            SetCMDOptions(args, in, n_y);

            KstTopLevelViewPtr tlv = kst->activeView();

            if (!tlv) {
                // if there was no active view then we create one...
                kst->newWindow(false);
                tlv = kst->activeView();
            }

            if (!tlv) {
                kstdError() << i18n("Can't create a view.") << endl;
                return 0;
            }

            CreatePlots(in, tlv);
            Kst2DPlotList plist = kstObjectSubList<KstViewObject, Kst2DPlot>(tlv->children());

            i_plot = 0;
            Kst2DPlotPtr plot = *plist.at(i_plot);

            KstVCurveList vcurves = kstObjectSubList<KstBaseCurve,KstVCurve>(plot->Curves);

            // make stand alone equations if there are no files
            if (args->count() < 1) {
                if (!yEqList.isEmpty()) {
                    QString eqS;
                    double max, min;
                    int n;
                    bool xeq;

                    SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq);
                    if (xeq) {
                        count = yEqList.size();
                        handled = 0;
                        kst->slotUpdateProgress( count, handled, creatingEquations );

                        for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) {
                            eqS = *eq_i;
                            if (NoVectorEq(eqS)) {
                                KstEquationPtr eq = new KstEquation(KST::suggestEQName(eqS), eqS, min, max, n);
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(eq->tag(), true),
                                                                eq->vX(), eq->vY(), 0L, 0L, 0L, 0L,
                                                                KstColorSequence::next(vcurves,plot->backgroundColor()));
                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(eq.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    i_plot++;
                                    if (i_plot < in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }

                            handled++;
                            kst->slotUpdateProgress( count, handled, creatingEquations );
                        }
                    }
                }
            }

            // make the requested curves for each data file
            count = args->count();
            handled = 0;
            kst->slotUpdateProgress( count, handled, creatingCurves );

            for (i_curve = i_v = 0, i_file = 0; i_file < args->count(); i_file++) {
                // make the file
                if (QFile::exists(args->arg(i_file))) {
                    fullPath = QFileInfo(args->arg(i_file)).absFilePath();
                } else {
                    fullPath = args->arg(i_file);
                }

                KstDataSourcePtr file = KstDataSource::loadSource(fullPath);

                if (file) {
                    if (!file->isValid() || file->isEmpty()) {
                        kstdError() << i18n("No data in file %1.  Trying to continue...").arg(args->arg(i_file)) << endl;
                        // The file might get data later!
                    }

                    KST::dataObjectList.lock().writeLock();
                    KST::dataSourceList.append(file);
                    KST::dataObjectList.lock().unlock();

                    KstRVectorPtr yvector;
                    KstRVectorPtr evector;
                    KstVCurvePtr curve;
                    KstPSDPtr psd;
                    KstHistogramPtr hs;
                    KstRVectorPtr xvector;

                    if (!ycolList.isEmpty()) { // if there are some xy plots
                        // make the x axis vector
                        xvector = GetOrCreateVector(args->getOption("x"), file, in);
                        if (xvector) {
                            // make the y axis vectors
                            for (i_ycol = 0; i_ycol < ycolList.count(); ++i_ycol ) {
                                yvector = GetOrCreateVector(*(ycolList.at(i_ycol)), file, in);
                                if (yvector) {
                                    // make the curves
                                    color = KstColorSequence::next(vcurves,plot->backgroundColor());
                                    curve = new KstVCurve(KST::suggestCurveName(yvector->tag(), false),
                                                          KstVectorPtr(xvector), KstVectorPtr(yvector),
                                                          0L, 0L, 0L, 0L, color);
                                    if (in.has_points) {
                                        curve->setHasPoints(true);
                                        curve->setHasLines(false);
                                    }

                                    if (i_ycol<errorList.count()) {
                                        evector = GetOrCreateVector(*(errorList.at(i_ycol)), file, in);
                                        if (evector) {
                                            curve->setYError(KstVectorPtr(evector));
                                            curve->setYMinusError(KstVectorPtr(evector));
                                        }
                                    }

                                    KST::dataObjectList.lock().writeLock();
                                    KST::dataObjectList.append(curve.data());
                                    KST::dataObjectList.lock().unlock();
                                    plot->addCurve(curve.data());

                                    if (in.sep_plots) {
                                        plot->setTagName(curve->tag());
                                        i_plot++;
                                        if (i_plot < in.n_plots) {
                                            plot = *plist.at(i_plot);
                                        }
                                    } // end (if they are separate plots)
                                }
                            } // next y col
                        }
                    } // end (if there are some xy plots)

                    if (!yEqList.isEmpty()) {
                        QString eqS;
                        double max, min;
                        int n;
                        bool xeq, eq_ok;

                        SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq);
                        for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) {
                            KstEquationPtr eq;

                            eqS = *eq_i;
                            ProcessEq(eqS, file, in, &eq_ok);

                            if (xeq) {
                                eq = new KstEquation(KST::suggestEQName(eqS), eqS, min,max,n);
                            } else {
                                if (!xvector) {
                                    xvector = GetOrCreateVector(args->getOption("x"), file, in);
                                }
                                if (xvector) {
                                    eq = new KstEquation(KST::suggestEQName(eqS), eqS, KstVectorPtr(xvector), true);
                                }
                            }

                            if (eq) {
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(eq->tag(), true),
                                                                eq->vX(), eq->vY(), 0L, 0L, 0L, 0L,
                                                                KstColorSequence::next(vcurves,plot->backgroundColor()));
                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(eq.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    plot->setTagName(eq->tag());
                                    i_plot++;
                                    if (i_plot <in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }
                        }
                    }

                    if (psdList.count() > 0) { // if there are some psd plots
                        KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList);
                        for (QCStringList::ConstIterator it = psdList.begin(); it != psdList.end(); ++it) {

                            yvector = GetOrCreateVector(*it, file, in);
                            if (yvector) {
                                color = KstColorSequence::next(vcurves,plot->backgroundColor());

                                psd = new KstPSD( KST::suggestPSDName(yvector->tag()), // FIXME: this was yvector->field(), is this right?
                                                  KstVectorPtr(yvector), in.rate, true, in.len,
                                                  true, true, in.VUnits, in.RUnits, WindowOriginal);
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(psd->tag(), true),
                                                                psd->vX(), psd->vY(), 0L, 0L, 0L, 0L, color);
                                if (in.has_points) {
                                    vc->setHasPoints(true);
                                    vc->setHasLines(false);
                                }
                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(psd.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    plot->setTagName(psd->tag());
                                    i_plot++;
                                    if (i_plot <in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }
                        } // next psd
                    } // end (if there are some psds)

                    if (hsList.count() > 0) { // if there are some histograms
                        double max, min;
                        int N;

                        KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList);
                        for (hs_string = hsList.begin(); hs_string != hsList.end(); ++hs_string) {
                            yvector = GetOrCreateVector(*hs_string, file, in);
                            if (yvector) {
                                color = KstColorSequence::next(vcurves,plot->backgroundColor());

                                KstHistogram::AutoBin(KstVectorPtr(yvector), &N, &max, &min);

                                hs = new KstHistogram(KST::suggestHistogramName(yvector->tag()),
                                                      KstVectorPtr(yvector), min, max, N, KST_HS_NUMBER);
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(hs->tag(), true),
                                                                hs->vX(), hs->vY(),
                                                                0L, 0L, 0L, 0L, color);

                                vc->setHasPoints(false);
                                vc->setHasLines(false);
                                vc->setHasBars(true);
                                vc->setBarStyle(1);

                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(hs.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    plot->setTagName(hs->tag());
                                    i_plot++;
                                    if (i_plot < in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }
                        } // next histogram
                    } // end (if there are some histograms)

                    if (matrixList.count() > 0) { // if there are some matrixes
                        for (mat_i = matrixList.begin(); mat_i != matrixList.end(); ++mat_i) {
                            QString tag_name = KST::suggestMatrixName(*mat_i);
                            if (!file->isValidMatrix(*mat_i)) {
                                startupErrors.append(i18n("Failed to create matrix '%1' from file '%2'.").arg(*mat_i).arg(file->fileName()));
                            }
                            KstRMatrixPtr matrix = new KstRMatrix(file, *mat_i,
                                                                  KstObjectTag(tag_name, file->tag()),
                                                                  0,0,-1,-1,false,false,0);
                            // xStart, yStart, xNumSteps, yNumSteps,
                            //doAve, doSkip, skip);

                            // Time to create the image from the matrix
                            tag_name = KST::suggestImageName(matrix->tag());
                            QStringList palList = KPalette::getPaletteList();
                            QString pal;
                            if (palList.contains("IDL 13 RAINBOW")) {
                                pal = QString("IDL 13 RAINBOW");
                            } else {
                                pal = QString(*palList.at(0));
                            }

                            KPalette* newPal = new KPalette(pal);
                            KstImagePtr image = new KstImage(tag_name, KstMatrixPtr(matrix), 0.0, 1.0,
                                                             true, newPal);
                            plot->addCurve(KstBaseCurvePtr(image));
                            KST::dataObjectList.lock().writeLock();
                            KST::dataObjectList.append(image.data());
                            KST::dataObjectList.lock().unlock();
                            image = 0L; // drop the reference

                            if (in.sep_plots) {
                                plot->setTagName(matrix->tag());
                                i_plot++;
                                if (i_plot < in.n_plots) {
                                    plot = *plist.at(i_plot);
                                }
                            }
                        }
                    }
                } else {
                    startupErrors.append(i18n("Failed to load file '%1'.").arg(args->arg(i_file)));
                }
                handled++;
                kst->slotUpdateProgress( count, handled, creatingCurves );
            } // next data file

            count = in.n_plots;
            handled = 0;
            kst->slotUpdateProgress( count, handled, creatingPlots );
            for (i_plot = 0; i_plot < in.n_plots; i_plot++) {
                plot = *plist.at(i_plot);
                plot->generateDefaultLabels();

                // if we have only images in a plot then set the scale mode to AUTO (instead of AUTOBORDER)
                KstImageList images = kstObjectSubList<KstBaseCurve,KstImage>(plot->Curves);
                if (images.count() == plot->Curves.count()) {
                    plot->setXScaleMode(AUTO);
                    plot->setYScaleMode(AUTO);
                }

                if (plot->Curves.count() > 3 || in.dolegend) {
                    KstViewLegendPtr vl = plot->getOrCreateLegend();
                    vl->resizeFromAspect(0.1, 0.1, 0.2, 0.1);
                    vl->setBorderWidth(2);
                }
                handled++;
                kst->slotUpdateProgress( count, handled, creatingPlots );
            }

            kst->slotUpdateProgress( 0, 0, QString::null );
        } else if (args->count() > 0) { // open a kst file
            // some of the options can be overridden
            kst->openDocumentFile(args->arg(0),
                                  args->getOption("F"),             // override FileName
                                  args->getOption("n").toInt(&nOK), // override number of frames
                                  args->getOption("f").toInt(&nOK), // override starting frame
                                  args->getOption("s").toInt(&nOK), // override skip
                                  args->isSet("a"),                 // add averaging
                                  !print_and_exit);                 // delayed
        } else {
            //kst->openDocumentFile();
            showQuickStart = true;
        }

        if (args->isSet("nq")) {
            showQuickStart = false;
        }
        if (args->isSet("w")) {
            showDataWizard = true;
            showQuickStart = false;
        }

        if (printfile != "<none>") {
            kst->forceUpdate();
            kst->immediatePrintToFile(printfile, false);
        }

        if (pngfile != "<none>") {
            kst->forceUpdate();
            kst->immediatePrintToPng(pngfile);
        }

        kst->document()->setModified(false);

        if (print_and_exit) {
            delete kst;
            return 0;
        } else {
            kst->updateDialogs();

            if (showQuickStart) {
                kst->showQuickStartDialog();
            }
            if (showDataWizard) {
                kst->showDataWizardWithFile(wizardfile);
            }
            for (size_t i = 0; i < startupErrors.size(); ++i) {
                KstDebug::self()->log(startupErrors[i], KstDebug::Error);
            }
            startupErrors.clear();
        }

        // LEAVE THIS HERE - causes crashes otherwise!
        int rc = app.exec();
        delete kst;
        return rc;
    }

    return app.exec();
}
Example #10
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" ),
                          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( "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( "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( "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( "enableFileView",
                 ki18n( "Enable tab to see gpxFileView" ) );
    options.add( "tile-id", ki18n( "Show tile IDs" ) );
    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 = QString();
    }
    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( "enableFileView" ) ) {
        window->marbleControl()->setFileViewTabShown( 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();
}
Example #11
0
static int startApp()
{
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    // Stop daemon and exit?
    if (args->isSet("s"))
    {
        KDEsuClient client;
        if (client.ping() == -1)
        {
            kError(1206) << "Daemon not running -- nothing to stop\n";
            exit(1);
        }
        if (client.stopServer() != -1)
        {
            kDebug(1206) << "Daemon stopped\n";
            exit(0);
        }
        kError(1206) << "Could not stop daemon\n";
        exit(1);
    }

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

    bool prompt = true;
    if ( args->isSet("d"))
	prompt = false;

    // Get target uid
    QByteArray user = args->getOption("u").toLocal8Bit();
    QByteArray auth_user = user;
    struct passwd *pw = getpwnam(user);
    if (pw == 0L)
    {
        kError(1206) << "User " << user << " does not exist\n";
        exit(1);
    }
    bool other_uid = (getuid() != pw->pw_uid);
    bool change_uid = other_uid;
    if (!change_uid) {
        char *cur_user = getenv("USER");
        if (!cur_user)
            cur_user = getenv("LOGNAME");
        change_uid = (!cur_user || user != cur_user);
    }

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

    // Get priority/scheduler
    QString tmp = args->getOption("p");
    bool ok;
    int priority = tmp.toInt(&ok);
    if (!ok || (priority < 0) || (priority > 100))
    {
        KCmdLineArgs::usageError(i18n("Illegal priority: %1", tmp));
        exit(1);
    }
    int scheduler = SuProcess::SchedNormal;
    if (args->isSet("r"))
        scheduler = SuProcess::SchedRealtime;
    if ((priority > 50) || (scheduler != SuProcess::SchedNormal))
    {
        change_uid = true;
        auth_user = "******";
    }

    // Get command
    if (args->isSet("c"))
    {
        command = args->getOption("c").toLocal8Bit();
        // Accepting additional arguments here is somewhat weird,
        // but one can conceive use cases: have a complex command with
        // redirections and additional file names which need to be quoted
        // safely.
    }
    else
    {
        if( args->count() == 0 )
        {
            KCmdLineArgs::usageError(i18n("No command specified."));
            exit(1);
        }
    }
    for (int i = 0; i < args->count(); i++)
    {
        command += ' ';
        command += QFile::encodeName(KShell::quoteArg(args->arg(i)));
    }

    // Don't change uid if we're don't need to.
    if (!change_uid)
    {
        int result = system(command);
        result = WEXITSTATUS(result);
        return result;
    }

    // Check for daemon and start if necessary
    bool just_started = false;
    bool have_daemon = true;
    KDEsuClient client;
    if (!client.isServerSGID())
    {
        kWarning(1206) << "Daemon not safe (not sgid), not using it.\n";
        have_daemon = false;
    }
    else if (client.ping() == -1)
    {
        if (client.startServer() == -1)
        {
            kWarning(1206) << "Could not start daemon, reduced functionality.\n";
            have_daemon = false;
        }
        just_started = true;
    }

    // Try to exec the command with kdesud.
    bool keep = !args->isSet("n") && have_daemon;
    bool terminal = args->isSet("t");
    bool withIgnoreButton = args->isSet("ignorebutton");
    int winid = -1;
    bool attach = args->isSet("attach");
    if(attach) {
        winid = args->getOption("attach").toInt(&attach, 0);  //C style parsing.  If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
        if(!attach)
            kWarning(1206) << "Specified winid to attach to is not a valid number";
    } else if(args->isSet("embed")) {
        /* KDialog originally used --embed for attaching the dialog box.  However this is misleading and so we changed to --attach.
         * For consistancy, we silently map --embed to --attach */
        attach = true;
        winid = args->getOption("embed").toInt(&attach, 0);  //C style parsing.  If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
        if(!attach)
            kWarning(1206) << "Specified winid to attach to is not a valid number";
    }


    QList<QByteArray> env;
    QByteArray options;
    env << ( "DESKTOP_STARTUP_ID=" + kapp->startupId());

    if (pw->pw_uid)
    {
       // Only propagate KDEHOME for non-root users,
       // root uses KDEROOTHOME

       // Translate the KDEHOME of this user to the new user.
       QString kdeHome = KGlobal::dirs()->relativeLocation("home", KGlobal::dirs()->localkdedir());
       if (kdeHome[0] != '/')
          kdeHome.prepend("~/");
       else
          kdeHome.clear(); // Use default

       env << ("KDEHOME="+ QFile::encodeName(kdeHome));
    }

    KUser u;
    env << (QByteArray) ("KDESU_USER="******"rlimit(): " << ERR << "\n";
        exit(1);
    }

    // Read configuration
    KConfigGroup config(KGlobal::config(), "Passwords");
    int timeout = config.readEntry("Timeout", defTimeout);

    // Check if we need a password
    SuProcess proc;
    proc.setUser(auth_user);
    int needpw = proc.checkNeedPassword();
    if (needpw < 0)
    {
        QString err = i18n("Su returned with an error.\n");
        KMessageBox::error(0L, err);
        exit(1);
    }
    if (needpw == 0)
    {
        keep = 0;
        kDebug() << "Don't need password!!\n";
    }

    // Start the dialog
    QString password;
    if (needpw)
    {
#ifdef Q_WS_X11
        KStartupInfoId id;
        id.initId( kapp->startupId());
        KStartupInfoData data;
        data.setSilent( KStartupInfoData::Yes );
        KStartupInfo::sendChange( id, data );
#endif
        KDEsuDialog dlg(user, auth_user, keep && !terminal, icon, withIgnoreButton);
        if (prompt)
            dlg.addCommentLine(i18n("Command:"), QFile::decodeName(command));
        if (defKeep)
            dlg.setKeepPassword(true);

        if ((priority != 50) || (scheduler != SuProcess::SchedNormal))
        {
            QString prio;
            if (scheduler == SuProcess::SchedRealtime)
                prio += i18n("realtime: ");
            prio += QString("%1/100").arg(priority);
            if (prompt)
                dlg.addCommentLine(i18n("Priority:"), prio);
        }

	//Attach dialog
#ifdef Q_WS_X11
	if(attach)
            KWindowSystem::setMainWindow(&dlg, (WId)winid);
#endif
        int ret = dlg.exec();
        if (ret == KDEsuDialog::Rejected)
        {
#ifdef Q_WS_X11
            KStartupInfo::sendFinish( id );
#endif
            exit(1);
        }
        if (ret == KDEsuDialog::AsUser)
            change_uid = false;
        password = dlg.password();
        keep = dlg.keepPassword();
#ifdef Q_WS_X11
        data.setSilent( KStartupInfoData::No );
        KStartupInfo::sendChange( id, data );
#endif
    }

    // Some events may need to be handled (like a button animation)
    kapp->processEvents();

    // Run command
    if (!change_uid)
    {
        int result = system(command);
        result = WEXITSTATUS(result);
        return result;
    }
    else if (keep && have_daemon)
    {
        client.setPass(password.toLocal8Bit(), timeout);
        client.setPriority(priority);
        client.setScheduler(scheduler);
        int result = client.exec(command, user, options, env);
        if (result == 0)
        {
            result = client.exitCode();
            return result;
        }
    } else
    {
        SuProcess proc;
        proc.setTerminal(terminal);
        proc.setErase(true);
        proc.setUser(user);
        proc.setEnvironment(env);
        proc.setPriority(priority);
        proc.setScheduler(scheduler);
        proc.setCommand(command);
        int result = proc.exec(password.toLocal8Bit());
        return result;
    }
    return -1;
}
Example #12
0
int main( int argc, char **argv )
{
  KAboutData aboutData( "testincidence", 0, ki18n( "Test Incidence" ), "0.1" );
  KCmdLineArgs::init( argc, argv, &aboutData );

  KCmdLineOptions options;
  options.add( "verbose", ki18n( "Verbose output" ) );
  KCmdLineArgs::addCmdLineOptions( options );

  KComponentData componentData( &aboutData );
  //QCoreApplication app( KCmdLineArgs::qtArgc(), KCmdLineArgs::qtArgv() );

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  bool verbose = false;
  if ( args->isSet( "verbose" ) ) {
    verbose = true;
  }

  ICalFormat f;

  Event::Ptr event1 = Event::Ptr( new Event );
  event1->setSummary( "Test Event" );
  event1->recurrence()->setDaily( 2 );
  event1->recurrence()->setDuration( 3 );

  QString eventString1 = f.toString( event1.staticCast<Incidence>() );
  if ( verbose ) {
    kDebug() << "EVENT1 START:" << eventString1 << "EVENT1 END";
  }

  event1->setSchedulingID( "foo" );
  Incidence::Ptr event2 = Incidence::Ptr( event1->clone() );

  Q_ASSERT( event1->uid() == event2->uid() );
  Q_ASSERT( event1->schedulingID() == event2->schedulingID() );

  QString eventString2 = f.toString( event2.staticCast<Incidence>() );
  if ( verbose ) {
    kDebug() << "EVENT2 START:" << eventString2 << "EVENT2 END";
  }

  if ( eventString1 != eventString2 ) {
    kDebug() << "Clone Event FAILED.";
  } else {
    kDebug() << "Clone Event SUCCEEDED.";
  }

  Todo::Ptr todo1 = Todo::Ptr( new Todo );
  todo1->setSummary( "Test todo" );
  QString todoString1 = f.toString( todo1.staticCast<Incidence>() );
  if ( verbose ) {
    kDebug() << "todo1 START:" << todoString1 << "todo1 END";
  }

  Incidence::Ptr todo2 = Incidence::Ptr( todo1->clone() );
  QString todoString2 = f.toString( todo2 );
  if ( verbose ) {
    kDebug() << "todo2 START:" << todoString2 << "todo2 END";
  }

  if ( todoString1 != todoString2 ) {
    kDebug() << "Clone Todo FAILED.";
  } else {
    kDebug() << "Clone Todo SUCCEEDED.";
  }
}
Example #13
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;
}
Example #14
0
int main(int argc, char *argv[]) {
  int i_file, i_v, i_curve;
  int i_plot;

  KAboutData aboutData( "kst", I18N_NOOP("Kst"),
                        "0.95-devel", description, KAboutData::License_GPL,
                        I18N_NOOP("(c) 2000-2003 Barth Netterfield"),
                        0,
                        "http://extragear.kde.org/apps/kst.php");
  aboutData.addAuthor("Barth Netterfield",
                      I18N_NOOP("Original author and maintainer."),
                      "*****@*****.**",
                      "http://omega.astro.utoronto.ca/");
  aboutData.addAuthor("Staikos Computing Services Inc.",
                      I18N_NOOP("Developed for the University of Toronto."),
                      "*****@*****.**",
                      "http://www.staikos.net/");

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

  KApplication app;
  KImageIO::registerFormats();

  if (app.isRestored()) {
    RESTORE(KstApp)
  } else {
    KstApp *kst = new KstApp;

    struct InType in;
    QColor color;
    QCStringList ycolList;
    QCStringList yEqList;
    QCStringList psdList;
    QCStringList hsList;
    QCStringList errorList;
    unsigned int i_ycol;
    QCStringList::Iterator psd;
    QCStringList::Iterator hs;
    QCStringList::Iterator eq_i;
    bool nOK;

    /* temp variables: these all get stuck into list objects */
    KstDataSourcePtr file;
    KstRVector *xvector=NULL;
    KstRVector *yvector;
    KstRVector *evector;
    KstVCurve *curve;
    KstPSDCurve *psdcurve;
    KstEquationCurve *eqcurve;
    KstHistogram *hscurve;
    KstPlot *plot;
    int n_y, n_eq=0;

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

    CheckForCMDErrors(args);

    // Initialise the plugin loader and collection.
    PluginCollection::self();

    /* get Y axis collums */
    ycolList = args->getOptionList("y");
    yEqList = args->getOptionList("ye");
    psdList = args->getOptionList("p");
    hsList = args->getOptionList("h");
    errorList = args->getOptionList("e");

    // y axis or PSD specified, so the files are data files, not kst files.
    n_y = ycolList.count() + psdList.count() + hsList.count()
      + yEqList.count();
    if (n_y > 0) {

      SetCMDOptions(args, in, n_y);

      CreatePlots(in);

      i_plot = 0;
      plot = KST::plotList.at(i_plot);

      /* make stand alone equations if there are no files */
      if (args->count()<1) {
        if (!yEqList.isEmpty()) {
	  QString eqS;
          double max, min;
          int n;
          bool xeq;
          SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq);
          if (xeq) {
            for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) {
              eqS = *eq_i;
              if (NoVectorEq(eqS)) {
                eqcurve =
                  new KstEquationCurve(QString("E")+QString::number(n_eq+1)+
                                       "-" + eqS,
                                       eqS,
                                       min,max,n, KstColorSequence::next());

                KST::dataObjectList.lock().writeLock();
                KST::dataObjectList.append(eqcurve);
                KST::dataObjectList.lock().writeUnlock();
                plot->addCurve(eqcurve);

                if (in.sep_plots) {
                  i_plot++;
                  if (i_plot <in.n_plots) plot = KST::plotList.at(i_plot);
                }
              }
            }
          }
        }
      }

      /* Make the requested curves for each data file */
      for (i_curve = i_v = 0, i_file = 0; i_file < args->count(); i_file++) {
        /* Make the file */
        file = KstDataSource::loadSource(args->arg(i_file));

        if (!file) {
          kdWarning() << I18N_NOOP("Error: No data in file: ")
	              << args->arg(i_file) << endl;
          delete kst;
          exit(0);
        }

	if (!file->isValid() || file->frameCount() < 1) {
          kdWarning() << I18N_NOOP("Error: No data in file: ")
	              << args->arg(i_file) << endl;
          // The file might get data later!
	}

        KST::dataObjectList.lock().writeLock();
        KST::dataSourceList.append(file);
        KST::dataObjectList.lock().writeUnlock();

        if (!ycolList.isEmpty()) { // if there are some xy plots
          /* make the x axis vector */
          xvector = GetOrCreateVector(args->getOption("x"), file, in);

          /* make the y axis vectors */
          for (i_ycol = 0; i_ycol < ycolList.count(); ++i_ycol ) {
            yvector = GetOrCreateVector(*(ycolList.at(i_ycol)), file, in);

            /* make the curves */
            color = KstColorSequence::next();
            curve = new KstVCurve(QString("C") + QString::number(1+i_curve++)
                                  + "-" + yvector->getField(),
                                  KstVectorPtr(xvector), KstVectorPtr(yvector),
                                  0L, 0L, color);
            if (in.has_points) {
              curve->setHasPoints(true);
              curve->setHasLines(false);
            }

            if (i_ycol<errorList.count()) {
              evector = GetOrCreateVector(*(errorList.at(i_ycol)), file, in);
              curve->setYError(KstVectorPtr(evector));
            }

            KST::dataObjectList.lock().writeLock();
            KST::dataObjectList.append(curve);
            KST::dataObjectList.lock().writeUnlock();
            plot->addCurve(curve);

            if (in.sep_plots) {
              i_plot++;
              if (i_plot < in.n_plots)
                plot = KST::plotList.at(i_plot);
            } // end (if they are separate plots)
          } // next y col
        } // end (if there are some xy plots)
	if (!yEqList.isEmpty()) {
	  QString eqS;
          double max, min;
          int n;
          bool xeq, eq_ok;

          SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq);
	  for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) {
	    eqS = *eq_i;
	    ProcessEq(eqS, file, in, &eq_ok);
            if (xeq) {
              eqcurve =
                new KstEquationCurve(QString("E")+QString::number(n_eq+1)+
                                     "-" + eqS,
                                     eqS,
                                     min,max,n, KstColorSequence::next());
            } else {
              if (xvector==NULL)
                xvector = GetOrCreateVector(args->getOption("x"), file, in);

              eqcurve =
                new KstEquationCurve(QString("E")+QString::number(n_eq+1)+eqS,
                                     eqS,
                                     KstVectorPtr(xvector),
                                     true, KstColorSequence::next());
            }
            KST::dataObjectList.lock().writeLock();
            KST::dataObjectList.append(eqcurve);
            KST::dataObjectList.lock().writeUnlock();
            plot->addCurve(eqcurve);

            if (in.sep_plots) {
              i_plot++;
              if (i_plot <in.n_plots) plot = KST::plotList.at(i_plot);
            }
	  }
	}
        if (psdList.count() > 0) { // if there are some psd plots
          KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList);
          for(psd = psdList.begin(); psd != psdList.end(); ++psd ) {

	    yvector = GetOrCreateVector(*psd, file, in);

            color = KstColorSequence::next();

            psdcurve = new KstPSDCurve(QString("P") +
                                       QString::number(1+i_curve++)
                                       + "-" + yvector->getField(),
                                       KstVectorPtr(yvector), in.rate, in.len,
                                       in.VUnits,in.RUnits,
                                       color);
            if (in.has_points) {
              psdcurve->setHasPoints(true);
              psdcurve->setHasLines(false);
            }
            KST::dataObjectList.lock().writeLock();
            KST::dataObjectList.append(psdcurve);
            KST::dataObjectList.lock().writeUnlock();
            plot->addCurve(psdcurve);

            if (in.sep_plots) {
              i_plot++;
              if (i_plot <in.n_plots) plot = KST::plotList.at(i_plot);
            }
          } // next psd
        } // end (if there are some psds)
        if (hsList.count()>0) { // if there are some histograms
          double max, min;
          int N;

          KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList);
          for (hs = hsList.begin(); hs != hsList.end(); ++hs ) {
	    yvector = GetOrCreateVector(*hs, file, in);

            color = KstColorSequence::next();

            KstHistogram::AutoBin(KstVectorPtr(yvector), &N, &max, &min);

            hscurve = new KstHistogram(QString("H") +
                                       QString::number(1+i_curve++)
                                       + "-" + yvector->getField(),
                                       KstVectorPtr(yvector), min, max, N,
                                       KST_HS_NUMBER,
                                       color);
            KST::dataObjectList.lock().writeLock();
            KST::dataObjectList.append(KstDataObjectPtr(hscurve));
            KST::dataObjectList.lock().writeUnlock();
            plot->addCurve(hscurve);

            if (in.sep_plots) {
              i_plot++;
              if (i_plot < in.n_plots)
                plot = KST::plotList.at(i_plot);
            }
          } // next histogram
        } // end (if there are some histograms)
      } // next data file
      for (i_plot = 0; i_plot < in.n_plots; i_plot++) {
        KST::plotList.at(i_plot)->GenerateDefaultLabels();
      }
      KST::plotList.setPlotCols(in.n_cols);

    } else if (args->count() > 0) {
      /* open a kst file */
      /* some of the options can be overridden */
      kst->openDocumentFile(args->arg(0),
			    args->getOption("F"), // override FileName
			    // override number of frames
			    args->getOption("n").toInt(&nOK),
			    // override starting frame
			    args->getOption("f").toInt(&nOK),
			    // override skip
			    args->getOption("s").toInt(&nOK),
			    // add averaging
			    args->isSet("a"));
    } else {
      //kst->openDocumentFile();
    }

    QString printfile;
    printfile = args->getOption("print");
    QString pngfile;
    pngfile = args->getOption("png");
    bool print_and_exit = false;

    if (printfile!="<none>") {
      args->clear();
      kst->forceUpdate();
      kst->immediatePrintToFile(printfile);
      print_and_exit = true;
    }

    if (pngfile!="<none>") {
      args->clear();
      kst->forceUpdate();
      kst->immediatePrintToPng(pngfile);
      print_and_exit = true;
    }

    if (print_and_exit) {
      delete kst;
      exit(0);
    } else {
      args->clear();
      app.setMainWidget(kst);
      kst->show();
    }

    // LEAVE THIS HERE - causes crashes otherwise!
    int rc = app.exec();
    delete kst;
    return rc;
  }
  return app.exec();
}
Example #15
0
int main(int argc, char *argv[])
{
    bool enableDeveloper = false;
    bool enableSocket = false;

#ifdef HAVE_KDE

    KAboutData aboutData("hotot",                                        // internal name
                         "hotot-qt",                                     // catalog name
                         ki18n("Hotot"),                            // program name
                         "0.9.9",                             // app version from config-kmess.h
                         ki18n("Lightweight, Flexible Microblogging"),  // short description
                         KAboutData::License_GPL_V2,                   // license
                         ki18n("(c) 2009-2011 Shellex Wai\n"),   // copyright
                         KLocalizedString(),
                         "http://www.hotot.org/",                   // home page
                         "https://github.com/shellex/Hotot/issues"               // address for bugs
                        );

    aboutData.addAuthor(ki18n("Shellex Wai"),       ki18n("Developer and Artwork"), "*****@*****.**");
    aboutData.addAuthor(ki18n("Jiahua Huang"),      ki18n("Developer"),             "jhuangjiahua" "@" "gmail" "." "com");
    aboutData.addAuthor(ki18n("Jimmy Xu"),          ki18n("Developer"),             "xu.jimmy.wrk" "@" "gmail" "." "com");
    aboutData.addAuthor(ki18n("Tualatrix Chou"),    ki18n("Developer"),             "tualatrix" "@" "gmail" "." "com");
    aboutData.addAuthor(ki18n("Xu Zhen"),           ki18n("Developer"),             "xnreformer" "@" "gmail" "." "com");
    aboutData.addAuthor(ki18n("Evan"),              ki18n("Artwork"),               "www.freemagi.com");
    aboutData.addAuthor(ki18n("Marguerite Su"),     ki18n("Document"),              "admin"  "@" "doublechou.pp.ru");

    KCmdLineOptions options;
    options.add("d");
    options.add("dev", ki18n("Enable developer Tool"));
    options.add("s");
    options.add("socket", ki18n("Use Proxy as Socket Proxy instead of HTTP Proxy"));
    KCmdLineArgs::init(argc, argv, &aboutData);

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

    enableDeveloper = args->isSet("dev");
    enableSocket = args->isSet("socket");

    KApplication a;
#else
#if !defined(Q_OS_WIN32) && !defined(Q_OS_MAC)
    bind_textdomain_codeset("hotot-qt", "UTF-8");
#endif
#ifdef MEEGO_EDITION_HARMATTAN
    MApplication a(argc, argv);
#else
    QApplication a(argc, argv);

    int opt;
    while ((opt = getopt(argc, argv, "sdh")) != -1) {
        switch (opt) {
        case 's':
            enableSocket = true;
            break;
        case 'd':
            enableDeveloper = true;
            break;
        case 'h':
            Usage();
            return 0;
        default:
            Usage();
            exit(EXIT_FAILURE);
            break;
        }
    }
#endif

#endif
    MainWindow w(enableSocket);
    w.setEnableDeveloperTool(enableDeveloper);

#ifdef MEEGO_EDITION_HARMATTAN
    w.setOrientationAngle(M::Angle0);
    w.setOrientationAngleLocked(true);
#endif

    w.show();

    return a.exec();
}
Example #16
0
int main( int argc, char **argv )
{
    KAboutData aboutData( "nspluginscan", "nsplugin", ki18n("nspluginscan"),
                          "0.3", ki18n("nspluginscan"), KAboutData::License_GPL,
                          ki18n("(c) 2000,2001 by Stefan Schimanski") );

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

    KCmdLineOptions options;
    options.add("verbose", ki18n("Show progress output for GUI"));
    KCmdLineArgs::addCmdLineOptions( options );
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    showProgress = args->isSet("verbose");
    if (showProgress) {
      printf("10\n"); fflush(stdout);
    }

    KApplication app(false);

    // Set up SIGCHLD handler
    struct sigaction act;
    act.sa_handler=sigChildHandler;
    sigemptyset(&(act.sa_mask));
    sigaddset(&(act.sa_mask), SIGCHLD);
    // Make sure we don't block this signal. gdb tends to do that :-(
    sigprocmask(SIG_UNBLOCK, &(act.sa_mask), 0);

    act.sa_flags = SA_NOCLDSTOP;

    // CC: take care of SunOS which automatically restarts interrupted system
    // calls (and thus does not have SA_RESTART)

#ifdef SA_RESTART
    act.sa_flags |= SA_RESTART;
#endif

    struct sigaction oldact;
    sigaction( SIGCHLD, &act, &oldact );


    // set up the paths used to look for plugins
    QStringList searchPaths = getSearchPaths();
    QStringList mimeInfoList;

    infoConfig = new KConfig( KGlobal::dirs()->saveLocation("data", "nsplugins") +
                              "/pluginsinfo" );
    infoConfig->group("<default>").writeEntry( "number", 0 );

    // open the cache file for the mime information
    QString cacheName = KGlobal::dirs()->saveLocation("data", "nsplugins")+"/cache";
    kDebug(1433) << "Creating MIME cache file " << cacheName;
    QFile cachef(cacheName);
    if (!cachef.open(QIODevice::WriteOnly))
        return -1;
    QTextStream cache(&cachef);
    if (showProgress) {
      printf("20\n"); fflush(stdout);
    }

    // read in the plugins mime information
    kDebug(1433) << "Scanning directories" << searchPaths;
    int count = searchPaths.count();
    int i = 0;
    for ( QStringList::const_iterator it = searchPaths.constBegin();
          it != searchPaths.constEnd(); ++it, ++i)
    {
        if ((*it).isEmpty())
            continue;
        scanDirectory( *it, mimeInfoList, cache );
        if (showProgress) {
          printf("%d\n", 25 + (50*i) / count ); fflush(stdout);
        }
    }

    if (showProgress) {
      printf("75\n"); fflush(stdout);
    }

    // We're done with forking,
    // KProcess needs SIGCHLD to be reset to what it was initially
    sigaction( SIGCHLD, &oldact, 0 );

    // delete old mime types
    kDebug(1433) << "Removing old mimetypes";
    const QStringList oldMimes = deletePluginMimeTypes();
    bool mimeTypesChanged = !oldMimes.isEmpty();

    if (showProgress) {
      printf("80\n");  fflush(stdout);
    }

    // write mimetype files
    kDebug(1433) << "Creating MIME type descriptions";
    QStringList mimeTypes;
    for ( QStringList::const_iterator it=mimeInfoList.constBegin();
          it!=mimeInfoList.constEnd(); ++it) {

      kDebug(1433) << "Handling MIME type " << *it;

      QStringList info = (*it).split(':', QString::KeepEmptyParts);
      if ( info.count()==4 ) {
          QString pluginName = info[0];
          QString type = info[1].toLower();
          QString extension = info[2];
          QString desc = info[3];

          // append to global mime type list
          if ( !mimeTypes.contains(type) ) {
              kDebug(1433) << " - mimeType=" << type;
              mimeTypes.append( type );

              // write or update mime type file, if
              // 1) it doesn't exist in ksycoca (meaning we never heard of it)
              // 2) or we just deleted it [it's still in ksycoca though]
              // This prevents noticing that a shared-mime-info upgrade brought
              // us a mimetype we needed; but doing this right requires launching
              // kbuildsycoca4 after removing mimetypes above, and that's really slow
              bool mustWriteMimeType = KMimeType::mimeType(type).isNull();
              if (!mustWriteMimeType)
                  mustWriteMimeType = oldMimes.contains(type);
              if ( mustWriteMimeType ) {
                  kDebug(1433) << " - creating MIME type description";
                  removeExistingExtensions( extension );
                  generateMimeType( type, extension, pluginName, desc );
                  mimeTypesChanged = true;
              } else {
                  kDebug(1433) << " - already exists";
              }
          }
        }
    }

    // done with new mimetypes, run update-mime-database
    if (mimeTypesChanged) {
        MimeTypeWriter::runUpdateMimeDatabase();
        // note that we'll run kbuildsycoca below anyway
    }

    if (showProgress) {
      printf("85\n"); fflush(stdout);
    }

    // close files
    kDebug(1433) << "Closing cache file";
    cachef.close();

    infoConfig->sync();
    delete infoConfig;

    // write plugin lib service file
    writeServicesFile( mimeTypes );
    if (showProgress) {
      printf("90\n"); fflush(stdout);
    }

    if (QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kded")) {
        // Tell kded to update sycoca database.
        QDBusInterface kbuildsycoca("org.kde.kded", "/kbuildsycoca",
                                    "org.kde.kded");
        kbuildsycoca.call("recreate");
    } else {
        // kded not running? fallback to calling kbuildsycoca directly:
        KProcess proc;
        proc << KStandardDirs::findExe(KBUILDSYCOCA_EXENAME);
        proc.setOutputChannelMode(KProcess::MergedChannels); // silence kbuildsycoca output
        proc.execute();
    }
}
Example #17
0
int main( int argc, char *argv[] )
{
  KAboutData aboutData( "ksystraycmd", 0, ki18n( "KSysTrayCmd" ),
			"KSysTrayCmd 0.1",
			ki18n( "Allows any application to be kept in the system tray" ),
			KAboutData::License_GPL,
			ki18n("(C) 2001-2002 Richard Moore ([email protected])") );
  aboutData.addAuthor( ki18n("Richard Moore"), KLocalizedString(), "*****@*****.**" );

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

  KCmdLineOptions options;
  options.add("!+command", ki18n("Command to execute"));
  // "!" means: all options after command are treated as arguments to the command
  options.add("window <regexp>", ki18n("A regular expression matching the window title\n"
                  "If you do not specify one, then the very first window\n"
				 "to appear will be taken - not recommended."));
  options.add("wid <int>", ki18n("The window id of the target window\n"
                  "Specifies the id of the window to use. If the id starts with 0x\n"
			   "it is assumed to be in hex."));
  options.add("hidden", ki18n( "Hide the window to the tray on startup" ));
  options.add("startonshow", ki18n( "Wait until we are told to show the window before\n"
			      "executing the command" ));
  options.add("tooltip <text>", ki18n( "Sets the initial tooltip for the tray icon" ));
  options.add("keeprunning", ki18n( "Keep the tray icon even if the client exits. This option\n"
			 "has no effect unless startonshow is specified." ));
  options.add("ownicon", ki18n( "Use ksystraycmd's icon instead of the window's icon in the systray\n"
             "(should be used with --icon to specify ksystraycmd icon)" ));
  options.add("ontop", ki18n( "Try to keep the window above other windows"));
  options.add("quitonhide", ki18n( "Quit the client when we are told to hide the window.\n"
             "This has no effect unless startonshow is specified and implies keeprunning." ));
  /*options.add("menuitem <item>", ki18n( "Adds a custom entry to the tray icon menu\n"
      "The item should have the form text:command." ));*/
  KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.

  KApplication app;

  //
  // Setup the tray icon from the arguments.
  //
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  KSysTrayCmd cmd;

  // Read the window id
  QString wid = args->getOption( "wid" );
  if ( !wid.isEmpty() ) {
      int base = 10;
      if ( wid.startsWith( "0x" ) ) {
	  base = 16;
	  wid = wid.right( wid.length() - 2 );
      }

      bool ok=true;
      ulong w = wid.toULong( &ok, base );
      if ( ok )
	  cmd.setTargetWindow( w );
      else {
	  kWarning() << "KSysTrayCmd: Got bad win id" ;
      }
  }

  // Read window title regexp
  QString title = args->getOption( "window" );
  if ( !title.isEmpty() )
      cmd.setPattern( title );

  if ( title.isEmpty() && wid.isEmpty() && (args->count() == 0) )
    KCmdLineArgs::usageError(i18n("No command or window specified"));

  // Read the command
  QString command;
  for ( int i = 0; i < args->count(); i++ )
    command += KShell::quoteArg(args->arg(i)) + ' ';
  if ( !command.isEmpty() )
      cmd.setCommand( command );

  // Tooltip
  QString tip = args->getOption( "tooltip" );
  if ( !tip.isEmpty() )
    cmd.setDefaultTip( tip );

  // Apply icon and tooltip
  cmd.refresh();

  // Keep running flag
  if ( args->isSet( "keeprunning" )  )
    cmd.setNoQuit( true );

  if ( args->isSet( "quitonhide" ) ) {
    cmd.setNoQuit( true );
    cmd.setQuitOnHide( true );
  }

  // Start hidden
  if ( args->isSet( "hidden" ) )
    cmd.hideWindow();

  // On top
  if ( args->isSet( "ontop" ) )
    cmd.setOnTop(true);

  // Use ksystraycmd icon
  if ( args->isSet( "ownicon" ) )
    cmd.setOwnIcon(true);

  // Lazy invocation flag
  if ( args->isSet( "startonshow" ) ) {
    cmd.setStartOnShow( true );
    cmd.show();
  }
  else {
    if ( !cmd.start() )
      return 1;
  }

  fcntl(ConnectionNumber(QX11Info::display()), F_SETFD, 1);
  args->clear();

  return app.exec();
}
Example #18
0
bool KoApplication::start()
{
    ResetStarting resetStarting; // reset m_starting to false when we're done
    Q_UNUSED(resetStarting);

    // Find the *.desktop file corresponding to the kapp instance name
    KoDocumentEntry entry = KoDocumentEntry(KoDocument::readNativeService());
    if (entry.isEmpty()) {
        kError(30003) << KGlobal::mainComponent().componentName() << "part.desktop not found." << endl;
        kError(30003) << "Run 'kde4-config --path services' to see which directories were searched, assuming kde startup had the same environment as your current shell." << endl;
        kError(30003) << "Check your installation (did you install KOffice in a different prefix than KDE, without adding the prefix to /etc/kderc ?)" << endl;
        return false;
    }

    // Get the command line arguments which we have to parse
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    int argsCount = args->count();

    KCmdLineArgs *koargs = KCmdLineArgs::parsedArgs("koffice");
    QString dpiValues = koargs->getOption("dpi");
    if (!dpiValues.isEmpty()) {
        int sep = dpiValues.indexOf(QRegExp("[x, ]"));
        int dpiX;
        int dpiY = 0;
        bool ok = true;
        if (sep != -1) {
            dpiY = dpiValues.mid(sep + 1).toInt(&ok);
            dpiValues.truncate(sep);
        }
        if (ok) {
            dpiX = dpiValues.toInt(&ok);
            if (ok) {
                if (!dpiY) dpiY = dpiX;
                KoGlobal::setDPI(dpiX, dpiY);
            }
        }
    }

    // No argument -> create an empty document
    if (!argsCount) {
        QString errorMsg;
        KoDocument* doc = entry.createDoc(&errorMsg);
        if (!doc) {
            if (!errorMsg.isEmpty())
                KMessageBox::error(0, errorMsg);
            return false;
        }
        KoMainWindow *shell = new KoMainWindow(doc->componentData());
        shell->show();
        QObject::connect(doc, SIGNAL(sigProgress(int)), shell, SLOT(slotProgress(int)));
        // for initDoc to fill in the recent docs list
        // and for KoDocument::slotStarted
        doc->addShell(shell);

        if (doc->checkAutoSaveFile()) {
            shell->setRootDocument(doc);
        } else {
            doc->showStartUpWidget(shell);
        }

        // FIXME This needs to be moved someplace else
        QObject::disconnect(doc, SIGNAL(sigProgress(int)), shell, SLOT(slotProgress(int)));
    } else {
        const bool print = koargs->isSet("print");
        const bool exportAsPdf = koargs->isSet("export-pdf");
        QString pdfFileName = koargs->getOption("export-filename");
        const bool doTemplate = koargs->isSet("template");
        koargs->clear();

        // Loop through arguments

        short int n = 0; // number of documents open
        short int nPrinted = 0;
        for (int i = 0; i < argsCount; i++) {
            // For now create an empty document
            QString errorMsg;
            KoDocument* doc = entry.createDoc(&errorMsg, 0);
            if (doc) {
                // show a shell asap
                KoMainWindow *shell = new KoMainWindow(doc->componentData());
                shell->show();
                // are we just trying to open a template?
                if (doTemplate) {
                    QStringList paths;
                    if (args->url(i).isLocalFile() && QFile::exists(args->url(i).toLocalFile())) {
                        paths << QString(args->url(i).toLocalFile());
                        kDebug(30003) << "using full path...";
                    } else {
                        QString desktopName(args->arg(i));
                        QString appName = KGlobal::mainComponent().componentName();

                        paths = KGlobal::dirs()->findAllResources("data", appName + "/templates/*/" + desktopName);
                        if (paths.isEmpty()) {
                            paths = KGlobal::dirs()->findAllResources("data", appName + "/templates/" + desktopName);
                        }
                        if (paths.isEmpty()) {
                            KMessageBox::error(0L, i18n("No template found for: %1 ", desktopName));
                            delete shell;
                        } else if (paths.count() > 1) {
                            KMessageBox::error(0L,  i18n("Too many templates found for: %1", desktopName));
                            delete shell;
                        }
                    }

                    if (!paths.isEmpty()) {
                        KUrl templateBase;
                        templateBase.setPath(paths[0]);
                        KDesktopFile templateInfo(paths[0]);

                        QString templateName = templateInfo.readUrl();
                        KUrl templateURL;
                        templateURL.setPath(templateBase.directory() + '/' + templateName);
                        if (shell->openDocument(doc, templateURL)) {
                            doc->resetURL();
                            doc->setEmpty();
                            doc->setTitleModified();
                            kDebug(30003) << "Template loaded...";
                            n++;
                        } else {
                            KMessageBox::error(0L, i18n("Template %1 failed to load.", templateURL.prettyUrl()));
                            delete shell;
                        }
                    }
                    // now try to load
                }
                else if (shell->openDocument(doc, args->url(i))) {
                    if (print) {
                        shell->slotFilePrint();
                        // delete shell; done by ~KoDocument
                        nPrinted++;
                    } else if (exportAsPdf) {
                        KoPrintJob *job = shell->exportToPdf(pdfFileName);
                        if (job)
                            connect (job, SIGNAL(destroyed(QObject*)), shell,
                                    SLOT(slotFileQuit()), Qt::QueuedConnection);
                        nPrinted++;
                    } else {
                        // Normal case, success
                        n++;
                    }
                } else {
                    // .... if failed
                    // delete doc; done by openDocument
                    // delete shell; done by ~KoDocument
                }
            }
        }
        if (print || exportAsPdf)
            return nPrinted > 0;
        if (n == 0) // no doc, e.g. all URLs were malformed
            return false;
    }

    args->clear();
    // not calling this before since the program will quit there.
    return true;
}
Example #19
0
int main(int argc, char** argv)
{
    int minargs = 2;
    bool gui = false;
    /* if (argc < minargs) {
        usage();
        RETURN(0);
      }*/
    QFileInfo info = QFileInfo(argv[0]);
    prgname = info.baseName().toLatin1();

    KAboutData aboutData(prgname, 0, ki18n("KexiDBTest"),
                         KEXI_VERSION_STRING, KLocalizedString(), KAboutData::License_GPL,
                         ki18n("(c) 2003-2010, Kexi Team\n"
                               "(c) 2003-2006, OpenOffice Software.\n"),
                         KLocalizedString(),
                         "http://www.calligra.org/kexi",
                         "*****@*****.**");
    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("test <test_name>", ki18n("Available tests:\n"
                                          "- cursors: test for cursors behaviour\n"
                                          "- schema: test for db schema retrieving\n"
                                          "- dbcreation: test for new db creation\n"
                                          "- tables: test for tables creation and data\n"
                                          "   inserting\n"
#ifndef NO_GUI
                                          "- tableview: test for KexiDataTableView data-aware\n"
                                          "   widget\n"
#endif
                                          "- parser: test for parsing sql statements,\n"
                                          "   returns debug string for a given\n"
                                          "   sql statement or error message\n"
                                          "- dr_prop: shows properties of selected driver"));
    options.add("buffered-cursors", ki18n("Optional switch: turns cursors used in any tests\n"
                                          " to be buffered"));
    options.add("query-params <params>", ki18n("Query parameters separated\n"
                "by '|' character that will be passed to query\n"
                "statement to replace [...] placeholders."));
    options.add("", ki18n(" Notes:\n"
                          "1. 'dr_prop' requires <db_name> argument.\n"
                          "2. 'parser' test requires <db_name>,\n"
                          " <driver_name> and <sql_statement> arguments\n"
                          "3. All other tests require <db_name>\n"
                          " and <driver_name> arguments.\n"
                          "4. 'tables' test automatically runs 'dbcreation'\n"
                          " test. (<new_db_name> is removed if already exists).\n"
                          "5. <db_name> must be a valid kexi database\n"
                          " e.g. created with 'tables' test."));
    options.add("+driver_name", ki18n("Driver name"));
    options.add("+[db_name]", ki18n("Database name"));
    options.add("+[sql_statement]", ki18n("Optional SQL statement (for parser test)"));
    KCmdLineArgs::addCmdLineOptions(options);

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    QStringList tests;
    tests << "cursors" << "schema" << "dbcreation" << "tables"
    << "tableview" << "parser" << "dr_prop";
    if (!args->isSet("test")) {
        kDebug() << "No test specified. Use --help.";
        RETURN(1);
    }
    test_name = args->getOption("test");
    if (!tests.contains(test_name)) {
        kDebug() << QString("No such test \"%1\". Use --help.").arg(test_name);
        RETURN(1);
    }

    if (test_name == "tableview") {
        gui = true;
    } else if (test_name == "parser") {
        minargs = 3;
    } else if (test_name == "dr_prop") {
        minargs = 1;
        db_name_required = false;
    }
    if ((int)args->count() < minargs) {
        kDebug() << QString("Not enough args (%1 required). Use --help.").arg(minargs);
        RETURN(1);
    }

    if (gui) {
        app = new QApplication(true);
        app->setWindowIcon(koIcon("table"));
        instance = new KComponentData(KGlobal::mainComponent());
        KIconLoader::global()->addAppDir("kexi");
    } else {
        instance = new KComponentData(prgname);
    }

    drv_name = args->arg(0);

    KexiDB::DriverManager manager;
    QStringList names = manager.driverNames();
    kDebug() << "DRIVERS: ";
    for (QStringList::ConstIterator it = names.constBegin(); it != names.constEnd() ; ++it)
        kDebug() << *it;
    if (manager.error() || names.isEmpty()) {
        manager.debugError();
        RETURN(1);
    }

    //get driver
    const KexiDB::Driver::Info drv_info = manager.driverInfo(drv_name);
    driver = manager.driver(drv_name);
    if (drv_info.name.isEmpty() || manager.error()) {
        manager.debugError();
        RETURN(1);
    }
    kDebug() << "MIME type for '" << drv_info.name << "': " << drv_info.fileDBMimeType;

    //open connection
    if (args->count() >= 2)
        db_name = args->arg(1);

    if (db_name_required && db_name.isEmpty()) {
        kDebug() << prgname << ": database name?";
        RETURN(1);
    }
    if (!db_name.isEmpty()) {
        //additional switches:
        if (args->isSet("buffered-cursors")) {
            cursor_options |= KexiDB::Cursor::Buffered;
        }
        KexiProjectData project_data;
        project_data.setDatabaseName(db_name);
        if (drv_info.fileBased) {
            project_data.connectionData()->setFileName(db_name);
        }
        project_data.connectionData()->driverName = drv_name;
        project = new KexiProject(project_data);
        bool incompatibleWithKexi = false;
        tristate res;
        if (test_name == "dbcreation" || test_name == "tables")
            res = project->create(true /*force overwrite*/);
        else
            res = project->open(incompatibleWithKexi);
        if (res != true) {
            if (incompatibleWithKexi)
                kDebug() << "incompatibleWithKexi";
            project->debugError();
            RETURN(1);
        }
        conn = project->dbConnection();
/*        conn = driver->createConnection(conn_data);
        if (!conn || driver->error()) {
            driver->debugError();
            RETURN(1);
        }
        if (!conn->connect()) {
            conn->debugError();
            RETURN(1);
        }*/
    }

    //start test:
    int r = 0;
    if (test_name == "cursors")
        r = cursorsTest();
    else if (test_name == "schema")
        r = schemaTest();
    else if (test_name == "dbcreation")
        r = dbCreationTest();
    else if (test_name == "tables")
        r = tablesTest();
#ifndef NO_GUI
    else if (test_name == "tableview")
        r = tableViewTest();
#endif
    else if (test_name == "parser") {
        QStringList params;
        if (args->isSet("query-params"))
            params = args->getOption("query-params").split('|');
        r = parserTest(QString(args->arg(2)), params);
    } else if (test_name == "dr_prop")
        r = drPropTest();
    else {
        kWarning() << "No such test: " << test_name;
//  usage();
        RETURN(1);
    }

    if (app && r == 0)
        app->exec();

    if (r)
        kDebug() << "RECENT SQL STATEMENT: " << conn->recentSQLString();

    if (project) {
        if (!project->closeConnection())
            r = 1;
        delete project;
    }
//    if (conn && !conn->disconnect())
//        r = 1;

// kDebug() << "!!! KexiDB::Transaction::globalcount == " << KexiDB::Transaction::globalCount();
// kDebug() << "!!! KexiDB::TransactionData::globalcount == " << KexiDB::TransactionData::globalCount();

    delete app;

    RETURN(r);
}
Example #20
0
int main(int argc, char **argv)
{
    KAboutData about("kwinstartmenu", 0, ki18n("kwinstartmenu"), "1.4",
                     ki18n("An application to create/update or remove Windows Start Menu entries"),
                     KAboutData::License_GPL,
                     ki18n("(C) 2008-2011 Ralf Habacker"));
    KCmdLineArgs::init( argc, argv, &about);

    KCmdLineOptions options;
    options.add("remove",     ki18n("remove installed start menu entries"));
    options.add("install",    ki18n("install start menu entries"));
    options.add("update",     ki18n("update start menu entries"));
    options.add("cleanup",    ki18n("remove start menu entries from unused kde installation"));

    options.add("query-path", ki18n("query root path of start menu entries"));

    options.add("enable-categories", ki18n("use categories for start menu entries (default)"));
    options.add("disable-categories", ki18n("don't use categories for start menu entries"));
    options.add("categories", ki18n("query current value of categories in start menu"));
    
    options.add("set-custom-string <argument>", ki18n("set custom string for root start menu entry"));
    // @TODO unset-custom-string is required because args->isSet("set-root-custom-string") do not
    // detect --set-custom-string ""  as present set-root-custom-string option and
    options.add("unset-custom-string", ki18n("remove custom string from root start menu entry"));
    options.add("custom-string", ki18n("query current value of root start menu entry custom string"));

    options.add("set-name-string <argument>", ki18n("set custom name string for root start menu entry"));
    options.add("unset-name-string", ki18n("remove custom name string from root start menu entry"));
    options.add("name-string", ki18n("query current value of start menu entry custom name string"));

    options.add("set-version-string <argument>", ki18n("set custom version string for root start menu entry"));
    options.add("unset-version-string", ki18n("remove custom version string from root start menu entry"));
    options.add("version-string", ki18n("query current value of root start menu entry version string"));
    KCmdLineArgs::addCmdLineOptions( options ); // Add my own options.

    KComponentData a(&about);

    // Get application specific arguments
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    KApplication app(false);

    // override global settings from command line 
    if (args->isSet("categories"))
        fprintf(stdout,"%s",settings.useCategories() ? "on" : "off");
    else if (args->isSet("enable-categories"))
    {
        settings.setUseCategories(true);
    }
    else if (args->isSet("disable-categories"))
    {
        settings.setUseCategories(false);
    }

    if (args->isSet("custom-string"))
        fprintf(stdout,"%s",qPrintable(settings.customString()));
    else if (args->isSet("unset-custom-string"))
    {
        settings.setCustomString("");
    }
    else if (args->isSet("set-custom-string"))
    {
        settings.setCustomString(args->getOption("set-custom-string"));
    }

    if (args->isSet("name-string"))
        fprintf(stdout,"%s",qPrintable(settings.nameString()));
    else if (args->isSet("unset-name-string"))
    {
        settings.setNameString("");
    }
    else if (args->isSet("set-name-string"))
    {
        settings.setNameString(args->getOption("set-name-string"));
    }

    if (args->isSet("version-string"))
        fprintf(stdout,"%s",qPrintable(settings.versionString()));
    else if (args->isSet("unset-version-string"))
    {
        settings.setVersionString("");
    }
    else if (args->isSet("set-version-string"))
    {
        settings.setVersionString(args->getOption("set-version-string"));
    }

    // determine initial values on fresh install or remove
    if (settings.nameString().isEmpty() && settings.versionString().isEmpty() &&  settings.customString().isEmpty())
    {
        if (args->isSet("install"))
        {
            QString version = KDE::versionString();
            QStringList versions = version.split(' ');
            settings.setVersionString(versions[0]);
            settings.setNameString("KDE");
            kWarning() << "no name, version or custom string set, using default values for install" << settings.nameString() << settings.versionString();
        }
        else if (args->isSet("remove") || args->isSet("update"))
        {
            kError() << "cannot remove/update start menu entries: no name, version or custom string set";
            return 1;
        }
    }
    /**
      @TODO how to solve the case if any --set-... option is used and the start menu entries are not removed before
      should we remove them before, to have a clean state or better something else ?
    */
    if (args->isSet("query-path"))
        fprintf(stdout,"%s",qPrintable(QDir::toNativeSeparators(getKDEStartMenuPath())));
    else if (args->isSet("remove"))
        removeStartMenuLinks();
    else if (args->isSet("update"))
        updateStartMenuLinks();
    else if (args->isSet("install"))
        updateStartMenuLinks();
    else if (args->isSet("cleanup"))
        cleanupStartMenuLinks();

    return 0;
}
Example #21
0
int kScreenSaverMain( int argc, char** argv, KScreenSaverInterface& screenSaverInterface )
{
    KLocale::setMainCatalog("libkscreensaver");
    KCmdLineArgs::init(argc, argv, screenSaverInterface.aboutData());


    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"));

    options.add("demo", ki18n("Start screen saver in demo mode"), "default");

    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    // Set a useful default icon.
    app.setWindowIcon(KIcon("preferences-desktop-screensaver"));

    // Disable session management so screensaver windows don't get restored on login (bug#314859)
    app.disableSessionManagement();


    if (!pipe(termPipe))
    {
        struct sigaction sa;
        sa.sa_handler = termHandler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        sigaction(SIGTERM, &sa, 0);
        QSocketNotifier *sn = new QSocketNotifier(termPipe[0], QSocketNotifier::Read, &app);
        QObject::connect(sn, SIGNAL(activated(int)), &app, SLOT(quit()));
    }

#ifdef Q_WS_X11
    oldXErrorHandler = XSetErrorHandler(xErrorHandler);
#endif
    KCrash::setCrashHandler( crashHandler );
    KGlobal::locale()->insertCatalog("klock");
    KGlobal::locale()->insertCatalog("kscreensaver");

    DemoWindow *demoWidget = 0;
    Window saveWin = 0;
    KScreenSaver *target;

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    if (args->isSet("setup"))
    {
       QDialog *dlg = screenSaverInterface.setup();
       args->clear();
       dlg->exec();
       delete dlg;
       return 0;
    }

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

#ifdef Q_WS_X11 //FIXME
    if (args->isSet("root"))
    {
        QX11Info inf;
        saveWin = RootWindow(QX11Info::display(), inf.screen());
    }
#endif

    if (args->isSet("demo"))
    {
        saveWin = 0;
    }

    if (saveWin == 0)
    {
        demoWidget = new DemoWindow();
        demoWidget->setAttribute(Qt::WA_NoSystemBackground);
        demoWidget->setAttribute(Qt::WA_PaintOnScreen);
        demoWidget->show();
        app.processEvents();
        saveWin = demoWidget->winId();
    }

    target = screenSaverInterface.create( saveWin );
    target->setAttribute(Qt::WA_PaintOnScreen);
    target->show();

    if (demoWidget)
    {
        target->installEventFilter( demoWidget );
    }

    args->clear();
    app.exec();

    delete target;
    delete demoWidget;

    return 0;
}
Example #22
0
KuickShow::KuickShow( const char *name )
    : KMainWindow( 0L, name ),
      m_slideshowCycle( 1 ),
      fileWidget( 0L ),
      dialog( 0L ),
      id( 0L ),
      m_viewer( 0L ),
      oneWindowAction( 0L ),
      m_accel( 0L ),
      m_delayedRepeatItem( 0L ),
      m_slideShowStopped(false)
{
    aboutWidget = 0L;
    kdata = new KuickData;
    kdata->load();

    initImlib();
    resize( 400, 500 );

    m_slideTimer = new QTimer( this );
    connect( m_slideTimer, SIGNAL( timeout() ), SLOT( nextSlide() ));


    KConfig *kc = KGlobal::config();

    bool isDir = false; // true if we get a directory on the commandline

    // parse commandline options
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    // files to display
    // either a directory to display, an absolute path, a relative path, or a URL
    KURL startDir;
    startDir.setPath( QDir::currentDirPath() + '/' );

    int numArgs = args->count();
    if ( numArgs >= 10 )
    {
        // Even though the 1st i18n string will never be used, it needs to exist for plural handling - mhunter
        if ( KMessageBox::warningYesNo(
                 this,
                 i18n("Do you really want to display this 1 image at the same time? This might be quite resource intensive and could overload your computer.<br>If you choose %1, only the first image will be shown.", 
                      "Do you really want to display these %n images at the same time? This might be quite resource intensive and could overload your computer.<br>If you choose %1, only the first image will be shown.", numArgs).arg(KStdGuiItem::no().plainText()),
                 i18n("Display Multiple Images?"))
             != KMessageBox::Yes )
        {
            numArgs = 1;
        }
    }

    for ( int i = 0; i < numArgs; i++ ) {
        KURL url = args->url( i );
        KFileItem item( KFileItem::Unknown, KFileItem::Unknown, url, false );

        // for remote URLs, we don't know if it's a file or directory, but
        // FileWidget::isImage() should correct in most cases.
        // For non-local non-images, we just assume directory.

        if ( FileWidget::isImage( &item ) )
        {
            showImage( &item, true, false, true ); // show in new window, not fullscreen-forced and move to 0,0
//    showImage( &item, true, false, false ); // show in new window, not fullscreen-forced and not moving to 0,0
        }
        else if ( item.isDir() )
        {
            startDir = url;
            isDir = true;
        }

        // need to check remote files
        else if ( !url.isLocalFile() )
        {
            KMimeType::Ptr mime = KMimeType::findByURL( url );
            QString name = mime->name();
            if ( name == "application/octet-stream" ) // unknown -> stat()
                name = KIO::NetAccess::mimetype( url, this );

	    // text/* is a hack for bugs.kde.org-attached-images urls.
	    // The real problem here is that NetAccess::mimetype does a HTTP HEAD, which doesn't
	    // always return the right mimetype. The rest of KDE start a get() instead....
            if ( name.startsWith( "image/" ) || name.startsWith( "text/" ) )
            {
                FileWidget::setImage( item, true );
                showImage( &item, true, false, true );
            }
            else // assume directory, KDirLister will tell us if we can't list
            {
                startDir = url;
                isDir = true;
            }
        }
        // else // we don't handle local non-images
    }

    if ( (kdata->startInLastDir && args->count() == 0) || args->isSet( "lastfolder" )) {
        kc->setGroup( "SessionSettings");
        startDir = kc->readPathEntry( "CurrentDirectory", startDir.url() );
    }

    if ( s_viewers.isEmpty() || isDir ) {
        initGUI( startDir );
	if (!kapp->isRestored()) // during session management, readProperties() will show()
            show();
    }

    else { // don't show browser, when image on commandline
        hide();
        KStartupInfo::appStarted();
    }
}
Example #23
0
int main(int argc, char *argv[])
{
    _argc = argc;
    _argv = argv;

    QApplication::setColorSpec( QApplication::ManyColor );

    KAboutData aboutData(PACKAGE,
                         I18N_NOOP("SIM"),
                         VERSION,
                         I18N_NOOP("ICQ client"),
                         KAboutData::License_GPL,
                         "Copyright (C) 2002, Vladimir Shutoff",
                         0,
                         "http://sim-icq.sourceforge.net/",
                         "*****@*****.**");

    aboutData.addAuthor("Vladimir Shutoff",I18N_NOOP("Maintainer"),"*****@*****.**");
    appAboutData = &aboutData;

#ifdef USE_KDE
    KCmdLineArgs::init( argc, argv, &aboutData );
    KCmdLineOptions options[] =
        {
            { "b <dir>", i18n("Directory for files"), 0 },
            { "d <loglevel>", i18n("Loglevel"), 0 },
            { 0, 0, 0 }
        };
    KCmdLineArgs::addCmdLineOptions( options );
    KUniqueApplication::addCmdLineOptions();

    if (!KUniqueApplication::start())
        exit(-1);
    SimApp app;
    kApp = &app;
#else
    SimApp app(argc, argv);
#endif
    pSplash = new Splash;
    initIcons("");
    pMain = new MainWindow;
#ifdef USE_KDE
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->isSet("b"))
        pMain->homeDir = strdup(args->getOption("b"));
    if (args->isSet("d"))
        log_level = atoi(args->getOption("d"));

#else
    for (int i = 0; i < argc; i++){
        if (!strcmp(argv[i], "-b") && argv[i+1])
            pMain->homeDir = argv[++i];
        if (!strcmp(argv[i], "-d") && argv[i+1])
            log_level = atoi(argv[++i]);
    }
#endif
    if (!pMain->init())
        return 0;
    app.setMainWidget(pMain);
    pSplash->hide();

    return app.exec();
}
Example #24
0
void KrashConfig :: readConfig()
{
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  m_signalnum = args->getOption( "signal" ).toInt();
  m_pid = args->getOption( "pid" ).toInt();
  m_startedByKdeinit = args->isSet("kdeinit");
  m_safeMode = args->isSet("safer");
  m_execname = args->getOption( "appname" );
  if ( !args->getOption( "apppath" ).isEmpty() )
    m_execname.prepend( args->getOption( "apppath" ) + '/' );

  QCString programname = args->getOption("programname");
  if (programname.isEmpty())
    programname.setStr(I18N_NOOP("unknown"));
  // leak some memory... Well. It's only done once anyway :-)
  const char * progname = qstrdup(programname);
  m_aboutData = new KAboutData(args->getOption("appname"),
                               progname,
                               args->getOption("appversion"),
                               0, 0, 0, 0, 0,
                               args->getOption("bugaddress"));

  QCString startup_id( args->getOption( "startupid" ));
  if (!startup_id.isEmpty())
  { // stop startup notification
    KStartupInfoId id;
    id.initId( startup_id );
    KStartupInfo::sendFinish( id );
  }

  KConfig *config = KGlobal::config();
  config->setGroup("drkonqi");

  // maybe we should check if it's relative?
  QString configname = config->readEntry("ConfigName",
                                         QString::fromLatin1("enduser"));

  QString debuggername = config->readEntry("Debugger",
                                           QString::fromLatin1("gdb"));

  KConfig debuggers(QString::fromLatin1("debuggers/%1rc").arg(debuggername),
                    true, false, "appdata");

  debuggers.setGroup("General");
  m_debugger = debuggers.readPathEntry("Exec");
  m_debuggerBatch = debuggers.readPathEntry("ExecBatch");
  m_tryExec = debuggers.readPathEntry("TryExec");
  m_backtraceCommand = debuggers.readEntry("BacktraceCommand");
  m_removeFromBacktraceRegExp = debuggers.readEntry("RemoveFromBacktraceRegExp");
  m_invalidStackFrameRegExp = debuggers.readEntry("InvalidStackFrameRegExp");
  m_frameRegExp = debuggers.readEntry("FrameRegExp");
  m_neededInValidBacktraceRegExp = debuggers.readEntry("NeededInValidBacktraceRegExp");
  m_kcrashRegExp = debuggers.readEntry("KCrashRegExp");

  KConfig preset(QString::fromLatin1("presets/%1rc").arg(configname),
                 true, false, "appdata");

  preset.setGroup("ErrorDescription");
  if (preset.readBoolEntry("Enable"), true)
    m_errorDescriptionText = preset.readEntry("Name");

  preset.setGroup("WhatToDoHint");
  if (preset.readBoolEntry("Enable"))
    m_whatToDoText = preset.readEntry("Name");

  preset.setGroup("General");
  m_showbugreport = preset.readBoolEntry("ShowBugReportButton", false);
  m_showdebugger = m_showbacktrace = m_pid != 0;
  if (m_showbacktrace)
  {
    m_showbacktrace = preset.readBoolEntry("ShowBacktraceButton", true);
    m_showdebugger = preset.readBoolEntry("ShowDebugButton", true);
  }
  m_disablechecks = preset.readBoolEntry("DisableChecks", false);

  bool b = preset.readBoolEntry("SignalDetails", true);

  QString str = QString::number(m_signalnum);
  // use group unknown if signal not found
  if (!preset.hasGroup(str))
    str = QString::fromLatin1("unknown");
  preset.setGroup(str);
  m_signalName = preset.readEntry("Name");
  if (b)
    m_signalText = preset.readEntry("Comment");
}
Example #25
0
int main( int argc, char **argv )
{

    qRegisterMetaType<ElementList>();

    options.add("convert-sqlite3", ki18n("Convert the current SQLite 2.x database to SQLite 3 and exit") , 0 );
    options.add( 0, KLocalizedString(), 0 );


    KAboutData about( "krecipes", 0, ki18n( "Krecipes" ), version, ki18n( "The KDE Cookbook" ), KAboutData::License_GPL, ki18n( "(C) 2003 Unai Garro\n(C) 2004-2006 Jason Kivlighn"), ki18n("This product is RecipeML compatible.\nYou can get more information about this file format in:\nhttp://www.formatdata.com/recipeml" ), "http://krecipes.sourceforge.net/" );
    about.addAuthor( ki18n("Unai Garro"), KLocalizedString(), "*****@*****.**", 0 );
    about.addAuthor( ki18n("Jason Kivlighn"), KLocalizedString(), "*****@*****.**", 0 );
    about.addAuthor( ki18n("Cyril Bosselut"), KLocalizedString(), "*****@*****.**", "http://b1project.com" );

    about.addCredit( ki18n("Colleen Beamer"), ki18n("Testing, bug reports, suggestions"), "*****@*****.**", 0 );
    about.addCredit( ki18n("Robert Wadley"), ki18n("Icons and artwork"), "*****@*****.**", 0 );
    about.addAuthor( ki18n("Daniel Sauvé"), ki18n("Porting to KDE4"), "*****@*****.**", "http://metres.homelinux.com" );

    about.addAuthor( ki18n("Laurent Montel"), ki18n("Porting to KDE4"), "*****@*****.**", 0 );
    about.addAuthor( ki18n("José Manuel Santamaría Lema"), ki18n("Porting to KDE4, current maintainer"), "*****@*****.**", 0 );
    about.addAuthor( ki18n("Martin Engelmann"), ki18n("Porting to KDE4, developer"), "*****@*****.**", 0 );

    about.addCredit( ki18n("Patrick Spendrin"), ki18n("Patches to make Krecipes work under Windows"), "*****@*****.**", 0 );
    about.addCredit( ki18n("Mike Ferguson"), ki18n("Help with bugs, patches"), "", 0 );
    about.addCredit( ki18n("Warren Severin"), ki18n("Code to export recipes to *.mx2 files"), "", 0 );

    about.addCredit( ki18n("Eduardo Robles Elvira"),
                     ki18n("He advised using WebKit to fix printing support during Akademy-es 2010."),
                     "*****@*****.**", 0 );
    about.addCredit( ki18n("José Millán Soto"),
                     ki18n("He advised using WebKit to fix printing support during Akademy-es 2010."),
                     "", 0 );

    KCmdLineArgs::init( argc, argv, &about );
    KCmdLineArgs::addCmdLineOptions( options );
    KUniqueApplication::addCmdLineOptions();

    if ( !KUniqueApplication::start() ) {
        std::cerr << "Krecipes is already running!" << std::endl;
        return 0;
    }

    KUniqueApplication app;

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

        QApplication::flush();

        if ( args->isSet("convert-sqlite3") ) {
            ConvertSQLite3 sqliteConverter;
            sqliteConverter.convert();
            return 0;
        }

        Krecipes * widget = new Krecipes;
        app.setTopWidget( widget );
        widget->show();

        args->clear();
    }

    return app.exec();
}
Example #26
0
int main( int argc, char** argv )
{
    QString calligraVersion(CALLIGRA_VERSION_STRING);
    QString version;


#ifdef CALLIGRA_GIT_SHA1_STRING
    QString gitVersion(CALLIGRA_GIT_SHA1_STRING);
    version = QString("%1 (git %2)").arg(calligraVersion).arg(gitVersion).toLatin1();
#else
    version = calligraVersion;
#endif


    KAboutData aboutData("kritagemini",
                         "krita",
                         ki18n("Krita Gemini"),
                         version.toLatin1(),
                         ki18n("Krita Gemini: Painting at Home and on the Go for Artists"),
                         KAboutData::License_GPL,
                         ki18n("(c) 1999-%1 The Krita team and KO GmbH.\n").subs(CALLIGRA_YEAR),
                         KLocalizedString(),
                         "http://www.kritastudio.com",
                         "*****@*****.**");

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

    KCmdLineOptions options;
    options.add( "+[files]", ki18n( "Images to open" ) );
    options.add( "vkb", ki18n( "Use the virtual keyboard" ) );
    options.add( "fullscreen", ki18n( "Use full-screen display" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    QStringList fileNames;
    if (args->count() > 0) {
        for (int i = 0; i < args->count(); ++i) {
            QString fileName = args->arg(i);
            if (QFile::exists(fileName)) {
                fileNames << fileName;
            }
        }
    }

    KApplication app;
    app.setApplicationName("kritagemini");
    KIconLoader::global()->addAppDir("krita");
    KIconLoader::global()->addAppDir("kritasketch");

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

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    // If there's no kdehome, set it and restart the process.
    //QMessageBox::information(0, "krita sketch", "KDEHOME: " + env.value("KDEHOME"));
    if (!env.contains("KDEHOME") ) {
        _putenv_s("KDEHOME", QDesktopServices::storageLocation(QDesktopServices::DataLocation).toLocal8Bit());
    }
    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());
    }
    if (!env.contains("KDEDIR")) {
        _putenv_s("KDEDIR", appdir.absolutePath().toLocal8Bit());
    }
    if (!env.contains("KDEDIRS")) {
        _putenv_s("KDEDIRS", appdir.absolutePath().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 Q_OS_WIN
    KisTabletSupportWin::init();
    app.setEventFilter(&KisTabletSupportWin::eventFilter);
#elif defined Q_WS_X11
    KisTabletSupportX11::init();
    app.setEventFilter(&KisTabletSupportX11::eventFilter);
#endif
	
	if (qgetenv("KDE_FULL_SESSION").isEmpty()) {
        // There are two themes that work for Krita, oxygen and plastique. Try to set plastique first, then oxygen
        qobject_cast<QApplication*>(QApplication::instance())->setStyle("Plastique");
		qobject_cast<QApplication*>(QApplication::instance())->setStyle("Oxygen");
    }

	bool showFullscreen = false;
	if (args->isSet("fullscreen")) {
        showFullscreen = true;
    }

    // then create the pixmap from an xpm: we cannot get the
    // location of our datadir before we've started our components,
    // so use an xpm.
    // If fullscreen, hide splash screen
    QPixmap pm(splash_screen_xpm);
    QSplashScreen splash(pm);
    if (!showFullscreen) {
        splash.show();
        splash.showMessage(".");
        app.processEvents();
    }

#if defined Q_WS_X11 && QT_VERSION >= 0x040800
    QApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

    MainWindow window(fileNames);

    if (args->isSet("vkb")) {
        app.setInputContext(new SketchInputContext(&app));
    }

    if (showFullscreen) {
        window.showFullScreen();
    } else {
#ifdef Q_OS_WIN
		window.showMaximized();
#else
		window.show();
#endif
	}
    splash.finish(&window);

    return app.exec();
}
Example #27
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;
}
Example #28
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    K4AboutData about("kf5-config", "kdelibs4", ki18n("kf5-config"), "1.0",
                      ki18n("A little program to output installation paths"),
                      K4AboutData::License_GPL,
                      ki18n("(C) 2000 Stephan Kulow"));
    KCmdLineArgs::init(argc, argv, &about);

    KCmdLineOptions options;
    options.add("expandvars",  ki18n("Left for legacy support"));
    options.add("prefix",      ki18n("Compiled in prefix for KDE libraries"));
    options.add("exec-prefix", ki18n("Compiled in exec_prefix for KDE libraries"));
    options.add("libsuffix",   ki18n("Compiled in library path suffix"));
    //options.add("localprefix", ki18n("Prefix in $HOME used to write files"));
    options.add("kde-version", ki18n("Compiled in version string for KDE libraries"));
    options.add("types",       ki18n("Available KDE resource types"));
    options.add("path type",       ki18n("Search path for resource type"));
    options.add("locate filename", ki18n("Find filename inside the resource type given to --path"));
    options.add("userpath type",   ki18n("User path: desktop|autostart|document"));
    options.add("install type",    ki18n("Prefix to install resource files to"));
    options.add("qt-prefix",   ki18n("Installation prefix for Qt"));
    options.add("qt-binaries", ki18n("Location of installed Qt binaries"));
    options.add("qt-libraries", ki18n("Location of installed Qt libraries"));
    options.add("qt-plugins", ki18n("Location of installed Qt plugins"));
    KCmdLineArgs::addCmdLineOptions(options);   // Add my own options.

    (void)KGlobal::dirs(); // trigger the creation
    (void)KSharedConfig::openConfig();

    // Get application specific arguments
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    if (args->isSet("prefix")) {
        printResult(QFile::decodeName(CMAKE_INSTALL_PREFIX));
        return 0;
    }

    if (args->isSet("exec-prefix")) {
        printResult(QFile::decodeName(EXEC_INSTALL_PREFIX));
        return 0;
    }

#if 0
    if (args->isSet("libsuffix")) {
        QString tmp(QFile::decodeName(KDELIBSUFF));
        tmp.remove(QLatin1Char('"'));
        printResult(tmp);
        return 0;
    }
#endif

#if 0
    if (args->isSet("localprefix")) {
        printResult(KGlobal::dirs()->localkdedir());
        return 0;
    }
#endif

    if (args->isSet("kde-version")) {
        printf("%s\n", KDE_VERSION_STRING);
        return 0;
    }

    if (args->isSet("types")) {
        QStringList types = KGlobal::dirs()->allTypes();
        types.sort();
        const char *helptexts[] = {
            "apps", I18N_NOOP("Applications menu (.desktop files)"),
            "autostart", I18N_NOOP("Autostart directories"),
            "cache", I18N_NOOP("Cached information (e.g. favicons, web-pages)"),
            "config", I18N_NOOP("Configuration files"),
            "data", I18N_NOOP("Where applications store data"),
            "emoticons", I18N_NOOP("Emoticons"),
            "exe", I18N_NOOP("Executables in $prefix/bin"),
            "html", I18N_NOOP("HTML documentation"),
            "icon", I18N_NOOP("Icons"),
            "kcfg", I18N_NOOP("Configuration description files"),
            "lib", I18N_NOOP("Libraries"),
            "include", I18N_NOOP("Includes/Headers"),
            "locale", I18N_NOOP("Translation files for KLocale"),
            "module", I18N_NOOP("Loadable modules"),
            "pixmap", I18N_NOOP("Legacy pixmaps"),
            "qtplugins", I18N_NOOP("Qt plugins"),
            "services", I18N_NOOP("Services"),
            "servicetypes", I18N_NOOP("Service types"),
            "sound", I18N_NOOP("Application sounds"),
            "templates", I18N_NOOP("Templates"),
            "wallpaper", I18N_NOOP("Wallpapers"),
            "xdgdata", I18N_NOOP("XDG Shared Data"),
            "xdgdata-apps", I18N_NOOP("XDG Application menu (.desktop files)"),
            "xdgdata-dirs", I18N_NOOP("XDG Menu descriptions (.directory files)"),
            "xdgdata-icon", I18N_NOOP("XDG Icons"),
            "xdgdata-pixmap", I18N_NOOP("Legacy pixmaps"),
            "xdgdata-mime", I18N_NOOP("XDG Mime Types"),
            "xdgconf", I18N_NOOP("XDG Configuration Files"),
            "xdgconf-menu", I18N_NOOP("XDG Menu layout (.menu files)"),
            "xdgconf-autostart", I18N_NOOP("XDG autostart directory"),
            "tmp", I18N_NOOP("Temporary files (specific for both current host and current user)"),
            "socket", I18N_NOOP("UNIX Sockets (specific for both current host and current user)"),
            0, 0
        };
        Q_FOREACH (const QString &type, types) {
            int index = 0;
            while (helptexts[index] && type != QLatin1String(helptexts[index])) {
                index += 2;
            }
            if (helptexts[index]) {
                printf("%s - %s\n", helptexts[index], i18n(helptexts[index + 1]).toLocal8Bit().constData());
            } else {
                printf("%s", i18n("%1 - unknown type\n", type).toLocal8Bit().constData());
            }
        }
Example #29
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");
	QCStringList	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 (QCStringList::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."));
	}