Example #1
0
void TrashProtocol::mkdir( const KUrl& url, int /*permissions*/ )
{
    INIT_IMPL;
    // create info about deleted dir
    // ############ Problem: we don't know the original path.
    // Let's try to avoid this case (we should get to copy() instead, for local files)
    kDebug() << "mkdir: " << url;
    QString dir = url.directory();

    if ( dir.length() <= 1 ) // new toplevel entry
    {
        // ## we should use TrashImpl::parseURL to give the right filename to createInfo
        int trashId;
        QString fileId;
        if ( !impl.createInfo( url.path(), trashId, fileId ) ) {
            error( impl.lastErrorCode(), impl.lastErrorMessage() );
        } else {
            if ( !impl.mkdir( trashId, fileId, permissions ) ) {
                (void)impl.deleteInfo( trashId, fileId );
                error( impl.lastErrorCode(), impl.lastErrorMessage() );
            } else
                finished();
        }
    } else {
        // Well it's not allowed to add a directory to an existing deleted directory.
        error( KIO::ERR_ACCESS_DENIED, url.prettyUrl() );
    }
}
void KUI_project::modelSetup(QString modelPath)
{
  qDebug() << "opening model in: " << path;
  
  if ( !model  )
    delete model;
  
  model = new DomModel( modelPath, this );
  
  KUrl url;
  url.setPath( modelPath );
  
  path = url.directory();
  QDir::setCurrent( path );
  
  qDebug() << "changing current directory: " << path; 
  
  usersList->setModel( model );
  usersList->setRootIndex( model->index( 0, 0, QModelIndex() ));

  connect( usersList->selectionModel(), SIGNAL( selectionChanged(QItemSelection,QItemSelection)),
           this, SLOT( updateActions(QItemSelection,QItemSelection)) );
  
  playBar->updateInterface( Default );
  collection->action("add")->setEnabled( true );
  
}
Example #3
0
void TrashProtocol::restore( const KUrl& trashURL )
{
    int trashId;
    QString fileId, relativePath;
    bool ok = TrashImpl::parseURL( trashURL, trashId, fileId, relativePath );
    if ( !ok ) {
        error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1", trashURL.prettyUrl() ) );
        return;
    }
    TrashedFileInfo info;
    ok = impl.infoForFile( trashId, fileId, info );
    if ( !ok ) {
        error( impl.lastErrorCode(), impl.lastErrorMessage() );
        return;
    }
    KUrl dest;
    dest.setPath( info.origPath );
    if ( !relativePath.isEmpty() )
        dest.addPath( relativePath );

    // Check that the destination directory exists, to improve the error code in case it doesn't.
    const QString destDir = dest.directory();
    KDE_struct_stat buff;
    if ( KDE_lstat( QFile::encodeName( destDir ), &buff ) == -1 ) {
        error( KIO::ERR_SLAVE_DEFINED,
               i18n( "The directory %1 does not exist anymore, so it is not possible to restore this item to its original location. "
                     "You can either recreate that directory and use the restore operation again, or drag the item anywhere else to restore it.", destDir ) );
        return;
    }

    copyOrMove( trashURL, dest, false /*overwrite*/, Move );
}
void KUI_project::openFileSlot()
{
  updateActions(QItemSelection(), QItemSelection());
  
  KUrl url;
  url.setDirectory( path );
  QString modelPath = KFileDialog::getOpenFileName(url, QString("*.xui"), this, QString("Open"));
  
  if ( modelPath.isEmpty() )
    return;
  
  url.setPath( modelPath );
  
  path = url.directory();
  QDir::setCurrent( path );
  
  qDebug() << "New path: " << path;
  
  if (modelPath.isEmpty()) {
    return;
  }
  

  modelSetup( modelPath );
  
}
KUrl ContextBuilder::findModulePath(const QString& name)
{
    QStringList modulePath = name.split(".");

    KUrl currentPath = currentContext()->url().toUrl();
    Q_ASSERT(currentPath.url().length());
    kDebug() << " >>>>>>>>> Got URL: " << currentPath.upUrl().url(KUrl::RemoveTrailingSlash);

    IProject* currentProject = ICore::self()->projectController()->findProjectForUrl(currentPath);
    if ( ! currentProject ) {
        kError() << "Cannot import module contexts without a project opened.";
        return KUrl();
    }

    // easiest case: current directory
    KUrl filename(currentPath.directory(KUrl::AppendTrailingSlash) + modulePath.first() + ".py");
    kDebug() << "filename url: " << filename;
    if ( currentProject->filesForUrl(filename).length() > 0 ) {
        ProjectFileItem* result = currentProject->filesForUrl(filename).first();
        kDebug() << "Found! " << result->url();
        return result->url();
    }

    return KUrl();
}
void Cache::updateDirectoryEntry(Socket *socket, KUrl &path, filesize_t filesize)
{
  KUrl url = socket->getCurrentUrl();
  url.setPath(path.directory());
  url.adjustPath(KUrl::RemoveTrailingSlash);
  
  if (m_listingCache.contains(url)) {
    DirectoryListing listing = m_listingCache[url];
    listing.updateEntry(path.fileName(), filesize);
    
    m_listingCache.insert(url, listing);
  }
}
Example #7
0
void KonqPopupMenuPrivate::slotShowOriginalFile()
{
    const KFileItem item = m_popupItemProperties.items().first();
    const QString dest = item.linkDest();
    KUrl destUrl = m_sViewURL;
    if (dest.startsWith('/')) {
        destUrl.setPath(dest);
    } else {
        destUrl.addPath(dest);
    }
    // Now destUrl points to the target file, let's go up to parent dir
    destUrl.setPath(destUrl.directory());
    KRun::runUrl(destUrl, "inode/directory", m_parentWidget);
}
Example #8
0
ContentFetch::ContentFetch(TransferGroup* parent, TransferFactory* factory,
                           Scheduler* scheduler, const KUrl& source,
                           const KUrl& dest, const QString &scriptFile,
                           const QDomElement* e)
    : Transfer(parent, factory, scheduler, source, dest, e),
      m_p_group(parent), m_scriptFile(scriptFile), m_destDir(dest.directory(KUrl::AppendTrailingSlash))
{
    m_p_script = new Script(this, source);
    connect(m_p_script, SIGNAL(newTransfer(QString,QString)),
            this, SLOT(slotAddTransfer(QString,QString)));
    connect(m_p_script, SIGNAL(finished()), this, SLOT(slotFinish()));
    connect(m_p_script, SIGNAL(aborted(QString)), this, SLOT(slotAbort(QString)));
    connect(m_p_script, SIGNAL(percentUpdated(int)), this, SLOT(setPercent(int)));
    connect(m_p_script, SIGNAL(textStatusUpdated(QString)), this, SLOT(slotSetTextStatus(QString)));
}
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);
}
Example #10
0
    void updateItemFromDocument( ProjectBaseItem *item, const QString &name )
    {
        QDomElement child = findElementInDocument( item, name );
        KUrl folder;
        if (item->folder())
            folder = item->folder()->url();
        if (item->file())
            folder = item->file()->url();

        QString relativeFileName =
            KUrl::relativePath( projectFile.directory(), folder.directory() );
        relativeFileName.append(folder.fileName());
        QDomElement newNode = child.cloneNode().toElement();
        newNode.setAttribute("name",folder.fileName());
        newNode.setAttribute("url",relativeFileName);

        child.parentNode().replaceChild( newNode, child );
    }
