Ejemplo n.º 1
0
AudioPreview::AudioPreview( QWidget *parent, const KUrl &url, const QString &mimeType)
  : KVBox( parent )
{
  m_isTempFile = false;
  pic = 0;
  m_player = 0L;
  description = 0;
  setSpacing( 0 );
  if( url.isValid() && url.isLocalFile() ) {
    m_localFile = url.toLocalFile();
    pic = new QLabel(this);
    pic->setPixmap(KIO::pixmapForUrl( url ));
    pic->adjustSize();
    initView( mimeType );
  } else if( !url.isLocalFile() ) {
    KUrlLabel *label = new KUrlLabel( this );
    label->setText(i18n("This audio file is not stored\non the local host.\nClick on this label to load it.\n" ) );
    label->setUrl( url.prettyUrl() );
    connect(label, SIGNAL(leftClickedUrl(const QString&)), SLOT(downloadFile(const QString&)));
    pic = label;
  } else {
    description = new QLabel(this );
    description->setText(i18n("Unable to load audio file") );
  }
}
Ejemplo n.º 2
0
void KexiBlobTableEdit::handleInsertFromFileAction(const KUrl& url)
{
    if (isReadOnly())
        return;

    QString fileName(url.isLocalFile() ? url.toLocalFile() : url.prettyUrl());

    //! @todo download the file if remote, then set fileName properly
    QFile f(fileName);
    if (!f.open(IO_ReadOnly)) {
        //! @todo err msg
        return;
    }
    QByteArray ba = f.readAll();
    if (f.error() != QFile::NoError) {
        //! @todo err msg
        f.close();
        return;
    }
    f.close();
// m_valueMimeType = KImageIO::mimeType( fileName );
    setValueInternal(ba, true);
    signalEditRequested();
    //emit acceptRequested();
}
BreadcrumbSiblingList
FileBrowser::Private::siblingsForDir( const KUrl &path )
{
    BreadcrumbSiblingList siblings;
    if( path.protocol() == "places" )
    {
        for( int i = 0; i < placesModel->rowCount(); i++ )
        {
            QModelIndex idx = placesModel->index( i, 0 );

            QString name = idx.data( Qt::DisplayRole ).toString();
            QString url = idx.data( KFilePlacesModel::UrlRole ).toString();
            if( url.isEmpty() )
                // the place perhaps needs mounting, use places url instead
                url = placesString + name;
            siblings << BreadcrumbSibling( idx.data( Qt::DecorationRole ).value<QIcon>(),
                                           name, url );
        }
    }
    else if( path.isLocalFile() )
    {
        QDir dir( path.toLocalFile() );
        dir.cdUp();
        foreach( const QString &item, dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) )
        {
            siblings << BreadcrumbSibling( KIcon( "folder-amarok" ), item,
                                           dir.absoluteFilePath( item ) );
        }
    }
