コード例 #1
0
ファイル: ItemHandle_nix.cpp プロジェクト: aszlig/Desurium
inline gcString createDesktopFile(ItemInfoI* i)
{
	// KDE menu doesn't accept files like "Publisher Name-GameName.desktop" so we replace all " " with "_"
	gcString publisher = boost::algorithm::replace_all_copy(std::string(i->getPublisher()), " ", "_");

	gcString tmpPath("{0}/{1}-{2}.desktop",
	                 UTIL::OS::getCachePath(),
	                 publisher,
	                 i->getShortName());

	std::ofstream desktopFile(tmpPath);
	desktopFile << "[Desktop Entry]"
	            << "\nType=Application"
	            << "\nName=" << i->getName()
	            << "\nComment=" << i->getDesc()
	            << "\nIcon=" << i->getIcon()
	            << "\nTryExec=" << i->getActiveExe()->getExe()
	            << "\nExec=" << i->getActiveExe()->getExe() << ' '
	                         << i->getActiveExe()->getExeArgs()
	            << "\nCategories=Game;" << i->getGenre() << ';'
	            << std::endl;
	desktopFile.close();

	return tmpPath;
}
コード例 #2
0
void LauncherApplet::slotRemove()
{
    host()->detach(this);
    
    QFile desktopFile(_url.path());
    desktopFile.remove();
    
    delete this;
}
コード例 #3
0
ファイル: wallpaper.cpp プロジェクト: Tayyib/uludag
Wallpaper::Wallpaper( QWidget *parent, const char* name )
    : WallpaperDlg( parent, name )
{
    changePaper = true;
    selectedPaper = "";

    QStringList lst = KGlobal::dirs()->findAllResources("wallpaper", "*.desktop", false /* no recursion */, true /* unique files */ );
    QString line,lname,lang,langCode;

    // FIXME: What about other languages?
    lang = QString(getenv("LC_ALL"));
    if (lang == "tr_TR.UTF-8")
        langCode="Name[tr]";
    else
        langCode="Name";

    for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it)
    {
        if(!(*it).endsWith(".svgz.desktop"))
        {
                QFile desktopFile(*it);
                QTextStream stream(&desktopFile);
                desktopFile.open(IO_ReadOnly);

                bool foundName = false;
                while(!foundName && (line = stream.readLine()))
                {
                    if (line.startsWith(langCode))
                    {
                        lname = line.section("=",1,1);
                        foundName=true;
                    }
                }
            papers.insert(lname, (*it).remove(".desktop"));
            desktopFile.close();
        }
    }

    QMap<QString, QString>::ConstIterator it = papers.begin();
    for(; it != papers.constEnd(); ++it)
        wallpaperBox->insertItem(it.key());

    connect(testButton, SIGNAL(clicked()), this , SLOT(testWallpaper()));
    connect(wallpaperBox, SIGNAL(activated(int)), this, SLOT(paperSelected(int)));
    connect(changeCheck, SIGNAL(toggled(bool)), this, SLOT(optionChanged(bool)));

    emit paperSelected(0);

    // Backup old walpaper name
    DCOPClient *client = kapp->dcopClient();
    QByteArray replyData;
    QCString replyType;

    client->call("kdesktop", "KBackgroundIface", "currentWallpaper(int)", 6, replyType, replyData);
    QDataStream reply(replyData, IO_ReadOnly);
    reply >> oldWallpaper;
}
コード例 #4
0
ファイル: touchpadconfig.cpp プロジェクト: lxde/lxqt-config
void TouchpadConfig::accept()
{
    for (const TouchpadDevice& device : devices)
    {
        device.saveSettings(settings);
    }

    LXQt::AutostartEntry autoStart("lxqt-config-touchpad-autostart.desktop");
    XdgDesktopFile desktopFile(XdgDesktopFile::ApplicationType, "lxqt-config-touchpad-autostart", "lxqt-config-input --load-touchpad");
    desktopFile.setValue("OnlyShowIn", "LXQt");
    desktopFile.setValue("Comment", "Autostart touchpad settings for lxqt-config-input");
    autoStart.setFile(desktopFile);
    autoStart.commit();
}
コード例 #5
0
void NotifierServiceAction::save() const
{
	QFile::remove( m_filePath );
	KDesktopFile desktopFile(m_filePath);

	desktopFile.setGroup(QString("Desktop Action ") + m_service.m_strName);
	desktopFile.writeEntry(QString("Icon"), m_service.m_strIcon);
	desktopFile.writeEntry(QString("Name"), m_service.m_strName);
	desktopFile.writeEntry(QString("Exec"), m_service.m_strExec);

	desktopFile.setDesktopGroup();

	desktopFile.writeEntry(QString("ServiceTypes"), m_mimetypes, ",");
	desktopFile.writeEntry(QString("Actions"),
	                       QStringList(m_service.m_strName),";");
}
コード例 #6
0
void KonqSidebarTree::addUrl(KonqSidebarTreeTopLevelItem* item, const KUrl & url)
{
    QString path;
    if (item)
        path = item->path();
    else
        path = m_dirtreeDir.dir.path();

    KUrl destUrl;

    if (url.isLocalFile() && url.fileName().endsWith(".desktop"))
    {
        QString filename = findUniqueFilename(path, url.fileName());
        destUrl.setPath(filename);
        KIO::NetAccess::file_copy(url, destUrl, this);
    }
    else
    {
        QString name = url.host();
        if (name.isEmpty())
            name = url.fileName();
        QString filename = findUniqueFilename(path, name);
        destUrl.setPath(filename);

        KDesktopFile desktopFile(filename);
        KConfigGroup cfg = desktopFile.desktopGroup();
        cfg.writeEntry("Encoding", "UTF-8");
        cfg.writeEntry("Type","Link");
        cfg.writeEntry("URL", url.url());
        QString icon = "folder";
        if (!url.isLocalFile())
            icon = KMimeType::favIconForUrl(url);
        if (icon.isEmpty())
            icon = KProtocolInfo::icon( url.protocol() );
        cfg.writeEntry("Icon", icon);
        cfg.writeEntry("Name", name);
        cfg.writeEntry("Open", false);
        cfg.sync();
    }

    destUrl.setPath( destUrl.directory() );
    OrgKdeKDirNotifyInterface::emitFilesAdded( destUrl.url() );

    if (item)
        item->setOpen(true);
}
コード例 #7
0
KSycocaEntry* KBuildServiceTypeFactory::createEntry(const QString &file, const char *resource) const
{
    QString name = file;
    int pos = name.lastIndexOf('/');
    if (pos != -1) {
        name = name.mid(pos+1);
    }

    if (name.isEmpty())
        return 0;

    KDesktopFile desktopFile(resource, file);
    const KConfigGroup desktopGroup = desktopFile.desktopGroup();

    if ( desktopGroup.readEntry( "Hidden", false ) == true )
        return 0;

    const QString type = desktopGroup.readEntry( "Type" );
    if ( type != QLatin1String( "ServiceType" ) ) {
        kWarning(7012) << "The service type config file " << desktopFile.fileName() << " has Type=" << type << " instead of Type=ServiceType";
        return 0;
    }

    const QString serviceType = desktopGroup.readEntry( "X-KDE-ServiceType" );

    if ( serviceType.isEmpty() ) {
        kWarning(7012) << "The service type config file " << desktopFile.fileName() << " does not contain a ServiceType=... entry";
        return 0;
    }

    KServiceType* e = new KServiceType( &desktopFile );

    if (e->isDeleted()) {
        delete e;
        return 0;
    }

    if ( !(e->isValid()) ) {
        kWarning(7012) << "Invalid ServiceType : " << file;
        delete e;
        return 0;
    }

    return e;
}
コード例 #8
0
ファイル: main.cpp プロジェクト: amoskvin/qcategorizedview
    ConfigPaneModel(): QAbstractListModel()
    {
        if (preferredCategoryOrder.isEmpty())
            preferredCategoryOrder << "Personal" << "Hardware" << "System";

        QDir dir(qApp->applicationDirPath() + "/items/");
        Q_FOREACH (const QFileInfo &fileInfo, dir.entryInfoList(QStringList() << "*.desktop"))
        {
            QSettings desktopFile(fileInfo.filePath(), QSettings::IniFormat);
            desktopFile.beginGroup("Desktop Entry");

            ConfigPane pane;
            pane.id() = desktopFile.value("Icon").toString();
            pane.name() = desktopFile.value("Name").toString();
            pane.category() = desktopFile.value("Category").toString();
            m_list.append(pane);
        }

        qSort(m_list.begin(), m_list.end(), categorySorter);
    }
