Ejemplo n.º 1
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;
}
int main(int argc, char **argv)
{
    KAboutData about("kftpgrabber", 0, ki18n("KFTPgrabber"), version, ki18n(description),
                     KAboutData::License_GPL, ki18n("(C) 2008, The KFTPgrabber developers"), KLocalizedString(), "http://www.kftp.org");
    about.addAuthor(ki18n("Jernej Kos"), ki18n("Lead developer"), "*****@*****.**");
    about.addAuthor(ki18n("Markus Brüffer"), ki18n("Developer"), "*****@*****.**");
    
    about.addCredit(ki18n("Lee Joseph"), ki18n("Fedora ambassador responsible for promotion, testing and debugging; also a package maintainer for Fedora-compatible distributions"), "*****@*****.**");
    about.addCredit(ki18n("libssh2 Developers"), ki18n("SSH library"), "*****@*****.**");
    about.addCredit(ki18n("Anthony D. Urso"), ki18n("otpCalc code"));
    about.addCredit(ki18n("Kopete Developers"), ki18n("KopeteBalloon popup code"), "*****@*****.**");
    about.addCredit(ki18n("KSysGuard Developers"), ki18n("Traffic graph widget"), "*****@*****.**");
    about.addCredit(ki18n("Bob Ziuchkovski"), ki18n("Icon design"), "*****@*****.**");
    about.addCredit(ki18n("Tobias Ussing"), ki18n("Testing and debugging"), "*****@*****.**");
    about.addCredit(ki18n("Tim Kosse"), ki18n("Directory parser code"), "*****@*****.**");
    about.addCredit(ki18n("Peter Penz"), ki18n("Listview column handling code"), "*****@*****.**");

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

    KCmdLineOptions options;
    options.add("+[url]", ki18n("An optional URL to connect to"));
    KCmdLineArgs::addCmdLineOptions(options);
    KUniqueApplication app;
    
    if (app.isSessionRestored()) {
      RESTORE(MainWindow);
    } else {
      MainWindow *mainWindow = 0;
      KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

      KSplashScreen *splash = 0L;
      QString splashPath = KStandardDirs::locate("appdata", "kftpgrabber-logo.png");
      if (!KFTPCore::Config::startMinimized() && KFTPCore::Config::showSplash()) {
        // Show the splash screen
        if (!splashPath.isNull()) {
          QPixmap splashImage = QPixmap(splashPath);
          splash = new KSplashScreen(splashImage);
          splash->setMaximumWidth(400);
          splash->show();
        }
      }
      
      mainWindow = new MainWindow();
      if (!KFTPCore::Config::startMinimized())
        mainWindow->show();
        
      // Check if an URL was passed as a command line argument
      if (args->count() == 1) {
        KUrl remoteUrl = args->url(0);
        
        if (!remoteUrl.isLocalFile()) {
          if (!remoteUrl.port())
            remoteUrl.setPort(21);
            
          if (!remoteUrl.hasUser())
            remoteUrl.setUser("anonymous");
            
          if (!remoteUrl.hasPass()) {
            if (!KFTPCore::Config::anonMail().isEmpty())
              remoteUrl.setPass(KFTPCore::Config::anonMail());
            else
              remoteUrl.setPass("*****@*****.**");
          }

          KFTPSession::Manager::self()->spawnRemoteSession(KFTPSession::IgnoreSide, remoteUrl);
        }
      }
        
      if (splash != 0L) {
        splash->finish(mainWindow);
        delete splash;
      }
      
      args->clear();
    }
    
    return app.exec();
}
Ejemplo n.º 3
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;
}
int main( int argc, char *argv[] )
{
	KAboutData aboutData( "kopetepasswordtest", 0, ki18n("kopetepasswordtest"), "version" );
	KCmdLineArgs::init( argc, argv, &aboutData );

	KCmdLineOptions opts;
	opts.add("id <id>", ki18n("Config group to store password in"), "TestAccount");
	opts.add("set <new>", ki18n("Set password to new"));
	opts.add("error", ki18n("Claim password was erroneous"));
	opts.add("prompt <prompt>", ki18n("Password prompt"), "Enter a password");
	opts.add("image <filename>", ki18n("Image to display in password dialog"));
	KCmdLineArgs::addCmdLineOptions( opts );
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	KApplication app( "kopetepasswordtest" );

	bool setPassword = args->isSet("set");
	QString newPwd = args->getOption("set");
	QString passwordId = args->getOption("id");
	bool error = args->isSet("error");
	QString prompt = args->getOption("prompt");
	QPixmap image = QString(args->getOption("image"));

	_out << (image.isNull() ? "image is null" : "image is valid") << endl;

	Password pwd( passwordId, 0, false );
	pwd.setWrong( error );

	_out << "Cached value is null: " << pwd.cachedValue().isNull() << endl;

	QString pass = retrieve( pwd, image, prompt );

	if ( !pass.isNull() )
		_out << "Read password: "******"Could not read a password" << endl;

	_out << "Cached value: " << (pwd.cachedValue().isNull() ? "null" : pwd.cachedValue()) << endl;

	if ( setPassword )
	{
		if ( newPwd.isEmpty() )
		{
			_out << "Clearing password" << endl;
			newPwd.clear();
		}
		else
		{
			_out << "Setting password to " << newPwd << endl;
		}
		pwd.set( newPwd );
	}

	// without this, setting passwords will fail since they're
	// set asynchronously.
	QTimer::singleShot( 0, &app, SLOT(deref()) );
	app.exec();

	if ( setPassword )
	{
		pass = retrieve( pwd, image, i18n("Hopefully this popped up because you set the password to the empty string.") );
		if( pass == newPwd )
			_out << "Password successfully set." << endl;
		else
			_out << "Failed: password ended up as " << pass << endl;
	}

	return 0;
}
Ejemplo n.º 5
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"));


    if (!pipe(termPipe))
    {
#ifndef Q_WS_WIN
        struct sigaction sa;
        sa.sa_handler = termHandler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        sigaction(SIGTERM, &sa, 0);
#endif
        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"))
    {
#ifdef Q_WS_WIN
        saveWin = (HWND)(args->getOption("window-id").toULong());
#else
        saveWin = args->getOption("window-id").toInt();
#endif
    }

#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;
}
Ejemplo n.º 6
0
static int startApp()
{
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    // Stop daemon and exit?
    if (args->isSet("s"))
    {
        KDEsuClient client;
        if (client.ping() == -1)
        {
            kdError(1206) << "Daemon not running -- nothing to stop\n";
            exit(1);
        }
        if (client.stopServer() != -1)
        {
            kdDebug(1206) << "Daemon stopped\n";
            exit(0);
        }
        kdError(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
    QCString user = args->getOption("u");
    QCString auth_user = user;
    struct passwd *pw = getpwnam(user);
    if (pw == 0L)
    {
        kdError(1206) << "User " << user << " does not exist\n";
        exit(1);
    }
    bool change_uid = (getuid() != pw->pw_uid);

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

    // Get priority/scheduler
    QCString tmp = args->getOption("p");
    bool ok;
    int priority = tmp.toInt(&ok);
    if (!ok || (priority < 0) || (priority > 100))
    {
        KCmdLineArgs::usage(i18n("Illegal priority: %1").arg(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");
        for (int i=0; i<args->count(); i++)
        {
            QString arg = QFile::decodeName(args->arg(i));
            KRun::shellQuote(arg);
            command += " ";
            command += QFile::encodeName(arg);
        }
    }
    else 
    {
        if( args->count() == 0 )
        {
            KCmdLineArgs::usage(i18n("No command specified."));
            exit(1);
        }
        command = args->arg(0);
        for (int i=1; i<args->count(); i++)
        {
            QString arg = QFile::decodeName(args->arg(i));
            KRun::shellQuote(arg);
            command += " ";
            command += QFile::encodeName(arg);
        }
    }

    // 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())
    {
        kdWarning(1206) << "Daemon not safe (not sgid), not using it.\n";
        have_daemon = false;
    }
    else if (client.ping() == -1)
    {
        if (client.startServer() == -1)
        {
            kdWarning(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 new_dcop = args->isSet("newdcop");
    bool withIgnoreButton = args->isSet("ignorebutton");
    
    QCStringList env;
    QCString 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=QString::null; // Use default

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

    KUser u;
    env << (QCString) ("KDESU_USER="******"KDESYCOCA="+QFile::encodeName(locateLocal("cache", "ksycoca"));
        env << ksycoca;

        options += "xf"; // X-only, dcop forwarding enabled.
    }

    if (keep && !terminal && !just_started)
    {
        client.setPriority(priority);
        client.setScheduler(scheduler);
        int result = client.exec(command, user, options, env);
        if (result == 0)
        {
           result = client.exitCode();
           return result;
        }
    }

    // Set core dump size to 0 because we will have
    // root's password in memory.
    struct rlimit rlim;
    rlim.rlim_cur = rlim.rlim_max = 0;
    if (setrlimit(RLIMIT_CORE, &rlim))
    {
        kdError(1206) << "rlimit(): " << ERR << "\n";
        exit(1);
    }

    // Read configuration
    KConfig *config = KGlobal::config();
    config->setGroup("Passwords");
    int timeout = config->readNumEntry("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;
        kdDebug() << "Don't need password!!\n";
    }

    // Start the dialog
    QCString password;
    if (needpw)
    {
        KStartupInfoId id;
        id.initId( kapp->startupId());
        KStartupInfoData data;
        data.setSilent( KStartupInfoData::Yes );
        KStartupInfo::sendChange( id, data );
        KDEsuDialog dlg(user, auth_user, keep && !terminal,icon, withIgnoreButton);
	if (prompt)
	    dlg.addLine(i18n("Command:"), command);
        if ((priority != 50) || (scheduler != SuProcess::SchedNormal))
        {
            QString prio;
            if (scheduler == SuProcess::SchedRealtime)
                prio += i18n("realtime: ");
            prio += QString("%1/100").arg(priority);
	    if (prompt)
		dlg.addLine(i18n("Priority:"), prio);
        }
        int ret = dlg.exec();
        if (ret == KDEsuDialog::Rejected)
        {
            KStartupInfo::sendFinish( id );
            exit(0);
        }
        if (ret == KDEsuDialog::AsUser)
            change_uid = false;
        password = dlg.password();
        keep = dlg.keep();
        data.setSilent( KStartupInfoData::No );
        KStartupInfo::sendChange( id, data );
    }

    // 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, 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);
        if (!new_dcop)
        {
            proc.setXOnly(true);
            proc.setDCOPForwarding(true);
        }
        proc.setEnvironment(env);
        proc.setPriority(priority);
        proc.setScheduler(scheduler);
        proc.setCommand(command);
        int result = proc.exec(password);
        return result;
    }
    return -1;
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
    KLocalizedString::setApplicationDomain( "koconverter" );

    K4AboutData aboutData("calligraconverter", 0, ki18n("CalligraConverter"), CalligraVersionWrapper::versionString().toLatin1(),
                         ki18n("Calligra Document Converter"),
                         K4AboutData::License_GPL,
                         ki18n("(c) 2001-2011 Calligra developers"));
    aboutData.addAuthor(ki18n("David Faure"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Nicolas Goutte"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Dan Leinir Turthra Jensen"), KLocalizedString(), "*****@*****.**");
    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("+in", ki18n("Input file"));
    options.add("+out", ki18n("Output file"));
    options.add("backup", ki18n("Make a backup of the destination file"));
    options.add("batch", ki18n("Batch mode: do not show dialogs"));
    options.add("interactive", ki18n("Interactive mode: show dialogs (default)"));
    options.add("mimetype <mime>", ki18n("Mimetype of the output file"));

    // PDF related options.
    options.add("print-orientation <name>", ki18n("The print orientation. This could be either Portrait or Landscape."));
    options.add("print-papersize <name>", ki18n("The paper size. A4, Legal, Letter, ..."));
    options.add("print-margin <size>", ki18n("The size of the paper margin. By default this is 0.2."));

    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    // Get the command line arguments which we have to parse
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->count() != 2) {
        KCmdLineArgs::usageError(i18n("Two arguments required"));
        return 3;
    }

    const QUrl urlIn = args->url(0);
    const QUrl urlOut = args->url(1);

    // Are we in batch mode or in interactive mode.
    bool batch = args->isSet("batch");
    if (args->isSet("interactive")) {
        batch = false;
    }

    if (args->isSet("backup")) {
        // Code form koDocument.cc
        KIO::UDSEntry entry;
        if (KIO::NetAccess::stat(urlOut, entry, 0L)) {   // this file exists => backup
            kDebug() << "Making backup...";
            QUrl backup(urlOut);
            backup.setPath(urlOut.path() + '~');
            KIO::FileCopyJob *job = KIO::file_copy(urlOut, backup, -1, KIO::Overwrite | KIO::HideProgressInfo);
            job->exec();
        }
    }

    QMimeDatabase db;
    QMimeType inputMimetype = db.mimeTypeForUrl(urlIn);
    if (!inputMimetype.isValid() || inputMimetype.isDefault()) {
        kError() << i18n("Mimetype for input file %1 not found!", urlIn.toDisplayString()) << endl;
        return 1;
    }

    QMimeType outputMimetype;
    if (args->isSet("mimetype")) {
        QString mime = args->getOption("mimetype");
        outputMimetype = db.mimeTypeForName(mime);
        if (! outputMimetype.isValid()) {
            kError() << i18n("Mimetype not found %1", mime) << endl;
            return 1;
        }
    } else {
        outputMimetype = db.mimeTypeForUrl(urlOut);
        if (!outputMimetype.isValid() || outputMimetype.isDefault()) {
            kError() << i18n("Mimetype not found, try using the -mimetype option") << endl;
            return 1;
        }
    }

    QApplication::setOverrideCursor(Qt::WaitCursor);

    QString outputFormat = outputMimetype.name();
    bool ok = false;
    if (outputFormat == "application/pdf") {
        QString orientation = args->getOption("print-orientation");
        QString papersize = args->getOption("print-papersize");
        QString margin = args->getOption("print-margin");
        ok = convertPdf(urlIn, inputMimetype.name(), urlOut, outputFormat, orientation, papersize, margin);
    } else {
        ok = convert(urlIn, inputMimetype.name(), urlOut, outputFormat, batch);
    }

    QTimer::singleShot(0, &app, SLOT(quit()));
    app.exec();

    QApplication::restoreOverrideCursor();

    if (!ok) {
        kError() << i18n("*** The conversion failed! ***") << endl;
        return 2;
    }

    return 0;
}
Ejemplo n.º 8
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);
				}
			}
		}
	}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{

    KCmdLineArgs::init(argc, argv, "Testkhtml", "a basic web browser using the KHTML library", "1.0");
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication a;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs( );
    if ( args->count() == 0 ) {
	KCmdLineArgs::usage();
	::exit( 1 );
    }

    KHTMLFactory *fac = new KHTMLFactory();

    KMainWindow *toplevel = new KMainWindow();
    KHTMLPart *doc = new KHTMLPart( toplevel, 0, toplevel, 0, KHTMLPart::BrowserViewGUI );

    Dummy *dummy = new Dummy( doc );
    QObject::connect( doc->browserExtension(), SIGNAL( openURLRequest( const KURL &, const KParts::URLArgs & ) ),
		      dummy, SLOT( slotOpenURL( const KURL&, const KParts::URLArgs & ) ) );

    if (args->url(0).url().right(4).find(".xml", 0, false) == 0) {
        KParts::URLArgs ags(doc->browserExtension()->urlArgs());
        ags.serviceType = "text/xml";
        doc->browserExtension()->setURLArgs(ags);
    }

    doc->openURL( args->url(0) );

//     DOMTreeView * dtv = new DOMTreeView(0, doc, "DomTreeView");
//     dtv->show();

    toplevel->setCentralWidget( doc->widget() );
    toplevel->resize( 640, 800);

//     dtv->resize(toplevel->width()/2, toplevel->height());

    QDomDocument d = doc->domDocument();
    QDomElement viewMenu = d.documentElement().firstChild().childNodes().item( 2 ).toElement();
    QDomElement e = d.createElement( "action" );
    e.setAttribute( "name", "debugRenderTree" );
    viewMenu.appendChild( e );
    e = d.createElement( "action" );
    e.setAttribute( "name", "debugDOMTree" );
    viewMenu.appendChild( e );
    QDomElement toolBar = d.documentElement().firstChild().nextSibling().toElement();
    e = d.createElement( "action" );
    e.setAttribute( "name", "reload" );
    toolBar.insertBefore( e, toolBar.firstChild() );
    e = d.createElement( "action" );
    e.setAttribute( "name", "print" );
    toolBar.insertBefore( e, toolBar.firstChild() );

    (void)new KAction( "Reload", "reload", Qt::Key_F5, dummy, SLOT( reload() ), doc->actionCollection(), "reload" );
    KAction* kprint = new KAction( "Print", "print", 0, doc->browserExtension(), SLOT( print() ), doc->actionCollection(), "print" );
    kprint->setEnabled(true);

    toplevel->guiFactory()->addClient( doc );

    doc->setJScriptEnabled(true);
    doc->setJavaEnabled(true);
    doc->setURLCursor(QCursor(Qt::PointingHandCursor));
    a.setTopWidget(doc->widget());
    QWidget::connect(doc, SIGNAL(setWindowCaption(const QString &)),
		     doc->widget(), SLOT(setCaption(const QString &)));
    doc->widget()->show();
    toplevel->show();
    ((QScrollView *)doc->widget())->viewport()->show();


    int ret = a.exec();
    
    //delete doc;
    //delete dtv;

    khtml::Cache::clear();
    khtml::CSSStyleSelector::clear();
    khtml::RenderStyle::cleanup();

    delete fac;
    return ret;
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
    KCmdLineOptions options;
    options.add("+file", ki18n("URL to open"));

    KCmdLineArgs::init(argc, argv, "testkhtml", 0, ki18n("Testkhtml"),
            "1.0", ki18n("a basic web browser using the KHTML library"));
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication a;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs( );
    if ( args->count() == 0 ) {
	KCmdLineArgs::usage();
	::exit( 1 );
    }

    new KHTMLGlobal;

    KXmlGuiWindow *toplevel = new KXmlGuiWindow();
    KHTMLPart *doc = new KHTMLPart( toplevel, toplevel, KHTMLPart::BrowserViewGUI );

    Dummy *dummy = new Dummy( doc );
    QObject::connect( doc->browserExtension(), SIGNAL(openUrlRequest(KUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)),
		      dummy, SLOT(slotOpenURL(KUrl,KParts::OpenUrlArguments,KParts::BrowserArguments)) );

    QObject::connect( doc, SIGNAL(completed()), dummy, SLOT(handleDone()) );

    if (args->url(0).url().right(4).toLower() == ".xml") {
        KParts::OpenUrlArguments args(doc->arguments());
        args.setMimeType("text/xml");
        doc->setArguments(args);
    }

    doc->openUrl( args->url(0) );

    toplevel->setCentralWidget( doc->widget() );
    toplevel->resize( 800, 600);

    QDomDocument d = doc->domDocument();
    QDomElement viewMenu = d.documentElement().firstChild().childNodes().item( 2 ).toElement();
    QDomElement e = d.createElement( "action" );
    e.setAttribute( "name", "debugRenderTree" );
    viewMenu.appendChild( e );
    e = d.createElement( "action" );
    e.setAttribute( "name", "debugDOMTree" );
    viewMenu.appendChild( e );
    e = d.createElement( "action" );
    e.setAttribute( "name", "debugDoBenchmark" );
    viewMenu.appendChild( e );

    QDomElement toolBar = d.documentElement().firstChild().nextSibling().toElement();
    e = d.createElement( "action" );
    e.setAttribute( "name", "editable" );
    toolBar.insertBefore( e, toolBar.firstChild() );
    e = d.createElement( "action" );
    e.setAttribute( "name", "navigable" );
    toolBar.insertBefore( e, toolBar.firstChild() );
    e = d.createElement( "action" );
    e.setAttribute( "name", "reload" );
    toolBar.insertBefore( e, toolBar.firstChild() );
    e = d.createElement( "action" );
    e.setAttribute( "name", "print" );
    toolBar.insertBefore( e, toolBar.firstChild() );

    KAction *action = new KAction(KIcon("view-refresh"),  "Reload", doc );
    doc->actionCollection()->addAction( "reload", action );
    QObject::connect(action, SIGNAL(triggered(bool)), dummy, SLOT(reload()));
    action->setShortcut(Qt::Key_F5);

    KAction *bench = new KAction( KIcon(), "Benchmark...", doc );
    doc->actionCollection()->addAction( "debugDoBenchmark", bench );
    QObject::connect(bench, SIGNAL(triggered(bool)), dummy, SLOT(doBenchmark()));

    KAction *kprint = new KAction(KIcon("document-print"),  "Print", doc );
    doc->actionCollection()->addAction( "print", kprint );
    QObject::connect(kprint, SIGNAL(triggered(bool)), doc->browserExtension(), SLOT(print()));
    kprint->setEnabled(true);
    KToggleAction *ta = new KToggleAction( KIcon("edit-rename"), "Navigable", doc );
    doc->actionCollection()->addAction( "navigable", ta );
    ta->setShortcuts( KShortcut() );
    ta->setChecked(doc->isCaretMode());
    QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleNavigable(bool)));
    ta = new KToggleAction( KIcon("document-properties"), "Editable", doc );
    doc->actionCollection()->addAction( "editable", ta );
    ta->setShortcuts( KShortcut() );
    ta->setChecked(doc->isEditable());
    QWidget::connect(ta, SIGNAL(toggled(bool)), dummy, SLOT(toggleEditable(bool)));
    toplevel->guiFactory()->addClient( doc );

    doc->setJScriptEnabled(true);
    doc->setJavaEnabled(true);
    doc->setPluginsEnabled( true );
    doc->setURLCursor(QCursor(Qt::PointingHandCursor));
    a.setTopWidget(doc->widget());
    QWidget::connect(doc, SIGNAL(setWindowCaption(QString)),
		     doc->widget()->topLevelWidget(), SLOT(setCaption(QString)));
    doc->widget()->show();
    toplevel->show();
    doc->view()->viewport()->show();
    doc->view()->widget()->show();


    int ret = a.exec();
    return ret;
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
0
int main(int argc, char **argv)
{
	KLocale::setMainCatalogue("kdelibs");
	KCmdLineArgs::init(argc, argv, "ktelnetservice", I18N_NOOP("telnet service"),
			   I18N_NOOP("telnet protocol handler"), "unknown");
	KCmdLineArgs::addCmdLineOptions(options);

	KApplication app;

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
	
	if (args->count() != 1)
		return 1;

	KConfig *config = new KConfig("kdeglobals", true);
	config->setGroup("General");
	QString terminal = config->readPathEntry("TerminalApplication", "konsole");

	KURL url(args->arg(0));
	QStringList cmd;
	if (terminal == "konsole")
	    cmd << "--noclose";

	cmd << "-e";
        if ( url.protocol() == "telnet" )
            cmd << "telnet";
        else if ( url.protocol() == "ssh" )
            cmd << "ssh";
        else if ( url.protocol() == "rlogin" )
            cmd << "rlogin";
        else {
            kdError() << "Invalid protocol " << url.protocol() << endl;
            return 2;
        }
        
        if (!app.authorize("shell_access"))
        {
            KMessageBox::sorry(0, 
            	i18n("You do not have permission to access the %1 protocol.").arg(url.protocol()));
            return 3;
        }
        
	if (!url.user().isEmpty())
	{
		cmd << "-l";
		cmd << url.user();
	}

        QString host;
        if (!url.host().isEmpty())
           host = url.host(); // telnet://host
        else if (!url.path().isEmpty())
           host = url.path(); // telnet:host

        if (host.isEmpty() || host.startsWith("-"))
        {
            kdError() << "Invalid hostname " << host << endl;
            return 2;
        }

        cmd << host;
        
	if (url.port()){
            if ( url.protocol() == "ssh" )
		cmd << "-p" << QString::number(url.port());
	    else
		cmd << QString::number(url.port());
	}

	app.kdeinitExec(terminal, cmd);

	return 0;
}
Ejemplo n.º 13
0
int main( int argc, char **argv )
{
  KAboutData aboutData(
    "testrecurrencenew", 0,
    ki18n( "Load recurrence rules with the new class and print out debug messages" ), "0.1" );
  KCmdLineArgs::init( argc, argv, &aboutData );

  KCmdLineOptions options;
  options.add( "verbose", ki18n( "Verbose output" ) );
  options.add( "+input", ki18n( "Name of input file" ) );
  options.add( "[+output]", ki18n( "optional name of output file for the recurrence dates" ) );
  KCmdLineArgs::addCmdLineOptions( options );

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

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  if ( args->count() < 1 ) {
    args->usage( "Wrong number of arguments." );
  }

  QString input = args->arg( 0 );
  kDebug() << "Input file:" << input;

  QTextStream *outstream;
  outstream = 0;
  QString fn( "" );
  if ( args->count() > 1 ) {
    fn = args->arg( 1 );
    kDebug() << "We have a file name given:" << fn;
  }
  QFile outfile( fn );
  if ( !fn.isEmpty() && outfile.open( QIODevice::WriteOnly ) ) {
    kDebug() << "Opened output file!!!";
    outstream = new QTextStream( &outfile );
  }

  MemoryCalendar::Ptr cal( new MemoryCalendar( KDateTime::UTC ) );

  KDateTime::Spec viewSpec;
  FileStorage store( cal, input );
  if ( !store.load() ) return 1;
  QString tz = cal->nonKDECustomProperty( "X-LibKCal-Testsuite-OutTZ" );
  if ( !tz.isEmpty() ) {
    viewSpec = KDateTime::Spec( KSystemTimeZones::zone( tz ) );
  }

  Incidence::List inc = cal->incidences();

  for ( Incidence::List::Iterator it = inc.begin(); it != inc.end(); ++it ) {
    Incidence::Ptr incidence = *it;
    kDebug() << "*+*+*+*+*+*+*+*+*+*";
    kDebug() << " ->" << incidence->summary() << "<-";

    incidence->recurrence()->dump();

    KDateTime dt( incidence->recurrence()->endDateTime() );
    int i = 0;
    if ( outstream ) {
      if ( !dt.isValid() ) {
        if ( viewSpec.isValid() ) {
          dt = KDateTime( QDate( 2011, 1, 1 ), QTime( 0, 0, 1 ), viewSpec );
        } else {
          dt = KDateTime( QDate( 2011, 1, 1 ), QTime( 0, 0, 1 ) );
        }
      } else {
        dt = dt.addYears( 2 );
      }
      kDebug() << "-------------------------------------------";
      kDebug() << " *~*~*~*~ Starting with date:" << dumpTime( dt, viewSpec );
      // Output to file for testing purposes
      while ( dt.isValid() && i < 500 ) {
        ++i;
        dt = incidence->recurrence()->getPreviousDateTime( dt );
        if ( dt.isValid() ) {
          (*outstream) << dumpTime( dt, viewSpec ) << endl;
        }
      }
    } else {
      if ( !dt.isValid() ) {
        dt = KDateTime( QDate( 2005, 7, 31 ), QTime( 23, 59, 59 ), KDateTime::Spec::UTC() );
      } else {
        dt = dt.addYears( 2 );
      }
      incidence->recurrence()->dump();
      kDebug() << "-------------------------------------------";
      kDebug() << " *~*~*~*~ Starting with date:" << dumpTime( dt, viewSpec );
      // Output to konsole
      while ( dt.isValid() && i < 50 ) {
        ++i;
        kDebug() << "-------------------------------------------";
        dt = incidence->recurrence()->getPreviousDateTime( dt );
        if ( dt.isValid() ) {
          kDebug() << " *~*~*~*~ Previous date is:" << dumpTime( dt, viewSpec );
        }
      }
    }
  }

  delete outstream;
  outfile.close();
  return 0;
}
Ejemplo n.º 14
0
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;
    }
