void QmlConsoleItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); painter->save(); // Set Colors QColor textColor; QIcon taskIcon; ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data( ConsoleItem::TypeRole).toInt(); switch (type) { case ConsoleItem::DebugType: textColor = QColor(CONSOLE_LOG_TEXT_COLOR); taskIcon = m_logIcon; break; case ConsoleItem::WarningType: textColor = QColor(CONSOLE_WARNING_TEXT_COLOR); taskIcon = m_warningIcon; break; case ConsoleItem::ErrorType: textColor = QColor(CONSOLE_ERROR_TEXT_COLOR); taskIcon = m_errorIcon; break; case ConsoleItem::InputType: textColor = QColor(CONSOLE_EDITOR_TEXT_COLOR); taskIcon = m_prompt; break; default: textColor = QColor(CONSOLE_EDITOR_TEXT_COLOR); break; } // Paint background QColor backgroundColor = drawBackground(painter, opt.rect, index, bool(opt.state & QStyle::State_Selected)); // Calculate positions const QTreeView *view = qobject_cast<const QTreeView *>(opt.widget); int level = 0; QModelIndex idx(index); while (idx.parent() != QModelIndex()) { idx = idx.parent(); level++; } int width = view->width() - level * view->indentation() - view->verticalScrollBar()->width(); bool showTypeIcon = index.parent() == QModelIndex(); bool showExpandableIcon = type == ConsoleItem::DefaultType; QRect rect(opt.rect.x(), opt.rect.top(), width, opt.rect.height()); ConsoleItemPositions positions(rect, opt.font, showTypeIcon, showExpandableIcon); // Paint TaskIconArea: if (showTypeIcon) painter->drawPixmap(positions.adjustedLeft(), positions.adjustedTop(), taskIcon.pixmap(positions.typeIconWidth(), positions.typeIconHeight())); // Set Text Color painter->setPen(textColor); // Paint TextArea: // Layout the description QString str = index.data(Qt::DisplayRole).toString(); bool showFileLineInfo = true; // show complete text if selected if (view->selectionModel()->currentIndex() == index) { QTextLayout tl(str, opt.font); layoutText(tl, positions.textAreaWidth(), &showFileLineInfo); tl.draw(painter, QPoint(positions.textAreaLeft(), positions.adjustedTop())); } else { QFontMetrics fm(opt.font); painter->drawText(positions.textArea(), fm.elidedText(str, Qt::ElideRight, positions.textAreaWidth())); } // skip if area is editable if (showExpandableIcon) { // Paint ExpandableIconArea: QIcon expandCollapseIcon; if (index.model()->rowCount(index) || index.model()->canFetchMore(index)) { if (view->isExpanded(index)) expandCollapseIcon = m_collapseIcon; else expandCollapseIcon = m_expandIcon; } painter->drawPixmap(positions.expandCollapseIconLeft(), positions.adjustedTop(), expandCollapseIcon.pixmap(positions.expandCollapseIconWidth(), positions.expandCollapseIconHeight())); } if (showFileLineInfo) { // Check for file info QString file = index.data(ConsoleItem::FileRole).toString(); const QUrl fileUrl = QUrl(file); if (fileUrl.isLocalFile()) file = fileUrl.toLocalFile(); if (!file.isEmpty()) { QFontMetrics fm(option.font); // Paint FileArea const int pos = file.lastIndexOf(QLatin1Char('/')); if (pos != -1) file = file.mid(pos +1); const int realFileWidth = fm.width(file); painter->setClipRect(positions.fileArea()); painter->drawText(positions.fileAreaLeft(), positions.adjustedTop() + fm.ascent(), file); if (realFileWidth > positions.fileAreaWidth()) { // draw a gradient to mask the text int gradientStart = positions.fileAreaLeft() - 1; QLinearGradient lg(gradientStart + ELLIPSIS_GRADIENT_WIDTH, 0, gradientStart, 0); lg.setColorAt(0, Qt::transparent); lg.setColorAt(1, backgroundColor); painter->fillRect(gradientStart, positions.adjustedTop(), ELLIPSIS_GRADIENT_WIDTH, positions.lineHeight(), lg); } // Paint LineArea QString lineText = index.data(ConsoleItem::LineRole).toString(); painter->setClipRect(positions.lineArea()); const int realLineWidth = fm.width(lineText); painter->drawText(positions.lineAreaRight() - realLineWidth, positions.adjustedTop() + fm.ascent(), lineText); } } painter->setClipRect(opt.rect); painter->restore(); }
QString SettingsManager::getHost(const QUrl &url) { return (url.isLocalFile() ? QLatin1String("localhost") : url.host()); }
bool SynchronizerDirList::load(const QString &urlIn, bool wait) { if (busy) return false; currentUrl = urlIn; QUrl url = QUrl::fromUserInput(urlIn, QString(), QUrl::AssumeLocalFile); QHashIterator< QString, vfile *> lit(*this); while (lit.hasNext()) delete lit.next().value(); clear(); if (fileIterator) { delete fileIterator; fileIterator = 0; } if (url.isLocalFile()) { QString path = url.adjusted(QUrl::StripTrailingSlash).path(); QT_DIR* dir = QT_OPENDIR(path.toLocal8Bit()); if (!dir) { KMessageBox::error(parentWidget, i18n("Cannot open the %1 directory.", path), i18n("Error")); emit finished(result = false); return false; } QT_DIRENT* dirEnt; QString name; while ((dirEnt = QT_READDIR(dir)) != NULL) { name = QString::fromLocal8Bit(dirEnt->d_name); if (name == "." || name == "..") continue; if (ignoreHidden && name.startsWith('.')) continue; QString fullName = path + '/' + name; QT_STATBUF stat_p; QT_LSTAT(fullName.toLocal8Bit(), &stat_p); QString perm = KRpermHandler::mode2QString(stat_p.st_mode); bool symLink = S_ISLNK(stat_p.st_mode); QString symlinkDest; bool brokenLink = false; if (symLink) { // who the link is pointing to ? char symDest[256]; memset(symDest, 0, 256); int endOfName = 0; endOfName = readlink(fullName.toLocal8Bit(), symDest, 256); if (endOfName != -1) { QString absSymDest = symlinkDest = QString::fromLocal8Bit(symDest); if (!absSymDest.startsWith('/')) absSymDest = QDir::cleanPath(path + '/' + absSymDest); if (QDir(absSymDest).exists()) perm[0] = 'd'; if (!QDir(path).exists(absSymDest)) brokenLink = true; } } QString mime; QUrl fileURL = QUrl::fromLocalFile(fullName); vfile* item = new vfile(name, stat_p.st_size, perm, stat_p.st_mtime, symLink, brokenLink, stat_p.st_uid, stat_p.st_gid, mime, symlinkDest, stat_p.st_mode); item->vfile_setUrl(fileURL); insert(name, item); } QT_CLOSEDIR(dir); emit finished(result = true); return true; } else { KIO::Job *job = KIO::listDir(url, KIO::HideProgressInfo, true); connect(job, SIGNAL(entries(KIO::Job*, const KIO::UDSEntryList&)), this, SLOT(slotEntries(KIO::Job*, const KIO::UDSEntryList&))); connect(job, SIGNAL(result(KJob*)), this, SLOT(slotListResult(KJob*))); busy = true; if (!wait) return true; while (busy) qApp->processEvents(); return result; } }
void CSVImportExportPluginInterface::exportCSV() { QPointer<KAddressBookImportExport::KAddressBookContactSelectionDialog> dlg = new KAddressBookImportExport::KAddressBookContactSelectionDialog(itemSelectionModel(), false, parentWidget()); dlg->setMessageText(i18n("Which contact do you want to export?")); dlg->setDefaultAddressBook(defaultCollection()); if (!dlg->exec() || !dlg) { delete dlg; return; } const KContacts::AddresseeList contacts = dlg->selectedContacts().addressList(); delete dlg; if (contacts.isEmpty()) { KMessageBox::sorry(Q_NULLPTR, i18n("You have not selected any contacts to export.")); return; } KAddressBookImportExport::KAddressBookImportExportContactList contactLists; contactLists.setAddressList(contacts); QFileDialog::Options options = QFileDialog::DontConfirmOverwrite; QUrl url = QFileDialog::getSaveFileUrl(parentWidget(), QString(), QUrl::fromLocalFile(QStringLiteral("addressbook.csv")), QString(), Q_NULLPTR, options); if (url.isEmpty()) { return; } 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; } 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; } exportToFile(&tmpFile, contactLists.addressList()); tmpFile.flush(); auto job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url, -1, KIO::Overwrite); KJobWidgets::setWindow(job, parentWidget()); 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; } exportToFile(&file, contactLists.addressList()); file.close(); } }
KIOExec::KIOExec(const QStringList &args, bool tempFiles, const QString &suggestedFileName) : mExited(false) , mTempFiles(tempFiles) , mSuggestedFileName(suggestedFileName) , expectedCounter(0) , command(args.first()) , jobCounter(0) { qDebug() << "command=" << command << "args=" << args; for ( int i = 1; i < args.count(); i++ ) { const QUrl urlArg = QUrl::fromUserInput(args.value(i)); if (!urlArg.isValid()) { KMessageBox::error( 0L, i18n("Invalid URL: %1", args.value(i)) ); exit(1); } KIO::StatJob* mostlocal = KIO::mostLocalUrl( urlArg ); bool b = mostlocal->exec(); if (!b) { KMessageBox::error( 0L, i18n("File not found: %1", urlArg.toDisplayString())); exit(1); } Q_ASSERT(b); const QUrl url = mostlocal->mostLocalUrl(); //kDebug() << "url=" << url.url() << " filename=" << url.fileName(); // A local file, not an URL ? // => It is not encoded and not shell escaped, too. if ( url.isLocalFile() ) { FileInfo file; file.path = url.toLocalFile(); file.url = url; fileList.append(file); } // It is an URL else { if ( !url.isValid() ) KMessageBox::error( 0L, i18n( "The URL %1\nis malformed" , url.url() ) ); else if ( mTempFiles ) KMessageBox::error( 0L, i18n( "Remote URL %1\nnot allowed with --tempfiles switch" , url.toDisplayString() ) ); else // We must fetch the file { QString fileName = KIO::encodeFileName( url.fileName() ); if ( !suggestedFileName.isEmpty() ) fileName = suggestedFileName; // Build the destination filename, in ~/.kde/cache-*/krun/ // Unlike KDE-1.1, we put the filename at the end so that the extension is kept // (Some programs rely on it) QString krun_writable = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/krun/"; QDir().mkpath(krun_writable); // error handling will be done by the job QString tmp = krun_writable + QStringLiteral("%1_%2_%3").arg(QCoreApplication::applicationPid()).arg(jobCounter++).arg(fileName); FileInfo file; file.path = tmp; file.url = url; fileList.append(file); expectedCounter++; const QUrl dest = QUrl::fromLocalFile(tmp); qDebug() << "Copying" << url << " to" << dest; KIO::Job *job = KIO::file_copy( url, dest ); jobList.append( job ); connect( job, SIGNAL( result( KJob * ) ), SLOT( slotResult( KJob * ) ) ); } } } if ( mTempFiles ) { slotRunApp(); return; } counter = 0; if ( counter == expectedCounter ) slotResult( 0L ); }
bool BE::Contacts::eventFilter(QObject *o, QEvent *e) { if (o == m_ui->filter) { if (e->type() == QEvent::KeyPress) if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Down) m_ui->contacts->setFocus(); return false; } if (o == m_ui->contacts) { if (e->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Up && !m_ui->contacts->currentIndex().row()) { m_ui->filter->setFocus(); return true; } else if (ke->key() == Qt::Key_Delete) { removeCurrentContact(); return true; } } return false; } if (!m_currentContact) return false; switch (e->type()) { case QEvent::DragEnter: case QEvent::DragMove: case QEvent::Drop: { if (o != m_ui2->photo) return false; QDropEvent *de = static_cast<QDropEvent*>(e); if (!de->mimeData()) return false; QList<QUrl> urls = de->mimeData()->urls(); if (urls.isEmpty()) return false; QUrl url = urls.first(); if ( #if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0) url.isLocalFile() #else (url.scheme() == QLatin1String("file")) #endif && QImageReader(url.path()).canRead()) { if (e->type() == QEvent::Drop) importPhoto(url.path()); else de->acceptProposedAction(); } return false; } case QEvent::KeyPress: { const int key = static_cast<QKeyEvent*>(e)->key(); if (key == Qt::Key_Delete && o == m_ui2->photo) { // reset photo if (m_currentContact) m_currentContact->setData(QString(), Gui::AbookAddressbook::Photo); m_ui2->photo->setPixmap(m_incognitoPic); } else if (key == Qt::Key_Escape && o != m_ui2->photo) if (QLabel *l = qobject_cast<QLabel*>(o)) { setText(l, l->text()); return true; // prevent closing the dialog! } } default: return false; } return false; }
bool Manager::replace(const KileTemplate::Info& toBeReplaced, const QUrl &newTemplateSourceURL, const QString& newName, const QUrl& newIcon) { KileDocument::Type type = m_kileInfo->extensions()->determineDocumentType(newTemplateSourceURL); //start by copying the files that belong to the new template to a safe place QString templateTempFile, iconTempFile; if( newTemplateSourceURL.isLocalFile() ) { // file protocol. We do not need the network templateTempFile = newTemplateSourceURL.toLocalFile(); } else { QTemporaryFile tmpFile; tmpFile.setAutoRemove( false ); tmpFile.open(); templateTempFile = tmpFile.fileName(); m_TempFilePath = tmpFile.fileName(); KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newTemplateSourceURL, QUrl::fromLocalFile(templateTempFile), -1, KIO::Overwrite ); KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() ); if( ! fileCopyJob->exec() ) { return false; } } if( newIcon.isLocalFile() ) { // file protocol. We do not need the network iconTempFile = newIcon.toLocalFile(); } else { QTemporaryFile tmpFile; tmpFile.setAutoRemove( false ); tmpFile.open(); iconTempFile = tmpFile.fileName(); m_TempFilePath = tmpFile.fileName(); KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newIcon, QUrl::fromLocalFile(iconTempFile), -1, KIO::Overwrite ); KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() ); if( ! fileCopyJob->exec() ) { if( ! templateTempFile.isEmpty() ) QFile::remove( templateTempFile ); return false; } } //now delete the template that should be replaced if(!remove(toBeReplaced)) { if( ! templateTempFile.isEmpty() ) QFile::remove( templateTempFile ); if( ! iconTempFile.isEmpty() ) QFile::remove( iconTempFile ); } //finally, create the new template if(!add(QUrl::fromUserInput(templateTempFile), type, newName, QUrl::fromUserInput(iconTempFile))) { if( ! templateTempFile.isEmpty() ) QFile::remove( templateTempFile ); if( ! iconTempFile.isEmpty() ) QFile::remove( iconTempFile ); return false; } if( ! templateTempFile.isEmpty() ) QFile::remove( templateTempFile ); if( ! iconTempFile.isEmpty() ) QFile::remove( iconTempFile ); return true; }
bool QPlatformFileDialogHelper::isSupportedUrl(const QUrl &url) const { return url.isLocalFile(); }
void QQuickStyledTextPrivate::parseImageAttributes(const QChar *&ch, const QString &textIn, QString &textOut) { qreal imgWidth = 0.0; if (!updateImagePositions) { QQuickStyledTextImgTag *image = new QQuickStyledTextImgTag; image->position = textOut.length() + 1; QPair<QStringRef,QStringRef> attr; do { attr = parseAttribute(ch, textIn); if (attr.first == QLatin1String("src")) { image->url = QUrl(attr.second.toString()); } else if (attr.first == QLatin1String("width")) { image->size.setWidth(attr.second.toString().toInt()); } else if (attr.first == QLatin1String("height")) { image->size.setHeight(attr.second.toString().toInt()); } else if (attr.first == QLatin1String("align")) { if (attr.second.toString() == QLatin1String("top")) { image->align = QQuickStyledTextImgTag::Top; } else if (attr.second.toString() == QLatin1String("middle")) { image->align = QQuickStyledTextImgTag::Middle; } } } while (!ch->isNull() && !attr.first.isEmpty()); if (preloadImages && !image->size.isValid()) { // if we don't know its size but the image is a local image, // we load it in the pixmap cache and save its implicit size // to avoid a relayout later on. QUrl url = baseUrl.resolved(image->url); if (url.isLocalFile()) { image->pix = new QQuickPixmap(context->engine(), url, image->size); if (image->pix && image->pix->isReady()) { image->size = image->pix->implicitSize(); } else { delete image->pix; image->pix = 0; } } } imgWidth = image->size.width(); imgTags->append(image); } else { // if we already have a list of img tags for this text // we only want to update the positions of these tags. QQuickStyledTextImgTag *image = imgTags->value(nbImages); image->position = textOut.length() + 1; imgWidth = image->size.width(); QPair<QStringRef,QStringRef> attr; do { attr = parseAttribute(ch, textIn); } while (!ch->isNull() && !attr.first.isEmpty()); nbImages++; } QFontMetricsF fm(layout.font()); QString padding(qFloor(imgWidth / fm.width(QChar::Nbsp)), QChar::Nbsp); textOut += QLatin1Char(' '); textOut += padding; textOut += QLatin1Char(' '); }
/*! */ QString SceneDocument::toFilePath(const QUrl& file_url) noexcept { return file_url.isLocalFile() ? file_url.toLocalFile() // Local file : ":" + file_url.toString(QUrl::RemoveScheme); // Resource file }
void OpenProjectDialog::validateOpenUrl( const QUrl& url_ ) { bool isDir = false; QString extension; bool isValid = false; const QUrl url = url_.adjusted(QUrl::StripTrailingSlash); if( url.isLocalFile() ) { QFileInfo info( url.toLocalFile() ); isValid = info.exists(); if ( isValid ) { isDir = info.isDir(); extension = info.suffix(); } } else if ( url.isValid() ) { KIO::StatJob* statJob = KIO::stat( url, KIO::HideProgressInfo ); KJobWidgets::setWindow(statJob, Core::self()->uiControllerInternal()->defaultMainWindow() ); isValid = statJob->exec(); // TODO: do this asynchronously so that the user isn't blocked while typing every letter of the hostname in sftp://hostname if ( isValid ) { KIO::UDSEntry entry = statJob->statResult(); isDir = entry.isDir(); extension = QFileInfo( entry.stringValue( KIO::UDSEntry::UDS_NAME ) ).suffix(); } } if ( isValid ) { // reset header openPage->setHeader(i18n("Open \"%1\" as project", url.fileName())); } else { // report error KColorScheme scheme(palette().currentColorGroup()); const QString errorMsg = i18n("Selected URL is invalid"); openPage->setHeader(QStringLiteral("<font color='%1'>%2</font>") .arg(scheme.foreground(KColorScheme::NegativeText).color().name(), errorMsg) ); setAppropriate( projectInfoPage, false ); setAppropriate( openPage, true ); setValid( openPage, false ); return; } if( isDir || extension != ShellExtension::getInstance()->projectFileExtension() ) { setAppropriate( projectInfoPage, true ); m_url = url; if( !isDir ) { m_url = m_url.adjusted(QUrl::StripTrailingSlash | QUrl::RemoveFilename); } ProjectInfoPage* page = qobject_cast<ProjectInfoPage*>( projectInfoPage->widget() ); if( page ) { page->setProjectName( m_url.fileName() ); OpenProjectPage* page2 = qobject_cast<OpenProjectPage*>( openPage->widget() ); if( page2 ) { // Default manager page->setProjectManager( QStringLiteral("Generic Project Manager") ); // clear the filelist m_fileList.clear(); if( isDir ) { // If a dir was selected fetch all files in it KIO::ListJob* job = KIO::listDir( m_url ); connect( job, &KIO::ListJob::entries, this, &OpenProjectDialog::storeFileList); KJobWidgets::setWindow(job, Core::self()->uiController()->activeMainWindow()); job->exec(); } else { // Else we'lll just take the given file m_fileList << url.fileName(); } // Now find a manager for the file(s) in our filelist. bool managerFound = false; foreach( const QString& manager, page2->projectFilters().keys() ) { foreach( const QString& filterexp, page2->projectFilters().value(manager) ) { if( !m_fileList.filter( QRegExp( filterexp, Qt::CaseSensitive, QRegExp::Wildcard ) ).isEmpty() ) { managerFound = true; break; } } if( managerFound ) { page->setProjectManager( manager ); break; } } } } m_url.setPath( m_url.path() + '/' + m_url.fileName() + '.' + ShellExtension::getInstance()->projectFileExtension() ); } else
Load::Load(QObject *parent) : QObject(parent), d_ptr(new LoadPrivate(this)) { Q_D(Load); ins = this; setObjectName("Load"); auto avProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/video/av%2/"); url = url.arg(Utils::customUrl(Utils::Bilibili)).arg(i); if (!p.isEmpty()){ url += QString("index_%1.html").arg(p); } forward(QNetworkRequest(url), Page); break; } case Page: { d->model->clear(); QString api, id, video(reply->readAll()); int part = video.indexOf("<select"); if (part != -1 && sharp == -1){ QRegularExpression r("(?<=>).*?(?=</option>)"); QStringRef list(&video, part, video.indexOf("</select>", part) - part); QRegularExpressionMatchIterator i = r.globalMatch(list); api = "http://www.%1/video/%2/index_%3.html"; api = api.arg(Utils::customUrl(Utils::Bilibili)); while (i.hasNext()){ int index = d->model->rowCount() + 1; QStandardItem *item = new QStandardItem; item->setData(QUrl(api.arg(task.code).arg(index)), UrlRole); item->setData((task.code + "#%1").arg(index), StrRole); item->setData(Page, NxtRole); item->setData(Utils::decodeXml(i.next().captured()), Qt::EditRole); d->model->appendRow(item); } } if (d->model->rowCount() > 0){ emit stateChanged(task.state = Part); } else{ QRegularExpression r = QRegularExpression("cid[=\":]*\\d+", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatchIterator i = r.globalMatch(video); while (i.hasNext()){ QString m = i.next().captured(); m = QRegularExpression("\\d+").match(m).captured(); if (id.isEmpty()){ id = m; } else if (id != m){ id.clear(); break; } } if (!id.isEmpty()){ api = "http://comment.%1/%2.xml"; api = api.arg(Utils::customUrl(Utils::Bilibili)); forward(QNetworkRequest(api.arg(id)), File); } else{ emit stateChanged(203); qDebug() << "Fail to load danmaku, try biliApi"; dequeue(); } } break; } case File: { dumpDanmaku(reply->readAll(), Utils::Bilibili, false); emit stateChanged(task.state = None); dequeue(); break; } } }; auto avRegular = [](QString &code){ code.remove(QRegularExpression("/index(?=_\\d+\\.html)")); QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ avRegular, 0, avProcess }); auto bbProcess = [this, avProcess](QNetworkReply *reply) { Q_D(Load); Task &task = d->queue.head(); switch (task.state) { case None: { QString i = task.code.mid(2); QString u = "http://www.%1/bangumi/i/%2/"; u = u.arg(Utils::customUrl(Utils::Bilibili)).arg(i); forward(QNetworkRequest(u), Page); break; } case Page: { d->model->clear(); QString page(reply->readAll()); QStringList list = page.split("<li data-index"); if (list.size() < 2) { emit stateChanged(task.state = None); dequeue(); break; } list.removeFirst(); QListIterator<QString> iter(list); iter.toBack(); while (iter.hasPrevious()) { QRegularExpression r; const QString &i = iter.previous(); r.setPattern("(?<=href=\")[^\"]+"); QString c = r.match(i).captured(); fixCode(c); r.setPattern("(?<=<span>).+(?=</span>)"); QString t = Utils::decodeXml(r.match(i).captured()); QStandardItem *item = new QStandardItem; item->setData(c, StrRole); item->setData(None, NxtRole); item->setData(t, Qt::EditRole); d->model->appendRow(item); } emit stateChanged(task.state = Part); } } }; auto bbRegular = [](QString &code) { code.replace(QRegularExpression("bangumi/i/(?=\\d+)"), "bb"); QRegularExpression r("b(b(\\d+)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ bbRegular, 0, bbProcess }); auto acProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/v/ac%2"); url = url.arg(Utils::customUrl(Utils::AcFun)).arg(i); if (!p.isEmpty()){ url += QString("_%1").arg(p); } forward(QNetworkRequest(url), Page); break;; } case Page: { d->model->clear(); QRegularExpressionMatchIterator match = QRegularExpression("data-vid.*?</a>").globalMatch(reply->readAll()); while (match.hasNext()){ QStandardItem *item = new QStandardItem; QString part = match.next().captured(); QRegularExpression r; r.setPattern("(?<=>)[^>]+?(?=</a>)"); item->setData(Utils::decodeXml(r.match(part).captured()), Qt::EditRole); r.setPattern("(?<=data-vid=\").+?(?=\")"); QString next("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); next = next.arg(Utils::customUrl(Utils::AcFun)).arg(r.match(part).captured()); item->setData(next, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (sharp == -1 && d->model->rowCount() >= 2){ emit stateChanged(task.state = Part); } else{ int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1; if (i >= 0 && i < d->model->rowCount()){ forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File); } else{ emit stateChanged(203); dequeue(); } } break; } case File: { QByteArray data = reply->readAll(); if (data != "[[],[],[]]"){ QNetworkRequest &request = task.request; QUrl url = request.url(); int page = QUrlQuery(url).queryItemValue("pageNo").toInt(); url.setQuery(QString()); request.setUrl(url); dumpDanmaku(data, Utils::AcFun, false); QUrlQuery query; query.addQueryItem("pageSize", "1000"); query.addQueryItem("pageNo", QString::number(page + 1)); url.setQuery(query); request.setUrl(url); forward(request, File); } else{ emit stateChanged(task.state = None); dequeue(); } break; } } }; auto acRegular = getRegular(QRegularExpression("a(c(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption)); d->pool.append({ acRegular, 0, acProcess }); auto abProcess = [this, acProcess](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString url("http://www.%1/bangumi/video/page?bangumiId=%2&pageSize=30&pageNo=%3&order=2"); url = url.arg(Utils::customUrl(Utils::AcFun)).arg(task.code.mid(2, sharp - 2)); url = url.arg(sharp == -1 ? 1 : (task.code.mid(sharp + 1).toInt() - 1) / 30 + 1); forward(QNetworkRequest(url), Page); break; } case Page: { if (sharp != -1){ QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object()["data"].toObject(); int i = task.code.mid(sharp + 1).toInt(); if (i > 0){ i = (i - 1) % 30; } else{ i = data["totalCount"].toInt(); if (i > 30){ task.code = task.code.left(sharp) + QString("#%1").arg(i); task.state = None; task.processer->process(nullptr); break; } } QJsonArray list = data["list"].toArray(); if (i < 0 || i >= list.size()){ emit stateChanged(203); dequeue(); break; } QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); head = head.arg(Utils::customUrl(Utils::AcFun)); head = head.arg(list[i].toObject()["danmakuId"].toString()); forward(QNetworkRequest(head), File); break; } else{ d->model->clear(); } } case Part: { QJsonObject info = QJsonDocument::fromJson(reply->readAll()).object(); if (!info["success"].toBool() && d->model->rowCount() == 0){ emit stateChanged(info["status"].toInt()); dequeue(); } QJsonObject data = info["data"].toObject(); for (const QJsonValue &value : data["list"].toArray()){ QStandardItem *item = new QStandardItem; QJsonObject data = value.toObject(); item->setData(data["title"].toString(), Qt::EditRole); QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); head = head.arg(Utils::customUrl(Utils::AcFun)).arg(data["danmakuId"].toString()); item->setData(head, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (task.state != Part){ emit stateChanged(task.state = Part); } if (data["pageNo"].toInt() < data["totalPage"].toInt()){ QUrl url = reply->request().url(); auto arg = QUrlQuery(url).queryItems(); for (auto &p : arg){ if (p.first == "pageNo"){ p.second = QString::number(p.second.toInt() + 1); break; } } QUrlQuery query; query.setQueryItems(arg); url.setQuery(query); d->remain.insert(d->manager.get(QNetworkRequest(url))); } break; } case File: { acProcess(reply); break; } } }; auto abRegular = getRegular(QRegularExpression("a(b(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption)); d->pool.append({ abRegular, 0, abProcess }); auto ccProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/play/h%2/"); url = url.arg(Utils::customUrl(Utils::TuCao)).arg(i); if (!p.isEmpty()){ url += QString("#%1").arg(p); } forward(QNetworkRequest(url), Page); break; } case Page: { QString page = reply->readAll(); d->model->clear(); QRegularExpressionMatch m; QRegularExpression r("(?<=<li>)[^<]*(?=</li>)"); m = r.match(page, page.indexOf("<ul id=\"player_code\"")); QStringList list = m.captured().split("**"); m = r.match(page, m.capturedEnd()); QString code = m.captured(); for (const QString &iter : list){ QStandardItem *item = new QStandardItem; item->setData(iter.mid(iter.indexOf('|') + 1), Qt::EditRole); QString api("http://www.%1/index.php?m=mukio&c=index&a=init&playerID=%2"); api = api.arg(Utils::customUrl(Utils::TuCao)).arg((code + "-%1").arg(d->model->rowCount())); item->setData(api, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (sharp == -1 && d->model->rowCount() >= 2){ emit stateChanged(task.state = Part); } else{ int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1; if (i >= 0 && i < d->model->rowCount()){ forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File); } else{ emit stateChanged(203); dequeue(); } } break; } case File: { dumpDanmaku(reply->readAll(), Utils::TuCao, false); emit stateChanged(task.state = None); dequeue(); break; } } }; auto ccRegular = [](QString &code){ code.replace(QRegularExpression("[Hh](?=\\d)"), "cc"); QRegularExpression r("c(c(\\d+([#_])?(\\d+)?)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ ccRegular, 0, ccProcess }); d->pool.append(Proc()); Proc *directProc = &d->pool.last(); directProc->process = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state){ case None: { QUrl url = QUrl::fromUserInput(task.code); task.request.setUrl(url); task.state = File; forward(); break; } case File: { Record load; QUrl url = reply->url(); QByteArray data(reply->readAll()); load.source = url.url(); load.access = url.isLocalFile() ? url.toLocalFile() : load.source; load.string = QFileInfo(task.code).fileName(); load.delay = task.delay; QString head = Utils::decodeTxt(data.left(512)); if (head.startsWith("[Script Info]")){ load.danmaku = Parse::parseComment(data, Utils::ASS); } else if (!head.startsWith("<?xml")){ load.danmaku = Parse::parseComment(data, Utils::AcFun); } else if (head.indexOf("<packet>") != -1){ load.danmaku = Parse::parseComment(data, Utils::Niconico); } else if (head.indexOf("<i>") != -1){ load.danmaku = Parse::parseComment(data, Utils::Bilibili); QString i = QRegularExpression("(?<=<chatid>)\\d+(?=</chatid>)").match(head).captured(); if (!i.isEmpty()){ load.source = "http://comment.%1/%2.xml"; load.source = load.source.arg(Utils::customUrl(Utils::Bilibili)).arg(i); } } else if (head.indexOf("<c>") != -1){ load.danmaku = Parse::parseComment(data, Utils::AcfunLocalizer); } if (load.delay != 0){ for (Comment &c : load.danmaku){ c.time += load.delay; } } Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); break; } } }; directProc->priority = -100; directProc->regular = [this, directProc](QString &code){ if (code.startsWith("full?") || code.startsWith("hist?")){ code.clear(); return false; } QUrl u = QUrl::fromUserInput(code); if (!u.host().isEmpty() && !u.path().isEmpty()){ return true; } if (QFileInfo(code).exists()){ return true; } code.clear(); return false; }; auto fullBiProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state) { case None: { emit progressChanged(0); QString api("http://comment.%1/rolldate,%2"); api = api.arg(Utils::customUrl(Utils::Bilibili)); task.code = QUrlQuery(task.code.mid(5)).queryItemValue("source"); forward(QNetworkRequest(api.arg(QFileInfo(task.code).baseName())), Page); break; } case Page: { QByteArray data = reply->readAll(); QJsonArray date = QJsonDocument::fromJson(data).array(); if (date.isEmpty()) { emit stateChanged(203); dequeue(); break; } QJsonObject head = date.first().toObject(); QString url("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(head["timestamp"].toVariant().toInt()); url = url.arg(QFileInfo(task.code).baseName()); QNetworkRequest request(url); request.setAttribute(QNetworkRequest::User, data); forward(request, Code); break; } case Code: { QByteArray data = task.request.attribute(QNetworkRequest::User).toByteArray(); QJsonArray date = QJsonDocument::fromJson(data).array(); QMap<int, int> count; for (auto iter : date) { QJsonObject item = iter.toObject(); count[item["timestamp"].toVariant().toInt()] += item["new"].toVariant().toInt(); } data = reply->readAll(); if (count.size() >= 2) { int max = QRegularExpression("(?<=\\<max_count\\>).+(?=\\</max_count\\>)").match(data).captured().toInt(); int now = 0; auto getHistory = [d, &count, &task](int date) { QString url("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(date); url = url.arg(QFileInfo(task.code).baseName()); return d->manager.get(QNetworkRequest(url)); }; for (auto iter = count.begin() + 1;; ++iter) { now += iter.value(); if (iter + 1 == count.end()) { d->remain += getHistory(iter.key()); break; } else if (now + (iter + 1).value() > max) { d->remain += getHistory(iter.key()); now = 0; } } auto pool = QSharedPointer<QVector<Parse::ResultDelegate>>::create(); pool->append(Parse::parseComment(data, Utils::Bilibili)); double total = d->remain.size() + 2; for (QNetworkReply *iter : d->remain) { connect(iter, &QNetworkReply::finished, [=, &task]() { QByteArray data = iter->readAll(); pool->append(Parse::parseComment(data, Utils::Bilibili)); switch (iter->error()) { case QNetworkReply::NoError: emit progressChanged((total - d->remain.size()) / total); case QNetworkReply::OperationCanceledError: if (d->remain.isEmpty() && !pool->empty()) { Record load; load.full = true; for (auto &iter : *pool) { load.danmaku.append(iter); } load.source = task.code; Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); } default: break; } }); } emit progressChanged(2 / total); emit stateChanged(task.state = File); break; } else { emit progressChanged(1); dumpDanmaku(data, Utils::Bilibili, true); emit stateChanged(task.state = None); dequeue(); break; } } } }; auto fullBiRegular = QRegularExpression("^full\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml$"); fullBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption); d->pool.append({ getRegular(fullBiRegular), 100, fullBiProcess }); auto histBiProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state){ case None: { QUrlQuery query(task.code.mid(5)); task.code = query.queryItemValue("source"); QString cid = QFileInfo(task.code).baseName(); QString dat = query.queryItemValue("date"); QString url; QNetworkRequest request; if (dat != "0" && dat.toUInt() != QDateTime(QDate::currentDate()).toTime_t()){ url = QString("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(dat).arg(cid); int limit = QDateTime(QDateTime::fromTime_t(dat.toInt()).date().addDays(1)).toTime_t(); request.setAttribute(QNetworkRequest::User, limit); } else{ url = QString("http://comment.%1/%2.xml").arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(cid); } request.setUrl(url); forward(request, File); break; } case File: { Record load; load.danmaku = Parse::parseComment(reply->readAll(), Utils::Bilibili); load.source = task.code; for (Record &iter : Danmaku::instance()->getPool()){ if (iter.source == load.source){ iter.full = false; iter.danmaku.clear(); iter.limit = 1; break; } } load.limit = task.request.attribute(QNetworkRequest::User).toInt(); Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); break; } } }; auto histBiRegular = QRegularExpression("^hist\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml&date=\\d+$"); histBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption); d->pool.append({ getRegular(histBiRegular), 100, histBiProcess }); connect(this, &Load::stateChanged, [this](int code){ switch (code){ case None: case Page: case Part: case Code: case File: break; default: { Q_D(Load); if (!d->tryNext()){ emit errorOccured(code); } break; } } }); }
void SettingsManager::removeOverride(const QUrl &url) { QSettings(m_overridePath, QSettings::IniFormat).remove(url.isLocalFile() ? QLatin1String("localhost") : url.host()); }
QString QPlayer::getMedia() { QUrl u = mp->media().canonicalUrl(); return u.isLocalFile() ? u.toLocalFile() : QString(); }
void AddressWidget::handleUserInput(const QString &text) { const BookmarkInformation *bookmark = BookmarksManager::getBookmarkByKeyword(text); if (bookmark) { WindowsManager *windowsManager = SessionsManager::getWindowsManager(); if (windowsManager) { windowsManager->open(bookmark); return; } } if (text == QString(QLatin1Char('~')) || text.startsWith(QLatin1Char('~') + QDir::separator())) { const QStringList locations = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); if (!locations.isEmpty()) { emit requestedLoadUrl(QUrl(locations.first() + text.mid(1))); return; } } if (QFileInfo(text).exists()) { emit requestedLoadUrl(QUrl::fromLocalFile(QFileInfo(text).canonicalFilePath())); return; } const QUrl url = QUrl::fromUserInput(text); if (url.isValid() && (url.isLocalFile() || QRegularExpression(QLatin1String("^(\\w+\\:\\S+)|([\\w\\-]+\\.[a-zA-Z]{2,}(/\\S*)?$)")).match(text).hasMatch())) { emit requestedLoadUrl(url); return; } const QString shortcut = text.section(QLatin1Char(' '), 0, 0); const QStringList engines = SearchesManager::getSearchEngines(); SearchInformation *engine = NULL; for (int i = 0; i < engines.count(); ++i) { engine = SearchesManager::getSearchEngine(engines.at(i)); if (engine && shortcut == engine->shortcut) { emit requestedSearch(text.section(QLatin1Char(' '), 1), engine->identifier); return; } } const int lookupTimeout = SettingsManager::getValue(QLatin1String("AddressField/HostLookupTimeout")).toInt(); if (url.isValid() && lookupTimeout > 0) { if (text == m_lookupQuery) { return; } m_lookupQuery = text; if (m_lookupTimer != 0) { QHostInfo::abortHostLookup(m_lookupIdentifier); killTimer(m_lookupTimer); m_lookupTimer = 0; } m_lookupIdentifier = QHostInfo::lookupHost(url.host(), this, SLOT(verifyLookup(QHostInfo))); m_lookupTimer = startTimer(lookupTimeout); return; } emit requestedSearch(text, SettingsManager::getValue(QLatin1String("Search/DefaultSearchEngine")).toString()); }
bool QWindowsServices::openDocument(const QUrl &url) { return shellExecute(url.isLocalFile() ? url.toLocalFile() : url.toString()); }
void ProjectSelectionPage::validateData() { QUrl url = ui->locationUrl->url(); if( !url.isLocalFile() || url.isEmpty() ) { ui->locationValidWidget->setText( i18n("Invalid location") ); ui->locationValidWidget->animatedShow(); emit invalid(); return; } if( appName().isEmpty() ) { ui->locationValidWidget->setText( i18n("Empty project name") ); ui->locationValidWidget->animatedShow(); emit invalid(); return; } if( !appName().isEmpty() ) { QString appname = appName(); QString templatefile = m_wizardDialog->appInfo().appTemplate; // Read template file KConfig config(templatefile); KConfigGroup configgroup(&config, "General"); QString pattern = configgroup.readEntry( "ValidProjectName" , "^[a-zA-Z][a-zA-Z0-9_]+$" ); // Validation int pos = 0; QRegExp regex( pattern ); QRegExpValidator validator( regex ); if( validator.validate(appname, pos) == QValidator::Invalid ) { ui->locationValidWidget->setText( i18n("Invalid project name") ); emit invalid(); return; } } QDir tDir(url.toLocalFile()); while (!tDir.exists() && !tDir.isRoot()) { if (!tDir.cdUp()) { break; } } if (tDir.exists()) { QFileInfo tFileInfo(tDir.absolutePath()); if (!tFileInfo.isWritable() || !tFileInfo.isExecutable()) { ui->locationValidWidget->setText( i18n("Unable to create subdirectories, " "missing permissions on: %1", tDir.absolutePath()) ); ui->locationValidWidget->animatedShow(); emit invalid(); return; } } QStandardItem* item = getCurrentItem(); if( item && !item->hasChildren() ) { ui->locationValidWidget->animatedHide(); emit valid(); } else { ui->locationValidWidget->setText( i18n("Invalid project template, please choose a leaf item") ); ui->locationValidWidget->animatedShow(); emit invalid(); return; } // Check for non-empty target directory. Not an error, but need to display a warning. url.setPath( url.path() + '/' + encodedAppName() ); QFileInfo fi( url.toLocalFile() ); if( fi.exists() && fi.isDir() ) { if( !QDir( fi.absoluteFilePath()).entryList( QDir::NoDotAndDotDot | QDir::AllEntries ).isEmpty() ) { ui->locationValidWidget->setText( i18n("Path already exists and contains files. Open it as a project.") ); ui->locationValidWidget->animatedShow(); emit invalid(); return; } } }
void KIOExec::slotRunApp() { if ( fileList.isEmpty() ) { qDebug() << "No files downloaded -> exiting"; mExited = true; QApplication::exit(1); return; } KService service(QStringLiteral("dummy"), command, QString()); QList<QUrl> list; // Store modification times QList<FileInfo>::Iterator it = fileList.begin(); for ( ; it != fileList.end() ; ++it ) { QFileInfo info(QFile::encodeName(it->path)); it->time = info.lastModified(); QUrl url = QUrl::fromLocalFile(it->path); list << url; } KIO::DesktopExecParser execParser(service, list); QStringList params = execParser.resultingArguments(); qDebug() << "EXEC " << params.join(QStringLiteral(" ")); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) // propagate the startup identification to the started process KStartupInfoId id; QByteArray startupId; #if HAVE_X11 if (QX11Info::isPlatformX11()) { startupId = QX11Info::nextStartupId(); } #endif id.initId(startupId); id.setupStartupEnv(); #endif QString exe( params.takeFirst() ); const int exit_code = QProcess::execute( exe, params ); #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) KStartupInfo::resetStartupEnv(); #endif qDebug() << "EXEC done"; // Test whether one of the files changed for(it = fileList.begin(); it != fileList.end(); ++it ) { QString src = it->path; const QUrl dest = it->url; QFileInfo info(src); if ( info.exists() && (it->time != info.lastModified()) ) { if ( mTempFiles ) { if ( KMessageBox::questionYesNo( 0L, i18n( "The supposedly temporary file\n%1\nhas been modified.\nDo you still want to delete it?", dest.toDisplayString(QUrl::PreferLocalFile)), i18n( "File Changed" ), KStandardGuiItem::del(), KGuiItem(i18n("Do Not Delete")) ) != KMessageBox::Yes ) continue; // don't delete the temp file } else if ( ! dest.isLocalFile() ) // no upload when it's already a local file { if ( KMessageBox::questionYesNo( 0L, i18n( "The file\n%1\nhas been modified.\nDo you want to upload the changes?" , dest.toDisplayString()), i18n( "File Changed" ), KGuiItem(i18n("Upload")), KGuiItem(i18n("Do Not Upload")) ) == KMessageBox::Yes ) { qDebug() << "src='" << src << "' dest='" << dest << "'"; // Do it the synchronous way. KIO::CopyJob* job = KIO::copy(QUrl::fromLocalFile(src), dest); if ( !job->exec() ) { KMessageBox::error( 0L, job->errorText() ); continue; // don't delete the temp file } } } } if ((!dest.isLocalFile() || mTempFiles) && exit_code == 0) { // Wait for a reasonable time so that even if the application forks on startup (like OOo or amarok) // it will have time to start up and read the file before it gets deleted. #130709. qDebug() << "sleeping..."; QThread::currentThread()->sleep(180); // 3 mn qDebug() << "about to delete " << src; QFile( QFile::encodeName(src) ).remove(); } } mExited = true; QApplication::exit(exit_code); }
void WebView::contextMenuEvent(QContextMenuEvent* e) { m_result = page()->mainFrame()->hitTestContent(e->pos()); // Clear the previous collection entries first... m_actionCollection->clear(); KParts::BrowserExtension::PopupFlags flags = KParts::BrowserExtension::DefaultPopupItems; KParts::BrowserExtension::ActionGroupMap mapAction; QString mimeType (QL1S("text/html")); bool forcesNewWindow = false; QUrl emitUrl; if (m_result.isContentEditable()) { if (m_result.element().hasAttribute(QL1S("disabled"))) { e->accept(); return; } flags |= KParts::BrowserExtension::ShowTextSelectionItems; editableContentActionPopupMenu(mapAction); } else if (isMultimediaElement(m_result.element())) { multimediaActionPopupMenu(mapAction); } else if (!m_result.linkUrl().isValid()) { if (m_result.imageUrl().isValid()) { emitUrl = m_result.imageUrl(); extractMimeTypeFor(emitUrl, mimeType); } else { flags |= KParts::BrowserExtension::ShowBookmark; flags |= KParts::BrowserExtension::ShowReload; emitUrl = m_part->url(); if (m_result.isContentSelected()) { flags |= KParts::BrowserExtension::ShowTextSelectionItems; selectActionPopupMenu(mapAction); } else { flags |= KParts::BrowserExtension::ShowNavigationItems; } } partActionPopupMenu(mapAction); } else { flags |= KParts::BrowserExtension::ShowBookmark; flags |= KParts::BrowserExtension::ShowReload; flags |= KParts::BrowserExtension::IsLink; emitUrl = m_result.linkUrl(); linkActionPopupMenu(mapAction); if (emitUrl.isLocalFile()) mimeType = KMimeType::findByUrl(emitUrl, 0, true, false)->name(); else extractMimeTypeFor(emitUrl, mimeType); partActionPopupMenu(mapAction); // Show the OpenInThisWindow context menu item forcesNewWindow = (page()->currentFrame() != m_result.linkTargetFrame()); } if (!mapAction.isEmpty()) { KParts::OpenUrlArguments args; KParts::BrowserArguments bargs; args.setMimeType(mimeType); bargs.setForcesNewWindow(forcesNewWindow); e->accept(); emit m_part->browserExtension()->popupMenu(e->globalPos(), emitUrl, static_cast<mode_t>(-1), args, bargs, flags, mapAction); return; } KWebView::contextMenuEvent(e); }
Mrl::Mrl(const QUrl &url) { if (url.isLocalFile()) m_loc = _L("file://") % url.toLocalFile(); else m_loc = url.toString(); }
int CommandExec::exec(const QCommandLineParser *parser) { m_pCPart->parser = const_cast<QCommandLineParser*>(parser); m_pCPart->args = parser->positionalArguments(); if (m_pCPart->args.isEmpty()) { return -1; } m_lastMessages.clear(); m_lastMessagesLines = 0; m_pCPart->m_SvnWrapper->reInitClient(); bool dont_check_second = false; bool dont_check_all = false; bool path_only = false; bool no_revision = false; bool check_force = false; if (m_pCPart->args.count() >= 2) { m_pCPart->cmd = m_pCPart->args.at(1); m_pCPart->cmd = m_pCPart->cmd.toLower(); } QByteArray slotCmd; if (!QString::compare(m_pCPart->cmd, "log")) { slotCmd = SLOT(slotCmd_log()); } else if (!QString::compare(m_pCPart->cmd, "cat")) { slotCmd = SLOT(slotCmd_cat()); m_pCPart->single_revision = true; } else if (!QString::compare(m_pCPart->cmd, "get")) { slotCmd = SLOT(slotCmd_get()); m_pCPart->single_revision = true; } else if (!QString::compare(m_pCPart->cmd, "help")) { slotCmd = SLOT(slotCmd_help()); } else if (!QString::compare(m_pCPart->cmd, "blame") || !QString::compare(m_pCPart->cmd, "annotate")) { slotCmd = SLOT(slotCmd_blame()); } else if (!QString::compare(m_pCPart->cmd, "update")) { slotCmd = SLOT(slotCmd_update()); m_pCPart->single_revision = true; } else if (!QString::compare(m_pCPart->cmd, "diff")) { m_pCPart->start = svn::Revision::WORKING; slotCmd = SLOT(slotCmd_diff()); } else if (!QString::compare(m_pCPart->cmd, "info")) { slotCmd = SLOT(slotCmd_info()); m_pCPart->single_revision = true; } else if (!QString::compare(m_pCPart->cmd, "commit") || !QString::compare(m_pCPart->cmd, "ci")) { slotCmd = SLOT(slotCmd_commit()); } else if (!QString::compare(m_pCPart->cmd, "list") || !QString::compare(m_pCPart->cmd, "ls")) { slotCmd = SLOT(slotCmd_list()); } else if (!QString::compare(m_pCPart->cmd, "copy") || !QString::compare(m_pCPart->cmd, "cp")) { slotCmd = SLOT(slotCmd_copy()); dont_check_second = true; } else if (!QString::compare(m_pCPart->cmd, "move") || !QString::compare(m_pCPart->cmd, "rename") || !QString::compare(m_pCPart->cmd, "mv")) { slotCmd = SLOT(slotCmd_move()); dont_check_second = true; } else if (!QString::compare(m_pCPart->cmd, "checkout") || !QString::compare(m_pCPart->cmd, "co")) { slotCmd = SLOT(slotCmd_checkout()); dont_check_second = true; } else if (!QString::compare(m_pCPart->cmd, "checkoutto") || !QString::compare(m_pCPart->cmd, "coto")) { slotCmd = SLOT(slotCmd_checkoutto()); dont_check_second = true; } else if (!QString::compare(m_pCPart->cmd, "export")) { slotCmd = SLOT(slotCmd_export()); dont_check_second = true; } else if (!QString::compare(m_pCPart->cmd, "exportto")) { slotCmd = SLOT(slotCmd_exportto()); dont_check_second = true; } else if (!QString::compare(m_pCPart->cmd, "delete") || !QString::compare(m_pCPart->cmd, "del") || !QString::compare(m_pCPart->cmd, "rm") || !QString::compare(m_pCPart->cmd, "remove")) { slotCmd = SLOT(slotCmd_delete()); } else if (!QString::compare(m_pCPart->cmd, "add")) { slotCmd = SLOT(slotCmd_add()); dont_check_all = true; path_only = true; } else if (!QString::compare(m_pCPart->cmd, "undo") || !QString::compare(m_pCPart->cmd, "revert")) { slotCmd = SLOT(slotCmd_revert()); } else if (!QString::compare(m_pCPart->cmd, "checknew") || !QString::compare(m_pCPart->cmd, "addnew")) { slotCmd = SLOT(slotCmd_addnew()); } else if (!QString::compare(m_pCPart->cmd, "switch")) { slotCmd = SLOT(slotCmd_switch()); } else if (!QString::compare(m_pCPart->cmd, "tree")) { slotCmd = SLOT(slotCmd_tree()); } else if (!QString::compare(m_pCPart->cmd, "lock")) { slotCmd = SLOT(slotCmd_lock()); no_revision = true; check_force = true; } else if (!QString::compare(m_pCPart->cmd, "unlock")) { slotCmd = SLOT(slotCmd_unlock()); no_revision = true; check_force = true; } bool found = connect(this, SIGNAL(executeMe()), this, slotCmd.constData()); if (!found) { KMessageBox::sorry(0, i18n("Command \"%1\" not implemented or known", m_pCPart->cmd), i18n("SVN Error")); return -1; } QString tmp; QString mainProto; for (int j = 2; j < m_pCPart->args.count(); ++j) { QUrl tmpurl = QUrl::fromUserInput(m_pCPart->args.at(j), QDir::currentPath()); tmpurl.setScheme(svn::Url::transformProtokoll(tmpurl.scheme())); if (tmpurl.scheme().indexOf(QLatin1String("ssh")) != -1) { SshAgent ag; // this class itself checks if done before ag.addSshIdentities(); } m_pCPart->extraRevisions[j - 2] = svn::Revision::HEAD; if (tmpurl.isLocalFile() && (j == 2 || !dont_check_second) && !dont_check_all) { QUrl repoUrl; if (m_pCPart->m_SvnWrapper->isLocalWorkingCopy(tmpurl.path(), repoUrl)) { tmp = tmpurl.path(); m_pCPart->repoUrls[j - 2] = repoUrl; m_pCPart->extraRevisions[j - 2] = svn::Revision::WORKING; if (j == 2) { mainProto.clear(); } } else { tmp = tmpurl.url(); if (j == 2) { mainProto = QLatin1String("file://"); } } } else if (path_only) { tmp = tmpurl.path(); } else { tmp = tmpurl.url(); if (j == 2) { mainProto = tmpurl.scheme(); } } if ((j > 2 && dont_check_second) || dont_check_all) { if (mainProto.isEmpty()) { tmp = tmpurl.path(); } } const QStringList l = tmp.split(QLatin1Char('?'), QString::SkipEmptyParts); if (!l.isEmpty()) { tmp = l[0]; } while (tmp.endsWith(QLatin1Char('/'))) { tmp.chop(1); } m_pCPart->urls.append(tmp); if ((j > 2 && dont_check_second) || dont_check_all) { continue; } const QList<QPair<QString, QString> > q = QUrlQuery(tmpurl).queryItems(); for(int i = 0; i < q.size(); ++i) { if (q.at(i).first == QLatin1String("rev")) { svn::Revision re = q.at(i).second; if (re) { m_pCPart->extraRevisions[j - 2] = re; } } } } if (m_pCPart->urls.isEmpty()) { m_pCPart->urls.append(QLatin1String(".")); } if (!no_revision) { if (m_pCPart->parser->isSet("R")) { m_pCPart->ask_revision = true; if (!askRevision()) { return 0; } } else if (m_pCPart->parser->isSet("r")) { scanRevision(); } } m_pCPart->force = check_force && m_pCPart->parser->isSet("f"); if (m_pCPart->parser->isSet("o")) { m_pCPart->outfile_set = true; m_pCPart->outfile = m_pCPart->parser->value("o"); } if (m_pCPart->parser->isSet("l")) { QString s = m_pCPart->parser->value("l"); m_pCPart->log_limit = s.toInt(); if (m_pCPart->log_limit < 0) { m_pCPart->log_limit = 0; } } emit executeMe(); if (Kdesvnsettings::self()->cmdline_show_logwindow() && m_lastMessagesLines >= Kdesvnsettings::self()->cmdline_log_minline()) { QPointer<KSvnSimpleOkDialog> dlg(new KSvnSimpleOkDialog(QStringLiteral("kdesvn_cmd_log"), QApplication::activeModalWidget())); QTextBrowser *ptr = new QTextBrowser(dlg); ptr->setText(m_lastMessages); ptr->setReadOnly(true); dlg->addWidget(ptr); QString cmd = qApp->arguments().join(QLatin1Char(' ')); dlg->setWindowTitle(cmd); dlg->exec(); delete dlg; } return 0; }
bool KonqHistoryManager::filterOut(const QUrl &url) { return (url.isLocalFile() || url.host().isEmpty()); }
void MainWindow::openUrl(const QString &input) { const BookmarkInformation *bookmark = BookmarksManager::getBookmark(input); if (bookmark) { WindowsManager *windowsManager = SessionsManager::getWindowsManager(); if (windowsManager) { windowsManager->open(bookmark); return; } } if (input == QString(QLatin1Char('~')) || input.startsWith(QLatin1Char('~') + QDir::separator())) { const QStringList locations = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); if (!locations.isEmpty()) { m_windowsManager->open(QUrl(locations.first() + input.mid(1))); return; } } if (QFileInfo(input).exists()) { m_windowsManager->open(QUrl::fromLocalFile(QFileInfo(input).canonicalFilePath())); return; } const QUrl url = QUrl::fromUserInput(input); if (url.isValid() && (url.isLocalFile() || QRegularExpression(QLatin1String("^(\\w+\\:\\S+)|([\\w\\-]+\\.[a-zA-Z]{2,}(/\\S*)?$)")).match(input).hasMatch())) { m_windowsManager->open(url); return; } const QString keyword = input.section(QLatin1Char(' '), 0, 0); const QStringList engines = SearchesManager::getSearchEngines(); SearchInformation *engine = NULL; for (int i = 0; i < engines.count(); ++i) { engine = SearchesManager::getSearchEngine(engines.at(i)); if (engine && keyword == engine->keyword) { m_windowsManager->search(input.section(QLatin1Char(' '), 1), engine->identifier); return; } } m_windowsManager->open(); }
bool FileReader::is_local_file(const QUrl &filename) { return filename.isLocalFile(); }
void InputInterpreter::interpret(const QString &text, WindowsManager::OpenHints hints, bool ignoreBookmarks) { if (text.startsWith(QLatin1String("bookmarks:"))) { BookmarksItem *bookmark = (text.startsWith(QLatin1String("bookmarks:/")) ? BookmarksManager::getModel()->getItem(text.mid(11)) : BookmarksManager::getBookmark(text.mid(10).toULongLong())); if (bookmark) { emit requestedOpenBookmark(bookmark, hints); deleteLater(); return; } } if (!ignoreBookmarks) { BookmarksItem *bookmark = BookmarksManager::getBookmark(text); if (bookmark) { emit requestedOpenBookmark(bookmark, hints); deleteLater(); return; } } if (text == QString(QLatin1Char('~')) || text.startsWith(QLatin1Char('~') + QDir::separator())) { const QStringList locations = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); if (!locations.isEmpty()) { emit requestedOpenUrl(locations.first() + text.mid(1), hints); deleteLater(); return; } } const QFileInfo fileInformation(text); if (fileInformation.exists() && fileInformation.isAbsolute()) { emit requestedOpenUrl(QUrl::fromLocalFile(QFileInfo(text).canonicalFilePath()), hints); deleteLater(); return; } const QUrl url = QUrl::fromUserInput(text); const QHostAddress address(text); if (!address.isNull() || (url.isValid() && (url.isLocalFile() || QRegularExpression(QLatin1String("^(\\w+\\:\\S+)|([\\w\\-]+\\.[a-zA-Z]{2,}(/\\S*)?$)")).match(text).hasMatch()))) { emit requestedOpenUrl(url, hints); deleteLater(); return; } const QString keyword = text.section(QLatin1Char(' '), 0, 0); const SearchEnginesManager::SearchEngineDefinition searchEngine = SearchEnginesManager::getSearchEngine(keyword, true); if (!searchEngine.identifier.isEmpty()) { emit requestedSearch(text.section(QLatin1Char(' '), 1), searchEngine.identifier, hints); deleteLater(); return; } if (keyword == QLatin1String("?")) { emit requestedSearch(text.section(QLatin1Char(' '), 1), QString(), hints); deleteLater(); return; } const int lookupTimeout = SettingsManager::getValue(QLatin1String("AddressField/HostLookupTimeout")).toInt(); if (url.isValid() && lookupTimeout > 0) { m_text = text; m_hints = hints; if (m_timer != 0) { QHostInfo::abortHostLookup(m_lookup); killTimer(m_timer); m_timer = 0; } m_lookup = QHostInfo::lookupHost(url.host(), this, SLOT(verifyLookup(QHostInfo))); m_timer = startTimer(lookupTimeout); return; } emit requestedSearch(text, QString(), hints); deleteLater(); return; }
void ClipboardJob::start() { const QString operation = operationName(); // first check for operations not needing an item if (operation == QLatin1String("clearHistory")) { m_klipper->slotAskClearHistory(); setResult(true); emitResult(); return; } else if (operation == QLatin1String("configureKlipper")) { m_klipper->slotConfigure(); setResult(true); emitResult(); return; } // other operations need the item HistoryItemConstPtr item = m_klipper->history()->find(QByteArray::fromBase64(destination().toUtf8())); if (item.isNull()) { setResult(false); emitResult(); return; } if (operation == QLatin1String("select")) { m_klipper->history()->slotMoveToTop(item->uuid()); setResult(true); } else if (operation == QLatin1String("remove")) { m_klipper->history()->remove(item); setResult(true); } else if (operation == QLatin1String("edit")) { connect(m_klipper, &Klipper::editFinished, this, [this, item](HistoryItemConstPtr editedItem, int result) { if (item != editedItem) { // not our item return; } setResult(result); emitResult(); } ); m_klipper->editData(item); return; } else if (operation == QLatin1String("barcode")) { #ifdef HAVE_PRISON int pixelWidth = parameters().value(QStringLiteral("width")).toInt(); int pixelHeight = parameters().value(QStringLiteral("height")).toInt(); Prison::AbstractBarcode *code = nullptr; switch (parameters().value(QStringLiteral("barcodeType")).toInt()) { case 1: { code = Prison::createBarcode(Prison::DataMatrix); const int size = qMin(pixelWidth, pixelHeight); pixelWidth = size; pixelHeight = size; break; } case 2: { code = Prison::createBarcode(Prison::Code39); break; } case 3: { code = Prison::createBarcode(Prison::Code93); break; } case 0: default: { code = Prison::createBarcode(Prison::QRCode); const int size = qMin(pixelWidth, pixelHeight); pixelWidth = size; pixelHeight = size; break; } } if (code) { code->setData(item->text()); QFutureWatcher<QImage> *watcher = new QFutureWatcher<QImage>(this); connect(watcher, &QFutureWatcher<QImage>::finished, this, [this, watcher, code] { setResult(watcher->result()); watcher->deleteLater(); delete code; emitResult(); } ); auto future = QtConcurrent::run(code, &Prison::AbstractBarcode::toImage, QSizeF(pixelWidth, pixelHeight)); watcher->setFuture(future); return; } else { setResult(false); } #else setResult(false); #endif } else if (operation == QLatin1String("action")) { m_klipper->urlGrabber()->invokeAction(item); setResult(true); } else if (operation == s_previewKey) { const int pixelWidth = parameters().value(s_previewWidthKey).toInt(); const int pixelHeight = parameters().value(s_previewHeightKey).toInt(); QUrl url = parameters().value(s_urlKey).toUrl(); qCDebug(KLIPPER_LOG) << "URL: " << url; KFileItem item(url); if (pixelWidth <= 0 || pixelHeight <= 0) { qCWarning(KLIPPER_LOG) << "Preview size invalid: " << pixelWidth << "x" << pixelHeight; iconResult(item); return; } if (!url.isValid() || !url.isLocalFile()) { // no remote files qCWarning(KLIPPER_LOG) << "Invalid or non-local url for preview: " << url; iconResult(item); return; } KFileItemList urls; urls << item; KIO::PreviewJob* job = KIO::filePreview(urls, QSize(pixelWidth, pixelHeight)); job->setIgnoreMaximumSize(true); connect(job, &KIO::PreviewJob::gotPreview, this, [this](const KFileItem &item, const QPixmap &preview) { QVariantMap res; res.insert(s_urlKey, item.url()); res.insert(s_previewKey, preview); res.insert(s_iconKey, false); res.insert(s_previewWidthKey, preview.size().width()); res.insert(s_previewHeightKey, preview.size().height()); setResult(res); emitResult(); } ); connect(job, &KIO::PreviewJob::failed, this, [this](const KFileItem &item) { iconResult(item); } ); job->start(); return; } else { setResult(false); } emitResult(); }
KoRecentDocumentsPane::KoRecentDocumentsPane(QWidget* parent, const QString& header) : KoDetailsPane(parent, header) , d(new KoRecentDocumentsPanePrivate) { setFocusProxy(m_documentList); m_openButton->setText(i18n("Open This Document")); m_openButton->setIcon(koIcon("document-open")); m_alwaysUseCheckBox->hide(); model()->setSortRole(0); // Disable sorting // load list of recent files from config KConfigGroup config(KSharedConfig::openConfig(), "RecentFiles"); QString fileKey; QString fileValue; QUrl url; QString nameValue; KFileItemList fileList; QStandardItem* rootItem = model()->invisibleRootItem(); for (int i = 1; i <= MAX_RECENTFILES_ENTRIES; ++i) { fileValue = config.readPathEntry(QString("File%1").arg(i), QString()); // ignore empty entries if (fileValue.isEmpty()) { continue; } url = QUrl::fromUserInput(fileValue); // ignore entries for files known to no longer exist if (url.isLocalFile() && !QFile::exists(url.toLocalFile())) { continue; } // ignore duplicated entries if (!fileList.findByUrl(url).isNull()) { continue; } nameValue = config.readPathEntry(QString("Name%1").arg(i), QString()); // handle name entries with empty strings if (nameValue.isEmpty()) { nameValue = url.fileName(); } KFileItem fileItem(url); fileList.prepend(fileItem); const QIcon icon = QIcon::fromTheme(fileItem.iconName()); KoFileListItem* item = new KoFileListItem(icon, nameValue, fileItem); item->setEditable(false); rootItem->insertRow(0, item); } //Select the first file QModelIndex firstIndex = model()->indexFromItem(model()->item(0)); m_documentList->selectionModel()->select(firstIndex, QItemSelectionModel::Select); m_documentList->selectionModel()->setCurrentIndex(firstIndex, QItemSelectionModel::Select); QStringList availablePlugins = KIO::PreviewJob::availablePlugins(); KIO::PreviewJob *previewJob = KIO::filePreview(fileList, QSize(IconExtent, IconExtent), &availablePlugins); d->m_previewJobs.append(previewJob); connect(previewJob, SIGNAL(result(KJob*)), SLOT(previewResult(KJob*))); connect(previewJob, SIGNAL(gotPreview(KFileItem,QPixmap)), SLOT(updateIcon(KFileItem,QPixmap))); }
void Bb10Ui::messagesInserted(const QModelIndex &parent, int start, int end) { Q_UNUSED(parent); bool hasFocus = Application::instance()->isFullscreen(); for (int i = start; i <= end; i++) { QModelIndex idx = Client::messageModel()->index(i, ChatLineModel::ContentsColumn); if (!idx.isValid()) { continue; } Message::Flags flags = (Message::Flags)idx.data(ChatLineModel::FlagsRole).toInt(); if (flags.testFlag(Message::Backlog) || flags.testFlag(Message::Self)) continue; BufferId bufId = idx.data(ChatLineModel::BufferIdRole).value<BufferId>(); BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId); // check if bufferId belongs to the shown chatlists // All chats will be shown, but keep this code here until I get the filter working. //if (!m_chatViews.contains(bufId)) { // continue; //} // check if it's the buffer currently displayed if (hasFocus && bufId == m_currentBufferId) { continue; } // This is a hack. // We need a way to notify ListView to update a single item. QModelIndex source_index = Client::bufferModel()->mapFromSource(Client::networkModel()->bufferIndex(bufId)); qobject_cast<DataModelAdapter*>(m_channelListView->dataModel())->handleBufferModelDataChanged(source_index, source_index); // only show notifications for higlights or queries if (bufType != BufferInfo::QueryBuffer && !(flags & Message::Highlight)) continue; // and of course: don't notify for ignored messages if (Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufId))) { qDebug() << "xxxxx Bb10Ui::messagesInserted early return for ignored message"; continue; } // seems like we have a legit notification candidate! QModelIndex senderIdx = Client::messageModel()->index(i, ChatLineModel::SenderColumn); QString sender = senderIdx.data(ChatLineModel::EditRole).toString(); QString contents = idx.data(ChatLineModel::DisplayRole).toString(); QString bufferName = (bufType == BufferInfo::QueryBuffer) ? "Private msg" : Client::networkModel()->bufferName(bufId); QString body = "[" + bufferName + "] " + sender + " says: " + contents; if (hasFocus) { SystemToast* toast = new SystemToast(this); toast->setBody(body); toast->setPosition(SystemUiPosition::MiddleCenter); toast->show(); } else { Notification* pNotification = new Notification(); pNotification->setTitle("Quassel IRC for BB10"); pNotification->setBody(body); pNotification->setInvokeRequest(m_invokeRequest); QUrl url = QUrl("file://" + QDir("./app/public/quassel.png").absolutePath()); //QUrl url = QUrl("app/public/quassel.png"); qDebug() << "xxxxx Bb10Ui::messagesInserted url.isValid = " << url.isValid() << " isLocalFile = " << url.isLocalFile() << " path = " << url.path(); pNotification->setIconUrl(url); // FIXME: call setData to add bufferId, so that we can open the page. pNotification->notify(); } } }
void ShowFoto::openFolder(const QUrl& url) { if (!url.isValid() || !url.isLocalFile()) { return; } // Parse image IO mime types registration to get files filter pattern. QString filter; QStringList mimeTypes = supportedImageMimeTypes(QIODevice::ReadOnly, filter); QString patterns = filter.toLower(); patterns.append (QLatin1String(" ")); patterns.append (filter.toUpper()); qCDebug(DIGIKAM_SHOWFOTO_LOG) << "patterns=" << patterns; // Get all image files from directory. QDir dir(url.toLocalFile(), patterns); dir.setFilter(QDir::Files); if (!dir.exists()) { return; } QFileInfoList fileinfolist = dir.entryInfoList(); if (fileinfolist.isEmpty()) { //emit signalSorry(); return; } QFileInfoList::const_iterator fi; ShowfotoItemInfoList infos; ShowfotoItemInfo iteminfo; DMetadata meta; // And open all items in image editor. for (fi = fileinfolist.constBegin(); fi != fileinfolist.constEnd(); ++fi) { iteminfo.name = (*fi).fileName(); iteminfo.mime = (*fi).suffix(); iteminfo.size = (*fi).size(); iteminfo.folder = (*fi).path(); iteminfo.url = QUrl::fromLocalFile((*fi).filePath()); iteminfo.dtime = (*fi).created(); meta.load((*fi).filePath()); iteminfo.ctime = meta.getImageDateTime(); iteminfo.width = meta.getImageDimensions().width(); iteminfo.height = meta.getImageDimensions().height(); iteminfo.photoInfo = meta.getPhotographInformation(); infos.append(iteminfo); } if (d->droppedUrls) { d->infoList << infos; } else { d->infoList = infos; d->model->clearShowfotoItemInfos(); emit signalInfoList(d->infoList); slotOpenUrl(d->thumbBar->currentInfo()); } d->lastOpenedDirectory = QUrl::fromLocalFile(dir.absolutePath()); }