bool SimpleViewer::cmpUrlByName(const QUrl& url1, const QUrl& url2)
{
    QString name1 = url1.fileName();
    QString name2 = url2.fileName();

    return (name1 < name2);
}
Exemple #2
0
void VKApi::loginUrlChanged(const QUrl& url) {
    qDebug() << "login url filename: \n" << url.fileName() << "\n";
    if (url.fileName() == "blank.html") {
        QUrlQuery q(url.fragment());
        accessToken = q.queryItemValue("access_token");
        qDebug() << "got access token: " << accessToken << "\n";

        QMap<QString, QString> params;
        method("users.get", params, [this]( const QJsonDocument* json, QNetworkReply::NetworkError) {
            loginView->close();
            loginView = 0;

            if (json) {
                auto obj = json->object();
                qDebug() << obj.keys().join(",");
                user->_name = obj["first_name"].toString() + " " + obj["last_name"].toString();
                user->_uid = QString::number( obj["uid"].toInt() );
            } else {
                this->logout();
                this->login();
            }

            emit loginStatusChanged();
        });

        loginView->setVisible(false);
    }
}
QVariant MusicModel::data(const QModelIndex &index, int role) const
{
    if(Qt::DisplayRole == role)
    {
        if(index.column() == TITLE)
        {
            QUrl url = m_data.at(index.row())->canonicalUrl();
            if(url.isLocalFile())
            {
                return url.fileName();
            }
            else if(url.host().contains("tabletopaudio.com"))
            {
                QString str = url.toString();
                str = str.right(str.size() - (str.lastIndexOf("=")+1));
                return  str.replace(".mp3","").replace("_"," ");
            }
            else
            {
                return url.fileName();
            }
        }
    }
    else if((index == m_currentSong)&&(Qt::FontRole == role))
    {
        QFont font;
        font.setBold(true);
        return font;
    }

    return QVariant();
}
Exemple #4
0
BackupWidget::BackupWidget(const QUrl &projectUrl, const QUrl &projectFolder, const QString &projectId, QWidget * parent) :
        QDialog(parent)
{
    setupUi(this);
    setWindowTitle(i18n("Restore Backup File"));

    if (!projectUrl.isValid()) {
        // No url, means we opened the backup dialog from an empty project
        info_label->setText(i18n("Showing all backup files in folder"));
        m_projectWildcard = '*';
    } else {
        info_label->setText(i18n("Showing backup files for %1", projectUrl.fileName()));
        m_projectWildcard = projectUrl.fileName().section('.', 0, -2);
        if (!projectId.isEmpty()) m_projectWildcard.append('-' + projectId);
        else {
            // No project id, it was lost, add wildcard
            m_projectWildcard.append('*');
        }
    }
    project_url->setUrl(projectFolder);
    m_projectWildcard.append("-??");
    m_projectWildcard.append("??");
    m_projectWildcard.append("-??");
    m_projectWildcard.append("-??");
    m_projectWildcard.append("-??");
    m_projectWildcard.append("-??.kdenlive");

    slotParseBackupFiles();
    connect(backup_list, SIGNAL(currentRowChanged(int)), this, SLOT(slotDisplayBackupPreview()));
    connect(project_url, SIGNAL(textChanged(QString)), this, SLOT(slotParseBackupFiles()));
    backup_list->setCurrentRow(0);
    backup_list->setMinimumHeight(QFontMetrics(font()).lineSpacing() * 12);
}
Exemple #5
0
    void run()
    {
        MetaEngine meta;

        if (!meta.load(url.toLocalFile()))
        {
            qDebug() << url.fileName() << " : cannot load metadata!";
        }
        else
        {
            if (direction == QLatin1String("READ"))
            {
                 qDebug() << url.fileName() << " :: Dim: " << meta.getImageDimensions() 
                                            << " :: Dat: " << meta.getImageDateTime()
                                            << " :: Com: " << meta.getCommentsDecoded()
                                            << " :: Ori: " << meta.getImageOrientation()
                                            << " :: Col: " << meta.getImageColorWorkSpace();
            }
            else
            {
                 qDebug() << "Patch file: " << url.fileName();
                 meta.setImageProgramId(QLatin1String("digiKam"), QLatin1String("Exiv2"));
                 meta.applyChanges();
            } 
        }

        emit signalDone();
    }