Ejemplo n.º 15
0
int main(int argc, char** argv)
{
    qInstallMsgHandler(messageOutput);
    KAboutData aboutData( "duchaintokross", 0, ki18n( "duchaintokross" ),
                          "33", ki18n("Wrapper generator from C++ to Kross"), KAboutData::License_GPL,
                          ki18n( "(c) 2008, The KDevelop developers" ), KLocalizedString(), "http://www.kdevelop.org" );
    KCmdLineArgs::init( argc, argv, &aboutData );
    KCmdLineOptions options;
    options.add("+file", ki18n("input .cpp file"), QByteArray());
    options.add("I <includes>", ki18n("include directories for the parser (colon separated)"), QByteArray());
    options.add("i <includes>", ki18n("include directories that the generated implementation file will have (colon separated)"), QByteArray());
    options.add("b <builddir>", ki18n("build dir where the Makefile for the input is added"), QByteArray());
    options.add("F <filename>", ki18n("filename to be used for the .moc and the .h file"), QByteArray());
    options.add("D <directory>", ki18n("directory where to put the .h output"), QByteArray());
    options.add("o <output>", ki18n("directory where to put the code output"), QByteArray());
    options.add("impl", ki18n("create implementation"), QByteArray());
    options.add("verbose", ki18n("Verbose output"), QByteArray());
    KCmdLineArgs::addCmdLineOptions( options );
    
    KApplication app;
    ConsoleIDEExtension::init();
    Core::initialize(0, Core::NoUi);
    
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    KUrl::List includes;
    KUrl input;
    
    for(int i=0; i<args->count(); i++)
    {
        QString arg=args->arg(i);
        input=KUrl(arg);
    }
    
    foreach(const QString& inc, args->getOption("I").split(':'))
        includes << KUrl(inc);
    KUrl builddir(args->getOption("b"));
    QString filename(args->getOption("F"));
    QString directory(args->getOption("D"));
    QStringList toinclude(args->getOption("i").split(':'));
    QString output(args->getOption("o"));
    verbose=args->isSet("verbose");
    bool createImpl=args->isSet("impl");
    args->clear();
    
    DUChainExtractor e;
    kDebug() << input << builddir << includes << toinclude;
    e.setWriteImpl(createImpl);
    e.start(input, builddir, includes, filename, directory, toinclude, output);
    
    return app.exec();
}
Ejemplo n.º 16
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();
    }
}
Ejemplo n.º 17
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());
            }
        }
