void
WlmContact::sendFile (const KUrl & sourceURL, const QString & fileName,
                      uint fileSize)
{
    Q_UNUSED( fileName );
    Q_UNUSED( fileSize );

    QString filePath;

    if (!sourceURL.isValid ())
        filePath =
            KFileDialog::getOpenFileName (KUrl (), "*", 0l,
                                          i18n ("Kopete File Transfer"));
    else
        filePath = sourceURL.path (KUrl::RemoveTrailingSlash);

    if (!filePath.isEmpty ())
    {
        quint32 fileSize = QFileInfo (filePath).size ();
        //Send the file
        static_cast <WlmChatSession *>
			(manager (Kopete::Contact::CanCreate))->sendFile (filePath,
                                                               fileSize);
    }
}
// Called when double-clicking on a row
void KonqHistoryDialog::slotOpenWindowForIndex(const QModelIndex& index)
{
    const KUrl url = m_historyView->urlForIndex(index);
    if (url.isValid()) {
        slotOpenWindow(url); // should we call slotOpenTab instead?
    }
}
Exemple #3
0
void ScanGallery::slotExportFile()
{
    FileTreeViewItem *curr = highlightedFileTreeViewItem();
    if (curr==NULL) return;

    if (curr->isDir())
    {
        kDebug() << "Not yet implemented!";
        return;
    }

    KUrl fromUrl(curr->url());

    QString filter;
    ImageFormat format = getImgFormat(curr);
    if (format.isValid()) filter = "*."+format.extension()+"|"+format.mime()->comment()+"\n";
// TODO: do we need the below?
    filter += "*|"+i18n("All Files");

    QString initial = "kfiledialog:///exportImage/"+fromUrl.fileName();
    KUrl fileName = KFileDialog::getSaveUrl(KUrl(initial), filter, this);
    if (!fileName.isValid()) return;			// didn't get a file name
    if (fromUrl==fileName) return;			// can't save over myself

    /* Since it is asynchron, we will never know if it succeeded. */
    ImgSaver::copyImage(fromUrl, fileName);
}
Exemple #4
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") );
  }
}
void ShareProvider::onFinishedReadingFile(KIO::Job* job, const QByteArray& data)
{
    job->disconnect(this);
    qobject_cast<KIO::FileJob *>(job)->close();

    if (data.length() == 0) {
        Q_EMIT finishedError(this, i18n("It was not possible to read the selected file"));
        return;
    }
    
    d->m_data.clear();

    AbstractSharer *sharer = d->getSharer();
    if (sharer) {
        KUrl sharerUrl = sharer->url();
        if (!sharerUrl.isValid()) {
            Q_EMIT finishedError(this, i18n("Service Url is not valid"));
            return;
        }
        KIO::TransferJob *tJob = KIO::http_post(sharer->url(), sharer->postBody(data), KIO::HideProgressInfo);
        tJob->setMetaData(sharer->headers());
        connect(tJob, SIGNAL(data(KIO::Job*,QByteArray)),
                this, SLOT(onTransferJobDataReceived(KIO::Job*,QByteArray)));
        connect(tJob, SIGNAL(result(KJob*)), this, SLOT(onTransferJobResultReceived(KJob*)));

    }
}
Exemple #6
0
void DirSelectWidget::setRootPath(const KUrl& rootUrl, const KUrl& currentUrl)
{
    d->m_rootUrl = rootUrl;
    clear();
    QString root = QDir::cleanPath(rootUrl.toLocalFile());

    if (!root.endsWith('/'))
    {
        root.append("/");
    }

    QString currentPath = QDir::cleanPath(currentUrl.isValid() ? currentUrl.toLocalFile() : root);

    d->m_item = addBranch( rootUrl, rootUrl.fileName() );
    setDirOnlyMode( d->m_item, true );
    currentPath      = currentPath.mid( root.length() );
    d->m_pendingPath = currentPath.split('/', QString::KeepEmptyParts);

    if ( !d->m_pendingPath[0].isEmpty() )
    {
        d->m_pendingPath.prepend( "" );    // ensure we open the root first.
    }

    connect( d->m_item, SIGNAL( populateFinished(K3FileTreeViewItem*) ),
             this, SLOT( load() ) );

    load();

    connect( this, SIGNAL( executed(Q3ListViewItem*) ),
             this, SLOT( slotFolderSelected(Q3ListViewItem*) ) );
}
Exemple #7
0
void MrimContact::sendFile( const KUrl &sourceURL,
                   const QString &fileName, uint fileSize ) {

    kDebug(kdeDebugArea()) << sourceURL << fileName << fileSize;

    QStringList fileNames;
    //If the file location is null, then get it from a file open dialog
    if( !sourceURL.isValid() ) {
        fileNames = KFileDialog::getOpenFileNames( KUrl() ,"*", 0l  , tr( "Kopete File Transfer" ));
    } else {
        fileNames << sourceURL.path(KUrl::RemoveTrailingSlash);
    }

    kDebug(kdeDebugArea()) << "start transfer";

    FileTransferTask *task = new FileTransferTask(
                  dynamic_cast<MrimAccount*>( account() )
                , this
                , fileNames
                , FileTransferTask::Outgoing
                , 0
                , this);

    connect(task, SIGNAL(transferComplete()),
            this, SLOT(slotTransferFinished()) );

    connect(task, SIGNAL(transferFailed()),
            this, SLOT(slotTransferFinished()) );

    d->transferTasks[task->getSessionId()] = task;

}
bool AttachmentHandler::view( const Attachment::Ptr &attachment )
{
  if ( !attachment ) {
    return false;
  }

  bool stat = true;
  if ( attachment->isUri() ) {
    KToolInvocation::invokeBrowser( attachment->uri() );
  } else {
    // put the attachment in a temporary file and launch it
    KUrl tempUrl = tempFileForAttachment( attachment );
    if ( tempUrl.isValid() ) {
      stat = KRun::runUrl( tempUrl, attachment->mimeType(), 0, true );
    } else {
      stat = false;
      KMessageBox::error(
        d->mParent,
        i18n( "Unable to create a temporary file for the attachment." ) );
    }
    delete s_tempFile;
    s_tempFile = 0;
  }
  return stat;
}
Exemple #9
0
void KImageFilePreview::showPreview( const KUrl &url, bool force )
{
    if (!url.isValid() ||
        (d->lastShownURL.isValid() &&
         url.equals(d->lastShownURL, KUrl::CompareWithoutTrailingSlash) &&
         d->currentURL.isValid()))
        return;

    d->clear = false;
    d->currentURL = url;
    d->lastShownURL = url;

    int w = d->imageLabel->contentsRect().width() - 4;
    int h = d->imageLabel->contentsRect().height() - 4;

    if (d->m_job) {
        disconnect(d->m_job, SIGNAL(result(KJob *)),
                    this, SLOT( _k_slotResult( KJob * )));
        disconnect(d->m_job, SIGNAL(gotPreview(const KFileItem&,
                                                const QPixmap& )), this,
                SLOT( gotPreview( const KFileItem&, const QPixmap& ) ));

        disconnect(d->m_job, SIGNAL(failed(const KFileItem&)),
                    this, SLOT(_k_slotFailed(const KFileItem&)));

        d->m_job->kill();
    }
Exemple #10
0
void RemoteProtocol::listDir(const KUrl &url)
{
	kDebug(1220) << "RemoteProtocol::listDir: " << url;

	if ( url.path().length() <= 1 )
	{
		listRoot();
		return;
	}

	int second_slash_idx = url.path().indexOf( '/', 1 );
	const QString root_dirname = url.path().mid( 1, second_slash_idx-1 );

	KUrl target = m_impl.findBaseURL( root_dirname );
	kDebug(1220) << "possible redirection target : " << target;
	if( target.isValid() )
	{
		if ( second_slash_idx < 0 ) {
			second_slash_idx = url.path().size();
		}
		target.addPath( url.path().remove(0, second_slash_idx) );
		kDebug(1220) << "complete redirection target : " << target;
		redirection(target);
		finished();
		return;
	}

	error(KIO::ERR_MALFORMED_URL, url.prettyUrl());
}
Exemple #11
0
int main(int argc, char* argv[])
{
    PLEAboutData aboutData;
    aboutData.setAppName("photolayoutseditor");
    aboutData.setCatalogName("kipiplugin_photolayoutseditor");

    KCmdLineArgs::init(argc,argv,&aboutData);
    KCmdLineOptions options;
    options.add("+file", ki18n("Input file"));
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;
    aboutData.setProgramLogo(KIcon("photolayoutseditor"));

    PhotoLayoutsEditor* w = PhotoLayoutsEditor::instance(0);
    w->setAttribute(Qt::WA_DeleteOnClose, true);

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    if (args->count())
    {
        KUrl url = args->url(0);
        if (url.isValid())
            w->open(url);
    }

    w->show();

    int result = app.exec();

    return result;
}
Exemple #12
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;
}
Exemple #13
0
bool DocumentChild::openDoc( const Document *doc, KoStore *store )
{
    Q_ASSERT ( m_doc == 0 );
    if ( isOpen() ) {
        KMessageBox::error( 0, i18n( "Document is already open:<br>%1", doc->url().pathOrUrl() ) );
        return false;
    }
    m_doc = doc;
    KUrl url;
    if ( doc->sendAs() == Document::SendAs_Copy ) {
        url = parentPackage()->extractFile( doc, store );
        if ( url.url().isEmpty() ) {
            KMessageBox::error( 0, i18n( "Could not extract document from storage:<br>%1", doc->url().pathOrUrl() ) );
            return false;
        }
        m_copy = true;
    } else {
        url = doc->url();
    }
    if ( ! url.isValid() ) {
        KMessageBox::error( 0, i18n( "Invalid URL:<br>%1", url.pathOrUrl() ) );
        return false;
    }
    setFileInfo( url );
    return true;
}
Exemple #14
0
bool DocumentChild::startProcess( KService::Ptr service, const KUrl &url )
{
    QStringList args;
    KUrl::List files;
    if ( url.isValid() ) {
        files << url;
    }
    if ( service ) {
        args = KRun::processDesktopExec( *service, files );
    } else {
        KUrl::List list;
        QPointer<KOpenWithDialog> dlg = new KOpenWithDialog( list, i18n("Edit with:"), QString(), 0 );
        if ( dlg->exec() == QDialog::Accepted && dlg ) {
            args << dlg->text();
        }
        if ( args.isEmpty() ) {
            kDebug(planworkDbg())<<"No executable selected";
            return false;
        }
        args << url.url();
        delete dlg;
    }
    kDebug(planworkDbg())<<args;
    m_process = new KProcess();
    m_process->setProgram( args );
    connect( m_process, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(slotEditFinished(int,QProcess::ExitStatus)) );
    connect( m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(slotEditError(QProcess::ProcessError)) );
    m_process->start();
    //kDebug(planworkDbg())<<m_process->pid()<<m_process->program();
    return true;
}
Exemple #15
0
void DOMTreeView::slotSaveClicked()
{
  //kDebug(90180) << "void KfingerCSSWidget::slotSaveAs()";
  KUrl url = KFileDialog::getSaveFileName( part->url().url(), "*.html",
					   this, i18n("Save DOM Tree as HTML") );
  if (!(url.isEmpty()) && url.isValid()) {
    QFile file(url.path());

    if (file.exists()) {
      const QString title = i18nc( "@title:window", "File Exists" );
      const QString text = i18n( "Do you really want to overwrite: \n%1?" , url.url());
      if (KMessageBox::Continue != KMessageBox::warningContinueCancel(this, text, title, i18n("Overwrite") ) ) {
	return;
      }
    }

    if (file.open(QIODevice::WriteOnly) ) {
      kDebug(90180) << "Opened File: " << url.url();
      m_textStream = new QTextStream(&file); //(stdOut)
      saveTreeAsHTML(part->document());
      file.close();
      kDebug(90180) << "File closed ";
      delete m_textStream;
    } else {
      const QString title = i18nc( "@title:window", "Unable to Open File" );
      const QString text = i18n( "Unable to open \n %1 \n for writing" , url.path());
      KMessageBox::sorry( this, text, title );
    }
  } else {
    const QString title = i18nc( "@title:window", "Invalid URL" );
    const QString text = i18n( "This URL \n %1 \n is not valid." , url.url());
    KMessageBox::sorry( this, text, title );
  }
}
Exemple #16
0
QString LinkDialog::link() const
{
    QString str;
    if (currentPage() == d->p1) {
        str = d->internetLink->text();
        if (!str.isEmpty())
            if (str.indexOf("http://") == -1)
                if (str.indexOf("https://") == -1)
                    if (str.indexOf("ftp://") == -1)
                        str.prepend("http://");
    } else if (currentPage() == d->p2) {
        str = d->mailLink->text();
        if (!str.isEmpty())
            if (str.indexOf("mailto:") == -1)
                str.prepend("mailto:");
        const QString subject = d->mailSubject->text().trimmed();
        if (! subject.isEmpty())
            str.append(QString("?subject=%1").arg(QString(QUrl::toPercentEncoding(subject))));
    } else if (currentPage() == d->p3) {
        KUrl url = d->fileLink->url();
        if (url.isValid()) {
            str = url.url();
        } else {
            str = d->fileText->text();
            if (!str.isEmpty())
                if (! str.contains(QRegExp("^(file|mailto|http|https|ftp):")))
                    str.prepend("file://");
        }
    } else if (currentPage() == d->p4) {
        str = d->cellLink->currentText();
    }

    return str;
}
Exemple #17
0
void MonthWidget::setImage( const KUrl &url )
{
    if (!url.isValid())
        return;

    // check if the file is an image
    QFileInfo fi(url.path());

    QString rawFilesExt(KDcrawIface::KDcraw::rawFiles());

    // Check if RAW image.
    if (!rawFilesExt.toUpper().contains( fi.suffix().toUpper() ))
    {
        // Check if image can be loaded by native Qt loader.
        if ( QImageReader::imageFormat( url.path() ).isEmpty() )
        {
            kWarning( AREA_CODE_LOADING ) << "Unknown image format for: " << url.prettyUrl();
            return;
        }
    }

    imagePath_ = url;
    CalSettings::instance()->setImage(month_, imagePath_);

    interface_->thumbnail( url, thumbSize.width() );
}
Exemple #18
0
void
CoverFetchInfoPayload::prepareUrls()
{
    KUrl url;
    CoverFetch::Metadata metadata;

    switch( m_src )
    {
    default:
    case CoverFetch::LastFm:
        url.setScheme( "http" );
        url.setHost( "ws.audioscrobbler.com" );
        url.setPath( "/2.0/" );
        url.addQueryItem( "api_key", Amarok::lastfmApiKey() );
        url.addQueryItem( "album", sanitizeQuery( album()->name() ) );

        if( album()->hasAlbumArtist() )
        {
            url.addQueryItem( "artist", sanitizeQuery( album()->albumArtist()->name() ) );
        }
        url.addQueryItem( "method", method() );

        metadata[ "source" ] = "Last.fm";
        metadata[ "method" ] = method();
        break;
    }

    if( url.isValid() )
        m_urls.insert( url, metadata );
}
Exemple #19
0
void KDirSelectDialog::setCurrentUrl( const KUrl& url )
{
    if ( !url.isValid() )
        return;

    if (url.protocol() != d->m_rootUrl.protocol()) {
        KUrl u( url );
        u.cd("/");//NOTE portability?
        d->m_treeView->setRootUrl( u );
        d->m_rootUrl = u;
    }

    //Check if url represents a hidden folder and enable showing them
    QString fileName = url.fileName();
    //TODO a better hidden file check?
    bool isHidden = fileName.length() > 1 && fileName[0] == '.' &&
                                                (fileName.length() > 2 ? fileName[1] != '.' : true);
    bool showHiddenFiles = isHidden && !d->m_treeView->showHiddenFiles();
    if (showHiddenFiles) {
        d->showHiddenFoldersAction->setChecked(true);
        d->m_treeView->setShowHiddenFiles(true);
    }

    d->m_treeView->setCurrentUrl( url );
}
Exemple #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);
  }
}
Exemple #21
0
KUrl ExportDialog::customStyleURL() const
{
    KUrl url = m_mainwidget->mCustomURL->url();
    if (m_mainwidget->mCustomButton->isChecked() && url.isValid())
        return url;

    return KUrl();
}
void DolphinViewContainer::startSearching(const QString &text)
{
    Q_UNUSED(text);
    const KUrl url = m_searchBox->urlForSearching();
    if (url.isValid() && !url.isEmpty()) {
        m_urlNavigator->setLocationUrl(url);
    }
}
Exemple #23
0
void Serialization::saveTutorial(const Tutorial* tutorial, const KUrl& url)
throw (IOException) {
    Q_ASSERT(tutorial);
    Q_ASSERT(url.isValid());

    QString serializedTutorial = TutorialWriter().writeTutorial(tutorial);
    writeFile(serializedTutorial, url);
}
Exemple #24
0
/*
 * TODO: put this logic into some kind of controller
 */
