Ejemplo n.º 1
0
void MANProtocol::stat( const QUrl& url)
{
    qCDebug(KIO_MAN_LOG) << "ENTERING STAT " << url.url();

    QString title, section;

    if (!parseUrl(url.path(), title, section))
    {
        error(KIO::ERR_MALFORMED_URL, url.url());
        return;
    }

    qCDebug(KIO_MAN_LOG) << "URL " << url.url() << " parsed to title='" << title << "' section=" << section;

    UDSEntry entry;
    entry.insert(KIO::UDSEntry::UDS_NAME, title);
    entry.insert(KIO::UDSEntry::UDS_FILE_TYPE, S_IFREG);

#if 0 // not useful, is it?
    QString newUrl = "man:"+title;
    if (!section.isEmpty())
        newUrl += QString("(%1)").arg(section);
    entry.insert(KIO::UDSEntry::UDS_URL, newUrl);
#endif

    entry.insert(KIO::UDSEntry::UDS_MIME_TYPE, QString::fromLatin1("text/html"));

    statEntry(entry);

    finished();
}
Ejemplo n.º 2
0
void SMBSlave::fileSystemFreeSpace(const QUrl& url)
{
    qCDebug(KIO_SMB) << url;

    SMBUrl smbcUrl = url;
    int handle = smbc_opendir(smbcUrl.toSmbcUrl());
    if (handle < 0) {
       error(KIO::ERR_COULD_NOT_STAT, url.url());
       return;
    }

    struct statvfs dirStat;
    memset(&dirStat, 0, sizeof(struct statvfs));
    int err = smbc_fstatvfs(handle, &dirStat);
    smbc_closedir(handle);

    if (err < 0) {
       error(KIO::ERR_COULD_NOT_STAT, url.url());
       return;
    }

    KIO::filesize_t blockSize;
    if (dirStat.f_frsize != 0) {
       blockSize = dirStat.f_frsize;
    } else {
       blockSize = dirStat.f_bsize;
    }

    setMetaData("total", QString::number(blockSize * dirStat.f_blocks));
    setMetaData("available", QString::number(blockSize * dirStat.f_bavail));

    finished();
}
Ejemplo n.º 3
0
void PopupsBarWidget::addPopup(const QUrl &url)
{
	QAction *action(m_popupsMenu->addAction(QString("%1").arg(fontMetrics().elidedText(url.url(), Qt::ElideMiddle, 256))));
	action->setData(url.url());

	m_ui->messageLabel->setText(tr("%1 wants to open %n pop-up window(s).", "", (m_popupsMenu->actions().count() - 2)).arg(m_parentUrl.host().isEmpty() ? QLatin1String("localhost") : m_parentUrl.host()));
}
Ejemplo n.º 4
0
//-----------------------------------------------------------------------------
HighscoresWidget::HighscoresWidget(QWidget *parent)
    : QWidget(parent),
      _scoresUrl(0), _playersUrl(0), _statsTab(0), _histoTab(0)
{
//     kDebug(11001) << ": HighscoresWidget";

    setObjectName( QLatin1String("show_highscores_widget" ));
    const ScoreInfos &s = internal->scoreInfos();
    const PlayerInfos &p = internal->playerInfos();

    QVBoxLayout *vbox = new QVBoxLayout(this);
    vbox->setSpacing(QApplication::fontMetrics().lineSpacing());

    _tw = new QTabWidget(this);
    connect(_tw, SIGNAL(currentChanged(int)), SLOT(tabChanged()));
    vbox->addWidget(_tw);

    // scores tab
    _scoresList = new HighscoresList(0);
    _scoresList->addHeader(s);
    _tw->addTab(_scoresList, i18n("Best &Scores"));

    // players tab
    _playersList = new HighscoresList(0);
    _playersList->addHeader(p);
    _tw->addTab(_playersList, i18n("&Players"));

    // statistics tab
    if ( internal->showStatistics ) {
        _statsTab = new StatisticsTab(0);
        _tw->addTab(_statsTab, i18n("Statistics"));
    }

    // histogram tab
    if ( p.histogram().size()!=0 ) {
        _histoTab = new HistogramTab(0);
        _tw->addTab(_histoTab, i18n("Histogram"));
    }

    // url labels
    if ( internal->isWWHSAvailable() ) {
        QUrl url = internal->queryUrl(ManagerPrivate::Scores);
        _scoresUrl = new KUrlLabel(url.url(),
                                   i18n("View world-wide highscores"), this);
        connect(_scoresUrl, SIGNAL(leftClickedUrl(QString)),
                SLOT(showURL(QString)));
        vbox->addWidget(_scoresUrl);

        url = internal->queryUrl(ManagerPrivate::Players);
        _playersUrl = new KUrlLabel(url.url(),
                                    i18n("View world-wide players"), this);
        connect(_playersUrl, SIGNAL(leftClickedUrl(QString)),
                SLOT(showURL(QString)));
        vbox->addWidget(_playersUrl);
    }
    load(-1);
}
Ejemplo n.º 5
0
void MANProtocol::listDir(const QUrl &url)
{
    qCDebug(KIO_MAN_LOG) << url;

    QString title;
    QString section;

    if ( !parseUrl(url.path(), title, section) ) {
        error( KIO::ERR_MALFORMED_URL, url.url() );
        return;
    }

    // stat() and listDir() declared that everything is an html file.
    // However we can list man: and man:(1) as a directory (e.g. in dolphin).
    // But we cannot list man:ls as a directory, this makes no sense (#154173)

    if (!title.isEmpty() && title != "/") {
	error(KIO::ERR_IS_FILE, url.url());
        return;
    }

    UDSEntryList uds_entry_list;

    if (section.isEmpty()) {
        for (QStringList::ConstIterator it = section_names.constBegin(); it != section_names.constEnd(); ++it) {
            UDSEntry     uds_entry;

            QString name = "man:/(" + *it + ')';
            uds_entry.insert( KIO::UDSEntry::UDS_NAME, sectionName( *it ) );
            uds_entry.insert( KIO::UDSEntry::UDS_URL, name );
            uds_entry.insert( KIO::UDSEntry::UDS_FILE_TYPE, S_IFDIR );

            uds_entry_list.append( uds_entry );
        }
    }

    QStringList list = findPages( section, QString(), false );

    QStringList::Iterator it = list.begin();
    QStringList::Iterator end = list.end();

    for ( ; it != end; ++it ) {
        stripExtension( &(*it) );

        UDSEntry     uds_entry;
        uds_entry.insert( KIO::UDSEntry::UDS_NAME, *it );
        uds_entry.insert(KIO::UDSEntry::UDS_FILE_TYPE, S_IFREG);
        uds_entry.insert(KIO::UDSEntry::UDS_MIME_TYPE, QString::fromLatin1("text/html"));
        uds_entry_list.append( uds_entry );
    }

    listEntries( uds_entry_list );
    finished();
}
Ejemplo n.º 6
0
bool ftp_vfs::populateVfsList(const QUrl &origin, bool showHidden)
{
    QString errorMsg;
    if (!origin.isValid())
        errorMsg = i18n("Malformed URL:\n%1", origin.url());
    if (!KProtocolManager::supportsListing(origin)) {
        if (origin.scheme() == "ftp" && KProtocolManager::supportsReading(origin))
            errorMsg = i18n("Krusader does not support FTP access via HTTP.\nIf it is not the case, please check and change the proxy settings in the System Settings.");
        else
            errorMsg = i18n("Protocol not supported by Krusader:\n%1", origin.url());
    }

    if (!errorMsg.isEmpty()) {
        printf("error\n");
        if (!quietMode)
            emit error(errorMsg);
        return false;
    }

    busy = true;

    vfs_origin = origin.adjusted(QUrl::StripTrailingSlash);

    //QTimer::singleShot( 0,this,SLOT(startLister()) );
    listError = false;
    // Open the directory marked by origin
    KIO::Job *job = KIO::listDir(vfs_origin, KIO::HideProgressInfo, showHidden);
    connect(job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)),
            this, SLOT(slotAddFiles(KIO::Job*, const KIO::UDSEntryList&)));
    connect(job, SIGNAL(redirection(KIO::Job*, const QUrl&)),
            this, SLOT(slotRedirection(KIO::Job*, const QUrl&)));
    connect(job, SIGNAL(permanentRedirection(KIO::Job*, const QUrl&, const QUrl&)),
            this, SLOT(slotPermanentRedirection(KIO::Job*, const QUrl&, const QUrl&)));

    connect(job, SIGNAL(result(KJob*)),
            this, SLOT(slotListResult(KJob*)));

    if(!parentWindow.isNull()) {
        KIO::JobUiDelegate *ui = static_cast<KIO::JobUiDelegate*>(job->uiDelegate());
        ui->setWindow(parentWindow);
    }

    if (!quietMode) {
        emit startJob(job);
    }

    while (busy && vfs_processEvents());

    if (listError) return false;

    return true;
}
Ejemplo n.º 7
0
QVariantHash ChooseSamba::values() const
{
    QVariantHash ret = m_args;

    QString address = ui->addressLE->text().trimmed();
    QUrl url;
    if (address.startsWith(QLatin1String("//"))) {
        url = QUrl(QLatin1String("smb:") % address);
    } else if (address.startsWith(QLatin1String("/"))) {
        url = QUrl(QLatin1String("smb:/") % address);
    } else if (address.startsWith(QLatin1String("://"))) {
        url = QUrl(QLatin1String("smb") % address);
    } else if (address.startsWith(QLatin1String("smb://"))) {
        url = QUrl(address);
    } else if (!QUrl::fromUserInput(address).scheme().isEmpty() &&
               QUrl::fromUserInput(address).scheme() != QStringLiteral("smb")) {
        url = QUrl::fromUserInput(address);
        url.setScheme(QStringLiteral("smb"));
    } else {
        url = QUrl(QStringLiteral("smb://") % address);
    }

    qDebug() << 1 << url;
    if (!ui->usernameLE->text().isEmpty()) {
        url.setUserName(ui->usernameLE->text());
    }

    if (!ui->passwordLE->text().isEmpty()) {
        url.setPassword(ui->passwordLE->text());
    }

    qDebug() << 2 << url;
    qDebug() << 3 << url.url() << url.path().section(QLatin1Char('/'), -1, -1);// same as url.fileName()
    qDebug() << 4 << url.fileName();
    qDebug() << 5 << url.host() << url.url().section(QLatin1Char('/'), 3, 3).toLower();

    ret[KCUPS_DEVICE_URI] = url.url();
    ret[KCUPS_DEVICE_INFO] = url.fileName();

    // if there is 4 '/' means the url is like
    // smb://group/host/printer, so the location is at a different place
    if (url.url().count(QLatin1Char('/') == 4)) {
        ret[KCUPS_DEVICE_LOCATION] = url.url().section(QLatin1Char('/'), 3, 3).toLower();
    } else {
        ret[KCUPS_DEVICE_LOCATION] = url.host();
    }

    return ret;
}
Ejemplo n.º 8
0
bool Helper::handleGetSaveX( bool url )
    {
    if( !readArguments( 4 ))
        return false;
    QString startDir = getArgument();
    QString filter = getArgument().replace("/", "\\/"); // TODO: ignored
    int selectFilter = getArgument().toInt();
    QString title = getArgument();
    long wid = getArgumentParent();
    if( !allArgumentsUsed())
        return false;

    if (title.isEmpty())
        title = i18n("Save As");

    // TODO: confirm overwrite
    if (url) {
        QUrl result = QFileDialog::getSaveFileUrl(nullptr, title, startDir);
        if (result.isValid()) {
            outputLine(QStringLiteral("0"));
            outputLine(result.url());
            return true;
        }
    } else {
        QString result = QFileDialog::getSaveFileName(nullptr, title, startDir);
        if (!result.isEmpty()) {
            KRecentDocument::add(QUrl::fromLocalFile(result));
            outputLine(QStringLiteral("0"));
            outputLine(result);
            return true;
        }
    }

    return false;
    }