Ejemplo n.º 4
0
void K3b::MovixDoc::addUrlsAt( const KUrl::List& urls, int pos )
{
    QList<K3b::MovixFileItem*> items;

    for( KUrl::List::ConstIterator it = urls.begin(); it != urls.end(); ++it ) {
        KUrl url = K3b::convertToLocalUrl( *it );

        QFileInfo f( url.toLocalFile() );
        if( !f.isFile() || !url.isLocalFile() )
            continue;

        QString newName = f.fileName();

        bool ok = true;
        while( ok && nameAlreadyInDir( newName, root() ) ) {
            newName = KInputDialog::getText( i18n("Enter New Filename"),
                                             i18n("A file with that name already exists. Please enter a new name:"),
                                             newName, &ok, view() );
        }

        if( ok ) {
            MovixFileItem* newItem = new MovixFileItem( f.absoluteFilePath(), *this, newName );
            root()->addDataItem( newItem );
            items.append( newItem );
        }
    }

    addMovixItems( items, pos );
}
Ejemplo n.º 5
0
void AsyncFileTester::checkIfFolder(const QModelIndex &index, QObject *object, const char *method)
{
    if (!index.isValid()) {
        callResultMethod(object, method, index, false);
        return;
    }

    KFileItem item = static_cast<const ProxyModel*>(index.model())->itemForIndex(index);
    KUrl url = item.targetUrl();
    
    if (item.isDir()) {
        callResultMethod(object, method, index, true);
        return;
    }
    
    if (item.isDesktopFile()) {
        // Check if the desktop file is a link to a local folder
        KDesktopFile file(url.path());
        if (file.readType() == "Link") {
            url = file.readUrl();
            if (url.isLocalFile()) {
                KFileItem destItem(KFileItem::Unknown, KFileItem::Unknown, url);
                callResultMethod(object, method, index, destItem.isDir());
                return;
            }
            
            if (KProtocolInfo::protocolClass(url.protocol()) == QString(":local")) {
                AsyncFileTester *tester = new AsyncFileTester(index, object, method);
                tester->delayedFolderCheck(url);
                return;
            }
        }
    }
    callResultMethod(object, method, index, false);
}
Ejemplo n.º 6
0
void KShellCmdPlugin::slotExecuteShellCommand()
{
    KParts::ReadOnlyPart *part = qobject_cast<KParts::ReadOnlyPart *>(parent());
    if (!part)  {
        KMessageBox::sorry(0L, i18n("KShellCmdPlugin::slotExecuteShellCommand: Program error, please report a bug."));
        return;
    }

    KUrl url = KIO::NetAccess::mostLocalUrl(part->url(), NULL);
    if (!url.isLocalFile()) {
        KMessageBox::sorry(part->widget(), i18n("Executing shell commands works only on local directories."));
        return;
    }

    QString path;
    KParts::FileInfoExtension *ext = KParts::FileInfoExtension::childObject(part);

    if (ext && ext->hasSelection() && (ext->supportedQueryModes() & KParts::FileInfoExtension::SelectedItems)) {
        KFileItemList list = ext->queryFor(KParts::FileInfoExtension::SelectedItems);
        QStringList fileNames;
        Q_FOREACH (const KFileItem &item, list) {
            fileNames << item.name();
        }
        path = KShell::joinArgs(fileNames);
    }
Ejemplo n.º 7
0
void KFileItem::setUDSEntry( const KIO::UDSEntry& _entry, const KUrl& _url,
                             bool _delayedMimeTypes, bool _urlIsDirectory )
{
    d->m_entry = _entry;
    d->m_url = _url;
    d->m_strName.clear();
    d->m_strText.clear();
    d->m_iconName.clear();
    d->m_strLowerCaseName.clear();
    d->m_pMimeType = 0;
    d->m_fileMode = KFileItem::Unknown;
    d->m_permissions = KFileItem::Unknown;
    d->m_bMarked = false;
    d->m_bLink = false;
    d->m_bIsLocalUrl = _url.isLocalFile();
    d->m_bMimeTypeKnown = false;
    d->m_hidden = KFileItemPrivate::Auto;
    d->m_guessedMimeType.clear();
    d->m_metaInfo = KFileMetaInfo();
    d->m_delayedMimeTypes = _delayedMimeTypes;
    d->m_useIconNameCache = false;

    d->readUDSEntry( _urlIsDirectory );
    d->init();
}
Ejemplo n.º 8
0
RKLoadAgent::RKLoadAgent (const KUrl &url, bool merge) {
	RK_TRACE (APP);
	RKWardMainWindow::getMain ()->slotSetStatusBarText (i18n ("Loading Workspace ..."));

	QString filename;
	if (!url.isLocalFile ()) {
		KIO::NetAccess::download (url, tmpfile, RKWardMainWindow::getMain ());
		filename = tmpfile;
	} else {
		filename = url.toLocalFile ();
	}
	

	RCommand *command;
	
	if (!merge) {
		RKWardMainWindow::getMain ()->slotCloseAllWindows ();
		command = new RCommand ("remove (list=ls (all.names=TRUE))", RCommand::App | RCommand::ObjectListUpdate);
		RKGlobals::rInterface ()->issueCommand (command);
	}

	command = new RCommand ("load (\"" + filename + "\")", RCommand::App | RCommand::ObjectListUpdate, QString::null, this, WORKSPACE_LOAD_COMMAND);
	RKGlobals::rInterface ()->issueCommand (command);

	RKWorkplace::mainWorkplace ()->setWorkspaceURL (url);
}
Ejemplo n.º 9
0
QString PixmapEdit::selectPixmapFileName()
{
    /*#ifdef PURE_QT
      QString url = QFileDialog::getOpenFileName();
      if (!url.isEmpty()) {
        m_edit->setPixmap(QPixmap(url));
        emit valueChanged(this);
      }
    #endif*/
    const QString caption(i18n("Insert Image From File (for \"%1\" property)", m_property->caption()));
    /*KDE4:
    #ifdef Q_WS_WIN
      QString recentDir;
      QString fileName = Q3FileDialog::getOpenFileName(
        KFileDialog::getStartURL(":lastVisitedImagePath", recentDir).path(),
        convertKFileDialogFilterToQFileDialogFilter(KImageIO::pattern(KImageIO::Reading)),
        this, 0, caption);
    #else*/
    const KUrl url(KFileDialog::getImageOpenUrl(
                 KUrl(":lastVisitedImagePath"), this, caption));
    QString fileName = url.isLocalFile() ? url.toLocalFile() : url.prettyUrl();

    //! @todo download the file if remote, then set fileName properly
//#endif
    return fileName;
}
Ejemplo n.º 10
0
bool NetAccess::exists( const KUrl & url, StatSide side, QWidget* window )
{
  if ( url.isLocalFile() )
    return QFile::exists( url.toLocalFile() );
  NetAccess kioNet;
  return kioNet.statInternal( url, 0 /*no details*/, side, window );
}
Ejemplo n.º 11
0
bool NetAccess::download(const KUrl& u, QString & target, QWidget* window)
{
  if (u.isLocalFile()) {
    // file protocol. We do not need the network
    target = u.toLocalFile();
    bool accessible = KStandardDirs::checkAccess(target, R_OK);
    if(!accessible)
    {
        if(!lastErrorMsg)
            lastErrorMsg = new QString;
        *lastErrorMsg = i18n("File '%1' is not readable", target);
        lastErrorCode = ERR_COULD_NOT_READ;
    }
    return accessible;
  }

  if (target.isEmpty())
  {
      KTemporaryFile tmpFile;
      tmpFile.setAutoRemove(false);
      tmpFile.open();
      target = tmpFile.fileName();
      if (!tmpfiles)
          tmpfiles = new QStringList;
      tmpfiles->append(target);
  }

  NetAccess kioNet;
  KUrl dest;
  dest.setPath( target );
  return kioNet.filecopyInternal( u, dest, -1, KIO::Overwrite, window, false /*copy*/);
}
Ejemplo n.º 12
0
bool KTCLI::load(const KUrl & url)
{
	QDir dir(url.toLocalFile());
	if (dir.exists() && dir.exists("torrent") && dir.exists("stats"))
	{
		// Load existing torrent
		if (loadFromDir(dir.absolutePath()))
		{
			tc->start();
			connect(&timer,SIGNAL(timeout()),this,SLOT(update()));
			timer.start(250);
			return true;
		}
	}
	else if (url.isLocalFile())
	{
		QString path = url.toLocalFile();
		if (loadFromFile(path))
		{
			tc->start();
			connect(&timer,SIGNAL(timeout()),this,SLOT(update()));
			timer.start(250);
			return true;
		}
	}
	else
	{
		Out(SYS_GEN|LOG_IMPORTANT) << "Non local files not supported" << endl;
	}
	
	return false;
}
Ejemplo n.º 13
0
 KFileItemPrivate(const KIO::UDSEntry& entry,
                  mode_t mode, mode_t permissions,
                  const KUrl& itemOrDirUrl,
                  bool urlIsDirectory,
                  bool delayedMimeTypes)
     : m_entry( entry ),
       m_url(itemOrDirUrl),
       m_strName(),
       m_strText(),
       m_iconName(),
       m_strLowerCaseName(),
       m_pMimeType( 0 ),
       m_fileMode( mode ),
       m_permissions( permissions ),
       m_bMarked( false ),
       m_bLink( false ),
       m_bIsLocalUrl(itemOrDirUrl.isLocalFile()),
       m_bMimeTypeKnown( false ),
       m_delayedMimeTypes( delayedMimeTypes ),
       m_useIconNameCache(false),
       m_hidden( Auto )
 {
     if (entry.count() != 0) {
         readUDSEntry( urlIsDirectory );
     } else {
         Q_ASSERT(!urlIsDirectory);
         m_strName = itemOrDirUrl.fileName();
         m_strText = KIO::decodeFileName( m_strName );
     }
     init();
 }
Ejemplo n.º 14
0
    void Core::loadSilently(const KUrl& url, const QString& group)
    {
        if (url.protocol() == "magnet")
        {
            MagnetLinkLoadOptions options;
            options.silently = true;
            options.group = group;
            load(bt::MagnetLink(url.prettyUrl()), options);
        }
        else if (url.isLocalFile())
        {
            QString path = url.toLocalFile();
            QString dir = locationHint(group);

            if (dir != QString::null)
                loadFromFile(path, dir, group, true);
        }
        else
        {
            // download to a random file in tmp
            KIO::Job* j = KIO::storedGet(url);
            connect(j, SIGNAL(result(KJob*)), this, SLOT(downloadFinishedSilently(KJob*)));
            if (!group.isNull())
                add_to_groups.insert(url, group);
        }
    }
Ejemplo n.º 15
0
QString KUrlNavigator::Private::firstButtonText() const
{
    QString text;

    // The first URL navigator button should get the name of the
    // place instead of the directory name
    if ((m_placesSelector != 0) && !m_showFullPath) {
        const KUrl placeUrl = m_placesSelector->selectedPlaceUrl();
        text = m_placesSelector->selectedPlaceText();
    }

    if (text.isEmpty()) {
        const KUrl currentUrl = q->locationUrl();
        if (currentUrl.isLocalFile()) {
            text = m_showFullPath ? QLatin1String("/") : i18n("Custom Path");
        } else {
            text = currentUrl.protocol() + QLatin1Char(':');
            if (!currentUrl.host().isEmpty()) {
                text += QLatin1Char(' ') + currentUrl.host();
            }
        }
    }

    return text;
}
Ejemplo n.º 16
0
void KWebPage::downloadResponse(QNetworkReply *reply)
{
    Q_ASSERT(reply);

    if (!reply)
        return;

    // Put the job on hold only for the protocols we know about (read: http).
    KIO::Integration::AccessManager::putReplyOnHold(reply);

    QString mimeType;
    KIO::MetaData metaData;

    if (handleReply(reply, &mimeType, &metaData)) {
        return;
    }

    const KUrl replyUrl (reply->url());

    // Ask KRun to handle the response when mimetype is unknown
    if (mimeType.isEmpty()) {
        (void)new KRun(replyUrl, d->windowWidget(), 0 , replyUrl.isLocalFile());
        return;
    }

    // Ask KRun::runUrl to handle the response when mimetype is inode/*
    if (mimeType.startsWith(QL1S("inode/"), Qt::CaseInsensitive) &&
        KRun::runUrl(replyUrl, mimeType, d->windowWidget(), false, false,
                     metaData.value(QL1S("content-disposition-filename")))) {
        return;
    }
}
Ejemplo n.º 17
0
QString CJobRunner::fileName(const KUrl &url)
{
    if(url.isLocalFile())
        return url.toLocalFile();
    else
    {
        KUrl local(KIO::NetAccess::mostLocalUrl(url, 0L));

        if(local.isLocalFile())
            return local.toLocalFile(); // Yipee! no need to download!!
        else
        {
            // Need to do actual download...
            if(!itsTempDir)
            {
                itsTempDir=new KTempDir(KStandardDirs::locateLocal("tmp", "fontinst"));
                itsTempDir->setAutoRemove(true);
            }

            QString tempName(itsTempDir->name()+QChar('/')+Misc::getFile(url.path()));
            if(KIO::NetAccess::download(url, tempName, 0L))
                return tempName;
            else
                return QString();
        }
    }
}
Ejemplo n.º 18
0
static KUrl promptUser (QWidget *parent, const KUrl& url, const QString& suggestedName)
{
    KUrl destUrl;
    int result = KIO::R_OVERWRITE;
    const QString fileName ((suggestedName.isEmpty() ? url.fileName() : suggestedName));

    do {
        // convert filename to URL using fromPath to avoid trouble with ':' in filenames (#184202)
        destUrl = KFileDialog::getSaveFileName(KUrl::fromPath(fileName), QString(), parent);

        if (destUrl.isLocalFile()) {
            QFileInfo finfo (destUrl.toLocalFile());
            if (finfo.exists()) {
                QDateTime now = QDateTime::currentDateTime();
                KIO::RenameDialog dlg (parent, i18n("Overwrite File?"), url, destUrl,
                                       KIO::RenameDialog_Mode(KIO::M_OVERWRITE | KIO::M_SKIP),
                                       -1, finfo.size(),
                                       now.toTime_t(), finfo.created().toTime_t(),
                                       now.toTime_t(), finfo.lastModified().toTime_t());
                result = dlg.exec();
            }
        }
    } while (result == KIO::R_CANCEL && destUrl.isValid());

    return destUrl;
}
Ejemplo n.º 19
0
KonfUpdate::KonfUpdate()
        : m_textStream(0), m_file(0)
{
    bool updateAll = false;
    m_oldConfig1 = 0;
    m_oldConfig2 = 0;
    m_newConfig = 0;

    m_config = new KConfig("kconf_updaterc");
    KConfigGroup cg(m_config, QString());

    QStringList updateFiles;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    m_debug = args->isSet("debug");

    m_bUseConfigInfo = false;
    if (args->isSet("check")) {
        m_bUseConfigInfo = true;
        QString file = KStandardDirs::locate("data", "kconf_update/" + args->getOption("check"));
        if (file.isEmpty()) {
            qWarning("File '%s' not found.", args->getOption("check").toLocal8Bit().data());
            log() << "File '" << args->getOption("check") << "' passed on command line not found" << endl;
            return;
        }
        updateFiles.append(file);
    } else if (args->count()) {
        for (int i = 0; i < args->count(); i++) {
            KUrl url = args->url(i);
            if (!url.isLocalFile()) {
                KCmdLineArgs::usageError(i18n("Only local files are supported."));
            }
            updateFiles.append(url.path());
        }
    } else {
        if (cg.readEntry("autoUpdateDisabled", false))
            return;
        updateFiles = findUpdateFiles(true);
        updateAll = true;
    }

    for (QStringList::ConstIterator it = updateFiles.constBegin();
            it != updateFiles.constEnd();
            ++it) {
        updateFile(*it);
    }

    if (updateAll && !cg.readEntry("updateInfoAdded", false)) {
        cg.writeEntry("updateInfoAdded", true);
        updateFiles = findUpdateFiles(false);

        for (QStringList::ConstIterator it = updateFiles.constBegin();
                it != updateFiles.constEnd();
                ++it) {
            checkFile(*it);
        }
        updateFiles.clear();
    }
}
Ejemplo n.º 20
0
void KstChangeFileDialog::sourceChanged(const QString& text)
{
  delete _configWidget;
  _configWidget = 0L;
  _configureSource->setEnabled(false);
  _file = QString::null;
  if (!text.isEmpty() && text != "stdin" && text != "-") {
    KUrl url;
    QString txt = _dataFile->completionObject()->replacedPath(text);
    if (QFile::exists(txt) && QFileInfo(txt).isRelative()) {
      url.setPath(txt);
    } else {
      url = KUrl::fromPathOrURL(txt);
    }

    if (!url.isLocalFile() && url.protocol() != "file" && !url.protocol().isEmpty()) {
      _fileType->setText(QString::null);
      return;
    }

    if (!url.isValid()) {
      _fileType->setText(QString::null);
      return;
    }

    QString file = txt;

    KstDataSourcePtr ds = *KST::dataSourceList.findReusableFileName(file);
    QStringList fl;
    QString fileType;

    if (ds) {
      ds->readLock();
      fl = ds->fieldList();
      fileType = ds->fileType();
      ds->unlock();
      ds = 0L;
    } else {
      bool complete = false;
      fl = KstDataSource::fieldListForSource(file, QString::null, &fileType, &complete);
    }

    if (!fl.isEmpty() && !fileType.isEmpty()) {
      if (ds) {
        ds->writeLock();
        _configWidget = ds->configWidget();
        ds->unlock();
      } else {
        _configWidget = KstDataSource::configWidgetForSource(file, fileType);
      }
    }

    _configureSource->setEnabled(_configWidget);
    _file = file;
    _fileType->setText(fileType.isEmpty() ? QString::null : tr("Data source of type: %1").arg(fileType));
  } else {
    _fileType->setText(QString::null);
  }
}
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);
}
Ejemplo n.º 22
0
bool NetAccess::exists( const KUrl & url, bool source, QWidget* window )
{
  if ( url.isLocalFile() )
    return QFile::exists( url.toLocalFile() );
  NetAccess kioNet;
  return kioNet.statInternal( url, 0 /*no details*/,
                              source ? SourceSide : DestinationSide, window );
}
Ejemplo n.º 23
0
KUrl K3b::convertToLocalUrl( const KUrl& url )
{
    if( !url.isLocalFile() ) {
        return KIO::NetAccess::mostLocalUrl( url, 0 );
    }

    return url;
}
Ejemplo n.º 24
0
void KFindTreeView::saveResults()
{
    KFileDialog *dlg = new KFileDialog(QString(), QString(), this);
    dlg->setOperationMode (KFileDialog::Saving);
    dlg->setCaption( i18nc("@title:window", "Save Results As") );
    dlg->setFilter( QString("*.html|%1\n*.txt|%2").arg( i18n("HTML page"), i18n("Text file") ) );
    dlg->setConfirmOverwrite(true);    
    
    dlg->exec();

    KUrl u = dlg->selectedUrl();
    
    QString filter = dlg->currentFilter();
    delete dlg;

    if (!u.isValid() || !u.isLocalFile())
        return;

    QString filename = u.toLocalFile();

    QFile file(filename);

    if ( !file.open(QIODevice::WriteOnly) )
    {
        KMessageBox::error(parentWidget(),
                i18n("Unable to save results."));
    }
    else
    {
        QTextStream stream( &file );
        stream.setCodec( QTextCodec::codecForLocale() );
        
        QList<KFindItem> itemList = m_model->getItemList();
        if ( filter == "*.html" ) 
        {
            stream << QString::fromLatin1("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
            "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
                            "<head>\n"
                            "<title>%2</title></head>\n"
                            "<meta charset=\"%1\">\n"
                            "<body>\n<h1>%2</h1>\n"
                            "<dl>\n")
            .arg(QString::fromLatin1(QTextCodec::codecForLocale()->name()))
            .arg(i18n("KFind Results File"));

            Q_FOREACH( const KFindItem & item, itemList )
            {
                const KFileItem fileItem = item.getFileItem();
                stream << QString::fromLatin1("<dt><a href=\"%1\">%2</a></dt>\n").arg( 
                    fileItem.url().url(), fileItem.url().prettyUrl() );

            }
            stream << QString::fromLatin1("</dl>\n</body>\n</html>\n");
        }
        else 
        {
Ejemplo n.º 25
0
bool MyMoneyTemplate::loadTemplate(const KUrl& url)
{
  QString filename;

  if (!url.isValid()) {
    qDebug("Invalid template URL '%s'", qPrintable(url.url()));
    return false;
  }

  m_source = url;
  if (url.isLocalFile()) {
    filename = url.toLocalFile();

  } else {
    bool rc;
    rc = KIO::NetAccess::download(url, filename, KMyMoneyUtils::mainWindow());
    if (!rc) {
      KMessageBox::detailedError(KMyMoneyUtils::mainWindow(),
                                 i18n("Error while loading file '%1'.", url.url()),
                                 KIO::NetAccess::lastErrorString(),
                                 i18n("File access error"));
      return false;
    }
  }

  bool rc = true;
  QFile file(filename);
  QFileInfo info(file);
  if (!info.isFile()) {
    QString msg = i18n("<p><b>%1</b> is not a template file.</p>", filename);
    KMessageBox::error(KMyMoneyUtils::mainWindow(), msg, i18n("Filetype Error"));
    return false;
  }

  if (file.open(QIODevice::ReadOnly)) {
    QString errMsg;
    int errLine, errColumn;
    if (!m_doc.setContent(&file, &errMsg, &errLine, &errColumn)) {
      QString msg = i18n("<p>Error while reading template file <b>%1</b> in line %2, column %3</p>", filename, errLine, errColumn);
      KMessageBox::detailedError(KMyMoneyUtils::mainWindow(), msg, errMsg, i18n("Template Error"));
      rc = false;
    } else {
      rc = loadDescription();
    }
    file.close();
  } else {
    KMessageBox::sorry(KMyMoneyUtils::mainWindow(), i18n("File '%1' not found.", filename));
    rc = false;
  }

  // if a temporary file was constructed by NetAccess::download,
  // then it will be removed with the next call. Otherwise, it
  // stays untouched on the local filesystem
  KIO::NetAccess::removeTempFile(filename);
  return rc;
}
void View::rename(const KUrl &source, const QString &name)
{
  KUrl dest(source.upUrl());
  dest.addPath(name);
  
  if (source.isLocalFile())
    KIO::rename(source, dest, KIO::HideProgressInfo); 
  else
    m_session->getClient()->rename(source, dest);
}
Ejemplo n.º 27
0
void HyperlinkStrategy::finishInteraction(Qt::KeyboardModifiers modifiers)
{
    if (d->textRect.contains(d->lastPoint)) {
        return;
    }
    Q_UNUSED(modifiers)
    selection()->activeSheet()->showStatusMessage(i18n("Link %1 activated", d->url));

    const KUrl url(d->url);
    if (!url.isValid() || url.isRelative()) {
        const Region region(d->url, selection()->activeSheet()->map(), selection()->activeSheet());
        if (region.isValid()) {
            if (region.firstSheet() != selection()->activeSheet()) {
                selection()->emitVisibleSheetRequested(region.firstSheet());
            }
            selection()->initialize(region);

            if (!region.firstRange().isNull()) {
                const Cell cell = Cell(region.firstSheet(), region.firstRange().topLeft());
            }
        }
    } else {
        const QString type = KMimeType::findByUrl(url, 0, url.isLocalFile())->name();
        if (!Util::localReferenceAnchor(d->url)) {
            const bool executable = KRun::isExecutableFile(url, type);
            if (executable) {
                const QString question = i18n("This link points to the program or script '%1'.\n"
                                              "Malicious programs can harm your computer. "
                                              "Are you sure that you want to run this program?", d->url);
                // this will also start local programs, so adding a "don't warn again"
                // checkbox will probably be too dangerous
                const int answer = KMessageBox::warningYesNo(tool()->canvas()->canvasWidget(), question,
                                   i18n("Open Link?"));
                if (answer != KMessageBox::Yes) {
                    return;
                }
            }
            new KRun(url, tool()->canvas()->canvasWidget(), 0, url.isLocalFile());
        }
    }

    tool()->repaintDecorations();
}
QString FileDialog::getSaveFileName(const KUrl& dir, const QString& filter, QWidget* parent, const QString& caption, bool* append)
{
    bool defaultDir = dir.isEmpty();
    bool specialDir = !defaultDir && dir.protocol() == "kfiledialog";
    // Use AutoQPointer to guard against crash on application exit while
    // the dialogue is still open. It prevents double deletion (both on
    // deletion of parent, and on return from this function).
    AutoQPointer<FileDialog> dlg = new FileDialog(specialDir ? dir : KUrl(), filter, parent);
    if (!specialDir && !defaultDir)
    {
        if (!dir.isLocalFile())
            kWarning() << "FileDialog::getSaveFileName called with non-local start dir " << dir;
        dlg->setSelection(dir.isLocalFile() ? dir.toLocalFile() : dir.path());  // may also be a filename
    }
    dlg->setOperationMode(Saving);
    dlg->setMode(KFile::File | KFile::LocalOnly);
    dlg->setConfirmOverwrite(true);
    if (!caption.isEmpty())
        dlg->setCaption(caption);
    mAppendCheck = 0;
    if (append)
    {
        // Show an 'append' option in the dialogue.
        // Note that the dialogue will take ownership of the QCheckBox.
        mAppendCheck = new QCheckBox(i18nc("@option:check", "Append to existing file"), 0);
        connect(mAppendCheck, SIGNAL(toggled(bool)), dlg, SLOT(appendToggled(bool)));
        dlg->fileWidget()->setCustomWidget(mAppendCheck);
        *append = false;
    }
    dlg->setWindowModality(Qt::WindowModal);
    dlg->exec();
    if (!dlg)
        return QString();   // dialogue was deleted

    QString filename = dlg->selectedFile();
    if (!filename.isEmpty())
    {
        if (append)
            *append = mAppendCheck->isChecked();
        KRecentDocument::add(filename);
    }
    return filename;
}
Ejemplo n.º 29
0
void Import::imageImport( const KUrl& url )
{
    Import* import = new Import;
    import->m_kimFileUrl = url;
    if ( !url.isLocalFile() )
         import->downloadUrl(url);
    else
        import->exec(url.path());
    // This instance will delete itself when done.
}
Ejemplo n.º 30
0
void ExportImageDialog::exportImage()
{
    //If the filename string contains no "/" separators, assume the
    //user wanted to place a file in their home directory.
    KUrl fileURL;
    if(!m_Url.contains("/"))
    {
        fileURL = QDir::homePath() + '/' + m_Url;
    }

    else
    {
        fileURL = m_Url;
    }

    if(fileURL.isValid())
    {
        KTemporaryFile tmpfile;
        QString fname;
        bool isLocalFile = fileURL.isLocalFile();

        if(isLocalFile)
        {
            fname = fileURL.toLocalFile();
        }

        else
        {
            tmpfile.open();
            fname = tmpfile.fileName();
        }

        //Determine desired image format from filename extension
        QString ext = fname.mid(fname.lastIndexOf(".") + 1);
        if(ext.toLower() == "svg")
        {
            exportSvg(fname);
        }

        else
        {
            exportRasterGraphics(fname);
        }

        if(!isLocalFile)
        {
            //attempt to upload image to remote location
            if(!KIO::NetAccess::upload(tmpfile.fileName(), fileURL, this))
            {
                QString message = i18n( "Could not upload image to remote location: %1", fileURL.prettyUrl() );
                KMessageBox::sorry( 0, message, i18n( "Could not upload file" ) );
            }
        }
    }
}