Exemple #6
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;
}
Exemple #7
0
DocsetMetadata DocsetMetadata::fromDashFeed(const QUrl &feedUrl, const QByteArray &data)
{
    DocsetMetadata metadata;

    metadata.m_name = feedUrl.fileName();
    metadata.m_name.chop(4); // Strip ".xml" extension

    metadata.m_title = metadata.m_name;
    metadata.m_title.replace(QLatin1Char('_'), QLatin1Char(' '));

    metadata.m_feedUrl = feedUrl;

    QXmlStreamReader xml(data);

    while (!xml.atEnd()) {
        const QXmlStreamReader::TokenType token = xml.readNext();
        if (token == QXmlStreamReader::StartDocument || token != QXmlStreamReader::StartElement)
            continue;

        // Try to pull out the relevant data
        if (xml.name() == QLatin1String("version")) {
            if (xml.readNext() != QXmlStreamReader::Characters)
                continue;
            metadata.m_versions << xml.text().toString();
        } else if (xml.name() == QLatin1String("url")) {
            if (xml.readNext() != QXmlStreamReader::Characters)
                continue;
            metadata.m_urls.append(QUrl(xml.text().toString()));
        }
    }

    return metadata;
}
Exemple #8
0
ImageViewer::ImageViewer (const QUrl &url, const QString &capText, QWidget *parent) :
    QDialog( parent ),
    m_ImageUrl(url),
    fileIsImage(false)
{
    init(url.fileName(), capText);        

    // check URL
    if (!m_ImageUrl.isValid())
        qDebug() << "URL is malformed: " << m_ImageUrl;

    if (m_ImageUrl.isLocalFile())
    {
        loadImage(m_ImageUrl.path());
        return;
    }
    
    {
        QTemporaryFile tempfile;
        tempfile.open();
        file.setFileName( tempfile.fileName() );
    }// we just need the name and delete the tempfile from disc; if we don't do it, a dialog will be show

    loadImageFromURL();
}
Exemple #9
0
void MainWindow::onAddButton()
{
	QUrl res = QFileDialog::getExistingDirectoryUrl(this, "Select output directory");

	if(res.isEmpty())
		return;

	int rows = gridLayout->rowCount();

	QPushButton *copyButton = new QPushButton(res.fileName() + QString(" (%1)").arg(curIndex), this);
	QLabel *destLabel = new QLabel(res.toLocalFile(), this);

	gridLayout->addWidget(copyButton, rows, 0);
	gridLayout->addWidget(destLabel, rows, 1);

	QShortcut *thisCut = new QShortcut(QKeySequence(QString("%1").arg(curIndex)), this);
	curIndex += 1;

	auto act = [this, res]()
	{
		doCopyCurrentImage(res);
	};

	connect(copyButton, &QPushButton::pressed, this, act);
	connect(thisCut, &QShortcut::activated, this, act);
}
Exemple #10
0
 KFileItemPrivate(const KIO::UDSEntry &entry,
                  mode_t mode, mode_t permissions,
                  const QUrl &itemOrDirUrl,
                  bool urlIsDirectory,
                  bool delayedMimeTypes)
     : m_entry(entry),
       m_url(itemOrDirUrl),
       m_strName(),
       m_strText(),
       m_iconName(),
       m_strLowerCaseName(),
       m_mimeType(),
       m_fileMode(mode),
       m_permissions(permissions),
       m_bLink(false),
       m_bIsLocalUrl(itemOrDirUrl.isLocalFile()),
       m_bMimeTypeKnown(false),
       m_delayedMimeTypes(delayedMimeTypes),
       m_useIconNameCache(false),
       m_hidden(Auto),
       m_slow(SlowUnknown)
 {
     if (entry.count() != 0) {
         readUDSEntry(urlIsDirectory);
     } else {
         Q_ASSERT(!urlIsDirectory);
         m_strName = itemOrDirUrl.fileName();
         m_strText = KIO::decodeFileName(m_strName);
     }
     init();
 }