void ImageViewer::saveFileToDisc()
{
    KUrl newURL = KFileDialog::getSaveUrl(m_ImageUrl.fileName());  // save-dialog with default filename
    if (!newURL.isEmpty())
    {
        QFile f (newURL.directory() + '/' +  newURL.fileName());
        if (f.exists())
        {
            int r=KMessageBox::warningContinueCancel(static_cast<QWidget *>(parent()),
                    i18n( "A file named \"%1\" already exists. "
                          "Overwrite it?" , newURL.fileName()),
                    i18n( "Overwrite File?" ),
                    KStandardGuiItem::overwrite() );
            if(r==KMessageBox::Cancel) return;

            f.remove();
        }
        saveFile (newURL);
    }
}
void MagnatuneDownloadDialog::downloadButtonClicked( )
{

    if (m_currentDownloadInfo == 0) return;

    QString format = formatComboBox->currentText();
    QString path = downloadTargetURLRequester->url().url();;

    //store to config for next download:
    KConfigGroup config = Amarok::config("Service_Magnatune");
    config.writeEntry( "Download Format", format );
    config.writeEntry( "Download Path", path );
    
    m_currentDownloadInfo->setFormatSelection( format );

    KUrl unpackLocation = downloadTargetURLRequester->url();
    unpackLocation.adjustPath( KUrl::AddTrailingSlash );
    m_currentDownloadInfo->setUnpackUrl( unpackLocation.directory( KUrl::ObeyTrailingSlash ) );

    emit( downloadAlbum( m_currentDownloadInfo ) );

    close();

}
Example #13
0
// Copy theme package into themes directory
void SplashInstaller::addNewTheme(const KUrl &srcURL)
{
  const QString dir = KGlobal::dirs()->saveLocation("ksplashthemes");

  KUrl url;
  QStringList themeNames;
  QString filename = srcURL.fileName();
  int i = filename.lastIndexOf('.');
  // Convert extension to lower case.
  if (i >= 0)
     filename = filename.left(i)+filename.mid(i).toLower();
  url.setPath(KStandardDirs::locateLocal("tmp",filename));

  // Remove file from temporary directory if it aleady exists - usually the result of a failed install.
  if ( KIO::NetAccess::exists( url, KIO::NetAccess::SourceSide, 0 ) )
    KIO::NetAccess::del( url, 0 );

  if (srcURL.fileName().toLower() == "theme.rc" ) // uncompressed theme selected
  {
    QString themeName;
    // Get the name of the Theme from the theme.rc file
    KConfig _cnf(srcURL.path());
    KConfigGroup cnf(&_cnf, QString("KSplash Theme: %1").arg(themeName) );

    // copy directory of theme.rc to ThemesDir
    KIO::NetAccess::dircopy(KUrl(srcURL.directory()), KUrl(dir + themeName));

    themeNames << themeName;
  }
  else
  {
    bool rc = KIO::NetAccess::file_copy(srcURL, url, 0);
    if (!rc)
    {
      kWarning() << "Failed to copy theme " << srcURL.fileName()
	  << " into temporary directory " << url.path() << endl;
      return;
    }

    // Extract into theme directory: we may have multiple themes in one tarball!
    KTar tarFile(url.path());
    if (!tarFile.open(QIODevice::ReadOnly))
    {
      kWarning() << "Unable to open archive: " << url.path();
      KIO::NetAccess::del( url, 0 );
      return;
    }
    KArchiveDirectory const *ad = tarFile.directory();

    // Find first directory entry.
    const QStringList entries = ad->entries();
    foreach(const QString& s, entries)
    {
      if( ad->entry(s)->isDirectory() )
      {
	// each directory may contain one theme
	themeNames << s;
      }
    }
    if (themeNames.count() < 1)
    {
      kWarning() << "No directory in archive: " << url.path();
      tarFile.close();
      KIO::NetAccess::del( url, 0 );
      return;
    }

    // copy the theme into the "ksplashthemes" directory
    ad->copyTo(dir);

    tarFile.close();
    KIO::NetAccess::del( url, 0 );

  }

  readThemesList();
  mThemesList->setCurrentRow(findTheme(themeNames.first()));
  if (mThemesList->currentItem())
  {
    mThemesList->currentItem()->setSelected(true);
  }
}
void OutputExecuteJob::start()
{
    Q_ASSERT( d->m_status == JobNotStarted );
    d->m_status = JobRunning;

    const bool isBuilder = d->m_properties.testFlag( IsBuilderHint );

    const KUrl effectiveWorkingDirectory = workingDirectory();
    if( effectiveWorkingDirectory.isEmpty() ) {
        if( d->m_properties.testFlag( NeedWorkingDirectory ) ) {
            // A directory is not given, but we need it.
            setError( InvalidWorkingDirectoryError );
            if( isBuilder ) {
                setErrorText( i18n( "No build directory specified for a builder job." ) );
            } else {
                setErrorText( i18n( "No working directory specified for a process." ) );
            }
            return emitResult();
        }

        setModel( new OutputModel );
    } else {
        // Basic sanity checks.
        if( !effectiveWorkingDirectory.isValid() ) {
            setError( InvalidWorkingDirectoryError );
            if( isBuilder ) {
                setErrorText( i18n( "Invalid build directory '%1'", effectiveWorkingDirectory.prettyUrl() ) );
            } else {
                setErrorText( i18n( "Invalid working directory '%1'", effectiveWorkingDirectory.prettyUrl() ) );
            }
            return emitResult();
        } else if( !effectiveWorkingDirectory.isLocalFile() ) {
            setError( InvalidWorkingDirectoryError );
            if( isBuilder ) {
                setErrorText( i18n( "Build directory '%1' is not a local path", effectiveWorkingDirectory.prettyUrl() ) );
            } else {
                setErrorText( i18n( "Working directory '%1' is not a local path", effectiveWorkingDirectory.prettyUrl() ) );
            }
            return emitResult();
        }

        QFileInfo workingDirInfo( effectiveWorkingDirectory.toLocalFile() );
        if( !workingDirInfo.isDir() ) {
            // If a working directory does not actually exist, either bail out or create it empty,
            // depending on what we need by properties.
            // We use a dedicated bool variable since !isDir() may also mean that it exists,
            // but is not a directory, or a symlink to an inexistent object.
            bool successfullyCreated = false;
            if( !d->m_properties.testFlag( CheckWorkingDirectory ) ) {
                successfullyCreated = QDir( effectiveWorkingDirectory.directory() ).mkdir( effectiveWorkingDirectory.fileName() );
            }
            if( !successfullyCreated ) {
                setError( InvalidWorkingDirectoryError );
                if( isBuilder ) {
                    setErrorText( i18n( "Build directory '%1' does not exist or is not a directory", effectiveWorkingDirectory.prettyUrl() ) );
                } else {
                    setErrorText( i18n( "Working directory '%1' does not exist or is not a directory", effectiveWorkingDirectory.prettyUrl() ) );
                }
                return emitResult();
            }
        }

        setModel( new OutputModel( effectiveWorkingDirectory ) );
    }
    Q_ASSERT( model() );

    model()->setFilteringStrategy( d->m_filteringStrategy );
    setDelegate( new OutputDelegate );

    // Slots hasRawStdout() and hasRawStderr() are responsible
    // for feeding raw data to the line maker; so property-based channel filtering is implemented there.
    if( d->m_properties.testFlag( PostProcessOutput ) ) {
        connect( d->m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)),
                 SLOT(postProcessStdout(QStringList)) );
        connect( d->m_lineMaker, SIGNAL(receivedStderrLines(QStringList)),
                 SLOT(postProcessStderr(QStringList)) );
    } else {
        connect( d->m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)), model(),
                 SLOT(appendLines(QStringList)) );
        connect( d->m_lineMaker, SIGNAL(receivedStderrLines(QStringList)), model(),
                 SLOT(appendLines(QStringList)) );
    }

    if( !d->m_properties.testFlag( NoSilentOutput ) || verbosity() != Silent ) {
        d->m_outputStarted = true;
        startOutput();
    }

    const QString joinedCommandLine = d->joinCommandLine();
    QString headerLine;
    if( !effectiveWorkingDirectory.isEmpty() ) {
        headerLine = effectiveWorkingDirectory.toLocalFile( KUrl::RemoveTrailingSlash ) + "> " + joinedCommandLine;
    } else {
        headerLine = joinedCommandLine;
    }
    model()->appendLine( headerLine );

    if( !effectiveWorkingDirectory.isEmpty() ) {
        d->m_process->setWorkingDirectory( effectiveWorkingDirectory.toLocalFile() );
    }
    d->m_process->setProcessEnvironment( d->effectiveEnvironment() );
    d->m_process->setProgram( d->effectiveCommandLine() );
    d->m_process->start();
}
Example #15
0
void TrashProtocol::copyOrMove( const KUrl &src, const KUrl &dest, bool overwrite, CopyOrMove action )
{
    if (src.protocol() == QLatin1String("trash") && dest.isLocalFile()) {
        // Extracting (e.g. via dnd). Ignore original location stored in info file.
        int trashId;
        QString fileId, relativePath;
        bool ok = TrashImpl::parseURL( src, trashId, fileId, relativePath );
        if ( !ok ) {
            error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1", src.prettyUrl() ) );
            return;
        }
        const QString destPath = dest.path();
        if ( QFile::exists( destPath ) ) {
            if ( overwrite ) {
                ok = QFile::remove( destPath );
                Q_ASSERT( ok ); // ### TODO
            } else {
                error( KIO::ERR_FILE_ALREADY_EXIST, destPath );
                return;
            }
        }

        if ( action == Move ) {
            kDebug() << "calling moveFromTrash(" << destPath << " " << trashId << " " << fileId << ")";
            ok = impl.moveFromTrash( destPath, trashId, fileId, relativePath );
        } else { // Copy
            kDebug() << "calling copyFromTrash(" << destPath << " " << trashId << " " << fileId << ")";
            ok = impl.copyFromTrash( destPath, trashId, fileId, relativePath );
        }
        if ( !ok ) {
            error( impl.lastErrorCode(), impl.lastErrorMessage() );
        } else {
            if ( action == Move && relativePath.isEmpty() )
                (void)impl.deleteInfo( trashId, fileId );
            finished();
        }
        return;
    } else if (src.isLocalFile() && dest.protocol() == QLatin1String("trash")) {
        QString dir = dest.directory();
        //kDebug() << "trashing a file to " << dir;
        // Trashing a file
        // We detect the case where this isn't normal trashing, but
        // e.g. if kwrite tries to save (moving tempfile over destination)
        if ( dir.length() <= 1 && src.fileName() == dest.fileName() ) // new toplevel entry
        {
            const QString srcPath = src.path();
            // In theory we should use TrashImpl::parseURL to give the right filename to createInfo,
            // in case the trash URL didn't contain the same filename as srcPath.
            // But this can only happen with copyAs/moveAs, not available in the GUI
            // for the trash (New/... or Rename from iconview/listview).
            int trashId;
            QString fileId;
            if ( !impl.createInfo( srcPath, trashId, fileId ) ) {
                error( impl.lastErrorCode(), impl.lastErrorMessage() );
            } else {
                bool ok;
                if ( action == Move ) {
                    kDebug() << "calling moveToTrash(" << srcPath << " " << trashId << " " << fileId << ")";
                    ok = impl.moveToTrash( srcPath, trashId, fileId );
                } else { // Copy
                    kDebug() << "calling copyToTrash(" << srcPath << " " << trashId << " " << fileId << ")";
                    ok = impl.copyToTrash( srcPath, trashId, fileId );
                }
                if ( !ok ) {
                    (void)impl.deleteInfo( trashId, fileId );
                    error( impl.lastErrorCode(), impl.lastErrorMessage() );
                } else {
                    // Inform caller of the final URL. Used by konq_undo.
                    const KUrl url = impl.makeURL( trashId, fileId, QString() );
                    setMetaData(QString::fromLatin1("trashURL-") + srcPath, url.url());
                    finished();
                }
            }
            return;
        } else {
            kDebug() << "returning KIO::ERR_ACCESS_DENIED, it's not allowed to add a file to an existing trash directory";
            // It's not allowed to add a file to an existing trash directory.
            error( KIO::ERR_ACCESS_DENIED, dest.prettyUrl() );
            return;
        }
    } else {
        error(KIO::ERR_UNSUPPORTED_ACTION, i18n("Internal error in copyOrMove, should never happen"));
    }
}
Example #16
0
void setPath(const QString &path) {
	if (path == fileName.directory(KUrl::AppendTrailingSlash)) return;
	KIO::move(fileName, KUrl( path + '/' + fileName.fileName() ));
	fileName = KUrl(path + fileName.fileName());
}
Example #17
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;
}