Ejemplo n.º 18
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;
    }
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
  KAboutData about("syanot", 0, ki18n("Syanot"), version, ki18n(description),
                    KAboutData::License_GPL, ki18n("(C) 2007 Gael de Chalendar"), KLocalizedString(), 0, "*****@*****.**");
  about.addAuthor( ki18n("Gael de Chalendar"), KLocalizedString(), "*****@*****.**" );
  KCmdLineArgs::init(argc, argv, &about);

  KCmdLineOptions options;
  options.add("+[URL]", ki18n( "Dot graph to open" ));
  options.add("comparewith file", ki18n("URL of a file containing an analysis to compare the main analysis with"));
  options.add("utterances list", ki18n("List of utterances ids to display"));
  KCmdLineArgs::addCmdLineOptions( options );
  KApplication app;
  
// see if we are starting with session management
  if (app.isSessionRestored())
  {
      RESTORE(Syanot);
  }
  else
  {
      // no session.. just start up normally
      KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

      Syanot *widget = 0;
      if ( args->count() == 0 )
      {
        widget = new Syanot();
        new SyanotAdaptor(widget);
        QDBusConnection::sessionBus().registerObject("/Syanot", widget);
        widget->show();
      }
      else
      {
        QDBusReply<bool> reply = QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.syanot" );
      
        bool instanceExists = reply.value();
  
        for (int i = 0; i < args->count(); i++ )
        {
          if (instanceExists 
              && (KMessageBox::questionYesNo(0, 
                                         i18n("There is already a Syanot window opened. What's your choice ?"),
                                         i18n("Opening in new window confirmation"),
                                             KGuiItem("Open in the existing one"),
                                             KGuiItem("Open in new window"),
                                             "openInNewWindowMode"   ) == KMessageBox::Yes) )
          {
            QByteArray tosenddata;
            QDataStream arg(&tosenddata, QIODevice::WriteOnly);
            QString strarg = args->arg(i);
            KUrl url;
            if (strarg.left(1) == "/")
              url = KUrl(strarg);
            else url = KUrl(QDir::currentPath() + '/' + strarg);
            arg << url;
            QDBusInterface iface("org.kde.syanot", "/Syanot", "", QDBusConnection::sessionBus());
            if (iface.isValid()) 
            {
              if (args->isSet("utterances"))
              {
                QDBusReply<void> reply = iface.call("slotSetUtterances", args->getOption("utterances"));
                if (reply.isValid())
                {
                  kDebug() << "Reply was valid" << endl;
                }
                else
                {
                  kError() << "Call failed: " << reply.error().message() << endl;
                  return 1;
                }
              }
              QDBusReply<void> reply = iface.call("openUrl", url.pathOrUrl());
              if (reply.isValid()) 
              {
                kDebug() << "Reply was valid" << endl;
              }
              else
              {
                kError() << "Call failed: " << reply.error().message() << endl;
                return 1;
              }
              if (args->isSet("comparewith"))
              {
                QString strarg = args->getOption("comparewith");
                KUrl url;
                if (strarg.left(1) == "/")
                  url = KUrl(strarg);
                else url = KUrl(QDir::currentPath() + '/' + strarg);
                reply = iface.call("openSecondaryUrl", url.pathOrUrl());
                if (reply.isValid())
                {
                  kDebug() << "Reply was valid" << endl;
                }
                else
                {
                  kError() << "Call failed: " << reply.error().message() << endl;
                  return 1;
                }
                return 0;
              }
            }
            kError() << "Invalid interface" << endl;
            exit(0);
          }
          else
          {
            widget = new Syanot;
            new SyanotAdaptor(widget);
            QDBusConnection::sessionBus().registerObject("/Syanot", widget);
            widget->show();
            if (args->isSet("utterances"))
            {
              widget->slotSetUtterances(args->getOption("utterances"));
            }
            widget->openUrl( args->url( i ) );
            if (args->isSet("comparewith"))
            {
                QString strarg = args->getOption("comparewith");
              kDebug() << "comparewith" << args->getOption("comparewith");
                KUrl url;
                if (strarg.left(1) == "/")
                  url = KUrl(strarg);
                else url = KUrl(QDir::currentPath() + '/' + strarg);
              kDebug() << "openSecondaryUrl" << url.pathOrUrl();
              widget->openSecondaryUrl(url.pathOrUrl());
            }
          }
        }
      }
      args->clear();
  }
  return app.exec();
}
Ejemplo n.º 20
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");
}
Ejemplo n.º 21
0
int Application::newInstance()
{
    static bool firstInstance = true;

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

    // handle session management
    if ((args->count() != 0) || !firstInstance || !isSessionRestored()) {
        // check for arguments to print help or other information to the
        // terminal, quit if such an argument was found
        if (processHelpArgs(args))
            return 0;

        bool openpty = is_use_openpty;


        // create a new window or use an existing one
        MainWindow* window = processWindowArgs(args);

        if (args->isSet("tabs-from-file")) {
            // create new session(s) as described in file
            processTabsFromFileArgs(args, window);
        } else {
            // select profile to use
            Profile::Ptr baseProfile = processProfileSelectArgs(args);

            // process various command-line options which cause a property of the
            // selected profile to be changed
            Profile::Ptr newProfile = processProfileChangeArgs(args, baseProfile);

            // create new session
            Session* session = window->createSession(newProfile, QString(), openpty);

            if (!args->isSet("close")) {
                session->setAutoClose(false);
            }
        }

        // if the background-mode argument is supplied, start the background
        // session ( or bring to the front if it already exists )
        if (args->isSet("background-mode")) {
            startBackgroundMode(window);
        } else {
            // Qt constrains top-level windows which have not been manually
            // resized (via QWidget::resize()) to a maximum of 2/3rds of the
            //  screen size.
            //
            // This means that the terminal display might not get the width/
            // height it asks for.  To work around this, the widget must be
            // manually resized to its sizeHint().
            //
            // This problem only affects the first time the application is run.
            // run. After that KMainWindow will have manually resized the
            // window to its saved size at this point (so the Qt::WA_Resized
            // attribute will be set)
            if (!window->testAttribute(Qt::WA_Resized))
                window->resize(window->sizeHint());

            window->show();
        }
    }

    firstInstance = false;
    args->clear();
    return 0;
}
Ejemplo n.º 22
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);
	}
