bool GDMPForm::addFile(const QString& path) { QByteArray str; qCDebug(DIGIKAM_WEBSERVICES_LOG) << "in addfile" << path; QMimeDatabase db; QMimeType ptr = db.mimeTypeForUrl(QUrl::fromLocalFile(path)); QString mime = ptr.name(); str += "--"; str += m_boundary; str += "\r\n"; str += "Content-Type: "; str += mime.toLatin1(); str += "\r\n\r\n"; QFile imageFile(path); if (!imageFile.open(QIODevice::ReadOnly)) { return false; } QByteArray imageData = imageFile.readAll(); m_file_size = QString::number(imageFile.size()); imageFile.close(); m_buffer.append(str); m_buffer.append(imageData); m_buffer.append("\r\n"); return true; }
void FolderListModel::readDirectory() { this->beginResetModel(); QFileInfoList fileinfolist = this->_directory.entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::DirsFirst); if(!this->_mimefilter.isEmpty()) { QMimeDatabase mimedb; QStringList mimefilter = this->_mimefilter.split("/"); this->_files.clear(); foreach(const QFileInfo& fi, fileinfolist) { if(fi.isDir()) { this->_files.append(fi); continue; } QMimeType mime = mimedb.mimeTypeForFile(fi.filePath()); QStringList mimestring = mime.name().split("/"); if(mimefilter[0] != mimestring[0]) continue; if((mimefilter.length() > 1) && mimefilter[1] != mimestring[1]) continue; this->_files.append(fi); } }
QVariant MessageComposer::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.column() != 0 || index.row() < 0 || index.row() >= m_attachments.size()) return QVariant(); switch (role) { case Qt::DisplayRole: return m_attachments[index.row()]->caption(); case Qt::ToolTipRole: return m_attachments[index.row()]->tooltip(); case Qt::DecorationRole: { // This is more or less copy-pasted from Gui/AttachmentView.cpp. Unfortunately, sharing the implementation // is not trivial due to the way how the static libraries are currently built. QMimeType mimeType = QMimeDatabase().mimeTypeForName(QString::fromUtf8(m_attachments[index.row()]->mimeType())); if (mimeType.isValid() && !mimeType.isDefault()) { return QIcon::fromTheme(mimeType.iconName(), UiUtils::loadIcon(QStringLiteral("mail-attachment"))); } else { return UiUtils::loadIcon(QStringLiteral("mail-attachment")); } } case Imap::Mailbox::RoleAttachmentContentDispositionMode: return static_cast<int>(m_attachments[index.row()]->contentDispositionMode()); } return QVariant(); }
const QString& vfile::vfile_getMime() { if (vfile_mimeType.isEmpty()) { if(vfile_isdir) vfile_mimeType = "inode/directory"; else if(vfile_isBrokenLink()) vfile_mimeType = "unknown"; else { QMimeDatabase db; QMimeType mt = db.mimeTypeForUrl(vfile_getUrl()); vfile_mimeType = mt.isValid() ? mt.name() : "unknown"; if (mt.isValid()) vfile_icon = mt.iconName(); if (vfile_mimeType == "inode/directory") { vfile_perm[0] = 'd'; vfile_isdir = true; } } if (vfile_isdir && vfile_userDefinedFolderIcons) { QUrl url = vfile_getUrl(); if (url.isLocalFile()) { QString file = url.toLocalFile() + "/.directory"; KDesktopFile cfg(file); QString icon = cfg.readIcon(); if(icon.startsWith(QLatin1String("./"))) // relative path icon = url.toLocalFile() + '/' + icon; if (!icon.isEmpty()) vfile_icon = icon; } } } return vfile_mimeType; }
void tst_QMimeDatabase::inheritsPerformance() { // Check performance of inherits(). // This benchmark (which started in 2009 in kmimetypetest.cpp) uses 40 mimetypes. QStringList mimeTypes; mimeTypes << QLatin1String("image/jpeg") << QLatin1String("image/png") << QLatin1String("image/tiff") << QLatin1String("text/plain") << QLatin1String("text/html"); mimeTypes += mimeTypes; mimeTypes += mimeTypes; mimeTypes += mimeTypes; QCOMPARE(mimeTypes.count(), 40); QMimeDatabase db; QMimeType mime = db.mimeTypeForName(QString::fromLatin1("text/x-chdr")); QVERIFY(mime.isValid()); QBENCHMARK { QString match; foreach (const QString &mt, mimeTypes) { if (mime.inherits(mt)) { match = mt; // of course there would normally be a "break" here, but we're testing worse-case // performance here } } QCOMPARE(match, QString::fromLatin1("text/plain")); } // Numbers from 2011, in release mode: // KDE 4.7 numbers: 0.21 msec / 494,000 ticks / 568,345 instr. loads per iteration // QMimeBinaryProvider (with Qt 5): 0.16 msec / NA / 416,049 instr. reads per iteration // QMimeXmlProvider (with Qt 5): 0.062 msec / NA / 172,889 instr. reads per iteration // (but the startup time is way higher) // And memory usage is flat at 200K with QMimeBinaryProvider, while it peaks at 6 MB when // parsing XML, and then keeps being around 4.5 MB for all the in-memory hashes. }
void ProjectView::slotClicked(QTreeWidgetItem *item) { if(!item) { item = currentItem(); } ProjectViewItem *itm = static_cast<ProjectViewItem*>(item); if(itm) { if(itm->type() == KileType::File) { emit(fileSelected(itm->url())); } else if(itm->type() == KileType::ProjectItem) { emit(fileSelected(itm->projectItem())); } else if(itm->type() != KileType::Folder) { // don't open project configuration files (*.kilepr) if(itm->url().toLocalFile().right(7) != ".kilepr") { //determine mimeType and open file with preferred application QMimeDatabase db; QMimeType pMime = db.mimeTypeForUrl(itm->url()); if(pMime.name().startsWith("text/")) { emit(fileSelected(itm->url())); } else { KRun::runUrl(itm->url(), pMime.name(), this); } } } clearSelection(); } }
QNetworkReply* Parse::uploadFileData(QByteArray data, QString name) { if (!isReady() || data.isEmpty()) return NULL; if (name.isEmpty()) { // compute name from content } setEndPoint( "files/"+name); QMimeDatabase db; QMimeType mime = db.mimeTypeForData(data); initHeaders(); setHeader(QNetworkRequest::ContentTypeHeader, mime.name().toUtf8()); m_conn = connect(this, &BaaS::replyFinished, [=]( QJsonDocument json){ disconnect(m_conn); if ( getHttpCode() == 201 ){ currentObject = json.object(); // Create fileLit object QString mainObj = "{\"url\": \""+currentObject.value("url").toString()+ "\",\"file\": {\"name\": \""+currentObject.value("name").toString()+ ",\"__type\": \"File\"}}"; setEndPoint("classes/FilesList"); create( mainObj); emit fileUploaded( currentObject); } } ); return request( BaaS::POST, data ); }
int Global::documentType(const QUrl& document) { QMimeType mime = QMimeDatabase{}.mimeTypeForUrl(document); QList<QPluginLoader*> plugins = KoJsonTrader::self()->query("Calligra/Part", mime.name()); for (int i = 0; i < plugins.count(); i++) { QPluginLoader* loader = plugins.at(i); if(loader->fileName().contains("words")) { return DocumentType::TextDocument; } else if(loader->fileName().contains("sheets")) { return DocumentType::Spreadsheet; } else if(loader->fileName().contains("stage")) { return DocumentType::Presentation; } } // Since we don't actually have a Calligra plugin that handles these... if(staticTextTypes.contains(mime.name())) { return DocumentType::StaticTextDocument; } return DocumentType::Unknown; }
bool MimeTypeChecker::isWantedCollection(const Collection &collection, const QString &wantedMimeType) { if (wantedMimeType.isEmpty() || !collection.isValid()) { return false; } const QStringList contentMimeTypes = collection.contentMimeTypes(); if (contentMimeTypes.isEmpty()) { return false; } foreach (const QString &mimeType, contentMimeTypes) { if (mimeType.isEmpty()) { continue; } if (mimeType == wantedMimeType) { return true; } QMimeDatabase db; const QMimeType mt = db.mimeTypeForName(mimeType); if (!mt.isValid()) { continue; } if (mt.inherits(wantedMimeType)) { return true; } } return false; }
QString AnimationResult::mimeType() { QMimeDatabase db; QMimeType type = db.mimeTypeForUrl(d->url); return type.name(); }
QNetworkReply* Parse::uploadFile(QUrl url, QString name) { QString filePath = url.toLocalFile(); if (!isReady() || !QFile::exists(filePath)) return NULL; if (name.isEmpty()) name = url.fileName(); setEndPoint( "files/"+name); QMimeDatabase db; QMimeType mime = db.mimeTypeForFile(filePath); QFile file(filePath); if (mime.inherits("text/plain")){ if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return NULL; } else{ if (!file.open(QIODevice::ReadOnly )) return NULL; } initHeaders(); setHeader(QNetworkRequest::ContentTypeHeader, mime.name().toUtf8()); m_conn = connect(this, &BaaS::replyFinished, [=]( QJsonDocument json){ disconnect(m_conn); if ( getHttpCode() == 201 ){ currentObject = json.object(); emit fileUploaded( currentObject); } } ); return request( BaaS::POST, file.readAll() ); }
void MainWindow::loadMedia(){ // mime database to detect file type QMimeDatabase db; // the mime type (to test if it is an audio file QMimeType type; // file list to be inserted into playlist QStringList filelist; // audio file to be opened QFileDialog d; filelist = d.getOpenFileNames(this,tr("Open File"), "/home", tr("Audio (*.wav *.mp3 *.ogg *.flac)")); // retrieve mime type for(QList<QString>::const_iterator it=filelist.begin(); it!= filelist.end(); it++){ type = db.mimeTypeForFile(*it); // test if the file is an audio file // if yes, send it to the playlist if(type.name().startsWith("audio")){ playlist->addMedia(QUrl::fromLocalFile(*it)); } } }
EditWithMenu::EditWithMenu(const QUrl& url, QWidget* parent) : QObject(parent) , m_menu(0) , m_url(url) { QMimeDatabase db; QMimeType type = db.mimeTypeForFile(url.path(), QMimeDatabase::MatchExtension); if ( !type.isValid() ) { qCDebug(log_cervisia) << "Couldn't find mime type!"; return; } m_offers = KMimeTypeTrader::self()->query(type.name()); if( !m_offers.isEmpty() ) { m_menu = new QMenu(i18n("Edit With")); KService::List::ConstIterator it = m_offers.constBegin(); for( int i = 0 ; it != m_offers.constEnd(); ++it, ++i ) { QAction* pAction = m_menu->addAction(QIcon::fromTheme((*it)->icon()), (*it)->name()); pAction->setData(i); } connect(m_menu, SIGNAL(triggered(QAction*)), this, SLOT(actionTriggered(QAction*))); }
Vector<String> MIMETypeRegistry::getExtensionsForMIMEType(const String& mimeTypeName) { Vector<String> extensions; QMimeType mimeType = QMimeDatabase().mimeTypeForName(mimeTypeName); if (mimeType.isValid() && !mimeType.isDefault()) { Q_FOREACH(const QString& suffix, mimeType.suffixes()) { extensions.append(suffix); } }
void NodeHelper::magicSetType(KMime::Content *node, bool aAutoDecode) { const QByteArray body = (aAutoDecode) ? node->decodedContent() : node->body(); QMimeDatabase db; QMimeType mime = db.mimeTypeForData(body); QString mimetype = mime.name(); node->contentType()->setMimeType(mimetype.toLatin1()); }
void openUrl() { if (urlToOpen.isValid()) { /// Guess mime type for url to open QMimeType mimeType = FileInfo::mimeTypeForUrl(urlToOpen); const QString mimeTypeName = mimeType.name(); /// Ask KDE subsystem to open url in viewer matching mime type KRun::runUrl(urlToOpen, mimeTypeName, parent, false, false); } }
QMimeType QMimeDatabasePrivate::mimeTypeForFileNameAndData(const QString &fileName, QIODevice *device, int *accuracyPtr) { // First, glob patterns are evaluated. If there is a match with max weight, // this one is selected and we are done. Otherwise, the file contents are // evaluated and the match with the highest value (either a magic priority or // a glob pattern weight) is selected. Matching starts from max level (most // specific) in both cases, even when there is already a suffix matching candidate. *accuracyPtr = 0; // Pass 1) Try to match on the file name QStringList candidatesByName = mimeTypeForFileName(fileName); if (candidatesByName.count() == 1) { *accuracyPtr = 100; const QMimeType mime = mimeTypeForName(candidatesByName.at(0)); if (mime.isValid()) return mime; candidatesByName.clear(); } // Extension is unknown, or matches multiple mimetypes. // Pass 2) Match on content, if we can read the data if (device->isOpen()) { // Read 16K in one go (QIODEVICE_BUFFERSIZE in qiodevice_p.h). // This is much faster than seeking back and forth into QIODevice. const QByteArray data = device->peek(16384); int magicAccuracy = 0; QMimeType candidateByData(findByData(data, &magicAccuracy)); // Disambiguate conflicting extensions (if magic matching found something) if (candidateByData.isValid() && magicAccuracy > 0) { // "for glob_match in glob_matches:" // "if glob_match is subclass or equal to sniffed_type, use glob_match" const QString sniffedMime = candidateByData.name(); foreach (const QString &m, candidatesByName) { if (inherits(m, sniffedMime)) { // We have magic + pattern pointing to this, so it's a pretty good match *accuracyPtr = 100; return mimeTypeForName(m); } } *accuracyPtr = magicAccuracy; return candidateByData; } } if (candidatesByName.count() > 1) { *accuracyPtr = 20; candidatesByName.sort(); // to make it deterministic const QMimeType mime = mimeTypeForName(candidatesByName.at(0)); if (mime.isValid()) return mime; } return mimeTypeForName(defaultMimeType()); }
void ProtocolMSITS::get( const QUrl& url ) { QString htmdata, fileName; chmUnitInfo ui; QByteArray buf; qCDebug(KIO_MITS_LOG) << "kio_msits::get() " << url.path(); if ( !parseLoadAndLookup ( url, fileName ) ) return; // error() has been called by parseLoadAndLookup qCDebug(KIO_MITS_LOG) << "kio_msits::get: parseLoadAndLookup returned " << fileName; if ( LCHMUrlFactory::handleFileType( url.path(), htmdata ) ) { buf = htmdata.toUtf8(); qCDebug(KIO_MITS_LOG) << "Using special handling for image pages: " << htmdata; } else { if ( isDirectory (fileName) ) { error( KIO::ERR_IS_DIRECTORY, url.toString() ); return; } if ( !ResolveObject ( fileName, &ui) ) { qCDebug(KIO_MITS_LOG) << "kio_msits::get: could not resolve filename " << fileName; error( KIO::ERR_DOES_NOT_EXIST, url.toString() ); return; } buf.resize( ui.length ); if ( RetrieveObject (&ui, (unsigned char*) buf.data(), 0, ui.length) == 0 ) { qCDebug(KIO_MITS_LOG) << "kio_msits::get: could not retrieve filename " << fileName; error( KIO::ERR_NO_CONTENT, url.toString() ); return; } } totalSize( buf.size() ); #if 0 //PORT QT5 QMimeDatabase db; QMimeType result = db.mimeTypeForNameAndData( fileName, buf ); qCDebug(KIO_MITS_LOG) << "Emitting mimetype " << result.name(); mimeType( result.name() ); #endif data( buf ); processedSize( buf.size() ); finished(); }
static QMimeType mimeType(const QString &name, const QString& fallback) { QMimeDatabase mime; QMimeType type; if ( !name.isEmpty() ) type = mime.mimeTypeForName(name); if ( !type.isValid() && fallback != name ) type = mime.mimeTypeForName(fallback); return type; }
static QByteArray chooseFormatAndUrl(const QUrl &u, const QMimeData *mimeData, const QStringList &formats, const QString &text, const QString &suggestedFileName, QWidget *widget, bool clipboard, QUrl *newUrl) { QMimeDatabase db; QStringList formatLabels; for (int i = 0; i < formats.size(); ++i) { const QString &fmt = formats[i]; QMimeType mime = db.mimeTypeForName(fmt); if (mime.isValid()) { formatLabels.append(i18n("%1 (%2)", mime.comment(), fmt)); } else { formatLabels.append(fmt); } } QString dialogText(text); if (dialogText.isEmpty()) { dialogText = i18n("Filename for clipboard content:"); } //using QString() instead of QString::null didn't compile (with gcc 3.2.3), because the ctor was mistaken as a function declaration, Alex //krazy:exclude=nullstrassign KIO::PasteDialog dlg(QString::null, dialogText, suggestedFileName, formatLabels, widget, clipboard); //krazy:exclude=nullstrassign if (dlg.exec() != QDialog::Accepted) { return QByteArray(); } if (clipboard && dlg.clipboardChanged()) { KMessageBox::sorry(widget, i18n("The clipboard has changed since you used 'paste': " "the chosen data format is no longer applicable. " "Please copy again what you wanted to paste.")); return QByteArray(); } const QString result = dlg.lineEditText(); const QString chosenFormat = formats[ dlg.comboItem() ]; //qDebug() << " result=" << result << " chosenFormat=" << chosenFormat; *newUrl = u; newUrl->setPath(newUrl->path() + '/' + result); // In Qt3, the result of clipboard()->mimeData() only existed until the next // event loop run (see dlg.exec() above), so we re-fetched it. // TODO: This should not be necessary with Qt5; remove this conditional // and test that it still works. if (clipboard) { mimeData = QApplication::clipboard()->mimeData(); } const QByteArray ba = mimeData->data(chosenFormat); return ba; }
KoDocumentInfoDlg::KoDocumentInfoDlg(QWidget* parent, KoDocumentInfo* docInfo) : KPageDialog(parent) , d(new KoDocumentInfoDlgPrivate) { d->info = docInfo; setWindowTitle(i18n("Document Information")); // setInitialSize(QSize(500, 500)); setFaceType(KPageDialog::List); setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); button(QDialogButtonBox::Ok)->setDefault(true); d->aboutUi = new Ui::KoDocumentInfoAboutWidget(); QWidget *infodlg = new QWidget(); d->aboutUi->setupUi(infodlg); d->aboutUi->cbLanguage->addItems(KoGlobal::listOfLanguages()); d->aboutUi->cbLanguage->setCurrentIndex(-1); KPageWidgetItem *page = new KPageWidgetItem(infodlg, i18n("General")); page->setHeader(i18n("General")); // Ugly hack, the mimetype should be a parameter, instead KoDocumentBase* doc = dynamic_cast< KoDocumentBase* >(d->info->parent()); if (doc) { QMimeDatabase db; QMimeType mime = db.mimeTypeForName(doc->mimeType()); if (mime.isValid()) { page->setIcon(KisIconUtils::loadIcon(mime.iconName())); } } else { // hide all entries not used in pages for KoDocumentInfoPropsPage d->aboutUi->filePathInfoLabel->setVisible(false); d->aboutUi->filePathLabel->setVisible(false); d->aboutUi->filePathSeparatorLine->setVisible(false); d->aboutUi->lblTypeDesc->setVisible(false); d->aboutUi->lblType->setVisible(false); } addPage(page); d->pages.append(page); initAboutTab(); d->authorUi = new Ui::KoDocumentInfoAuthorWidget(); QWidget *authordlg = new QWidget(); d->authorUi->setupUi(authordlg); page = new KPageWidgetItem(authordlg, i18n("Author")); page->setHeader(i18n("Last saved by")); page->setIcon(koIcon("user-identity")); addPage(page); d->pages.append(page); initAuthorTab(); }
bool Helper::writeMimeInfo( QMimeType mime ) { KService::Ptr service = KMimeTypeTrader::self()->preferredService( mime.name()); if( service ) { outputLine( mime.name()); outputLine( mime.comment()); outputLine( service->name()); return true; } return false; }
KIso::KIso(const QString& filename, const QString & _mimetype) : KArchive(0L) { KISOFUNC; KISODEBUG("Starting KIso: " << filename << " - type: " << _mimetype); m_startsec = -1; m_filename = filename; d = new KIsoPrivate; QString mimetype(_mimetype); bool forced = true; if (mimetype.isEmpty()) { QMimeDatabase db; QMimeType mt = db.mimeTypeForFile(filename, QMimeDatabase::MatchContent); if (mt.isValid()) mimetype = mt.name(); //qDebug() << "KIso::KIso mimetype=" << mimetype << endl; // Don't move to prepareDevice - the other constructor theoretically allows ANY filter if (mimetype == "application/x-tgz" || mimetype == "application/x-targz" || // the latter is deprecated but might still be around mimetype == "application/x-webarchive") // that's a gzipped tar file, so ask for gzip filter mimetype = "application/x-gzip"; else if (mimetype == "application/x-tbz") // that's a bzipped2 tar file, so ask for bz2 filter mimetype = "application/x-bzip2"; else { // Something else. Check if it's not really gzip though (e.g. for KOffice docs) QFile file(filename); if (file.open(QIODevice::ReadOnly)) { char firstByte; char secondByte; char thirdByte; file.getChar(&firstByte); file.getChar(&secondByte); file.getChar(&thirdByte); if (firstByte == 0037 && secondByte == (char)0213) mimetype = "application/x-gzip"; else if (firstByte == 'B' && secondByte == 'Z' && thirdByte == 'h') mimetype = "application/x-bzip2"; else if (firstByte == 'P' && secondByte == 'K' && thirdByte == 3) { char fourthByte; file.getChar(&fourthByte); if (fourthByte == 4) mimetype = "application/x-zip"; } } } forced = false; } prepareDevice(filename, mimetype, forced); }
void InfoPanel::showMetaDataFor(const QModelIndex &index) { showMetaData(); const Archive::Entry *entry = m_model->entryForIndex(index); QMimeDatabase db; QMimeType mimeType; if (entry->isDir()) { mimeType = db.mimeTypeForName(QStringLiteral("inode/directory")); } else { mimeType = db.mimeTypeForFile(entry->fullPath(), QMimeDatabase::MatchExtension); } m_typeValueLabel->setText(mimeType.comment()); if (!entry->property("owner").toString().isEmpty()) { m_ownerLabel->show(); m_ownerValueLabel->show(); m_ownerValueLabel->setText(entry->property("owner").toString()); } else { m_ownerLabel->hide(); m_ownerValueLabel->hide(); } if (!entry->property("group").toString().isEmpty()) { m_groupLabel->show(); m_groupValueLabel->show(); m_groupValueLabel->setText(entry->property("group").toString()); } else { m_groupLabel->hide(); m_groupValueLabel->hide(); } if (!entry->property("link").toString().isEmpty()) { m_targetLabel->show(); m_targetValueLabel->show(); m_targetValueLabel->setText(entry->property("link").toString()); } else { m_targetLabel->hide(); m_targetValueLabel->hide(); } if (entry->property("isPasswordProtected").toBool()) { m_passwordLabel->show(); m_passwordValueLabel->show(); } else { m_passwordLabel->hide(); m_passwordValueLabel->hide(); } }
QT_END_NAMESPACE static StandardItemList createRow(const QMimeType &t) { const QVariant v = QVariant::fromValue(t); QStandardItem *nameItem = new QStandardItem(t.name()); const Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled; nameItem->setData(v, mimeTypeRole); nameItem->setData(QVariant(false), iconQueriedRole); nameItem->setFlags(flags); nameItem->setToolTip(t.comment()); return StandardItemList{nameItem}; }
QString uwsgiProcess::findApplication(const QDir &projectDir) { QMimeDatabase m_db; QDirIterator it(projectDir.absolutePath(), QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { QString file = it.next(); QMimeType mime = m_db.mimeTypeForFile(file); if (mime.inherits(QStringLiteral("application/x-sharedlib"))) { return file; } } return QString(); }
QString vfile::vfile_getIcon() { if (vfile_icon.isEmpty()) { QString mime = vfile_getMime(); if (vfile_isBrokenLink()) vfile_icon = "file-broken"; else if (vfile_icon.isEmpty()) { QMimeDatabase db; QMimeType mt = db.mimeTypeForName(mime); vfile_icon = mt.isValid() ? mt.iconName() : "file-broken"; } } return vfile_icon; }
// create table of file lists qualified for search QHash<SearchWorker::WorkSet, QStringList> SearchWorker::createFileTable(QDir dir, QDir::Filter hidden, QHash<SearchWorker::WorkSet, bool> enabler) { QHash<SearchWorker::WorkSet, QStringList> wtab; QStringList filetypefilters; if (!enabler[SearchWorker::EnableMimeType]) { if (enabler[SearchWorker::EnableTxt]) { filetypefilters.clear(); filetypefilters << "*.txt"; wtab[SearchWorker::EnableTxt] = dir.entryList(filetypefilters, QDir::Files | hidden); } if (enabler[SearchWorker::EnableHtml]) { filetypefilters.clear(); filetypefilters << "*.html" << "*.htm"; wtab[SearchWorker::EnableHtml] = dir.entryList(filetypefilters, QDir::Files | hidden); } if (enabler[SearchWorker::EnableSrc]) { filetypefilters.clear(); filetypefilters << "*.cpp" << "*.c" << "*.h" << "*.py" << "*.sh" << "*.qml" << "*.js"; wtab[SearchWorker::EnableSrc] = dir.entryList(filetypefilters, QDir::Files | hidden); } if (enabler[SearchWorker::EnableApps]) { filetypefilters.clear(); filetypefilters << "*.desktop"; wtab[SearchWorker::EnableApps] = dir.entryList(filetypefilters, QDir::Files | hidden); } if (enabler[SearchWorker::EnableSqlite]) { filetypefilters.clear(); filetypefilters << "*.sqlite" << "*.sqlite3" << "*.db"; wtab[SearchWorker::EnableSqlite] = dir.entryList(filetypefilters, QDir::Files | hidden); } } if (enabler[SearchWorker::EnableMimeType]) { filetypefilters.clear(); QStringList names = dir.entryList(filetypefilters, QDir::Files | hidden); QMimeDatabase db; for (int i = 0 ; i < names.count() ; ++i) { QString fullpath = dir.absoluteFilePath(names.at(i)); QMimeType mime = db.mimeTypeForFile(fullpath); if ( mime.inherits("application/x-sqlite3") ) { if (enabler[SearchWorker::EnableSqlite]) wtab[SearchWorker::EnableSqlite].append(names.at(i)); } else if ( mime.inherits("application/x-desktop") ) { if (enabler[SearchWorker::EnableApps]) wtab[SearchWorker::EnableApps].append(names.at(i)); } else if ( mime.inherits("text/html") ) { if (enabler[SearchWorker::EnableHtml]) wtab[SearchWorker::EnableHtml].append(names.at(i)); } else if ( mime.inherits("text/x-csrc") || mime.inherits("application/x-shellscript") || mime.inherits("text/x-python") || mime.inherits("text/x-qml") ) { if (enabler[SearchWorker::EnableSrc]) wtab[SearchWorker::EnableSrc].append(names.at(i)); } else if ( mime.inherits("text/plain") ) { if (enabler[SearchWorker::EnableTxt]) wtab[SearchWorker::EnableTxt].append(names.at(i)); } } } return wtab; }
QStringList EpisodeFinder::getEpisodes(const QString &seasonPath, int season, int episode) const { QDir seasonDir(seasonPath); QMimeDatabase db; QStringList files; foreach (const QFileInfo &fileInfo, seasonDir.entryInfoList()) { if (!fileInfo.isFile()) continue; QMimeType mimeType = db.mimeTypeForFile(fileInfo); // must have got a video mime type if (!mimeType.name().startsWith("video/")) continue; if (season == -1) { files << fileInfo.absoluteFilePath(); continue; } QString fileName = fileInfo.fileName(); int fileSeason, fileEpisode; // SXXEXX expression? QRegularExpression re("\\bS([0-9]+)E([0-9]+)", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match = re.match(fileName); if (match.hasMatch()) { fileSeason = match.captured(1).toInt(); fileEpisode = match.captured(2).toInt(); if (fileSeason == season && fileEpisode == episode) files << fileInfo.absoluteFilePath(); continue; } // SxE expression? re.setPattern("\\b([0-9]+)x([0-9]+)"); match = re.match(fileName); if (match.hasMatch()) { fileSeason = match.captured(1).toInt(); fileEpisode = match.captured(2).toInt(); if (fileSeason == season && fileEpisode == episode) files << fileInfo.absoluteFilePath(); continue; } } return files; }
String MIMETypeRegistry::getMIMETypeForPath(const String& path) { QMimeType type = QMimeDatabase().mimeTypeForFile(path, QMimeDatabase::MatchExtension); if (type.isValid() && !type.isDefault()) return type.name(); const ExtensionMap *e = extensionMap; while (e->extension) { if (path.endsWith(e->dotExtension)) return e->mimeType; ++e; } return defaultMIMEType(); }