コード例 #9
0
void DesktopFile::load()
{
    if (m_path == "") {
        m_name = "";
        m_exec = "";
        m_comment = "";
        m_darkColor = "";
        m_iconName = "";
    } else {
        QSettings desktopFile(m_path, QSettings::IniFormat);
        desktopFile.setIniCodec("UTF-8");
        desktopFile.beginGroup("Desktop Entry");

        m_name = localizedValue(desktopFile, "Name").toString();
        m_exec = desktopFile.value("Exec").toString();
        m_comment = localizedValue(desktopFile, "Comment").toString();
        m_darkColor = desktopFile.value("X-Papyros-DarkColor").toString();
        m_iconName = desktopFile.value("Icon").toString();
    }

    emit dataChanged();
}
コード例 #10
0
void DolphinViewContainer::slotItemTriggered(const KFileItem& item)
{
    KUrl url = item.targetUrl();

    if (item.isDir()) {
        m_view->setUrl(url);
        return;
    }

    const GeneralSettings* settings = DolphinSettings::instance().generalSettings();
    const bool browseThroughArchives = settings->browseThroughArchives();
    if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
        // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
        // zip:/<path>/ when clicking on a zip file, etc.
        // The .protocol file specifies the mimetype that the kioslave handles.
        // Note that we don't use mimetype inheritance since we don't want to
        // open OpenDocument files as zip folders...
        const QString protocol = KProtocolManager::protocolForArchiveMimetype(item.mimetype());
        if (!protocol.isEmpty()) {
            url.setProtocol(protocol);
            m_view->setUrl(url);
            return;
        }
    }

    if (item.mimetype() == "application/x-desktop") {
        // redirect to the url in Type=Link desktop files
        KDesktopFile desktopFile(url.toLocalFile());
        if (desktopFile.hasLinkType()) {
            url = desktopFile.readUrl();
            m_view->setUrl(url);
            return;
        }
    }

    item.run();
}
コード例 #11
0
ファイル: knewfilemenu.cpp プロジェクト: vasi/kdelibs
void KNewFileMenuSingleton::parseFiles()
{
    //kDebug(1203);
    filesParsed = true;
    KNewFileMenuSingleton::EntryList::iterator templ = templatesList->begin();
    const KNewFileMenuSingleton::EntryList::iterator templ_end = templatesList->end();
    for (; templ != templ_end; ++templ)
    {
        QString iconname;
        QString filePath = (*templ).filePath;
        if (!filePath.isEmpty())
        {
            QString text;
            QString templatePath;
            // If a desktop file, then read the name from it.
            // Otherwise (or if no name in it?) use file name
            if (KDesktopFile::isDesktopFile(filePath)) {
                KDesktopFile desktopFile( filePath);
                text = desktopFile.readName();
                (*templ).icon = desktopFile.readIcon();
                (*templ).comment = desktopFile.readComment();
                QString type = desktopFile.readType();
                if (type == "Link")
                {
                    templatePath = desktopFile.desktopGroup().readPathEntry("URL", QString());
                    if (templatePath[0] != '/' && !templatePath.startsWith("__"))
                    {
                        if (templatePath.startsWith("file:/"))
                            templatePath = KUrl(templatePath).toLocalFile();
                        else
                        {
                            // A relative path, then (that's the default in the files we ship)
                            QString linkDir = filePath.left(filePath.lastIndexOf('/') + 1 /*keep / */);
                            //kDebug(1203) << "linkDir=" << linkDir;
                            templatePath = linkDir + templatePath;
                        }
                    }
                }
                if (templatePath.isEmpty())
                {
                    // No URL key, this is an old-style template
                    (*templ).entryType = KNewFileMenuSingleton::Template;
                    (*templ).templatePath = (*templ).filePath; // we'll copy the file
                } else {
                    (*templ).entryType = KNewFileMenuSingleton::LinkToTemplate;
                    (*templ).templatePath = templatePath;
                }

            }
            if (text.isEmpty())
            {
                text = KUrl(filePath).fileName();
                if (text.endsWith(".desktop"))
                    text.truncate(text.length() - 8);
            }
            (*templ).text = text;
            /*kDebug(1203) << "Updating entry with text=" << text
                          << "entryType=" << (*templ).entryType
                          << "templatePath=" << (*templ).templatePath;*/
        }
        else {
            (*templ).entryType = KNewFileMenuSingleton::Separator;
        }
    }
}
コード例 #12
0
ファイル: knetattach.cpp プロジェクト: cmacq2/plasma-desktop
bool KNetAttach::validateCurrentPage()
{
    if (currentPage() == _folderType){
	_host->setFocus();
	_connectionName->setFocus();

	if (_webfolder->isChecked()) {
	    setInformationText("WebFolder");
	    updateForProtocol("WebFolder");
	    _port->setValue(80);
	} else if (_fish->isChecked()) {
	    setInformationText("Fish");
	    updateForProtocol("Fish");
	    _port->setValue(22);
	} else if (_ftp->isChecked()) {
	    setInformationText("FTP");
	    updateForProtocol("FTP");
	    _port->setValue(21);
	    if (_path->text().isEmpty()) {
		_path->setText("/");
	    }
	} else if (_smb->isChecked()) {
	    setInformationText("SMB");
	    updateForProtocol("SMB");
	} else { //if (_recent->isChecked()) {
	    KConfig recent( "krecentconnections", KConfig::NoGlobals );
	    if (!recent.hasGroup(_recentConnectionName->currentText())) {
		KConfigGroup group = recent.group("General");
		QStringList idx = group.readEntry("Index",QStringList());
		if (idx.isEmpty()) {
		    _recent->setEnabled(false);
		    if (_recent->isChecked()) {
			_webfolder->setChecked(true);
		    }
		} else {
		    _recent->setEnabled(true);
		    _recentConnectionName->addItems(idx);
		}
		return false;
	    }
	    KConfigGroup group = recent.group(_recentConnectionName->currentText());
	    _type = group.readEntry("Type");
	    setInformationText(_type);
	    if (!updateForProtocol(_type)) {
		// FIXME: handle error
	    }
	    KUrl u(group.readEntry("URL"));
	    _host->setText(u.host());
	    _user->setText(u.user());
	    _path->setText(u.path());
	    if (group.hasKey("Port")) {
		_port->setValue(group.readEntry("Port",0));
	    } else {
		_port->setValue(u.port());
	    }
	    _connectionName->setText(_recentConnectionName->currentText());
	    _createIcon->setChecked(false);
	}
	updateParametersPageStatus();

    }else{
      button(BackButton)->setEnabled(false);
      button(FinishButton)->setEnabled(false);
      KUrl url;
      if (_type == "WebFolder") {
	  if (_useEncryption->isChecked()) {
	      url.setProtocol("webdavs");
	  } else {
	      url.setProtocol("webdav");
	  }
	  url.setPort(_port->value());
      } else if (_type == "Fish") {
      KConfig config("kio_fishrc");
      KConfigGroup cg(&config, _host->text().trimmed());
      cg.writeEntry("Charset", KCharsets::charsets()->encodingForName(_encoding->currentText()));
	  url.setProtocol(_protocolText->currentText());
	  url.setPort(_port->value());
      } else if (_type == "FTP") {
	  url.setProtocol("ftp");
	  url.setPort(_port->value());
      KConfig config("kio_ftprc");
      KConfigGroup cg(&config, _host->text().trimmed());
      cg.writeEntry("Charset", KCharsets::charsets()->encodingForName(_encoding->currentText()));
      config.sync();
      } else if (_type == "SMB") {
	  url.setProtocol("smb");
      } else { // recent
      }

      url.setHost(_host->text().trimmed());
      url.setUser(_user->text().trimmed());
      QString path = _path->text().trimmed();
  #ifndef Q_WS_WIN
      // could a relative path really be made absolute by simply prepending a '/' ?
      if (!path.startsWith('/')) {
	  path = QString("/") + path;
      }
  #endif
      url.setPath(path);
    _folderParameters->setEnabled(false);
      bool success = doConnectionTest(url);
    _folderParameters->setEnabled(true);
      if (!success) {
	  KMessageBox::sorry(this, i18n("Unable to connect to server.  Please check your settings and try again."));
	  button(BackButton)->setEnabled(true);
	  return false;
      }

      KRun::runUrl(url, "inode/directory", this);

      QString name = _connectionName->text().trimmed();

      if (_createIcon->isChecked()) {
	  KGlobal::dirs()->addResourceType("remote_entries", "data", "remoteview");

	  QString path = KGlobal::dirs()->saveLocation("remote_entries");
	  path += name + ".desktop";
	  KConfig _desktopFile( path, KConfig::SimpleConfig );
	  KConfigGroup desktopFile(&_desktopFile, "Desktop Entry");
	  desktopFile.writeEntry("Icon", "folder-remote");
	  desktopFile.writeEntry("Name", name);
	  desktopFile.writeEntry("Type", "Link");
	  desktopFile.writeEntry("URL", url.prettyUrl());
      desktopFile.writeEntry("Charset", url.fileEncoding());
	  desktopFile.sync();
	  org::kde::KDirNotify::emitFilesAdded( QUrl("remote:/") );
      }

      if (!name.isEmpty()) {
	  KConfig _recent("krecentconnections", KConfig::NoGlobals);
	  KConfigGroup recent(&_recent, "General");
	  QStringList idx = recent.readEntry("Index",QStringList());
	  _recent.deleteGroup(name); // erase anything stale
	  if (idx.contains(name)) {
	      idx.removeAll(name);
	      idx.prepend(name);
	      recent.writeEntry("Index", idx);
	  } else {
	      QString last;
	      if (!idx.isEmpty()) {
		  last = idx.last();
		  idx.pop_back();
	      }
	      idx.prepend(name);
	      _recent.deleteGroup(last);
	      recent.writeEntry("Index", idx);
	  }
	recent = KConfigGroup(&_recent,name);
	  recent.writeEntry("URL", url.prettyUrl());
	  if (_type == "WebFolder" || _type == "Fish" || _type == "FTP") {
	      recent.writeEntry("Port", _port->value());
	  }
	  recent.writeEntry("Type", _type);
	  recent.sync();
      }
    }
    return true;
}
コード例 #13
0
void KonqOperations::asyncDrop( const KFileItem & destItem )
{
    assert(m_info); // setDropInfo should have been called before asyncDrop
    bool m_destIsLocal = false;
    m_destUrl = destItem.mostLocalUrl(m_destIsLocal); // #168154

    //kDebug(1203) << "destItem->mode=" << destItem->mode() << " url=" << m_destUrl;
    // Check what the destination is
    if ( destItem.isDir() )
    {
        doDropFileCopy();
        return;
    }
    if ( !m_destIsLocal )
    {
        // We dropped onto a remote URL that is not a directory!
        // (e.g. an HTTP link in the sidebar).
        // Can't do that, but we can't prevent it before stating the dest....
        kWarning(1203) << "Cannot drop onto " << m_destUrl ;
        deleteLater();
        return;
    }
    if ( destItem.isDesktopFile() )
    {
        // Local .desktop file. What type ?
        KDesktopFile desktopFile( m_destUrl.path() );
        KConfigGroup desktopGroup = desktopFile.desktopGroup();
        if ( desktopFile.hasApplicationType() )
        {
            QString error;
            const QStringList urlStrList = m_info->urls.toStringList();
            if ( KToolInvocation::startServiceByDesktopPath( m_destUrl.path(), urlStrList, &error ) > 0 )
                KMessageBox::error( parentWidget(), error );
        }
        else
        {
            // Device or Link -> adjust dest
            if ( desktopFile.hasDeviceType() && desktopGroup.hasKey("MountPoint") ) {
                QString point = desktopGroup.readEntry( "MountPoint" );
                m_destUrl.setPath( point );
                QString dev = desktopFile.readDevice();
                KMountPoint::Ptr mp = KMountPoint::currentMountPoints().findByDevice( dev );
                // Is the device already mounted ?
                if ( mp ) {
                    doDropFileCopy();
                }
                else
                {
                    const bool ro = desktopGroup.readEntry( "ReadOnly", false );
                    const QByteArray fstype = desktopGroup.readEntry( "FSType" ).toLatin1();
                    KAutoMount* am = new KAutoMount( ro, fstype, dev, point, m_destUrl.path(), false );
                    connect( am, SIGNAL(finished()), this, SLOT(doDropFileCopy()) );
                }
                return;
            }
            else if ( desktopFile.hasLinkType() && desktopGroup.hasKey("URL") ) {
                m_destUrl = desktopGroup.readPathEntry("URL", QString());
                doDropFileCopy();
                return;
            }
            // else, well: mimetype, service, servicetype or .directory. Can't really drop anything on those.
        }
    }
    else
    {
        // Should be a local executable
        // (If this fails, there is a bug in KFileItem::acceptsDrops / KDirModel::flags)
        kDebug(1203) << m_destUrl.path() << "should be an executable";
        Q_ASSERT ( access( QFile::encodeName(m_destUrl.path()), X_OK ) == 0 );
        // Launch executable for each of the files
        QStringList args;
        const KUrl::List lst = m_info->urls;
        KUrl::List::ConstIterator it = lst.begin();
        for ( ; it != lst.end() ; it++ )
            args << (*it).path(); // assume local files
        kDebug(1203) << "starting " << m_destUrl.path() << " with " << lst.count() << " arguments";
        QProcess::startDetached( m_destUrl.path(), args );
    }
    deleteLater();
}
コード例 #14
0
void Launcher::dropUrls(const KUrl::List &urls, Qt::KeyboardModifiers modifiers)
{
    if (m_serviceGroup || !urls.count())
    {
        return;
    }

    if (m_mimeType->is("inode/directory"))
    {
        Qt::DropAction dropAction = Qt::CopyAction;

        if ((modifiers & Qt::ShiftModifier && modifiers & Qt::ControlModifier) || modifiers & Qt::AltModifier)
        {
            dropAction = Qt::LinkAction;
        }
        else if (modifiers & Qt::ShiftModifier)
        {
            dropAction = Qt::MoveAction;
        }
        else if (modifiers & Qt::ControlModifier)
        {
            dropAction = Qt::CopyAction;
        }
        else
        {
            KMenu *menu = new KMenu;
            QAction *moveAction = menu->addAction(KIcon("go-jump"), i18nc("@action:inmenu", "&Move Here\t<shortcut>%1</shortcut>", QKeySequence(Qt::ShiftModifier).toString()));
            QAction *copyAction = menu->addAction(KIcon("edit-copy"), i18nc("@action:inmenu", "&Copy Here\t<shortcut>%1</shortcut>", QKeySequence(Qt::ControlModifier).toString()));
            QAction *linkAction = menu->addAction(KIcon("insert-link"), i18nc("@action:inmenu", "&Link Here\t<shortcut>%1</shortcut>", QKeySequence(Qt::ControlModifier + Qt::ShiftModifier).toString()));

            menu->addSeparator();
            menu->addAction(KIcon("process-stop"), i18nc("@action:inmenu", "Cancel"));

            QAction *activatedAction = menu->exec(QCursor::pos());

            delete menu;

            if (activatedAction == moveAction)
            {
                dropAction = Qt::MoveAction;
            }
            else if (activatedAction == copyAction)
            {
                dropAction = Qt::CopyAction;
            }
            else if (activatedAction == linkAction)
            {
                dropAction = Qt::LinkAction;
            }
            else
            {
                return;
            }
        }

        switch (dropAction)
        {
            case Qt::MoveAction:
                KIO::move(urls, m_targetUrl);

                break;
            case Qt::CopyAction:
                KIO::copy(urls, m_targetUrl);

                break;
            case Qt::LinkAction:
                KIO::link(urls, m_targetUrl);

                break;
            default:
                return;
        }
    }
    else if (m_isExecutable)
    {
        QString arguments;
        QString command;

        for (int i = 0; i < urls.count(); ++i)
        {
            arguments += ' ' + KShell::quoteArg(urls[i].isLocalFile()?urls[i].path():urls[i].prettyUrl());
        }

        if (KDesktopFile::isDesktopFile(m_launcherUrl.toLocalFile()))
        {
            KDesktopFile desktopFile(m_launcherUrl.toLocalFile());
            KConfigGroup config = desktopFile.desktopGroup();

            command = config.readPathEntry("Exec", QString());

            if (command.isEmpty())
            {
                command = KShell::quoteArg(m_launcherUrl.path());
            }
        }
        else
        {
            command = KShell::quoteArg(m_launcherUrl.path());
        }

        KRun::runCommand(command + ' ' + arguments, NULL);
    }
}
コード例 #15
0
ファイル: installwindow.cpp プロジェクト: divan/wgames
//
// Step 6
// Extract icon and create .desktop files
//
bool InstallWindow::Step6CreateShortcuts()
{
    PrintStep(tr("Prepare desktop shortcut"));

    QDir desktopDir(DESKTOP_ENTRY_PATH),
            iconDir(ICONS_PATH),
            dbusDir(DBUS_PATH);

    if (!desktopDir.exists())
    {
        if (!desktopDir.mkpath(DESKTOP_ENTRY_PATH))
            return Failed(tr("Cannot create directory %1")
                       .arg(desktopDir.path()));

    }

    if (!iconDir.exists())
    {
        if (!iconDir.mkpath(ICONS_PATH))
            return Failed(tr("Cannot create directory %1")
                       .arg(iconDir.path()));
    }
    if (!dbusDir.exists())
    {
        if (!dbusDir.mkpath(DBUS_PATH))
            return Failed(tr("Cannot create directory %1")
                       .arg(dbusDir.path()));
    }

    // Icon path
    QString fullDataDir(_game->DataPath() +
                        "/usr/palm/applications/" +
                        _game->JsonID() + "/");
    QFile iconFile(fullDataDir + _game->JsonIcon());
    QString saneName =_game->JsonTitle().toLower();
    QString newName(QString(ICONS_PATH) +
                    QString("/") +
                    saneName + ".png");
    if (iconFile.exists() && !QFile::exists(newName))
    {
            if (!iconFile.copy(newName))
            {
                return Failed(tr("Cannot copy icon ") +
                              iconFile.fileName() +
                              "to " + ICONS_PATH + "/" + saneName + ".png");
            }
    }


    QString desktopEntry  =
            "[Desktop Entry]\n"
            "Encoding=UTF-8\n"
            "Version=1.0\n"
            "Type=Application\n"
            "Name=" + _game->JsonTitle() + "\n"
            "Exec=" + _game->Exec() + "\n"
            "X-Osso-Type=application/x-executable\n"
            "X-Osso-Service=" + _game->DBusName() + "\n"
            "X-Preenv-Generated=true\n"
            "X-Preenv-Vendor=" + _game->JsonVendor() + "\n"
            "X-Maemo-Category=Games\n"
            "Icon=" + saneName + "\n";

    QFile desktopFile(QString(DESKTOP_ENTRY_PATH) + QString("/") +
                      saneName  + ".desktop");
    if (!desktopFile.open(QFile::WriteOnly | QFile::Text))
        return Failed(tr("Cannot create .desktop file ") +
                   desktopFile.fileName());
    desktopFile.write(desktopEntry.toLocal8Bit());
    desktopFile.close();

    QString dbusEntry =
            "[D-BUS Service]\n"
            "Name=" + _game->DBusName() + "\n"
            "Exec=" + _game->Exec() + "\n";

    QFile dbusFile(QString(DBUS_PATH) + QString("/")
                   + saneName  + ".service");
    if (!dbusFile.open(QFile::WriteOnly | QFile::Text))
        return Failed(tr("Cannot create DBUS .service file ") +
                      dbusFile.fileName());

    dbusFile.write(dbusEntry.toLocal8Bit());
    dbusFile.close();

    PrintOK();
    return Step7PostInstall();
}
コード例 #16
0
void KonqPopupMenuPrivate::init(KonqPopupMenu::Flags kpf, KParts::BrowserExtension::PopupFlags flags)
{
    m_itemFlags = flags;
    q->setFont(KGlobalSettings::menuFont());

    Q_ASSERT(m_popupItemProperties.items().count() >= 1);

    bool bTrashIncluded = false;

    const KFileItemList lstItems = m_popupItemProperties.items();
    KFileItemList::const_iterator it = lstItems.constBegin();
    const KFileItemList::const_iterator kend = lstItems.constEnd();
    for ( ; it != kend; ++it )
    {
        const KUrl url = (*it).url();
        if ( !bTrashIncluded && (
             ( url.protocol() == "trash" && url.path().length() <= 1 ) ) ) {
            bTrashIncluded = true;
        }
    }

    const bool isDirectory = m_popupItemProperties.isDirectory();
    const bool sReading = m_popupItemProperties.supportsReading();
    bool sDeleting = (m_itemFlags & KParts::BrowserExtension::NoDeletion) == 0
                     && m_popupItemProperties.supportsDeleting();
    const bool sWriting = m_popupItemProperties.supportsWriting();
    const bool sMoving = sDeleting && m_popupItemProperties.supportsMoving();
    const bool isLocal = m_popupItemProperties.isLocal();

    KUrl url = m_sViewURL;
    url.cleanPath();

    bool isTrashLink     = false;
    bool isCurrentTrash = false;
    bool currentDir     = false;
    bool isSymLink = false;
    bool isSymLinkInSameDir = false; // true for "ln -s foo bar", false for links to foo/sub or /foo

    //check if url is current directory
    if ( lstItems.count() == 1 )
    {
        KFileItem firstPopupItem( lstItems.first() );
        if (firstPopupItem.isLink()) {
            isSymLink = true;
            isSymLinkInSameDir = !firstPopupItem.linkDest().contains('/');
        }
        KUrl firstPopupURL( firstPopupItem.url() );
        firstPopupURL.cleanPath();
        //kDebug(1203) << "View path is " << url.url();
        //kDebug(1203) << "First popup path is " << firstPopupURL.url();
        currentDir = firstPopupURL.equals( url, KUrl::CompareWithoutTrailingSlash );
        if ( firstPopupItem.isDesktopFile() ) {
            KDesktopFile desktopFile( firstPopupItem.localPath() );
            const KConfigGroup cfg = desktopFile.desktopGroup();
            isTrashLink = ( cfg.readEntry("Type") == "Link" && cfg.readEntry("URL") == "trash:/" );
        }

        if (isTrashLink) {
            sDeleting = false;
        }

        // isCurrentTrash: popup on trash:/ itself, or on the trash.desktop link
        isCurrentTrash = (firstPopupURL.protocol() == "trash" && firstPopupURL.path().length() <= 1)
                         || isTrashLink;
    }

    const bool isIntoTrash = (url.protocol() == "trash") && !isCurrentTrash; // trashed file, not trash:/ itself

    const bool bIsLink  = (m_itemFlags & KParts::BrowserExtension::IsLink);

    //kDebug() << "isLocal=" << isLocal << " url=" << url << " isCurrentTrash=" << isCurrentTrash << " isIntoTrash=" << isIntoTrash << " bTrashIncluded=" << bTrashIncluded;

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

    addGroup( "topactions" ); // used e.g. for ShowMenuBar. includes a separator at the end

    KAction * act;

    KAction *actNewWindow = 0;

#if 0 // TODO in the desktop code itself.
    if (( flags & KParts::BrowserExtension::ShowProperties ) && isOnDesktop &&
        !KAuthorized::authorizeKAction("editable_desktop_icons"))
    {
        flags &= ~KParts::BrowserExtension::ShowProperties; // remove flag
    }
#endif

    // Either 'newview' is in the actions we're given (probably in the tabhandling group)
    // or we need to insert it ourselves (e.g. for the desktop).
    // In the first case, actNewWindow must remain 0.
    if ( ((kpf & KonqPopupMenu::ShowNewWindow) != 0) && sReading )
    {
        const QString openStr = i18n("&Open");
        actNewWindow = new KAction(m_parentWidget /*for status tips*/);
        m_ownActions.append(actNewWindow);
        actNewWindow->setIcon( KIcon("window-new") );
        actNewWindow->setText( openStr );
        QObject::connect(actNewWindow, SIGNAL(triggered()), q, SLOT(slotPopupNewView()));
    }

    if ( isDirectory && sWriting && !isCurrentTrash ) // A dir, and we can create things into it
    {
        const bool mkdirRequested = m_itemFlags & KParts::BrowserExtension::ShowCreateDirectory;
        if ( (currentDir || mkdirRequested) && m_pMenuNew ) // Current dir -> add the "new" menu
        {
            // As requested by KNewFileMenu :
            m_pMenuNew->checkUpToDate();
            m_pMenuNew->setPopupFiles(m_popupItemProperties.urlList());

            q->addAction( m_pMenuNew );
            q->addSeparator();
        }
        else if (mkdirRequested)
        {
            KAction *actNewDir = new KAction(m_parentWidget);
            m_ownActions.append(actNewDir);
            actNewDir->setIcon( KIcon("folder-new") );
            actNewDir->setText( i18n( "Create &Folder..." ) );
            QObject::connect(actNewDir, SIGNAL(triggered()), q, SLOT(slotPopupNewDir()));
            q->addAction( actNewDir );
            q->addSeparator();
        }
    } else if ( isIntoTrash ) {
        // Trashed item, offer restoring
        act = new KAction(m_parentWidget /*for status tips*/);
        m_ownActions.append(act);
        act->setText( i18n( "&Restore" ) );
        act->setHelpText(i18n("Restores this file or directory, back to the location where it was deleted from initially"));
        QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotPopupRestoreTrashedItems()));
        q->addAction(act);
    }

    if (m_itemFlags & KParts::BrowserExtension::ShowNavigationItems)
    {
        if (m_itemFlags & KParts::BrowserExtension::ShowUp)
            addNamedAction( "go_up" );
        addNamedAction( "go_back" );
        addNamedAction( "go_forward" );
        if (m_itemFlags & KParts::BrowserExtension::ShowReload)
            addNamedAction( "reload" );
        q->addSeparator();
    }

    if (!currentDir && isSymLink && !isSymLinkInSameDir) {
        // #65151: offer to open the target's parent dir
        act = new KAction(m_parentWidget);
        m_ownActions.append(act);
        act->setText(isDirectory ? i18n("Show Original Directory") : i18n("Show Original File"));
        act->setHelpText(i18n("Opens a new file manager window showing the target of this link, in its parent directory."));
        QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotShowOriginalFile()));
        q->addAction(act);
    }

    // "open in new window" is either provided by us, or by the tabhandling group
    if (actNewWindow) {
        q->addAction(actNewWindow);
        q->addSeparator();
    }
    addGroup( "tabhandling" ); // includes a separator at the end

    if (m_itemFlags & KParts::BrowserExtension::ShowUrlOperations) {
        if ( !currentDir && sReading ) {
            if ( sDeleting ) {
                addNamedAction( "cut" );
            }
            addNamedAction( "copy" );
        }

        if ( isDirectory && sWriting ) {
            if ( currentDir )
                addNamedAction( "paste" );
            else
                addNamedAction( "pasteto" );
        }
    }
    if ( isCurrentTrash )
    {
        act = new KAction(m_parentWidget);
        m_ownActions.append(act);
        act->setIcon( KIcon("trash-empty") );
        act->setText( i18n( "&Empty Trash Bin" ) );
        KConfig trashConfig( "trashrc", KConfig::SimpleConfig);
        act->setEnabled( !trashConfig.group("Status").readEntry( "Empty", true ) );
        QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotPopupEmptyTrashBin()));
        q->addAction(act);
    }
    if ( isCurrentTrash )
    {
	act = new KAction(m_parentWidget);
	m_ownActions.append(act);
	act->setIcon( KIcon("trash-empty") );
	act->setText( i18n( "&Configure Trash Bin" ) );
	QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotConfigTrashBin()));
	q->addAction(act);
    }

    // This is used by KHTML, see khtml_popupmenu.rc (copy, selectAll, searchProvider etc.)
    // and by DolphinPart (rename, trash, delete)
    addGroup( "editactions" );

    if (m_itemFlags & KParts::BrowserExtension::ShowTextSelectionItems) {
        // OK, we have to stop here.

        // Anything else that is provided by the part
        addGroup( "partactions" );
        return;
    }

    if ( !isCurrentTrash && !isIntoTrash && (m_itemFlags & KParts::BrowserExtension::ShowBookmark))
    {
        QString caption;
        if (currentDir)
        {
           const bool httpPage = m_sViewURL.protocol().startsWith("http", Qt::CaseInsensitive);
           if (httpPage)
              caption = i18n("&Bookmark This Page");
           else
              caption = i18n("&Bookmark This Location");
        }
        else if (isDirectory)
           caption = i18n("&Bookmark This Folder");
        else if (bIsLink)
           caption = i18n("&Bookmark This Link");
        else
           caption = i18n("&Bookmark This File");

        act = new KAction(m_parentWidget);
        m_ownActions.append(act);
        act->setObjectName( QLatin1String("bookmark_add" )); // for unittest
        act->setIcon( KIcon("bookmark-new") );
        act->setText( caption );
        QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotPopupAddToBookmark()));
        if (lstItems.count() > 1)
            act->setEnabled(false);
        if (KAuthorized::authorizeKAction("bookmarks"))
            q->addAction( act );
        if (bIsLink)
            addGroup( "linkactions" ); // see khtml
    }

    // "Open With" actions

    m_menuActions.setItemListProperties(m_popupItemProperties);

    if ( sReading ) {
        m_menuActions.addOpenWithActionsTo(q, "DesktopEntryName != 'kfmclient' and DesktopEntryName != 'kfmclient_dir' and DesktopEntryName != 'kfmclient_html'");

        QList<QAction *> previewActions = m_actionGroups.value("preview");
        if (!previewActions.isEmpty()) {
            if (previewActions.count() == 1) {
                q->addAction(previewActions.first());
            } else {
                QMenu* subMenu = new QMenu(i18n("Preview In"), q);
                subMenu->menuAction()->setObjectName( QLatin1String("preview_submenu" )); // for the unittest
                q->addMenu(subMenu);
                subMenu->addActions(previewActions);
            }
        }
    }

    // Second block, builtin + user
    m_menuActions.addServiceActionsTo(q);

    q->addSeparator();

    // Use the Dolphin setting for showing the "Copy To" and "Move To" actions
    KSharedConfig::Ptr dolphin = KSharedConfig::openConfig("dolphinrc");

    // CopyTo/MoveTo menus
    if (m_itemFlags & KParts::BrowserExtension::ShowUrlOperations &&
        KConfigGroup(dolphin, "General").readEntry("ShowCopyMoveMenu", false)) {

        m_copyToMenu.setItems(lstItems);
        m_copyToMenu.setReadOnly(sMoving == false);
        m_copyToMenu.addActionsTo(q);
        q->addSeparator();
    }

    if (!isCurrentTrash && !isIntoTrash && sReading &&
        (kpf & KonqPopupMenu::NoPlugins) == 0) {
        addPlugins(); // now it's time to add plugins
    }

    if ( (m_itemFlags & KParts::BrowserExtension::ShowProperties) && KPropertiesDialog::canDisplay( lstItems ) ) {
        act = new KAction(m_parentWidget);
        m_ownActions.append(act);
        act->setObjectName( QLatin1String("properties" )); // for unittest
        act->setText( i18n( "&Properties" ) );
        QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotPopupProperties()));
        q->addAction(act);
    }

    while ( !q->actions().isEmpty() &&
            q->actions().last()->isSeparator() )
        delete q->actions().last();

    if ( isDirectory && isLocal ) {
        if ( KFileShare::authorization() == KFileShare::Authorized ) {
            q->addSeparator();
            act = new KAction(m_parentWidget);
            m_ownActions.append(act);
            act->setText( i18n("Share") );
            QObject::connect(act, SIGNAL(triggered()), q, SLOT(slotOpenShareFileDialog()));
            q->addAction(act);
        }
    }

    // Anything else that is provided by the part
    addGroup( "partactions" );
}
コード例 #17
0
ファイル: utility.cpp プロジェクト: Sc1ence/mirall
void Utility::setLaunchOnStartup(const QString &appName, const QString& guiName, bool enable)
{
#if defined(Q_OS_WIN)
    Q_UNUSED(guiName)
    QString runPath = QLatin1String(runPathC);
    QSettings settings(runPath, QSettings::NativeFormat);
    if (enable) {
        settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/','\\'));
    } else {
        settings.remove(appName);
    }
#elif defined(Q_OS_MAC)
    Q_UNUSED(guiName)
    QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath();
    CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8);
    CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true);
    LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0);

    if (loginItems && enable) {
        //Insert an item to the list.
        LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems,
                                                                     kLSSharedFileListItemLast, 0, 0,
                                                                     urlRef, 0, 0);
        if (item)
            CFRelease(item);
        CFRelease(loginItems);
    } else if (loginItems && !enable){
        // We need to iterate over the items and check which one is "ours".
        UInt32 seedValue;
        CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue);
        CFStringRef appUrlRefString = CFURLGetString(urlRef);
        for (int i = 0; i < CFArrayGetCount(itemsArray); i++) {
            LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i);
            CFURLRef itemUrlRef = NULL;

            if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) {
                CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
                if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) {
                    LSSharedFileListItemRemove(loginItems,item); // remove it!
                }
                CFRelease(itemUrlRef);
            }
        }
        CFRelease(itemsArray);
        CFRelease(loginItems);
    };

    CFRelease(folderCFStr);
    CFRelease(urlRef);