bool
XinePlayerBackend::openFile(const QString &filePath, bool &playingAfterCall)
{
	playingAfterCall = true;

	// the volume is adjusted when file playback starts and it's best if it's initially at 0
	xine_set_param(m_xineStream, m_softwareMixer ? XINE_PARAM_AUDIO_AMP_LEVEL : XINE_PARAM_AUDIO_VOLUME, 0);

	m_streamIsSeekable = false;

	QUrl fileUrl;
	fileUrl.setScheme("file");
	fileUrl.setPath(filePath);

	if(!xine_open(m_xineStream, fileUrl.url().toLocal8Bit()))
		return false;

	// no subtitles
	xine_set_param(m_xineStream, XINE_PARAM_SPU_CHANNEL, -1);

	if(!xine_play(m_xineStream, 0, 0))
		return false;

	setPlayerState(VideoPlayer::Playing);

	// this methods do nothing if the information is not available
	updateVideoData();
	updateAudioData();
	updatePosition();

	m_timesTimer.start(UPDATE_INTERVAL);

	return true;
}
Ejemplo n.º 10
0
void BookmarksRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &action)
{
    Q_UNUSED(context);
    const QString term = action.data().toString();
    QUrl url = QUrl(term);

    //support urls like "kde.org" by transforming them to http://kde.org
    if (url.scheme().isEmpty()) {
        const int idx = term.indexOf('/');

        url.clear();
        url.setHost(term.left(idx));
        if (idx != -1) {
            //allow queries
            const int queryStart = term.indexOf('?', idx);
            int pathLength = -1;
            if ((queryStart > -1) && (idx < queryStart)) {
                pathLength = queryStart - idx;
                url.setQuery(term.mid(queryStart));
            }

            url.setPath(term.mid(idx, pathLength));
        }
        url.setScheme(QStringLiteral("http"));
    }

    KToolInvocation::invokeBrowser(url.url());
}
Ejemplo n.º 11
0
void StreamWG::captureImage()
{
    QString fmt;
    QUrl currentFileURL;
    QUrl currentDir(Options::fitsDir());
    QTemporaryFile tmpfile;
    tmpfile.open();

    fmt = imgFormatCombo->currentText();

    currentFileURL = QFileDialog::getSaveFileUrl(KStars::Instance(), i18n("Save Image"), currentDir, fmt );

    if (currentFileURL.isEmpty()) return;

    if ( currentFileURL.isValid() )
    {
        streamFrame->kPix.save(currentFileURL.toLocalFile(), fmt.toLatin1());
    }
    else
    {
        QString message = i18n( "Invalid URL: %1", currentFileURL.url() );
        KMessageBox::sorry( 0, message, i18n( "Invalid URL" ) );
    }

}
Ejemplo n.º 12
0
Archivo: docpart.cpp Proyecto: KDE/kile
bool DocumentationViewer::urlSelected(const QString &url, int button, int state, const QString &_target, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments & /* browserArgs */)
{
	QUrl cURL = completeURL(url);
	QMimeDatabase db;
	QString mime = db.mimeTypeForUrl(cURL).name();

	//load this URL in the embedded viewer if KHTML can handle it, or when mimetype detection failed
	KService::Ptr service = KService::serviceByDesktopName("khtml");
	if (db.mimeTypeForUrl(cURL).isDefault() || (service && service->hasServiceType(mime))) {
		KHTMLPart::urlSelected(url, button, state, _target, args);
		openUrl(cURL);
		addToHistory(cURL.url());
	}
	//KHTML can't handle it, look for an appropriate application
	else {
		KService::List offers = KMimeTypeTrader::self()->query(mime, "Type == 'Application'");
		if(offers.isEmpty()) {
			KMessageBox::error(view(), i18n("No KDE service found for the MIME type \"%1\".", mime));
			return false;
		}
		QList<QUrl> lst;
		lst.append(cURL);
		KRun::runService(*(offers.first()), lst, view());
	}
	return true;
}
Ejemplo n.º 13
0
bool Helper::handleGetDirectoryX( bool url )
    {
    if( !readArguments( 2 ))
        return false;
    QString startDir = getArgument();
    QString title = getArgument();
    long wid = getArgumentParent();
    if( !allArgumentsUsed())
        return false;

    if (url) {
        QUrl result = QFileDialog::getExistingDirectoryUrl(nullptr, title, startDir);
        if (result.isValid()) {
            outputLine(result.url());
            return true;
        }
    } else {
        QString result = QFileDialog::getExistingDirectory(nullptr, title, startDir);
        if (!result.isEmpty()) {
            outputLine(QUrl::fromLocalFile(result).url());
            return true;
        }
    }

    return false;
    }