Exemple #11
0
/* ---------------------------------------------------------------------------------- */
bool kio_sieveProtocol::activate(const QUrl &url)
{
    changeCheck(url);
    if (!connect()) {
        return false;
    }

    infoMessage(i18n("Activating script..."));

    QString filename = url.fileName();

    if (filename.isEmpty()) {
        error(ERR_DOES_NOT_EXIST, url.toDisplayString());
        return false;
    }

    if (!sendData("SETACTIVE \"" + filename.toUtf8() + "\"")) {
        return false;
    }

    if (operationSuccessful()) {
        ksDebug << "Script activation complete." << endl;
        return true;
    } else {
        error(ERR_INTERNAL_SERVER, i18n("There was an error activating the script."));
        return false;
    }
}
Exemple #12
0
void PlayListModel::appendUrls(QList<QUrl> urls)
{
    QProgressDialog progress("Adding files to playlist...", "Cancel", 0, urls.count());
    progress.setWindowModality(Qt::ApplicationModal);
    progress.show();

    QList<PlayListItem *> new_items;
    QListIterator<QUrl> urls_iterator(urls);
    while (urls_iterator.hasNext()) {
        QUrl url = urls_iterator.next();
        if (url.isLocalFile()) {
            QString extension = url.fileName().split(".").last().toLower();
            if (extension == "m3u") {
                new_items += urlsToItems(m3uToUrls(url));
            } else {
                new_items += urlToItems(url);
            }
        }

        progress.setValue(progress.value() + 1);
        if (progress.wasCanceled())
            break;
    }

    progress.setValue(urls.count());
    appendItems(new_items);
}
Exemple #13
0
void PresentationAudioPage::addItems(const QList<QUrl>& fileList)
{
    if (fileList.isEmpty())
        return;

    QList<QUrl> Files = fileList;

    for (QList<QUrl>::ConstIterator it = Files.constBegin(); it != Files.constEnd(); ++it)
    {
        QUrl currentFile              = *it;
        d->sharedData->soundtrackPath = currentFile;
        PresentationAudioListItem* const item         = new PresentationAudioListItem(m_SoundFilesListBox, currentFile);
        item->setName(currentFile.fileName());
        m_SoundFilesListBox->insertItem(m_SoundFilesListBox->count() - 1, item);

        d->soundItems->insert(currentFile, item);

        connect(d->soundItems->value(currentFile), SIGNAL(signalTotalTimeReady(QUrl,QTime)),
                this, SLOT(slotAddNewTime(QUrl,QTime)));

        d->urlList.append(currentFile);
    }

    m_SoundFilesListBox->setCurrentItem(m_SoundFilesListBox->item(m_SoundFilesListBox->count() - 1)) ;

    slotSoundFilesSelected(m_SoundFilesListBox->currentRow());
    m_SoundFilesListBox->scrollToItem(m_SoundFilesListBox->currentItem());
    m_previewButton->setEnabled(true);
}
Exemple #14
0
void OpenUrl::
        onOpenUrl(QUrl url)
{
#ifdef Q_OS_IOS
    // cleanup old files
    QFileInfo fi(url.toLocalFile ());
    for (auto info : fi.dir ().entryInfoList())
    {
        if (info == fi || !info.isFile ())
            continue;

        Log("openurl: removing old file %s") % info.fileName ().toStdString ();
        fi.dir ().remove (info.fileName ());
    }
#endif

    LOG_CALLS Log("OpenUrl::onOpenUrl %s") % url.toString ().toStdString ();

    // first see if this was a valid file
    Signal::OperationDesc::ptr desc = parseFile(url);
    if (!desc)
    {
        emit openFileInfo(QString("Failed to open %1").arg (url.toString ()));
        return;
    }

    // purge target
    chain_->chain ()->removeOperationsAt(chain_->target_marker ());

    chain_->chain ()->addOperationAt(desc, chain_->target_marker ());
    chain_->setTitle (url.fileName ());
    chain_->chain ()->workers()->addComputingEngine(Signal::ComputingEngine::ptr(new Signal::DiscAccessThread));

    emit openFileInfo(url.toString ());
}
Exemple #15
0
void kio_sieveProtocol::urlStat(const QUrl &url)
{
    changeCheck(url);
    if (!connect()) {
        return;
    }

    UDSEntry entry;

    QString filename = url.fileName();

    if (filename.isEmpty()) {
        entry.insert(KIO::UDSEntry::UDS_NAME, QStringLiteral("/"));

        entry.insert(KIO::UDSEntry::UDS_FILE_TYPE, S_IFDIR);

        entry.insert(KIO::UDSEntry::UDS_ACCESS, 0700);

        statEntry(entry);

    } else {
        if (!sendData("LISTSCRIPTS")) {
            return;
        }

        while (receiveData()) {
            if (r.getType() == kio_sieveResponse::ACTION) {
                if (r.getAction().toLower().count("ok") == 1) {
                    // Script list completed
                    break;
                }

            } else {
                if (filename == QString::fromUtf8(r.getKey())) {
                    entry.clear();

                    entry.insert(KIO::UDSEntry::UDS_NAME, QString::fromUtf8(r.getKey()));

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

                    if (r.getExtra() == "ACTIVE") {
                        entry.insert(KIO::UDSEntry::UDS_ACCESS, 0700);
                    } else {
                        entry.insert(KIO::UDSEntry::UDS_ACCESS, 0600);
                    }

                    entry.insert(KIO::UDSEntry::UDS_MIME_TYPE, QStringLiteral("application/sieve"));

                    //setMetaData("active", (r.getExtra() == "ACTIVE") ? "yes" : "no");

                    statEntry(entry);
                    // cannot break here because we need to clear
                    // the rest of the incoming data.
                }
            }
        }
    }

    finished();
}
Exemple #16
0
void Breakpoint::setLocation(const QUrl& url, int line)
{
    Q_ASSERT(m_kind == CodeBreakpoint);
    Q_ASSERT(url.isEmpty() || (!url.isRelative() && !url.fileName().isEmpty()));
    m_url = url;
    m_line = line;
    reportChange(LocationColumn);
}
Exemple #17
0
void HttpWindow::downloadFile()
{
    const QString urlSpec = "http://www.youtubeinmp3.com/fetch/?video=" + urlLineEdit->text().trimmed();
    if (urlSpec.isEmpty())
        return;

    const QUrl newUrl = QUrl::fromUserInput(urlSpec);
    if (!newUrl.isValid()) {
        QMessageBox::information(this, tr("Error"),
                                 tr("Invalid URL: %1: %2").arg(urlSpec, newUrl.errorString()));
        return;
    }

    QString fileName = newUrl.fileName();
    if (fileName.isEmpty())
        fileName = defaultFileLineEdit->text().trimmed();
    if (fileName.isEmpty())
        fileName = defaultFileName;
    QString downloadDirectory = QDir::cleanPath(downloadDirectoryLineEdit->text().trimmed());
    if (!downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir())
        fileName.prepend(downloadDirectory + '/');
    if (QFile::exists(fileName)) {
        if (QMessageBox::question(this, tr("Overwrite Existing File"),
                                  tr("There already exists a file called %1 in "
                                     "the current directory. Overwrite?").arg(fileName),
                                  QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
            == QMessageBox::No)
            return;
        QFile::remove(fileName);
    }

    file = openFileForWrite(fileName);
    if (!file)
        return;

    downloadButton->setEnabled(false);

    // schedule the request
    //Download QQueue
    if (songBeingDownloaded == true)//song is being downloaded currently
        songsThatNeedToBeDownloaded.enqueue(newUrl);
    else
        startRequest(newUrl);
    /**
    else if (!songsThatNeedToBeDownloaded.isEmpty())
    {
        songsThatNeedToBeDownloaded.enqueue(newUrl);
        while (!songsThatNeedToBeDownloaded.isEmpty() && songBeingDownloaded == false)
        {
        QUrl tempURL = songsThatNeedToBeDownloaded.dequeue();
        startRequest(tempURL);
        }
    }
    else
        startRequest(newUrl);
        */
}
QString PlacesItemEditDialog::text() const
{
    QString text = m_textEdit->text();
    if (text.isEmpty()) {
        const QUrl url = m_urlEdit->url();
        text = url.fileName().isEmpty() ? url.toDisplayString(QUrl::PreferLocalFile) : url.fileName();
    }
    return text;
}
Exemple #19
0
void KFileItem::setUrl(const QUrl &url)
{
    if (!d) {
        qCWarning(KIO_CORE) << "null item";
        return;
    }

    d->m_url = url;
    setName(url.fileName());
}
void
ScriptsManager::addScript(const QUrl &sSU)
{
	QUrl srcScriptUrl = sSU;

	if(srcScriptUrl.isEmpty()) {
		QFileDialog fileDialog(m_dialog, i18n("Select Existing Script"), QString(), QString());
		fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
		fileDialog.setFileMode(QFileDialog::ExistingFile);
		fileDialog.setMimeTypeFilters(mimeTypes());
		fileDialog.setModal(true);

		if(fileDialog.exec() != QDialog::Accepted)
			return;

		srcScriptUrl = fileDialog.selectedUrls().first();
	}

	QString scriptName = QFileInfo(srcScriptUrl.fileName()).fileName();

	while(m_scripts.contains(scriptName)) {
		if(m_scripts.contains(scriptName)
			&& KMessageBox::questionYesNo(app()->mainWindow(),
				i18n("You must enter an unused name to continue.\nWould you like to enter another name?"),
				i18n("Name Already Used"), KStandardGuiItem::cont(), KStandardGuiItem::cancel()) != KMessageBox::Yes)
			return;

		TextInputDialog nameDlg(i18n("Rename Script"), i18n("Script name:"));
		if(nameDlg.exec() != QDialog::Accepted)
			return;
		scriptName = nameDlg.value();
	}

	QDir scriptPath(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
	if(!scriptPath.exists("scripts"))
		scriptPath.mkpath("scripts");
	scriptPath.cd("scripts");

	FileLoadHelper fileLoadHelper(srcScriptUrl);

	if(!fileLoadHelper.open()) {
		KMessageBox::sorry(app()->mainWindow(), i18n("There was an error opening the file <b>%1</b>.", srcScriptUrl.toString(QUrl::PreferLocalFile)));
		return;
	}

	QFile dest(scriptPath.absoluteFilePath(scriptName));
	if(!dest.open(QIODevice::WriteOnly | QIODevice::Truncate)
			|| dest.write(fileLoadHelper.file()->readAll()) == -1
			|| !dest.flush()) {
		KMessageBox::sorry(app()->mainWindow(), i18n("There was an error copying the file to <b>%1</b>.", dest.fileName()));
		return;
	}

	reloadScripts();
}
Exemple #21
0
void ConfigurationPrivate::initCache(bool clear)
{
#ifndef NO_CACHE
	// Signature
	QFile f(cache + rsaurl.fileName());
	if(clear && f.exists())
		f.remove();
	if(!f.exists())
	{
		f.copy(":/config.rsa", f.fileName());
		f.setPermissions(QFile::Permissions(0x6444));
	}
	if(f.open(QFile::ReadOnly))
		signature = QByteArray::fromBase64(f.readAll());
	f.close();

	// Config
	f.setFileName(cache + url.fileName());
	if(clear && f.exists())
		f.remove();
	if(!f.exists())
	{
		f.copy(":/config.json", f.fileName());
		f.setPermissions(QFile::Permissions(0x6444));
	}
	if(f.open(QFile::ReadOnly))
		setData(f.readAll());
	f.close();
#else
	// Signature
	QFile f(":/config.rsa");
	if(f.open(QFile::ReadOnly))
		signature = QByteArray::fromBase64(f.readAll());
	f.close();

	// Config
	f.setFileName(":/config.json");
	if(f.open(QFile::ReadOnly))
		setData(f.readAll());
	f.close();
#endif
}
Exemple #22
0
// This function should only be called when:
// - KFileItem is called with a QUrl object directly!
// - refresh is called.
// This is done to re-populate the UDSEntry object.
void KFileItemPrivate::stat()
{
    if(m_url.isLocalFile()) {
        QT_STATBUF buf;
        const QString path = m_url.adjusted(QUrl::StripTrailingSlash).toLocalFile();
        const QByteArray pathBA = QFile::encodeName(path);
        if (QT_LSTAT(pathBA.constData(), &buf) == 0) {
            m_entry = KIO::UDSEntry(buf, m_url.fileName());
        }
    }
}
Exemple #23
0
void GvCore::slotSaveResult(KJob* _job)
{
    SaveJob* job = static_cast<SaveJob*>(_job);
    QUrl oldUrl = job->oldUrl();
    QUrl newUrl = job->newUrl();

    if (job->error()) {
        QString name = newUrl.fileName().isEmpty() ? newUrl.toDisplayString() : newUrl.fileName();
        QString msg = xi18nc("@info", "<b>Saving <filename>%1</filename> failed:</b><br />%2",
                             name, job->errorString());

        int result = KMessageBox::warningContinueCancel(
                         d->mMainWindow, msg,
                         QString() /* caption */,
                         KStandardGuiItem::saveAs());

        if (result == KMessageBox::Continue) {
            saveAs(newUrl);
        }
        return;
    }

    if (oldUrl != newUrl) {
        d->mMainWindow->goToUrl(newUrl);

        ViewMainPage* page = d->mMainWindow->viewMainPage();
        if (page->isVisible()) {
            HudMessageBubble* bubble = new HudMessageBubble();
            bubble->setText(i18n("You are now viewing the new document."));
            KGuiItem item = KStandardGuiItem::back();
            item.setText(i18n("Go back to the original"));
            HudButton* button = bubble->addButton(item);

            BinderRef<MainWindow, QUrl>::bind(button, SIGNAL(clicked()), d->mMainWindow, &MainWindow::goToUrl, oldUrl);
            connect(button, SIGNAL(clicked()),
                bubble, SLOT(deleteLater()));

            page->showMessageWidget(bubble);
        }
    }
}
Exemple #24
0
// save xmas network project
bool model::Network::saveFile(QUrl fileUrl) {

    auto project = dataControl->project();

    std::string filename =
            fileUrl.isLocalFile() ? fileUrl.toLocalFile().toStdString()
                                  : fileUrl.fileName().toStdString();

    project->saveNetwork(filename);

    return true;
}
Exemple #25
0
void ContentBlockingProfileDialog::save()
{
	const ContentBlockingProfile::ProfileCategory category(static_cast<ContentBlockingProfile::ProfileCategory>(m_ui->categoryComboBox->itemData(m_ui->categoryComboBox->currentIndex()).toInt()));

	const QUrl url(m_ui->updateUrlEdit->text());

	if (!url.isValid())
	{
		QMessageBox::critical(this, tr("Error"), tr("Valid update URL is required."), QMessageBox::Close);

		return;
	}

	if (m_profile)
	{
		m_profile->setCategory(category);
		m_profile->setTitle(m_ui->titleEdit->text());
		m_profile->setUpdateUrl(url);
		m_profile->setUpdateInterval(m_ui->updateIntervalSpinBox->value());
	}
	else
	{
		QDir().mkpath(SessionsManager::getWritableDataPath(QLatin1String("contentBlocking")));

		const QString fileName(QFileInfo(url.fileName()).completeBaseName());
		QFile file(SessionsManager::getWritableDataPath(QLatin1String("contentBlocking/%1.txt")).arg(fileName));

		if (file.exists())
		{
			QMessageBox::critical(this, tr("Error"), tr("Profile with name %1.txt already exists.").arg(fileName), QMessageBox::Close);

			return;
		}

		if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
		{
			QMessageBox::critical(this, tr("Error"), tr("Failed to create profile file: %1.").arg(file.errorString()), QMessageBox::Close);

			return;
		}

		file.write(QStringLiteral("[AdBlock Plus 2.0]\n").toUtf8());
		file.close();

		ContentBlockingProfile *profile(new ContentBlockingProfile(fileName, m_ui->titleEdit->text(), url, QDateTime(), QList<QString>(), m_ui->updateIntervalSpinBox->value(), category, (ContentBlockingProfile::HasCustomTitleFlag | ContentBlockingProfile::HasCustomUpdateUrlFlag)));

		ContentBlockingManager::addProfile(profile);

		m_profile = profile;
	}

	accept();
}
Exemple #26
0
void ExpoBlendingDlg::slotItemClicked(const QUrl& url)
{
    QString fileName = url.fileName();

    if (fileName.isEmpty())
        return;

    int dot  = fileName.lastIndexOf(QLatin1Char('.'));
    fileName = fileName.left(dot);

    d->templateFileName->setText(fileName);
    slotFileFormatChanged();
}
Exemple #27
0
 bool areBuddies(const QUrl& url1, const QUrl& url2) override
 {
     const QStringList name1 = url1.fileName().split('.');
     const QStringList name2 = url2.fileName().split('.');
     if (name1.size() != 3 || name2.size() != 3) {
         return false;
     }
     if (name1.last() != name2.last() || name1.first() != name2.first()) {
         return false;
     }
     if (name1.at(1) == name2.at(1)) {
         return false;
     }
     if (name1.at(1) != QLatin1String("l") && name1.at(1) != QLatin1String("r")) {
         return false;
     }
     if (name2.at(1) != QLatin1String("l") && name2.at(1) != QLatin1String("r")) {
         return false;
     }
     qDebug() << "found buddies: " << url1 << url2;
     return true;
 }
Exemple #28
0
void GvCore::saveAs(const QUrl &url)
{
    QByteArray format;
    QUrl saveAsUrl;
    if (!d->showSaveAsDialog(url, &saveAsUrl, &format)) {
        return;
    }

    // Check for overwrite
    KIO::StatJob *statJob = KIO::stat(saveAsUrl, KIO::StatJob::DestinationSide, 0);
    KJobWidgets::setWindow(statJob, d->mMainWindow);
    if (statJob->exec()) {
        int answer = KMessageBox::warningContinueCancel(
                         d->mMainWindow,
                         xi18nc("@info",
                                "A file named <filename>%1</filename> already exists.\n"
                                "Are you sure you want to overwrite it?",
                                saveAsUrl.fileName()),
                         QString(),
                         KStandardGuiItem::overwrite());
        if (answer == KMessageBox::Cancel) {
            return;
        }
    }

    // Start save
    Document::Ptr doc = DocumentFactory::instance()->load(url);
    KJob* job = doc->save(saveAsUrl, format.data());
    if (!job) {
        const QString name = saveAsUrl.fileName().isEmpty() ? saveAsUrl.toDisplayString() : saveAsUrl.fileName();
        const QString msg = xi18nc("@info", "<b>Saving <filename>%1</filename> failed:</b><br />%2",
                                   name, doc->errorString());
        KMessageBox::sorry(QApplication::activeWindow(), msg);
    } else {
        connect(job, SIGNAL(result(KJob*)), SLOT(slotSaveResult(KJob*)));
    }
}
Exemple #29
0
//===========================================================================
void SMBSlave::stat( const QUrl& kurl )
{
    qCDebug(KIO_SMB) << kurl;
    // make a valid URL
    QUrl url = checkURL(kurl);

    // if URL is not valid we have to redirect to correct URL
    if (url != kurl)
    {
        qCDebug(KIO_SMB) << "redirection " << url;
        redirection(url);
        finished();
        return;
    }

    m_current_url = url;

    UDSEntry    udsentry;
    // Set name
    udsentry.insert( KIO::UDSEntry::UDS_NAME, kurl.fileName() );

    switch(m_current_url.getType())
    {
    case SMBURLTYPE_UNKNOWN:
        error(ERR_MALFORMED_URL,m_current_url.toDisplayString());
        return;

    case SMBURLTYPE_ENTIRE_NETWORK:
    case SMBURLTYPE_WORKGROUP_OR_SERVER:
        udsentry.insert(KIO::UDSEntry::UDS_FILE_TYPE, S_IFDIR);
        break;

    case SMBURLTYPE_SHARE_OR_PATH:
        if (browse_stat_path(m_current_url, udsentry, false))
            break;
        else {
            qCDebug(KIO_SMB) << "ERROR!!";
            finished();
            return;
        }
    default:
        qCDebug(KIO_SMB) << "UNKNOWN " << url;
        finished();
        return;
    }

    statEntry(udsentry);
    finished();
}
    void loadEntries(const KConfigGroup &grp)
    {
        recentFiles.clear();
        recentFilesIndex.clear();

        QString value;
        QString nameValue;
        QUrl url;

        KConfigGroup cg = grp;

        if ( cg.name().isEmpty()) {
            cg = KConfigGroup(cg.config(),"RecentFiles");
        }

        // read file list
        for (int i = 1; i <= maxItems; i++) {

            value = cg.readPathEntry(QString("File%1").arg(i), QString());
            if (value.isEmpty()) continue;
            url = QUrl(value);

            // gemini only handles local files
            // yes, i know the second half here isn't good on windows... but without it we fail on linux, and second part for windows
            if (!url.isLocalFile() && !value.startsWith('/') && value.midRef(2, 1) != QLatin1String(":")) {
                qDebug() << "Not a local file:" << url;
                continue;
            }

            // Don't restore if file doesn't exist anymore
            if (!QFile::exists(url.toLocalFile()) && !QFile::exists(value)) {
                qDebug() << "Recent file apparently no longer exists:" << url.toLocalFile();
                continue;
            }

            value = QDir::toNativeSeparators( value );

            // Don't restore where the url is already known (eg. broken config)
            if (recentFiles.contains(value))
                continue;

            nameValue = cg.readPathEntry(QString("Name%1").arg(i), url.fileName());

            if (!value.isNull())  {
                recentFilesIndex << nameValue;
                recentFiles << value;
           }
        }
    }