Ejemplo n.º 23
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.7",                             // app version 
                         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 Socks 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

    return a.exec();
}
Ejemplo n.º 24
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();
}
Ejemplo n.º 25
0
int main( int argc, char** argv )
{
    QString version = CalligraVersionWrapper::versionString(true);

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

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

    KCmdLineOptions options;
    options.add( "+[files]", ki18n( "Document to open" ) );
    options.add( "vkb", ki18n( "Use the virtual keyboard" ) );
    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("calligragemini");
    KIconLoader::global()->addAppDir("calligrawords");
    KIconLoader::global()->addAppDir("words");
    KIconLoader::global()->addAppDir("calligrastage");
    KIconLoader::global()->addAppDir("stage");

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

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

    if(envStringSet.length() > 0) {
        qDebug() << envStringSet << "were set from main, restarting application in new environment!";
        // Pass all the arguments along, but don't include the application name...
        QProcess::startDetached(app.applicationFilePath(), KCmdLineArgs::allArguments().mid(1));
        exit(0);
    }

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

    QStringList iconThemePaths;
    iconThemePaths << appdir.absolutePath() + "/share/icons";
    QIcon::setThemeSearchPaths(iconThemePaths);
    QIcon::setThemeName("oxygen");
#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");
    }

    // 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.