#elif defined(Q_OS_UNIX)
    QString userAutoStartPath = QDir::homePath()+QLatin1String("/.config/autostart/");
    QString desktopFileLocation = userAutoStartPath+appName+QLatin1String(".desktop");
    if (enable) {
        if (!QDir().exists(userAutoStartPath) && !QDir().mkdir(userAutoStartPath)) {
            qDebug() << "Could not create autostart directory";
            return;
        }
        QSettings desktopFile(desktopFileLocation, QSettings::IniFormat);
        desktopFile.beginGroup("Desktop Entry");
        desktopFile.setValue(QLatin1String("Name"), guiName);
        desktopFile.setValue(QLatin1String("GenericName"), QLatin1String("File Synchronizer"));
        desktopFile.setValue(QLatin1String("Exec"), QCoreApplication::applicationFilePath());
        desktopFile.setValue(QLatin1String("Terminal"), false);
        desktopFile.setValue(QLatin1String("Icon"), appName);
        desktopFile.setValue(QLatin1String("Categories"), QLatin1String("Network"));
        desktopFile.setValue(QLatin1String("StartupNotify"), false);
        desktopFile.endGroup();
    } else {
        if (!QFile::remove(desktopFileLocation)) {
            qDebug() << "Could not remove autostart desktop file";
        }
    }