void MainWindow::load( const KUrl &url )
{
    if ( !url.isValid() )
        return;

    if ( url.url().endsWith( ".ktechlab", Qt::CaseInsensitive ) )
    {
        // FIXME: create an IProject (i.e. KTechlab::Project) to open the url,
        // since this will prevent KTechLab from crashing...

        // This is a ktechlab project; it has to be handled separetly from a
        // normal file.

        KDevelop::Core::self()->projectController()->openProject( url );
        return;
    }

    QString target;
    // the below code is what you should normally do.  in this
    // example case, we want the url to our own.  you probably
    // want to use this code instead for your app

    // download the contents
    if ( !KIO::NetAccess::download( url, target, this ) )
    {
        // If the file could not be downloaded, for example does not
        // exist on disk, NetAccess will tell us what error to use
        KMessageBox::error(this, KIO::NetAccess::lastErrorString());

        return;
    }

//     addRecentFile( url );

    // set our caption
    setCaption( url.url() );

    //get interface for extension
    QStringList constraints;
    constraints << QString("'%1' in [X-KDevelop-SupportedMimeTypes]").arg(
            "application/x-circuit" );

    // load in the file (target is always local)
    KDevelop::Core *core = KDevelop::Core::self();
    Q_ASSERT( core != 0 );
    KDevelop::IPluginController *pc = core->pluginController();
    Q_ASSERT( pc != 0 );
    QList<KPluginInfo> plugins =
            pc->queryExtensionPlugins( "KTLDocument", constraints );

    foreach (KPluginInfo p, plugins) {
        qDebug() << p.name();
    }
    //KDevelop::PartDocument * document = new CircuitDocument( url, KDevelop::Core::self() );

    // and remove the temp file
    KIO::NetAccess::removeTempFile( target );
}
TestProject::TestProject(const KUrl& url, QObject* parent)
: IProject(parent)
, m_root(0)
, m_projectConfiguration(KGlobal::config())
{
    setProjectUrl(url.isValid() ? url : KUrl("file://tmp/kdev-testproject/"));
    m_root = new ProjectFolderItem(this, m_folder);
    ICore::self()->projectController()->projectModel()->appendRow( m_root );
}
void ImageViewer::loadImageFromURL()
{
    KUrl saveURL = KUrl::fromPath( file.fileName() );
    if (!saveURL.isValid())
        kDebug()<<"tempfile-URL is malformed\n";

    downloadJob = KIO::copy (m_ImageUrl, saveURL);	// starts the download asynchron
    connect (downloadJob, SIGNAL (result (KJob *)), SLOT (downloadReady (KJob *)));
}
Exemple #27
0
void
CoverFetchSearchPayload::prepareUrls()
{
    KUrl url;
    url.setScheme( "http" );
    CoverFetch::Metadata metadata;

    switch( m_src )
    {
    default:
    case CoverFetch::LastFm:
        url.setHost( "ws.audioscrobbler.com" );
        url.setPath( "/2.0/" );
        url.addQueryItem( "api_key", Amarok::lastfmApiKey() );
        url.addQueryItem( "limit", QString::number( 20 ) );
        url.addQueryItem( "page", QString::number( m_page ) );
        url.addQueryItem( "album", sanitizeQuery( m_query ) );
        url.addQueryItem( "method", method() );
        metadata[ "source" ] = "Last.fm";
        metadata[ "method" ] = method();
        break;

    case CoverFetch::Discogs:
        url.setHost( "www.discogs.com" );
        url.setPath( "/search" );
        url.addQueryItem( "api_key", Amarok::discogsApiKey() );
        url.addQueryItem( "page", QString::number( m_page + 1 ) );
        url.addQueryItem( "type", "all" );
        url.addQueryItem( "q", sanitizeQuery( m_query ) );
        url.addQueryItem( "f", "xml" );
        metadata[ "source" ] = "Discogs";
        break;

    case CoverFetch::Yahoo:
        url.setHost( "boss.yahooapis.com" );
        url.setPath( "/ysearch/images/v1/" + sanitizeQuery( m_query ) );
        url.addQueryItem( "appid", Amarok::yahooBossApiKey() );
        url.addQueryItem( "count", QString::number( 20 ) );
        url.addQueryItem( "start", QString::number( 20 * m_page ) );
        url.addQueryItem( "format", "xml" );
        metadata[ "source" ] = "Yahoo!";
        break;

    case CoverFetch::Google:
        url.setHost( "images.google.com" );
        url.setPath( "/images" );
        url.addQueryItem( "q", sanitizeQuery( m_query ) );
        url.addQueryItem( "gbv", QChar( '1' ) );
        url.addQueryItem( "filter", QChar( '1' ) );
        url.addQueryItem( "start", QString::number( 20 * m_page ) );
        metadata[ "source" ] = "Google";
        break;
    }

    if( url.isValid() )
        m_urls.insert( url, metadata );
}
Exemple #28
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 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 
        {
Exemple #30
0
void
AvatarDownloader::downloadAvatar( const QString& username, const KUrl& url )
{
    if( !url.isValid() )
        return;

    m_userAvatarUrls.insert( url, username );
    The::networkAccessManager()->getData( url, this,
         SLOT(downloaded(KUrl,QByteArray,NetworkAccessManagerProxy::Error)) );
}