//     QPixmap pm(splash_screen_xpm);
//     QSplashScreen splash(pm);
//     splash.show();
//     splash.showMessage(".");
    app.processEvents();

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

    MainWindow window(fileNames);

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

#ifdef Q_OS_WIN
    window.showMaximized();
#else
    window.show();
#endif
//    splash.finish(&window);

    return app.exec();
}
Ejemplo n.º 26
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;
}
Ejemplo n.º 27
0
extern "C" KDE_EXPORT int kdemain( int argc, char**argv )
{
   // Started via kdeinit.
   if (fcntl(LAUNCHER_FD, F_GETFD) == -1)
   {
      fprintf(stderr, "%s", i18n("klauncher: This program is not supposed to be started manually.\n"
                                 "klauncher: It is started automatically by kdeinit.\n").local8Bit().data());
      return 1;
   }

   QCString cname = KApplication::launcher();
   char *name = cname.data();
   KCmdLineArgs::init(argc, argv, name, "KLauncher", "A service launcher.",
                       "v1.0");

   KLauncher::addCmdLineOptions();
   KCmdLineArgs::addCmdLineOptions( options );

   // WABA: Make sure not to enable session management.
   putenv(strdup("SESSION_MANAGER="));

   // Allow the locale to initialize properly
   KLocale::setMainCatalogue("kdelibs");

   KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

   int maxTry = 3;
   while(true)
   {
      QCString dcopName = KApplication::dcopClient()->registerAs(name, false);
      if (dcopName.isEmpty())
      {
         kdWarning() << "DCOP communication problem!" << endl;
         return 1;
      }
      if (dcopName == cname)
         break; // Good!

      if (--maxTry == 0)
      {
         kdWarning() << "Another instance of klauncher is already running!" << endl;
         return 1;
      }
      
      // Wait a bit...
      kdWarning() << "Waiting for already running klauncher to exit." << endl;
      sleep(1);

      // Try again...
   }
   
   KLauncher *launcher = new KLauncher(LAUNCHER_FD, args->isSet("new-startup"));
   launcher->dcopClient()->setDefaultObject( name );
   launcher->dcopClient()->setDaemonMode( true );

   KCrash::setEmergencySaveFunction(sig_handler);
   signal( SIGHUP, sig_handler);
   signal( SIGPIPE, SIG_IGN);
   signal( SIGTERM, sig_handler);

   launcher->exec();
   return 0;
}
Ejemplo n.º 28
0
int main(int argc, char **argv)
{
    KCmdLineArgs::init(argc, argv, "kwmtheme", description, "0.1");

    KCmdLineOptions options;
    options.add("+[file]", ki18n("Path to a theme config file"));
    KCmdLineArgs::addCmdLineOptions( options );
    KApplication app(argc, argv);
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if(!args->count()) {
        kWarning(1212) << "You need to specify the path to a theme config file!" ;
        return(1);
    }

    QString srcStr = QString(args->arg(0));
    QFile f(srcStr);
    QString tmpStr;

    if(!f.exists()) {
        kWarning(1212) << "Specified theme config file doesn't exist!" ;
        return(2);
    }

    QStringList appDirs = KGlobal::dirs()->findDirs("data", "kwin");
    QString localDirStr = *(appDirs.end());
    if(localDirStr.isEmpty()) {
        localDirStr = KGlobal::dirs()->saveLocation("data", "kwin");
    }
    localDirStr += "/pics/";
    if(!QFile::exists(localDirStr))
        QDir().mkdir(localDirStr);

    QFileInfo fi(f);
    KSimpleConfig input(fi.absoluteFilePath());
    srcStr = fi.dirPath(true) + '/';
    KSharedConfig::Ptr output = KGlobal::config();
    input.setGroup("Window Border");
    output->setGroup("General");

    tmpStr = input.readEntry("shapePixmapTop");
    if(!tmpStr.isEmpty()) {
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    }
    output->writeEntry("wm_top", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("shapePixmapBottom");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("wm_bottom", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("shapePixmapLeft");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("wm_left", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("shapePixmapRight");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("wm_right", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("shapePixmapTopLeft");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("wm_topleft", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("shapePixmapTopRight");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("wm_topright", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("shapePixmapBottomLeft");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("wm_bottomleft", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("shapePixmapBottomRight");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("wm_bottomright", tmpStr, KConfig::Normal|KConfig::Global);


    input.setGroup("Window Titlebar");
    output->writeEntry("TitleAlignment", input.readEntry("TitleAlignment"), KConfig::Normal|KConfig::Global);
    output->writeEntry("PixmapUnderTitleText", input.readEntry("PixmapUnderTitleText"), KConfig::Normal|KConfig::Global);
    output->writeEntry("TitleFrameShaded", input.readEntry("TitleFrameShaded"), KConfig::Normal|KConfig::Global);

    tmpStr = input.readEntry("MenuButton");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("menu", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("PinUpButton");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("pinup", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("PinDownButton");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("pindown", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("CloseButton");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("close", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("MaximizeButton");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("maximize", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("MaximizeDownButton");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("maximizedown", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("MinimizeButton");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("iconify", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("TitlebarPixmapActive");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("TitlebarPixmapActive", tmpStr, KConfig::Normal|KConfig::Global);
    tmpStr = input.readEntry("TitlebarPixmapInactive");
    if(!tmpStr.isEmpty())
        copy(srcStr+tmpStr, localDirStr+tmpStr);
    output->writeEntry("TitlebarPixmapInactive", tmpStr, KConfig::Normal|KConfig::Global);

    input.setGroup("Window Button Layout");
    output->setGroup("Buttons");
    output->writeEntry("ButtonA", input.readEntry("ButtonA"), KConfig::Normal|KConfig::Global);
    output->writeEntry("ButtonB", input.readEntry("ButtonB"), KConfig::Normal|KConfig::Global);
    output->writeEntry("ButtonC", input.readEntry("ButtonC"), KConfig::Normal|KConfig::Global);
    output->writeEntry("ButtonD", input.readEntry("ButtonD"), KConfig::Normal|KConfig::Global);
    output->writeEntry("ButtonE", input.readEntry("ButtonE"), KConfig::Normal|KConfig::Global);
    output->writeEntry("ButtonF", input.readEntry("ButtonF"), KConfig::Normal|KConfig::Global);

    output->sync();

    return(0);
}
Ejemplo n.º 29
0
int main(int argc, char **argv)
{
  KAboutData about("kgrapheditor", 0, ki18n("KGraphEditor"), version, ki18n(description),
                    KAboutData::License_GPL, ki18n("(C) 2005-2010 Gaël de Chalendar"), KLocalizedString(), 0, "*****@*****.**");
  about.addAuthor( ki18n("Gaël de Chalendar"), KLocalizedString(), "*****@*****.**" );
  KCmdLineArgs::init(argc, argv, &about);

  KCmdLineOptions options;
  options.add("+[URL]", ki18n( "Dot graph to open" ));
  KCmdLineArgs::addCmdLineOptions( options );
  KApplication app;
  
// see if we are starting with session management
  if (app.isSessionRestored())
  {
      RESTORE(KGraphEditor);
  }
  else
  {
      // no session.. just start up normally
      KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

      KGraphEditor *widget = 0;
      if ( args->count() == 0 )
      {
        widget = new KGraphEditor;
        new KgrapheditorAdaptor(widget);
        QDBusConnection::sessionBus().registerObject("/KGraphEditor", widget);
        widget->show();
      }
      else
      {
        QDBusReply<bool> reply = QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.kgrapheditor" );
      
        bool instanceExists = reply.value();
  
        for (int i = 0; i < args->count(); i++ )
        {
          if (instanceExists 
              && (KMessageBox::questionYesNo(0, 
                                         i18n("A KGraphEditor window is already open, where do you want to open this file?"),
                                         i18n("Opening in new window confirmation"),
                                             KGuiItem(i18nc("Where to open a file", "Existing window")),
                                             KGuiItem(i18nc("Where to open a file", "New window")),
                                             "openInNewWindowMode"   ) == KMessageBox::Yes) )
          {
            QByteArray tosenddata;
            QDataStream arg(&tosenddata, QIODevice::WriteOnly);
            QString strarg = args->arg(i);
            KUrl url;
            if (strarg.left(1) == "/")
              url = KUrl(strarg);
            else url = KUrl(QDir::currentPath() + '/' + strarg);
            arg << url;
            QDBusInterface iface("org.kde.kgrapheditor", "/KGraphEditor", "", QDBusConnection::sessionBus());
            if (iface.isValid()) 
            {
              QDBusReply<void> reply = iface.call("openUrl", url.pathOrUrl());
              if (reply.isValid()) 
              {
                kDebug() << "Reply was valid" << endl;
                return 0;
              }

              kError() << "Call failed: " << reply.error().message() << endl;
              return 1;
            }
            kError() << "Invalid interface" << endl;
            exit(0);
          }
          else
          {
            widget = new KGraphEditor;
            new KgrapheditorAdaptor(widget);
            QDBusConnection::sessionBus().registerObject("/KGraphEditor", widget);
            widget->show();
            widget->openUrl( args->url( i ) );
          }
        }
      }
      args->clear();
    if (widget != 0)
    {
      widget->  reloadPreviousFiles();
    }
    
  }
  return app.exec();
}
Ejemplo n.º 30
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);
}