Ejemplo n.º 14
0
void checkFileNameOrUrl(const QString &pInFileNameOrUrl, bool &pOutIsLocalFile,
                        QString &pOutFileNameOrUrl)
{
    // Determine whether pInFileNameOrUrl refers to a local file or a remote
    // one, and set pOutIsLocalFile and pOutFileNameOrUrl accordingly
    // Note #1: to use QUrl::isLocalFile() is not enough. Indeed, say that
    //          pInFileNameOrUrl is equal to
    //              /home/me/mymodel.cellml
    //          then QUrl(pInFileNameOrUrl).isLocalFile() will be false. For it
    //          to be true, we would have to initialise the QUrl object using
    //          QUrl::fromLocalFile(), but we can't do that since we don't know
    //          whether pInFileNameOrUrl refers to a local file or not. So,
    //          instead we test for the scheme and host of the QUrl object...
    // Note #2: a local file can be passed as a URL. For example,
    //              file:///home/me/mymodel.cellml
    //          is a URL, but effectively a local file, hence pOutIsLocalFile is
    //          to be true and pOutFileNameOrUrl is to be set to
    //              /home/me/mymodel.cellml

    QUrl fileNameOrUrl = pInFileNameOrUrl;

    pOutIsLocalFile =    !fileNameOrUrl.scheme().compare("file")
                      ||  fileNameOrUrl.host().isEmpty();
    pOutFileNameOrUrl = pOutIsLocalFile?
                            !fileNameOrUrl.scheme().compare("file")?
                                nativeCanonicalFileName(fileNameOrUrl.toLocalFile()):
                                nativeCanonicalFileName(pInFileNameOrUrl):
                            fileNameOrUrl.url();
}
Ejemplo n.º 15
0
// Gets specific city XML data
void NOAAIon::getXMLData(const QString& source)
{
    foreach (const QString &fetching, m_jobList) {
        if (fetching == source) {
            // already getting this source and awaiting the data
            return;
        }
    }

    QString dataKey = source;
    dataKey.remove(QStringLiteral("noaa|weather|"));
    const QUrl url(m_places[dataKey].XMLurl);

    // If this is empty we have no valid data, send out an error and abort.
    if (url.url().isEmpty()) {
        setData(source, QStringLiteral("validate"), QStringLiteral("noaa|malformed"));
        return;
    }

    KIO::TransferJob* getJob = KIO::get(url, KIO::Reload, KIO::HideProgressInfo);
    m_jobXml.insert(getJob, new QXmlStreamReader);
    m_jobList.insert(getJob, source);

    connect(getJob, &KIO::TransferJob::data,
            this, &NOAAIon::slotDataArrived);
    connect(getJob, &KJob::result,
            this, &NOAAIon::slotJobFinished);
}
Ejemplo n.º 16
0
KoZipStore::KoZipStore(QWidget* window, const QUrl &_url, const QString & _filename, Mode mode,
                       const QByteArray & appIdentification, bool writeMimetype)
    : KoStore(mode, writeMimetype)
{
    debugStore << "KoZipStore Constructor url" << _url.url(QUrl::PreferLocalFile)
               << " filename = " << _filename
               << " mode = " << int(mode)
               << " mimetype = " << appIdentification << endl;
    Q_D(KoStore);

    d->url = _url;
    d->window = window;

    if (mode == KoStore::Read) {
        d->localFileName = _filename;
    } else {
        QTemporaryFile f("kozip");
        f.open();
        d->localFileName = f.fileName();
        f.close();
    }

    m_pZip = new KZip(d->localFileName);
    init(appIdentification);   // open the zip file and init some vars
}
bool Ilwis3CatalogConnector::loadItems()
{
    QUrl location = _location.url();
    QStringList namefilter;
    namefilter << "*.mpr" << "*.mpa" << "*.mps" << "*.mpp" << "*.tbt" << "*.dom" << "*.rpr" << "*.csy" << "*.grf" << "*.mpl";

    QFileInfoList fileList = loadFolders(namefilter);

    // remove duplicates, shoudnt happen but better save than sorry
    QSet<QFileInfo> reduced = fileList.toSet();
    fileList.clear();
    fileList = QList<QFileInfo>::fromSet(reduced);

    QList<ODFItem> odfitems;
    QList<Resource> folders;
    QHash<QString, quint64> names;
    foreach(QFileInfo file, fileList) {
        QUrl container = location.url();
        QString path = file.canonicalFilePath();
        QString loc = container.toLocalFile();
        if ( path.compare(loc,Qt::CaseInsensitive) == 0)
            container = file.canonicalPath();
        IlwisTypes tp = Ilwis3Connector::ilwisType(path);
        QUrl url("file:///" + path);
        if ( mastercatalog()->resource2id(url, tp) == i64UNDEF) {
            if ( tp & itILWISOBJECT ) {
                ODFItem item(path);
                odfitems.push_back(item);
                names[file.fileName().toLower()] = item.id();
            } else {
                folders.push_back(loadFolder(file, container, path, url));
            }
        }

    }
Ejemplo n.º 18
0
void TsDataRetrieverFTP::TestOKDownloadFile()
{
  try
  {
    QUrl url;
    url.setHost("ftp.dgi.inpe.br");
    url.setPath("/focos_operacao/");
    url.setScheme("FTP");
    url.setPort(21);
    url.setUserName("queimadas");
    url.setPassword("inpe_2012");

    curl_global_init(CURL_GLOBAL_ALL);

    //DataProvider information
    terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider();
    terrama2::core::DataProviderPtr dataProviderPtr(dataProvider);
    dataProvider->uri = url.url().toStdString();
    dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT;
    dataProvider->dataProviderType = "FTP";
    dataProvider->active = true;

    //empty filter
    terrama2::core::Filter filter;
    std::string path;
    std::string mask = "exporta_20160501_0230.csv";

    MockCurlWrapper mock_;

    ON_CALL(mock_, verifyURL(_)).WillByDefault(Return(CURLE_OK));
    ON_CALL(mock_, getDownloadFiles(_,_,_)).WillByDefault(Return(CURLE_OK));

    try
    {
      terrama2::core::DataRetrieverFTP retrieverFTP(dataProviderPtr, std::move(mock_));
      auto remover = std::make_shared<terrama2::core::FileRemover>();
      path = retrieverFTP.retrieveData(mask, filter, remover);
    }
    catch(...)
    {
      QFAIL("Unexpected exception!");
    }

    curl_global_cleanup();

  }
  catch(const terrama2::Exception& e)
  {
    QFAIL(boost::get_error_info< terrama2::ErrorDescription >(e)->toStdString().c_str());
  }

  catch(...)
  {
    QFAIL("Unexpected exception!");
  }

  return;

}
Ejemplo n.º 19
0
void VlcMediaWidget::setExternalSubtitle(const QUrl &subtitleUrl)
{
	if (libvlc_video_set_subtitle_file(vlcMediaPlayer,
	    subtitleUrl.toEncoded().constData()) == 0) {
		Log("VlcMediaWidget::setExternalSubtitle: cannot set subtitle file") <<
            subtitleUrl.url();
	}
}
Ejemplo n.º 20
0
// When the site returns the xml, extract the link and request the image download
void ImageLoader::xml_ready(QNetworkReply* xmlReply)
{
    if (xmlReply->error() != QNetworkReply::NoError)
    {
        emit problems("Connection to bing server has failed!! Reason: " + xmlReply->errorString());
        return;
    }

    // Get the market specified in this request
    QString mkt = xmlReply->url().url().right(5);

    // Parse the xml and get the download link for the image
    QXmlStreamReader reader(xmlReply->readAll());
    QUrl imageUrl;

    while (!reader.atEnd())
    {
        reader.readNext();

        int thingsToRead = 0;
        if (reader.name() == "urlBase")
        {
            // Embed the market as a query parameter, so the image_ready handler can easily see the market for the image
            // This query parameter should have no effect on the get request
            imageUrl = QUrl{ "http://www.bing.com" + reader.readElementText() + "_" + m_settings->resolution() + SettingsHandler::ImageExtension + "?market=" + mkt };

            if (++thingsToRead == 2)
                break;
        }
        else if (reader.name() == "copyright")
        {
            // Save the copyright quote into the matching BingImage
            auto bingImage = std::find_if(m_todaysImages->cbegin(), m_todaysImages->cend(), [mkt](const BingImage* img)
            {
                return img->market() == mkt;
            });

            if (bingImage !=  m_todaysImages->cend())
            {
                (*bingImage)->set_copyright(reader.readElementText());

                if (++thingsToRead == 2)
                    break;
            }
        }
    }

    // Download the image if the link is valid
    if (imageUrl.url() != "")
    {
        QNetworkRequest request{ imageUrl };
        m_image_manager.get(request);
    }

    // Schedule the network reply for deletion
    xmlReply->deleteLater();
}
Ejemplo n.º 21
0
void MainWindow::on_textBrowser_anchorClicked(const QUrl &arg1)
{
    QString linkURL=arg1.url();
    QStringList linkList=linkURL.split(":");
    if(linkList.value(0)=="client") {
        R->MainUI->textEdit->append(linkList.value(1)+", ");
        R->MainUI->textEdit->setFocus();
    }
}
Ejemplo n.º 22
0
void TsDataRetrieverFTP::TestFailUriInvalid()
{
  try
  {
    QUrl url;
    url.setHost("ftp.dgi.inpe.br");
    url.setPath("/operacao/");
    url.setScheme("FTP");
    url.setPort(21);
    url.setUserName("queimadas");
    url.setPassword("inpe_2012");

    curl_global_init(CURL_GLOBAL_ALL);

    //DataProvider information
    terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider();
    terrama2::core::DataProviderPtr dataProviderPtr(dataProvider);
    dataProvider->uri = url.url().toStdString();
    dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT;
    dataProvider->dataProviderType = "FTP";
    dataProvider->active = true;

    //empty filter
    terrama2::core::Filter filter;

    MockCurlWrapper mock_;

    ON_CALL(mock_, verifyURL(_)).WillByDefault(Return(CURLE_COULDNT_RESOLVE_HOST));

    try
    {
      terrama2::core::DataRetrieverFTP retrieverFTP(dataProviderPtr, std::move(mock_));

      QFAIL("Exception expected!");
    }
    catch(const terrama2::core::DataRetrieverException& e)
    {

    }

    curl_global_cleanup();

  }
  catch(const terrama2::Exception& e)
  {
    QFAIL(boost::get_error_info< terrama2::ErrorDescription >(e)->toStdString().c_str());
  }

  catch(...)
  {
    QFAIL("Unexpected exception!");
  }

  return;

}
Ejemplo n.º 23
0
void SettingsDialog::DownloadDBResult(const QUrl &url,bool result)
{
    if(QUrl::fromEncoded(ui->lineEditDBURL->text().toLocal8Bit()).url()==url.url())
    {
        QSettings settings("Jontisoft", "JAERO");
        if(result)settings.setValue("lastdbupdate3", QDate::currentDate());
        settings.setValue("updatedbinformed3", false);
        if(dbtext!=NULL)dbtext->importdb(ui->lineEditplanesfolder->text());
    }
}
void KexiStartupFileHandler::saveRecentDir()
{
    if (!d->recentDirClass.isEmpty()) {
        qDebug() << d->recentDirClass;

        QUrl dirUrl;
        if (d->requester)
            dirUrl = d->requester->url();
//removed in KEXI3        else if (d->dialog)
//removed in KEXI3            dirUrl = d->dialog->selectedUrl();
        qDebug() << dirUrl;
        if (dirUrl.isValid() && dirUrl.isLocalFile()) {
            dirUrl = dirUrl.adjusted(QUrl::RemoveFilename);
            dirUrl.setPath(dirUrl.path() + QString());
            qDebug() << "Added" << dirUrl.url() << "to recent dirs class" << d->recentDirClass;
            KRecentDirs::add(d->recentDirClass, dirUrl.url());
        }
    }
}
Ejemplo n.º 25
0
void TsDataRetrieverFTP::TestOKVectorWithFiles()
{
  try
  {
    QUrl url;

    //DataProvider information
    terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider();
    terrama2::core::DataProviderPtr dataProviderPtr(dataProvider);
    dataProvider->uri = url.url().toStdString();
    dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT;
    dataProvider->dataProviderType = "FTP";
    dataProvider->active = true;

    std::string path;
    std::string mask = "exporta_20160501_0230.csv";
    std::vector<std::string> vectorFiles;
    vectorFiles.push_back("exporta_20160501_0230.csv");

    //empty filter
    terrama2::core::Filter filter;

    std::unique_ptr<MockCurlWrapper> mock_(new MockCurlWrapper());

    EXPECT_CALL(*mock_, verifyURL(_,_)).WillOnce(Return());
    EXPECT_CALL(*mock_, listFiles(_)).WillOnce(Return(vectorFiles));
    EXPECT_CALL(*mock_, downloadFile(_,_,_)).WillOnce(Return());

    try
    {
      terrama2::core::DataRetrieverFTP retrieverFTP(dataProviderPtr, std::move(mock_));
      auto remover = std::make_shared<terrama2::core::FileRemover>();
      path = retrieverFTP.retrieveData(mask, filter, "UTC+00", remover);

    }
    catch(...)
    {
      QFAIL("Unexpected exception!");
    }
  }
  catch(const terrama2::Exception& e)
  {
    QFAIL(boost::get_error_info< terrama2::ErrorDescription >(e)->toStdString().c_str());
  }

  catch(...)
  {
    QFAIL("Unexpected exception!");
  }

  return;

}
Ejemplo n.º 26
0
    void updateURL(const QString &text) {
        QList<QUrl> urls;
        FileInfo::urlsInText(text, FileInfo::TestExistenceYes, file != NULL && file->property(File::Url).toUrl().isValid() ? QUrl(file->property(File::Url).toUrl()).path() : QString(), urls);
        if (!urls.isEmpty() && urls.first().isValid())
            urlToOpen = urls.first();
        else
            urlToOpen = QUrl();

        /// set special "open URL" button visible if URL (or file or DOI) found
        buttonOpenUrl->setVisible(urlToOpen.isValid());
        buttonOpenUrl->setToolTip(i18n("Open '%1'", urlToOpen.url(QUrl::PreferLocalFile)));
    }
Ejemplo n.º 27
0
void UnTiny::slot301Redirected(KIO::Job* job, QUrl fromUrl, QUrl toUrl)
{
    QPointer<Choqok::UI::PostWidget> postToParse = mParsingList.take(job);
    job->kill();
    if(postToParse){
        QString content = postToParse->content();
        QString fromUrlStr = fromUrl.url();
        content.replace(QRegExp(QStringLiteral("title='%1\'").arg(fromUrlStr)), QStringLiteral("title='%1\'").arg(toUrl.url()));
        content.replace(QRegExp(QStringLiteral("href='%1\'").arg(fromUrlStr)), QStringLiteral("href='%1\'").arg(toUrl.url()));
        postToParse->setContent(content);
        Choqok::ShortenManager::self()->emitNewUnshortenedUrl(postToParse, fromUrl, toUrl);
        if (toUrl.url().length() < 30 && fromUrl.host() == QLatin1String("t.co")){
            KIO::TransferJob *job = KIO::mimetype( toUrl, KIO::HideProgressInfo );
            if ( job ) {
                connect( job, &KIO::MimetypeJob::permanentRedirection, this, &UnTiny::slot301Redirected );
                mParsingList.insert(job, postToParse);
                job->start();
            }
        }
    }
}
Ejemplo n.º 28
0
bool CsvXXPort::exportContacts(const ContactList &contacts, VCardExportSelectionWidget::ExportFields) const
{
    QUrl url = QFileDialog::getSaveFileUrl(parentWidget(), QString(), QUrl::fromLocalFile(QStringLiteral("addressbook.csv")));
    if (url.isEmpty()) {
        return true;
    }

    if (QFileInfo(url.isLocalFile() ? url.toLocalFile() : url.path()).exists()) {
        if (url.isLocalFile() && QFileInfo(url.toLocalFile()).exists()) {
            PimCommon::RenameFileDialog::RenameFileDialogResult result = PimCommon::RenameFileDialog::RENAMEFILE_IGNORE;
            PimCommon::RenameFileDialog *dialog = new PimCommon::RenameFileDialog(url, false, parentWidget());
            result = static_cast<PimCommon::RenameFileDialog::RenameFileDialogResult>(dialog->exec());
            if (result == PimCommon::RenameFileDialog::RENAMEFILE_RENAME) {
                url = dialog->newName();
            } else if (result == PimCommon::RenameFileDialog::RENAMEFILE_IGNORE) {
                delete dialog;
                return true;
            }
            delete dialog;
        }
    }

    if (!url.isLocalFile()) {
        QTemporaryFile tmpFile;
        if (!tmpFile.open()) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b></qt>", url.url());
            KMessageBox::error(parentWidget(), msg);
            return false;
        }

        exportToFile(&tmpFile, contacts.addressList());
        tmpFile.flush();
        auto job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url, -1, KIO::Overwrite);
        KJobWidgets::setWindow(job, parentWidget());
        return job->exec();
    } else {
        QFile file(url.toLocalFile());
        if (!file.open(QIODevice::WriteOnly)) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b>.</qt>", url.toLocalFile());
            KMessageBox::error(parentWidget(), msg);
            return false;
        }

        exportToFile(&file, contacts.addressList());
        file.close();

        return true;
    }
}
Ejemplo n.º 29
0
// adds a url to the list, or increase rank of an existing url, making
// sure to bump it up the list if needed
void PopularUrls::addUrl(const QUrl& url)
{
    QUrl tmpurl = url;
    tmpurl.setPassword(QString()); // make sure no passwords are permanently stored
    if (!tmpurl.path().endsWith('/')) // make a uniform trailing slash policy
        tmpurl.setPath(tmpurl.path() + '/');
    UrlNodeP pnode;

    decreaseRanks();
    if (!head) { // if the list is empty ... (assumes dict to be empty as well)
        pnode = new UrlNode;
        pnode->rank = STARTING_RANK;
        pnode->url = tmpurl;
        appendNode(pnode);
        ranks.insert(tmpurl.url(), head);
    } else {
        if (ranks.find(tmpurl.url()) == ranks.end()) {  // is the added url new? if so, append it
            pnode = new UrlNode;
            pnode->rank = STARTING_RANK;
            pnode->url = tmpurl;
            appendNode(pnode);
            ranks.insert(tmpurl.url(), pnode);
        } else {
            pnode = ranks[ tmpurl.url()];
            pnode->rank += INCREASE;
        }
    }

    // do we need to change location for this one?
    relocateIfNeeded(pnode);

    // too many urls?
    if (count > maxUrls) removeNode(tail);

    //dumpList();
}
Ejemplo n.º 30
0
void BackendGoogleMaps::setMarkerPixmap(const int modelId, const int markerId,
                                        const QPoint& centerPoint, const QSize& iconSize,
                                        const QUrl& iconUrl
                                       )
{
    /// @todo Sort the parameters
    d->htmlWidget->runScript(QString::fromLatin1("kgeomapSetMarkerPixmap(%7,%1,%5,%6,%2,%3,'%4');")
                    .arg(markerId)
                    .arg(centerPoint.x())
                    .arg(centerPoint.y())
                    .arg(iconUrl.url()) /// @todo Escape characters like apostrophe
                    .arg(iconSize.width())
                    .arg(iconSize.height())
                    .arg(modelId)
                );
}