#endif
}
コード例 #18
0
KSycocaEntry *
KBuildServiceTypeFactory::createEntry(const TQString &file, const char *resource)
{
  TQString name = file;
  int pos = name.findRev('/');
  if (pos != -1)
  {
     name = name.mid(pos+1);
  }

  if (name.isEmpty())
     return 0;

  KDesktopFile desktopFile(file, true, resource);

  if ( desktopFile.readBoolEntry( "Hidden", false ) == true )
      return 0;

  // TODO check Type field first
  TQString mime = desktopFile.readEntry( "MimeType" );
  TQString service = desktopFile.readEntry( "X-TDE-ServiceType" );

  if ( mime.isEmpty() && service.isEmpty() )
  {
    TQString tmp = TQString("The service/mime type config file\n%1\n"
                  "does not contain a ServiceType=...\nor MimeType=... entry").arg( file );
    kdWarning(7012) << tmp << endl;
    return 0;
  }

  KServiceType* e;
  if ( mime == "inode/directory" )
    e = new KFolderType( &desktopFile );
  else if ( (mime == "application/x-desktop")
         || (mime == "media/builtin-mydocuments")
         || (mime == "media/builtin-mycomputer")
         || (mime == "media/builtin-mynetworkplaces")
         || (mime == "media/builtin-printers")
         || (mime == "media/builtin-trash")
         || (mime == "media/builtin-webbrowser") )
    e = new KDEDesktopMimeType( &desktopFile );
  else if ( mime == "application/x-executable" || mime == "application/x-shellscript" )
    e = new KExecMimeType( &desktopFile );
  else if ( !mime.isEmpty() )
    e = new KMimeType( &desktopFile );
  else
    e = new KServiceType( &desktopFile );

  if (e->isDeleted())
  {
    delete e;
    return 0;
  }

  if ( !(e->isValid()) )
  {
    kdWarning(7012) << "Invalid ServiceType : " << file << endl;
    delete e;
    return 0;
  }

  return e;
}