void ThemeChooser::Load(void) { SetBusyPopupMessage(tr("Loading Installed Themes")); QString MythVersion = MYTH_SOURCE_PATH; QStringList themesSeen; QDir themes(GetConfDir() + "/themes"); themes.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); themes.setSorting(QDir::Name | QDir::IgnoreCase); // FIXME: For now, treat git master the same as svn trunk if (MythVersion == "master") MythVersion = "trunk"; if (MythVersion != "trunk") { MythVersion = MYTH_BINARY_VERSION; // Example: 0.25.20101017-1 MythVersion.replace(QRegExp("\\.[0-9]{8,}.*"), ""); } m_infoList = themes.entryInfoList(); for( QFileInfoList::iterator it = m_infoList.begin(); it != m_infoList.end(); ++it ) { if (loadThemeInfo(*it)) { themesSeen << (*it).fileName(); m_themeStatuses[(*it).fileName()] = "default"; } } themes.setPath(GetThemesParentDir()); QFileInfoList sharedThemes = themes.entryInfoList(); for( QFileInfoList::iterator it = sharedThemes.begin(); it != sharedThemes.end(); ++it ) { if ((!themesSeen.contains((*it).fileName())) && (loadThemeInfo(*it))) { m_infoList << *it; themesSeen << (*it).fileName(); m_themeStatuses[(*it).fileName()] = "default"; } } QString remoteThemesFile = GetConfDir(); remoteThemesFile.append("/tmp/themes.zip"); QString themeSite = QString("%1/%2") .arg(gCoreContext->GetSetting("ThemeRepositoryURL", "http://themes.mythtv.org/themes/repository")).arg(MythVersion); int downloadFailures = gCoreContext->GetNumSetting("ThemeInfoDownloadFailures", 0); if (QFile::exists(remoteThemesFile)) { QFileInfo finfo(remoteThemesFile); if (finfo.lastModified() < mythCurrentDateTime().addSecs(-600)) { VERBOSE(VB_GUI, LOC + QString("%1 is over 10 minutes old, forcing " "remote theme list download").arg(remoteThemesFile)); m_refreshDownloadableThemes = true; } } else if (downloadFailures < 2) // (and themes.zip does not exist) { VERBOSE(VB_GUI, LOC + QString("%1 does not exist, forcing remote theme " "list download").arg(remoteThemesFile)); m_refreshDownloadableThemes = true; } if (m_refreshDownloadableThemes) { SetBusyPopupMessage(tr("Refreshing Downloadable Themes Information")); QString url = themeSite; url.append("/themes.zip"); QString destdir = GetMythUI()->GetThemeCacheDir(); destdir.append("/themechooser"); QString versiondir = QString("%1/%2").arg(destdir).arg(MythVersion); removeThemeDir(versiondir); QDir dir; dir.mkpath(destdir); bool result = GetMythDownloadManager()->download(url, remoteThemesFile); SetBusyPopupMessage(tr("Extracting Downloadable Themes Information")); if (!result || !extractZIP(remoteThemesFile, destdir)) { QFile::remove(remoteThemesFile); downloadFailures++; gCoreContext->SaveSetting("ThemeInfoDownloadFailures", downloadFailures); } } QDir remoteThemesDir(GetMythUI()->GetThemeCacheDir() .append("/themechooser/").append(MythVersion)); if ((QFile::exists(remoteThemesFile)) && (remoteThemesDir.exists())) { SetBusyPopupMessage(tr("Loading Downloadable Themes")); VERBOSE(VB_GUI, LOC + QString("%1 and %2 exist, using cached remote " "themes list").arg(remoteThemesFile) .arg(remoteThemesDir.absolutePath())); QString themesPath = remoteThemesDir.absolutePath(); themes.setPath(themesPath); QFileInfoList downloadableThemes = themes.entryInfoList(); for( QFileInfoList::iterator it = downloadableThemes.begin(); it != downloadableThemes.end(); ++it ) { QString dirName = (*it).fileName(); QString themeName = dirName; QString remoteDir = themeSite; remoteDir.append("/").append(dirName); QString localDir = themes.absolutePath(); localDir.append("/").append(dirName); if (themesSeen.contains(dirName)) { ThemeInfo remoteTheme((*it).absoluteFilePath()); ThemeInfo *localTheme = m_themeNameInfos[dirName]; themeName = remoteTheme.GetName(); int rmtMaj = remoteTheme.GetMajorVersion(); int rmtMin = remoteTheme.GetMinorVersion(); int locMaj = localTheme->GetMajorVersion(); int locMin = localTheme->GetMinorVersion(); if ((rmtMaj > locMaj) || ((rmtMaj == locMaj) && (rmtMin > locMin))) { if (loadThemeInfo(*it)) { m_infoList << *it; m_themeStatuses[themeName] = "updateavailable"; QFileInfo finfo(remoteTheme.GetPreviewPath()); GetMythDownloadManager()->queueDownload( remoteDir.append("/").append(finfo.fileName()), localDir.append("/").append(finfo.fileName()), NULL); } } else if ((rmtMaj == locMaj) && (rmtMin == locMin)) { m_themeStatuses[themeName] = "uptodate"; } } else { ThemeInfo *remoteTheme = loadThemeInfo(*it); if (remoteTheme) { themeName = remoteTheme->GetName(); themesSeen << dirName; m_infoList << *it; m_themeStatuses[themeName] = "updateavailable"; QFileInfo finfo(remoteTheme->GetPreviewPath()); GetMythDownloadManager()->queueDownload( remoteDir.append("/").append(finfo.fileName()), localDir.append("/").append(finfo.fileName()), NULL); } } } } ResetBusyPopup(); qSort(m_infoList.begin(), m_infoList.end(), sortThemeNames); }
void AntiPiracy::checkValidityAndSetScene(AbstractPane* root, QString urlToBypassHash) { // Save internally for future use if (root) { m_normalRoot = root; } m_urlToBypassHash = urlToBypassHash; // Check if the unlock key was already entered previously QSettings settings; settings.beginGroup("AntiPiracy"); if ((settings.contains("unlockKeyEnteredByUser")) && (this->hashThis(settings.value("unlockKeyEnteredByUser", "").toString()) == m_unlockKeyHash)) { // User already entered the correct key previously m_appInstalledFromBBW = true; } else { // The next code will check if the app was downloaded from BBW QDir dir("/pps/system/installer/appdetails/"); dir.setFilter(QDir::Files | QDir::System | QDir::Hidden | QDir::NoDotAndDotDot | QDir::AllEntries); QFileInfoList fileInfoList = dir.entryInfoList(); for (int i = 0; i < fileInfoList.size(); i++) { QString completePath = fileInfoList[i].path() + "/" + fileInfoList[i].fileName() + (fileInfoList[i].isDir() ? "/" : ""); if (this->checkFile(completePath)) { break; }; } } if ((m_appInstalledFromBBW) || (m_appInstalledFromBetaZone)) { // App was either installed from BBW/BetaZone or unlock key was previously entered correctly. // Set the normal main.qml as Scene Application::instance()->setScene(root); this->deleteLater(); } else { /* * Load a custom Page constructed in C++ to make sure it can't be altered * The Page is only a Label and an ActivityIndicator, but it's mostly used to be the * scene where the unlock key prompt will be shown */ Page *keyPromptPage = new Page(this); Container *keyPromptContainer = new Container(); keyPromptContainer->setLayout(new DockLayout()); Label *label = new Label(); label->setText(tr("Checking validity, please wait...")); label->setHorizontalAlignment(HorizontalAlignment::Center); ActivityIndicator *activityIndicator = new ActivityIndicator(); activityIndicator->setHorizontalAlignment(HorizontalAlignment::Center); activityIndicator->setMinHeight(300); activityIndicator->setMinWidth(activityIndicator->minHeight()); Container *container = new Container(); container->setHorizontalAlignment(HorizontalAlignment::Center); container->setVerticalAlignment(VerticalAlignment::Center); container->add(label); container->add(activityIndicator); keyPromptContainer->add(container); keyPromptPage->setContent(keyPromptContainer); Application::instance()->setScene(keyPromptPage); activityIndicator->start(); /* * Check online for a bypass. * This can be used while your app is in review period to avoid having the unlock prompt * shown to a BBW reviewer. To construct the bypass hash, use the function * printToConsoleHashOfThisKey() and pass the app version you'd like to whitelist * as a parameter. Use the hash printed to console and put it online. */ QUrl url(m_urlToBypassHash); QNetworkAccessManager *nam = new QNetworkAccessManager(this); QNetworkReply *reply = nam->get(QNetworkRequest(url)); connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished())); } }
QList<DiskInfo> GetLocalDiskList(quint64 minSizeInGb, const QString &type, const QString &table){ QList<DiskInfo> disklist; QFileInfoList devlist = QDir::drives(); for (int i = 0; i < devlist.size(); ++i) { QString devname = QDir::toNativeSeparators(devlist.at(i).path().toUpper()).remove("\\"); if (GetDriveType(LPWSTR(devname.utf16())) == DRIVE_FIXED) { ULARGE_INTEGER FreeAv,TotalBytes,FreeBytes; if (!GetDiskFreeSpaceEx(LPWSTR(devname.utf16()),&FreeAv,&TotalBytes,&FreeBytes)) { continue; } if ((FreeBytes.QuadPart/(1024*1024*1024)) < minSizeInGb) { qDebug()<<"Skip Disk"<<devname<<"Space not enough"<<FreeBytes.QuadPart/(1024*1024*1024); continue; } PARTITION_INFORMATION_EX piex; Xapi::GetPartitionEx (devname, &piex); QString format = "Unknow"; PartitonStyle style; switch (piex.PartitionStyle) { case PARTITION_STYLE_MBR: style = MBRPartition; if (!table.toUpper ().contains ("MBR")) { qDebug()<<"Skip Disk"<<devname<<"MBR"; continue; } switch (piex.Mbr.PartitionType) { case PARTITION_FAT32: case PARTITION_FAT_16: format = "FAT"; break; case 0x4A: case PARTITION_IFS: format = "NTFS"; break; default: break; } if (!type.toUpper ().contains (format.toUpper ())) { qDebug()<<"Skip Disk"<<devname<<format<<"Not a NTFS Disk"; continue; } break; case PARTITION_STYLE_GPT: style = GPTPartition; if (!table.toUpper ().contains ("GPT")) { qDebug()<<"Skip Disk"<<devname<<"GPT"; continue; } GUID PARTITION_BASIC_DATA_GUID; PARTITION_BASIC_DATA_GUID.Data1 = 0xEBD0A0A2L; PARTITION_BASIC_DATA_GUID.Data2 = 0xB9E5; PARTITION_BASIC_DATA_GUID.Data3 = 0x4433; PARTITION_BASIC_DATA_GUID.Data4[0] = 0x87; PARTITION_BASIC_DATA_GUID.Data4[1] = 0xC0; PARTITION_BASIC_DATA_GUID.Data4[2] = 0x68; PARTITION_BASIC_DATA_GUID.Data4[3] = 0xB6; PARTITION_BASIC_DATA_GUID.Data4[4] = 0xB7; PARTITION_BASIC_DATA_GUID.Data4[5] = 0x26; PARTITION_BASIC_DATA_GUID.Data4[6] = 0x99; PARTITION_BASIC_DATA_GUID.Data4[7] = 0xC7; if (PARTITION_BASIC_DATA_GUID != piex.Gpt.PartitionType) { qDebug()<<"Skip Disk"<<devname<<"Not a NTFS Disk"; continue; } break; case PARTITION_STYLE_RAW: style = RAWPartition; if (!table.toUpper ().contains ("RAW")) { continue; } break; default: style = UnknowPartition; qDebug()<<"Disk Type"<<devname<<"Unknow"; continue; } DiskInfo diskinfo; diskinfo.Name = devname; diskinfo.Style = style; diskinfo.FreeSpace = FreeBytes.QuadPart/(1024*1024*1024); QString result = Xapi::SynExec( "cmd", QString("/C \"chcp 437 & %1\\manage-bde -status %2\" ").arg(Xapi::SystemDirtory()).arg(devname)); QStringList list = result.split("\r").filter("BitLocker Version"); diskinfo.Encrypt = list.size() ? !list.first().contains("None") : false; qDebug()<<devname<<"System Type"<<diskinfo.Encrypt; disklist.push_back(diskinfo); } } return disklist; }
// IRIX 6.x void qt_parseSpoolInterface(QList<QPrinterDescription> *printers) { QDir lp(QLatin1String("/usr/spool/lp/interface")); if (!lp.exists()) return; QFileInfoList files = lp.entryInfoList(); if(files.isEmpty()) return; for (int i = 0; i < files.size(); ++i) { QFileInfo printer = files.at(i); if (!printer.isFile()) continue; // parse out some information QFile configFile(printer.filePath()); if (!configFile.open(QIODevice::ReadOnly)) continue; QByteArray line; line.resize(1025); QString namePrinter; QString hostName; QString hostPrinter; QString printerType; QString nameKey(QLatin1String("NAME=")); QString typeKey(QLatin1String("TYPE=")); QString hostKey(QLatin1String("HOSTNAME=")); QString hostPrinterKey(QLatin1String("HOSTPRINTER=")); while (!configFile.atEnd() && (configFile.readLine(line.data(), 1024)) > 0) { QString uline = QString::fromLocal8Bit(line); if (uline.startsWith(typeKey) ) { printerType = uline.mid(nameKey.length()); printerType = printerType.simplified(); } else if (uline.startsWith(hostKey)) { hostName = uline.mid(hostKey.length()); hostName = hostName.simplified(); } else if (uline.startsWith(hostPrinterKey)) { hostPrinter = uline.mid(hostPrinterKey.length()); hostPrinter = hostPrinter.simplified(); } else if (uline.startsWith(nameKey)) { namePrinter = uline.mid(nameKey.length()); namePrinter = namePrinter.simplified(); } } configFile.close(); printerType = printerType.trimmed(); if (printerType.indexOf(QLatin1String("postscript"), 0, Qt::CaseInsensitive) < 0) continue; int ii = 0; while ((ii = namePrinter.indexOf(QLatin1Char('"'), ii)) >= 0) namePrinter.remove(ii, 1); if (hostName.isEmpty() || hostPrinter.isEmpty()) { qt_perhapsAddPrinter(printers, printer.fileName(), QLatin1String(""), namePrinter); } else { QString comment; comment = namePrinter; comment += QLatin1String(" ("); comment += hostPrinter; comment += QLatin1Char(')'); qt_perhapsAddPrinter(printers, printer.fileName(), hostName, comment); } } }
void TileOpDriver::apply(QString in, vector<Envelope> envelopes, double buffer, QString out) { // create a job pp::Job job; job.setVerbose(Log::getInstance().getLevel() <= Log::Debug); // set the name job.setName("TileOpDriver"); // be nice and don't start the reduce tasks until most of the map tasks are done. job.getConfiguration().setDouble("mapred.reduce.slowstart.completed.maps", 0.98); // set the input/output pp::Hdfs fs; job.setInput(fs.getAbsolutePath(in.toStdString())); job.setOutput(fs.getAbsolutePath(out.toStdString())); if (_op == 0) { throw HootException("You must specify an operation."); } stringstream ss; ObjectOutputStream oos(ss); oos.writeObject(*_op); oos.flush(); LOG_INFO("oos size: " << ss.str().size()); job.getConfiguration().setBytes(TileOpReducer::opKey(), ss.str()); job.getConfiguration().set(TileOpMapper::envelopesKey(), _toString(envelopes)); job.getConfiguration().set(TileOpMapper::replacementsKey(), fs.getAbsolutePath(in.toStdString())); job.getConfiguration().setDouble(TileOpMapper::maxWaySizeKey(), buffer); job.getConfiguration().setDouble(TileOpMapper::bufferKey(), buffer); // read the max ids from in and write them to the configuration MapStats stats; stats.readDir(in); stats.write(job.getConfiguration()); // setup the mapper and reducer classes. job.setMapperClass(TileOpMapper::className()); job.setReducerClass(TileOpReducer::className()); job.setInputFormatClass(PbfInputFormat::className()); job.setRecordReaderClass(PbfRecordReader::className()); job.setRecordWriterClass(PbfRecordWriter::className()); // Adds all libraries in this directory to the job. job.addLibraryDirs(conf().getList("hoot.hadoop.libpath", "${HOOT_HOME}/lib/;${HOOT_HOME}/local/lib/;${HADOOP_HOME}/c++/Linux-amd64-64/lib/;" "${HOOT_HOME}/pretty-pipes/lib/")); LOG_INFO("Hoot home: " << conf().getString("foo", "${HOOT_HOME}")); const std::vector<std::string>& dirs = job.getLibraryDirs(); for (size_t i = 0; i < dirs.size(); i++) { LOG_INFO("lib dir: " << dirs[i]); } job.addFile(ConfPath::search("hoot.json").toStdString()); // if GDAL isn't installed on all nodes, then we'll need to copy over the projection info. QString gdalData = QString(getenv("GDAL_DATA")); if (gdalData != "") { QDir gdalDir(gdalData); if (gdalDir.exists() == false) { LOG_WARN("Could not find GDAL_DIR: " << gdalData); } else { QStringList filters; filters << "*.csv"; QFileInfoList fil = gdalDir.entryInfoList(filters, QDir::Files); for (int i = 0; i < fil.size(); i++) { LOG_INFO("Adding GDAL_DATA file: " << fil[i].absoluteFilePath()); job.addFile(fil[i].absoluteFilePath().toStdString()); } } } // This library will be used to provide mapper/reducer classes and anything else referenced // by the factory. job.addPlugin(getenv("HOOT_HOME") + string("/lib/libHootHadoop.so.1")); // serialize all the configuration settings. job.getConfiguration().set(settingsConfKey().toStdString(), conf().toString().toUtf8().constData()); _addDefaultJobSettings(job); QStringList fileDeps = conf().getList(fileDepsKey(), QStringList()); for (int i = 0; i < fileDeps.size(); i++) { job.addFile(fileDeps[i].toStdString()); } // conflation runs can go for a _long_ time. Setting timeout to 6 hours. job.getConfiguration().setInt("mapred.task.timeout", 6 * 3600 * 1000); // run the job. job.run(); }
/*! Processes the qdoc config file \a fileName. This is the controller for all of qdoc. */ static void processQdocconfFile(const QString &fileName) { #ifndef QT_NO_TRANSLATION QList<QTranslator *> translators; #endif /* The Config instance represents the configuration data for qdoc. All the other classes are initialized with the config. Here we initialize the configuration with some default values. */ Config config(tr("qdoc")); int i = 0; while (defaults[i].key) { config.setStringList(defaults[i].key, QStringList() << defaults[i].value); ++i; } config.setStringList(CONFIG_SYNTAXHIGHLIGHTING, QStringList(highlighting ? "true" : "false")); config.setStringList(CONFIG_SHOWINTERNAL, QStringList(showInternal ? "true" : "false")); config.setStringList(CONFIG_OBSOLETELINKS, QStringList(obsoleteLinks ? "true" : "false")); /* With the default configuration values in place, load the qdoc configuration file. Note that the configuration file may include other configuration files. The Location class keeps track of the current location in the file being processed, mainly for error reporting purposes. */ Location::initialize(config); config.load(fileName); /* Add the defines to the configuration variables. */ QStringList defs = defines + config.getStringList(CONFIG_DEFINES); config.setStringList(CONFIG_DEFINES,defs); Location::terminate(); QString prevCurrentDir = QDir::currentPath(); QString dir = QFileInfo(fileName).path(); if (!dir.isEmpty()) QDir::setCurrent(dir); /* Initialize all the classes and data structures with the qdoc configuration. */ Location::initialize(config); Tokenizer::initialize(config); Doc::initialize(config); CodeMarker::initialize(config); CodeParser::initialize(config); Generator::initialize(config); #ifndef QT_NO_TRANSLATION /* Load the language translators, if the configuration specifies any. */ QStringList fileNames = config.getStringList(CONFIG_TRANSLATORS); QStringList::Iterator fn = fileNames.constBegin(); while (fn != fileNames.constEnd()) { QTranslator *translator = new QTranslator(0); if (!translator->load(*fn)) config.lastLocation().error(tr("Cannot load translator '%1'") .arg(*fn)); QCoreApplication::instance()->installTranslator(translator); translators.append(translator); ++fn; } #endif //QSet<QString> outputLanguages = config.getStringSet(CONFIG_OUTPUTLANGUAGES); /* Get the source language (Cpp) from the configuration and the location in the configuration file where the source language was set. */ QString lang = config.getString(CONFIG_LANGUAGE); Location langLocation = config.lastLocation(); /* Initialize the tree where all the parsed sources will be stored. The tree gets built as the source files are parsed, and then the documentation output is generated by traversing the tree. */ Tree *tree = new Tree; tree->setVersion(config.getString(CONFIG_VERSION)); /* By default, the only output format is HTML. */ QSet<QString> outputFormats = config.getOutputFormats(); Location outputFormatsLocation = config.lastLocation(); /* Read some XML indexes containing definitions from other documentation sets. */ QStringList indexFiles = config.getStringList(CONFIG_INDEXES); dependModules += config.getStringList(CONFIG_DEPENDS); if (dependModules.size() > 0) { if (indexDirs.size() > 0) { for (int i = 0; i < indexDirs.size(); i++) { if (indexDirs[i].startsWith("..")) { const QString prefix(QDir(dir).relativeFilePath(prevCurrentDir)); if (!prefix.isEmpty()) indexDirs[i].prepend(prefix + QLatin1Char('/')); } } /* Add all subdirectories of the indexdirs as dependModules when an asterisk is used in the 'depends' list. */ if (dependModules.contains("*")) { dependModules.removeOne("*"); for (int i = 0; i < indexDirs.size(); i++) { QDir scanDir = QDir(indexDirs[i]); scanDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); QFileInfoList dirList = scanDir.entryInfoList(); for (int j = 0; j < dirList.size(); j++) { if (dirList[j].fileName().toLower() != config.getString(CONFIG_PROJECT).toLower()) dependModules.append(dirList[j].fileName()); } } } for (int i = 0; i < dependModules.size(); i++) { QString indexToAdd; QList<QFileInfo> foundIndices; for (int j = 0; j < indexDirs.size(); j++) { QString fileToLookFor = indexDirs[j] + QLatin1Char('/') + dependModules[i] + QLatin1Char('/') + dependModules[i] + QLatin1String(".index"); if (QFile::exists(fileToLookFor)) { QFileInfo tempFileInfo(fileToLookFor); if (!foundIndices.contains(tempFileInfo)) foundIndices.append(tempFileInfo); } } qSort(foundIndices.begin(), foundIndices.end(), creationTimeBefore); if (foundIndices.size() > 1) { /* QDoc should always use the last entry in the multimap when there are multiple index files for a module, since the last modified file has the highest UNIX timestamp. */ qDebug() << "Multiple indices found for dependency:" << dependModules[i] << "\nFound:"; for (int k = 0; k < foundIndices.size(); k++) qDebug() << foundIndices[k].absoluteFilePath(); qDebug() << "Using" << foundIndices[foundIndices.size() - 1].absoluteFilePath() << "as index for" << dependModules[i]; indexToAdd = foundIndices[foundIndices.size() - 1].absoluteFilePath(); } else if (foundIndices.size() == 1) { indexToAdd = foundIndices[0].absoluteFilePath(); } else { qDebug() << "No indices for" << dependModules[i] << "could be found in the specified index directories."; } if (!indexToAdd.isEmpty() && !indexFiles.contains(indexToAdd)) indexFiles << indexToAdd; } } else { qDebug() << "Dependant modules specified, but no index directories or install directory were set." << "There will probably be errors for missing links."; } } tree->readIndexes(indexFiles); QSet<QString> excludedDirs; QSet<QString> excludedFiles; QStringList headerList; QStringList sourceList; QStringList excludedDirsList; QStringList excludedFilesList; excludedDirsList = config.getCanonicalRelativePathList(CONFIG_EXCLUDEDIRS); foreach (const QString &excludeDir, excludedDirsList) { QString p = QDir::fromNativeSeparators(excludeDir); excludedDirs.insert(p); }
QString AudioPluginOSCGUI::getGUIFilePath(QString identifier) { QString type, soName, label; PluginIdentifier::parseIdentifier(identifier, type, soName, label); RG_DEBUG << "AudioPluginOSCGUI::getGUIFilePath(" << identifier << ")"; QFileInfo soInfo(soName); if (soInfo.isRelative()) { //!!! RG_DEBUG << "AudioPluginOSCGUI::AudioPluginOSCGUI: Unable to deal with relative .so path \"" << soName << "\" in identifier \"" << identifier << "\" yet"; throw Exception("Can't deal with relative .soname"); } QDir dir(soInfo.dir()); QString fileBase(soInfo.completeBaseName()); if (!dir.cd(fileBase)) { RG_DEBUG << "AudioPluginOSCGUI::AudioPluginOSCGUI: No GUI subdir for plugin .so " << soName; throw Exception("No GUI subdir available"); } QFileInfoList list = dir.entryInfoList(); // in order of preference: const char *suffixes[] = { "_rg", "_kde", "_qt", "_gtk2", "_gtk", "_x11", "_gui" }; int nsuffixes = int(sizeof(suffixes) / sizeof(suffixes[0])); for (int k = 0; k <= nsuffixes; ++k) { for (int fuzzy = 0; fuzzy <= 1; ++fuzzy) { QFileInfoList::iterator info; for (info = list.begin(); info != list.end(); ++info) { //### JAS Check for errors RG_DEBUG << "Looking at " << info->fileName() << " in path " << info->filePath() << " for suffix " << (k == nsuffixes ? "(none)" : suffixes[k]) << ", fuzzy " << fuzzy << endl; if (!(info->isFile() || info->isSymLink()) || !info->isExecutable()) { RG_DEBUG << "(not executable)"; continue; } if (fuzzy) { if (info->fileName().left(fileBase.length()) != fileBase) continue; RG_DEBUG << "(is file base)"; } else { if (info->fileName().left(label.length()) != label) continue; RG_DEBUG << "(is label)"; } if (k == nsuffixes || info->fileName().toLower().endsWith(suffixes[k])) { RG_DEBUG << "(ends with suffix " << (k == nsuffixes ? "(none)" : suffixes[k]) << " or out of suffixes)"; return info->filePath(); } RG_DEBUG << "(doesn't end with suffix " << (k == nsuffixes ? "(none)" : suffixes[k]) << ")"; } } } return QString(); }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (a.arguments().size() < 3) { qCritical() << "this application requires more arguments!"; return -1; } const QString trainDirName = a.arguments().at(1); const QString testDirName = a.arguments().at(2); const QString outputName = a.arguments().at(3); const QString extractorName = a.arguments().at(4); const QStringList extractorArgs = a.arguments().mid(5); ExtractorInterface *extractor = ExtractorFactory::getExtractor(extractorName, extractorArgs); if (extractor == NULL) { qCritical() << "failed to initialise extractor" << extractorName; return -2; } QDir trainDir(trainDirName); QStringList subdirs = QStringList() << "wood" << "straw" << "salt" << "linen"; QList<quint8> labels = QList<quint8>() << 32 << 96 << 160 << 224; QVector<LabelledData> trainData; #ifdef HAS_ELAPSED_TIMER QElapsedTimer extractionTimer; #else QTime extractionTimer; #endif int threadCount = 1; #ifdef _OPENMP #pragma omp parallel { #pragma omp single { threadCount = omp_get_num_threads(); } } #endif qDebug() << "using" << threadCount << "threads."; extractionTimer.start(); unsigned int imagesCount = 0; for (int j = 0; j < subdirs.size(); j++) { trainDir.cd(subdirs.at(j)); const QFileInfoList fileList = trainDir.entryInfoList(QStringList() << "*.png"); #ifdef HAS_ELAPSED_TIMER QElapsedTimer extractorTimer; #else QTime extractorTimer; #endif extractorTimer.start(); for (int i = 0; i < fileList.size(); i++) { imagesCount++; const QString filename = fileList.at(i).filePath(); const QImage image(filename); if (image.format() != QImage::Format_Indexed8) { qCritical("Image is not greyscale!"); return -1; } extractor->preprocess(image); if (extractor->extracts()) { unsigned int count = trainData.size(); trainData.resize(trainData.size() + image.width() * image.height()); LabelledData *trainDataPtr = trainData.data(); #pragma omp parallel for for (int x = 0; x < image.width(); x++) { for (int y = 0; y < image.height(); y++) { const QVector<nnreal> res = extractor->extract(image, x, y); Q_ASSERT(res.size() == extractor->size()); LabelledData li(res, labels.at(j)); const unsigned int idx = count + x * image.height() + y; trainDataPtr[idx] = li; } } } const QVector<QVector<nnreal> > ppFeatures = extractor->postprocess(image); const int ppCount = ppFeatures.size(); if (ppCount > 0) { const int count = trainData.size(); trainData.resize(trainData.size() + ppFeatures.size()); LabelledData *trainDataPtr = trainData.data(); #pragma omp parallel for for (int k = 0; k < ppCount; k++) { Q_ASSERT(ppFeatures.at(k).size() == extractor->size()); LabelledData ld(ppFeatures.at(k), labels.at(j)); trainDataPtr[count + k] = ld; } } qDebug() << fileList.at(i).filePath() << extractorTimer.restart(); } trainDir.cdUp(); } const int msecs = extractionTimer.elapsed(); qDebug() << "trainSize:" << trainData.size() << "extraction of " << imagesCount << "images took" << msecs << "msecs, average" << float(msecs) / imagesCount << "msecs per image"; const QString trainOutFilename(outputName + "_" + extractorName + "_train.out"); QFile trainOutput(trainOutFilename); if (!trainOutput.open(QIODevice::WriteOnly)) { qCritical() << "failed to open output file" << trainOutFilename; return -3; } { #ifdef HAS_ELAPSED_TIMER QElapsedTimer saveTimer; #else QTime saveTimer; #endif saveTimer.start(); QDataStream outstream(&trainOutput); saveFeatures(outstream, extractorName, extractorArgs, extractor->size(), trainData); int msecs = saveTimer.elapsed(); qDebug() << "saving took" << msecs << "msecs"; } trainOutput.close(); trainData.clear(); { QDir testDir(testDirName); const QFileInfoList dataFileList = testDir.entryInfoList(QStringList() << "test*.png"); const QFileInfoList labelFileList = testDir.entryInfoList(QStringList() << "label*.png"); Q_ASSERT(dataFileList.size() == labelFileList.size()); #ifdef HAS_ELAPSED_TIMER QElapsedTimer extractorTimer; #else QTime extractorTimer; #endif extractorTimer.start(); QTextStream out(stdout); for (int i = 0; i < dataFileList.size(); i++) { const QImage dataImage(dataFileList.at(i).filePath()); const QImage labelImage(labelFileList.at(i).filePath()); QVector<LabelledData> testData; extractor->preprocessTest(dataImage, labelImage); int cnt = 0; if (extractor->extracts()) { unsigned int count = testData.size(); testData.resize(dataImage.width() * dataImage.height()); LabelledData *testDataPtr = testData.data(); #pragma omp parallel for for (int x = 0; x < dataImage.width(); x++) { #pragma omp critical { cnt++; out << cnt * 100 / dataImage.width() << "%" << '\r'; out.flush(); } for (int y = 0; y < dataImage.height(); y++) { const QVector<nnreal> res = extractor->extract(dataImage, x, y); const quint8 c = labelImage.pixelIndex(x, y); LabelledData li(res, c); li.squeeze(); const unsigned int idx = count + x * dataImage.height() + y; testDataPtr[idx] = li; } } out << endl; } const QVector<LabelledData> ppFeatures = extractor->postprocessTest(dataImage, labelImage); testData << ppFeatures; qDebug() << dataFileList.at(i).filePath() << extractorTimer.restart(); const QString testOutFilename(outputName + "_" + extractorName + "_test" + QString::number(i) + ".out"); QFile testOutput(testOutFilename); if (!testOutput.open(QIODevice::WriteOnly)) { qCritical() << "failed to open output file" << testOutFilename; return -3; } { #ifdef HAS_ELAPSED_TIMER QElapsedTimer saveTimer; #else QTime saveTimer; #endif saveTimer.start(); QDataStream outstream(&testOutput); saveFeatures(outstream, extractorName, extractorArgs, extractor->size(), testData); int msecs = saveTimer.elapsed(); qDebug() << "saving took" << msecs << "msecs"; } testOutput.close(); } } delete extractor; return 0; }
int main(int argc, char **argv) { #ifdef CONSOLE_APPLICATION QApplication app(argc, argv, QApplication::Tty); #else QApplication app(argc, argv); #endif #ifdef DO_QWS_DEBUGGING qt_show_painter_debug_output = false; #endif DeviceType type = WidgetType; bool checkers_background = true; QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied; QLocale::setDefault(QLocale::c()); QStringList files; bool interactive = false; bool printdlg = false; bool highres = false; bool show_cmp = false; int width = 800, height = 800; int scaledWidth = width, scaledHeight = height; qreal scalefactor = 1.0; bool verboseMode = false; #ifndef QT_NO_OPENGL QGLFormat f = QGLFormat::defaultFormat(); f.setSampleBuffers(true); f.setStencil(true); f.setAlpha(true); f.setAlphaBufferSize(8); QGLFormat::setDefaultFormat(f); #endif char *arg; for (int i=1; i<argc; ++i) { arg = argv[i]; if (*arg == '-') { QString option = QString(arg + 1).toLower(); if (option == "widget") type = WidgetType; else if (option == "bitmap") type = BitmapType; else if (option == "pixmap") type = PixmapType; else if (option == "image") type = ImageType; else if (option == "imageformat") { Q_ASSERT_X(i + 1 < argc, "main", "-imageformat must be followed by a value"); QString format = QString(argv[++i]).toLower(); imageFormat = QImage::Format_Invalid; static const int formatCount = sizeof(imageFormats) / sizeof(imageFormats[0]); for (int ff = 0; ff < formatCount; ++ff) { if (QLatin1String(imageFormats[ff].name) == format) { imageFormat = imageFormats[ff].format; break; } } if (imageFormat == QImage::Format_Invalid) { printf("Invalid image format. Available formats are:\n"); for (int ff = 0; ff < formatCount; ++ff) printf("\t%s\n", imageFormats[ff].name); return -1; } } else if (option == "imagemono") type = ImageMonoType; else if (option == "imagewidget") type = ImageWidgetType; #ifndef QT_NO_OPENGL else if (option == "opengl") type = OpenGLType; else if (option == "glbuffer") type = OpenGLBufferType; #endif #ifdef USE_CUSTOM_DEVICE else if (option == "customdevice") type = CustomDeviceType; else if (option == "customwidget") type = CustomWidgetType; #endif else if (option == "pdf") type = PdfType; else if (option == "ps") type = PsType; else if (option == "picture") type = PictureType; else if (option == "printer") type = PrinterType; else if (option == "highres") { type = PrinterType; highres = true; } else if (option == "printdialog") { type = PrinterType; printdlg = true; } else if (option == "grab") type = GrabType; else if (option == "i") interactive = true; else if (option == "v") verboseMode = true; else if (option == "commands") { displayCommands(); return 0; } else if (option == "w") { Q_ASSERT_X(i + 1 < argc, "main", "-w must be followed by a value"); width = atoi(argv[++i]); } else if (option == "h") { Q_ASSERT_X(i + 1 < argc, "main", "-h must be followed by a value"); height = atoi(argv[++i]); } else if (option == "scalefactor") { Q_ASSERT_X(i + 1 < argc, "main", "-scalefactor must be followed by a value"); scalefactor = atof(argv[++i]); } else if (option == "cmp") { show_cmp = true; } else if (option == "bg-white") { checkers_background = false; } } else { #if defined (Q_WS_WIN) QString input = QString::fromLocal8Bit(argv[i]); if (input.indexOf('*') >= 0) { QFileInfo info(input); QDir dir = info.dir(); QFileInfoList infos = dir.entryInfoList(QStringList(info.fileName())); for (int ii=0; ii<infos.size(); ++ii) files.append(infos.at(ii).absoluteFilePath()); } else { files.append(input); } #else files.append(QString(argv[i])); #endif } } scaledWidth = width * scalefactor; scaledHeight = height * scalefactor; PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); QWidget *activeWidget = 0; if (interactive) { runInteractive(); if (!files.isEmpty()) interactive_widget->load(files.at(0)); } else if (files.isEmpty()) { printHelp(); return 0; } else { for (int j=0; j<files.size(); ++j) { const QString &fileName = files.at(j); QStringList content; QFile file(fileName); QFileInfo fileinfo(file); if (file.open(QIODevice::ReadOnly)) { QTextStream textFile(&file); QString script = textFile.readAll(); content = script.split("\n", QString::SkipEmptyParts); } else { printf("failed to read file: '%s'\n", qPrintable(fileinfo.absoluteFilePath())); continue; } pcmd.setContents(content); if (show_cmp) { QString pmFile = QString(files.at(j)).replace(".qps", "_qps") + ".png"; qDebug() << pmFile << QFileInfo(pmFile).exists(); QPixmap pixmap(pmFile); if (!pixmap.isNull()) { QLabel *label = createLabel(); label->setWindowTitle("VERIFY: " + pmFile); label->setPixmap(pixmap); label->show(); } } switch (type) { case WidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } case ImageWidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } #ifndef QT_NO_OPENGL case OpenGLBufferType: { QWindow win; win.setSurfaceType(QSurface::OpenGLSurface); win.create(); QOpenGLFramebufferObjectFormat fmt; fmt.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); fmt.setSamples(4); QOpenGLContext ctx; ctx.create(); ctx.makeCurrent(&win); QOpenGLFramebufferObject fbo(width, height, fmt); fbo.bind(); QOpenGLPaintDevice pdev(width, height); QPainter pt(&pdev); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image = fbo.toImage(); QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case OpenGLType: { OnScreenWidget<QGLWidget> *qGLWidget = new OnScreenWidget<QGLWidget>(files.at(j)); qGLWidget->setVerboseMode(verboseMode); qGLWidget->setType(type); qGLWidget->setCheckersBackground(checkers_background); qGLWidget->m_commands = content; qGLWidget->resize(width, height); qGLWidget->show(); activeWidget = qGLWidget; break; } #else case OpenGLType: case OpenGLBufferType: { printf("OpenGL type not supported in this Qt build\n"); break; } #endif #ifdef USE_CUSTOM_DEVICE case CustomDeviceType: { CustomPaintDevice custom(width, height); QPainter pt; pt.begin(&custom); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage *img = custom.image(); if (img) { QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(*img)); label->resize(label->sizeHint()); label->show(); activeWidget = label; img->save("custom_output_pixmap.png", "PNG"); } else { custom.save("custom_output_pixmap.png", "PNG"); } break; } case CustomWidgetType: { OnScreenWidget<CustomWidget> *cWidget = new OnScreenWidget<CustomWidget>; cWidget->setVerboseMode(verboseMode); cWidget->setType(type); cWidget->setCheckersBackground(checkers_background); cWidget->m_filename = files.at(j); cWidget->setWindowTitle(fileinfo.filePath()); cWidget->m_commands = content; cWidget->resize(width, height); cWidget->show(); activeWidget = cWidget; break; } #endif case PixmapType: { QPixmap pixmap(scaledWidth, scaledHeight); pixmap.setDevicePixelRatio(scalefactor); pixmap.fill(Qt::white); QPainter pt(&pixmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); pixmap.save("output_pixmap.png", "PNG"); break; } case BitmapType: { QBitmap bitmap(scaledWidth, scaledHeight); bitmap.setDevicePixelRatio(scalefactor); QPainter pt(&bitmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); bitmap.save("output_bitmap.png", "PNG"); QLabel *label = createLabel(); label->setPixmap(bitmap); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case ImageMonoType: case ImageType: { qDebug() << "Creating image"; QImage image(scaledWidth, scaledHeight, type == ImageMonoType ? QImage::Format_MonoLSB : imageFormat); image.setDevicePixelRatio(scalefactor); image.fill(0); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); image.convertToFormat(QImage::Format_ARGB32).save("output_image.png", "PNG"); image.setDevicePixelRatio(1.0); // reset scale factor: display "large" image. #ifndef CONSOLE_APPLICATION QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; #endif break; } case PictureType: { QPicture pic; QPainter pt(&pic); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(0); pt.begin(&image); pt.drawPicture(0, 0, pic); pt.end(); QLabel *label = createLabel(); label->setWindowTitle(fileinfo.absolutePath()); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case PrinterType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QString file = QString(files.at(j)).replace(".", "_") + ".ps"; QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); if (printdlg) { QPrintDialog printDialog(&p, 0); if (printDialog.exec() != QDialog::Accepted) break; } else { p.setOutputFileName(file); } QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); if (!printdlg) { printf("wrote file: %s\n", qPrintable(file)); } Q_ASSERT(!p.paintingActive()); #endif break; } case PsType: case PdfType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); QFileInfo input(files.at(j)); const QString file = input.baseName() + QLatin1Char('_') + input.suffix() + QStringLiteral(".pdf"); p.setOutputFormat(QPrinter::PdfFormat); p.setOutputFileName(file); p.setPageSize(QPrinter::A4); QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); printf("write file: %s\n", qPrintable(file)); #endif break; } case GrabType: { QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(QColor(Qt::white).rgb()); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image1(width, height, QImage::Format_RGB32); image1.fill(QColor(Qt::white).rgb()); QPainter pt1(&image1); pt1.drawImage(QPointF(0, 0), image); pt1.end(); QString filename = QString(files.at(j)).replace(".qps", "_qps") + ".png"; image1.save(filename, "PNG"); printf("%s grabbed to %s\n", qPrintable(files.at(j)), qPrintable(filename)); break; } default: break; } } } #ifndef CONSOLE_APPLICATION if (activeWidget || interactive) { QObject::connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit())); app.exec(); } delete activeWidget; #endif delete interactive_widget; return 0; }
QList<QString> MainWindow::getLangugagelist() { QProcess *lprocess = new QProcess(this); QSettings settings(QSettings::IniFormat, QSettings::UserScope, Organization, ProjectName); QString ocrCmd; if (settings.contains("OCR/program")) ocrCmd = settings.value("OCR/program").toString(); // TODO(zdenop): check for missing setting or empty string if (!settings.value("OCR/sys_prefix").toBool()) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("TESSDATA_PREFIX", settings.value("OCR/prefix").toString()); lprocess->setProcessEnvironment(env); } QStringList arguments; arguments << "a" << "b" << "-l" << "_ICQ_"; lprocess->start(ocrCmd, arguments); lprocess->waitForFinished(-1); QString s = QString::fromLocal8Bit(lprocess-> readAllStandardError().constData()); QStringList lines; QString line, langFile; lines = s.split("\n"); for (int i = 0; i < lines.size(); ++i) { line = lines.at(i); if (line.contains("_ICQ_")) { // tesseract 3.01 // Error opening data file /usr/local/share/tessdata/_ICQ_.traineddata langFile = line.replace("Error opening data file ", ""); // tesseract 3.00 ;-) // Error openning data file /usr/local/share/tessdata/_ICQ_.traineddata langFile = langFile.replace("Error openning data file ", ""); // tesseract 2.04 ;-) // Unable to load unicharset file /usr/share/tessdata/_ICQ_.unicharset langFile = langFile.replace("Unable to load unicharset file ", ""); } } if (langFile == "") ui->tb_Log->appendHtml("<font color=red><b>" + tr("Unexpexted error: tesseract did not produced expected information!") + "</b></font>"); QFileInfo fi(langFile); QString tessdataPath = fi.absolutePath(); QString extention = fi.suffix(); QDir dir(tessdataPath); if (!dir.exists()) { QMessageBox msgBox; msgBox.setText(tr("Cannot find the tessdata directory '%1'!\n").arg(tessdataPath) + tr("Please check your configuration or tesseract instalation")); msgBox.exec(); } QString filter = "*." + extention; QStringList filters; filters << filter.trimmed(); dir.setNameFilters(filters); QList<QString> languages; QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); languages.append(QString("%1").arg(fileInfo.baseName())); } qSort(languages); return languages; }
void parseDirectory(QString dir) { QDir themeDir(dir); cout << "Searching directory: " << qPrintable(themeDir.path()) << endl; themeDir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); themeDir.setSorting(QDir::DirsFirst); QDomDocument doc; QFileInfoList themeFiles = themeDir.entryInfoList(); QFileInfoList::const_iterator it; for (it = themeFiles.begin(); it != themeFiles.end(); ++it) { if ((*it).isDir()) { parseDirectory((*it).filePath()); continue; } if ((*it).suffix() != "xml") continue; cout << " Found: " << qPrintable((*it).filePath()) << endl; QFile fin((*it).absoluteFilePath()); if (!fin.open(QIODevice::ReadOnly)) { cerr << "Can't open " << qPrintable((*it).absoluteFilePath()) << endl; continue; } QString errorMsg; int errorLine = 0; int errorColumn = 0; if (!doc.setContent(&fin, false, &errorMsg, &errorLine, &errorColumn)) { cerr << "Error parsing: " << qPrintable((*it).absoluteFilePath()) << endl; cerr << "at line: " << errorLine << " column: " << errorColumn << endl; cerr << qPrintable(errorMsg) << endl; fin.close(); continue; } fin.close(); stringCount = 0; QDomElement docElem = doc.documentElement(); QDomNode n = docElem.firstChild(); while (!n.isNull()) { QDomElement e = n.toElement(); if (!e.isNull()) { parseElement(e); } n = n.nextSibling(); } cout << " Contains " << stringCount << " total strings" << endl; } }
void FileManager::copyFolder(QString scrPath, QString dstPath) { QFileInfoList fList; fList.clear(); getFolderFiles(scrPath, fList); if(fList.size() == 0) { //QMessageBox::warning(this, tr("Error"), tr("文件夹是空的:").arg(scrPath), 0, 0); qDebug() << tr("文件夹是空的:").arg(srcfileName); return; } if(srcfileName.compare(destinationPath) == 0) return; bool stopped = false; int curIndex = 0; while( !stopped ) { if( curIndex == fList.size() ) { stopped = true; continue; } QFileInfo curFileInfo = fList.at(curIndex); QString srcFileName = curFileInfo.filePath(); QFile src(srcFileName); QFileInfo srcTmp(srcfileName); QString srcTripname = srcFileName.remove(srcfileName); QString dstFileName = srcTripname.insert(0, dstPath+srcTmp.fileName()); QFile dst(dstFileName); QFileInfo tmp(dstFileName); qDebug() << tmp.path(); QDir d(tmp.path()); if(!d.exists()) d.mkpath(d.absolutePath()); //now copy if(!src.open(QFile::ReadOnly) || !dst.open(QFile::WriteOnly)) continue; fileSize = src.bytesAvailable(); qint64 BUFF_SIZE = 61440; char* buffer = new char[BUFF_SIZE]; //int oldPercent = 0; while( !src.atEnd() ) { dst.write(buffer, src.read(buffer, BUFF_SIZE)); //dst.flush(); } src.close(); dst.close(); delete[] buffer; buffer = NULL; curIndex++; int percent = (curIndex*100) / fList.size();//((curIndex + 1) * 100) / fileSize; //if (oldPercent != percent) { emit verificationProgressSignal(percent); //oldPercent = percent; } } fList.clear(); }
int QgsComposerPictureWidget::addDirectoryToPreview( const QString& path ) { //go through all files of a directory QDir directory( path ); if ( !directory.exists() || !directory.isReadable() ) { return 1; //error } QFileInfoList fileList = directory.entryInfoList( QDir::Files ); QFileInfoList::const_iterator fileIt = fileList.constBegin(); QProgressDialog progress( "Adding Icons...", "Abort", 0, fileList.size() - 1, this ); //cancel button does not seem to work properly with modal dialog //progress.setWindowModality(Qt::WindowModal); int counter = 0; for ( ; fileIt != fileList.constEnd(); ++fileIt ) { progress.setLabelText( tr( "Creating icon for file %1" ).arg( fileIt->fileName() ) ); progress.setValue( counter ); QCoreApplication::processEvents(); if ( progress.wasCanceled() ) { break; } QString filePath = fileIt->absoluteFilePath(); //test if file is svg or pixel format bool fileIsPixel = false; bool fileIsSvg = testSvgFile( filePath ); if ( !fileIsSvg ) { fileIsPixel = testImageFile( filePath ); } //exclude files that are not svg or image if ( !fileIsSvg && !fileIsPixel ) { ++counter; continue; } QListWidgetItem * listItem = new QListWidgetItem( mPreviewListWidget ); listItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled ); if ( fileIsSvg ) { QIcon icon( filePath ); listItem->setIcon( icon ); } else if ( fileIsPixel ) //for pixel formats: create icon from scaled pixmap { QPixmap iconPixmap( filePath ); if ( iconPixmap.isNull() ) { ++counter; continue; //unknown file format or other problem } //set pixmap hardcoded to 30/30, same as icon size for mPreviewListWidget QPixmap scaledPixmap( iconPixmap.scaled( QSize( 30, 30 ), Qt::KeepAspectRatio ) ); QIcon icon( scaledPixmap ); listItem->setIcon( icon ); } else { ++counter; continue; } listItem->setText( "" ); //store the absolute icon file path as user data listItem->setData( Qt::UserRole, fileIt->absoluteFilePath() ); ++counter; } return 0; }
Wad::Wad( QDir dir ) { ok = false; QFileInfoList tmds = dir.entryInfoList( QStringList() << "*.tmd" << "tmd.*", QDir::Files ); if( tmds.isEmpty() ) { Err( "TMD not found" ); return; } tmdData = ReadFile( tmds.at( 0 ).absoluteFilePath() ); if( tmdData.isEmpty() ) return; QFileInfoList tiks = dir.entryInfoList( QStringList() << "*.tik" << "cetk", QDir::Files ); if( tiks.isEmpty() ) { Err( "Ticket not found" ); return; } tikData = ReadFile( tiks.at( 0 ).absoluteFilePath() ); if( tikData.isEmpty() ) return; Tmd t( tmdData ); Ticket ticket( tikData ); //make sure to only add the tmd & ticket without all the cert mumbo jumbo tmdData = t.Data(); tikData = ticket.Data(); t = Tmd( tmdData ); ticket = Ticket( tikData ); quint16 cnt = t.Count(); bool tmdChanged = false; for( quint16 i = 0; i < cnt; i++ ) { QByteArray appD = ReadFile( dir.absoluteFilePath( t.Cid( i ) + ".app" ) ); if( appD.isEmpty() ) { Err( t.Cid( i ) + ".app not found" ); return; } if( (quint32)appD.size() != t.Size( i ) ) { t.SetSize( i, appD.size() ); tmdChanged = true; } QByteArray realHash = GetSha1( appD ); if( t.Hash( i ) != realHash ) { t.SetHash( i, realHash ); tmdChanged = true; } AesSetKey( ticket.DecryptedKey() ); appD = PaddedByteArray( appD, 0x40 ); QByteArray encData = AesEncrypt( t.Index( i ), appD ); partsEnc << encData; } //if something in the tmd changed, fakesign it if( tmdChanged ) { if( !t.FakeSign() ) { Err( "Error signing the wad" ); return; } else { tmdData = t.Data(); } } QFileInfoList certs = dir.entryInfoList( QStringList() << "*.cert", QDir::Files ); if( !certs.isEmpty() ) { certData = ReadFile( certs.at( 0 ).absoluteFilePath() ); } ok = true; }
void ImageImporter::slotImport() { //first save all slotSaveSettings(); //then init the regular expression QRegExp re(m_txtSourceFilename->text(), !m_chkIgnoreCase->isChecked()); //first find all possible files //listdir is used as a stack containing the directories to parse QStringList lstDirs = m_cmbSourceFolder->currentText(); //the list of files found in the directories QFileInfoList lstFiles; lstFiles.setAutoDelete(true); DlgImageImporterStatus* dlgStatus = new DlgImageImporterStatus(this, "StatusDialog"); dlgStatus->enableImageArchive(m_groupArchive->isChecked()); dlgStatus->show(); dlgStatus->appendStatusMessage(i18n("Starting...")); dlgStatus->setCurrentMode( DlgImageImporterStatus::ModeImport, i18n("Scanning for available Images...")); //now go thru all folders and collect all files that match the file regexp... while (!lstDirs.isEmpty()) { QDir d( lstDirs.front() ); lstDirs.pop_front(); dlgStatus->addFolder(); d.setMatchAllDirs(true); const QFileInfoList* list = d.entryInfoList(); if (list) { QFileInfoListIterator it( *list ); QFileInfo* fi; for ( ; ( fi = it.current() ) != 0; ++it ) { if ( fi->fileName() == "." || fi->fileName() == ".." ) { continue; } else if ( fi->isDir() && m_chkSrcIncludeSubfolders->isChecked()) { lstDirs.append(fi->absFilePath()); } else if( fi->isFile() ) { dlgStatus->addFile(); if (re.exactMatch(fi->fileName())) { dlgStatus->addMatch(); //save a copy of all FileInfos lstFiles.append(new QFileInfo(*fi)); } } // we return here and break all importing! if (dlgStatus->wasCanceled()) { return; } } } // we return here and break all importing! if (dlgStatus->wasCanceled()) { return; } } //archive the images, if requested ... if (m_groupArchive->isChecked()) { dlgStatus->setCurrentMode(DlgImageImporterStatus::ModeArchive, i18n("Archiving found images...")); importFiles(&lstFiles, m_txtArchiveBaseFolder->text(), m_txtArchiveSubfolders->text(), m_txtArchiveFilename->text(), m_chkArchiveLowercase->isChecked(), false, dlgStatus); if (dlgStatus->wasCanceled()) { //either canceled by user or error return; } } else { dlgStatus->appendStatusMessage(i18n("Archiving found images... skipped")); } QString msg = i18n("Moving found images..."); if (!m_chkSrcRemoveFilesFromSrc->isChecked()) { msg = i18n("Copying found images..."); } dlgStatus->setCurrentMode(DlgImageImporterStatus::ModeDestination, msg); // ... then copy/ move the images to their destinaion importFiles(&lstFiles, m_cmbDestBasefolder->currentText(), m_txtDestSubfolders->text(), m_txtDestFilename->text(), m_chkDestLowercase->isChecked(), m_chkSrcRemoveFilesFromSrc->isChecked(), dlgStatus); if (dlgStatus->wasCanceled()) { //either canceled by user or error return; } //yes, we are done :) dlgStatus->setCurrentMode( DlgImageImporterStatus::ModeFinished, i18n("Done.")); //now tell, that new images have arrived emit newImagesImported(m_cmbDestBasefolder->currentText()); }
void LDesktop::checkResolution(){ //Compare the current screen resolution with the last one used/saved and adjust config values *only* //NOTE: This is only run the first time this desktop is created (before loading all the interface) - not on each desktop change int oldWidth = settings->value(DPREFIX+"screen/lastWidth",-1).toInt(); int oldHeight = settings->value(DPREFIX+"screen/lastHeight",-1).toInt(); QRect scrn = LSession::handle()->screenGeom(desktopnumber); if(scrn.isNull()){ return; } issyncing = true; settings->setValue(DPREFIX+"screen/lastWidth",scrn.width()); settings->setValue(DPREFIX+"screen/lastHeight",scrn.height()); if(oldWidth<1 || oldHeight<1 || scrn.width()<1 || scrn.height()<1){ //nothing to do - something invalid }else if(scrn.width()==oldWidth && scrn.height()==oldHeight){ //nothing to do - same as before }else{ //Calculate the scale factor between the old/new sizes in each dimension // and forward that on to all the interface elements double xscale = scrn.width()/((double) oldWidth); double yscale = scrn.height()/((double) oldHeight); if(DEBUG){ qDebug() << "Screen Resolution Changed:" << desktopnumber; qDebug() << " - Old:" << QString::number(oldWidth)+"x"+QString::number(oldHeight); qDebug() << " - New:" << QString::number(scrn.width())+"x"+QString::number(scrn.height()); qDebug() << " - Scale Factors:" << xscale << yscale; } //Update any panels in the config file for(int i=0; i<4; i++){ QString PPREFIX = "panel"+QString::number(desktopnumber)+"."+QString::number(i)+"/"; int ht = settings->value(PPREFIX+"height",-1).toInt(); if(ht<1){ continue; } //no panel height defined QString loc = settings->value(PPREFIX+"location","top").toString().toLower(); if(loc=="top" || loc=="bottom"){ settings->setValue(PPREFIX+"height", (int) ht*yscale); //vertical dimension }else{ settings->setValue(PPREFIX+"height", (int) ht*xscale); //horizontal dimension } } //Update any desktop plugins QStringList plugs = settings->value(DPREFIX+"pluginlist").toStringList(); QFileInfoList files = LSession::handle()->DesktopFiles(); for(int i=0; i<files.length(); i++){ plugs << "applauncher::"+files[i].absoluteFilePath()+"---"+DPREFIX; } //QString pspath = QDir::homePath()+"/.lumina/desktop-plugins/%1.conf"; QSettings *DP = LSession::handle()->DesktopPluginSettings(); QStringList keys = DP->allKeys(); for(int i=0; i<plugs.length(); i++){ QStringList filter = keys.filter(plugs[i]); for(int j=0; j<filter.length(); j++){ //Has existing settings - need to adjust it if(filter[j].endsWith("location/height")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } if(filter[j].endsWith("location/width")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*xscale) ); } if(filter[j].endsWith("location/x")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*xscale) ); } if(filter[j].endsWith("location/y")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } if(filter[j].endsWith("IconSize")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } if(filter[j].endsWith("iconsize")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } } } DP->sync(); //make sure it gets saved to disk right away } issyncing = false; }
void InitAacEncTask::initAacEncImpl(const char *const toolName, const char *const fileNames[], const quint32 &toolMinVersion, const quint32 &verDigits, const quint32 &verShift, const char *const verStr, QRegExp ®ExpVer, QRegExp ®ExpSig) { static const size_t MAX_FILES = 8; const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath(); QFileInfoList fileInfo; for(size_t i = 0; fileNames[i] && (fileInfo.count() < MAX_FILES); i++) { fileInfo.append(QFileInfo(QString("%1/%2").arg(appPath, QString::fromLatin1(fileNames[i])))); } for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++) { if(!(iter->exists() && iter->isFile())) { qDebug("%s encoder binaries not found -> Encoding support will be disabled!\n", toolName); return; } if((iter->suffix().compare("exe", Qt::CaseInsensitive) == 0) && (!MUtils::OS::is_executable_file(iter->canonicalFilePath()))) { qDebug("%s executable is invalid -> %s support will be disabled!\n", MUTILS_UTF8(iter->fileName()), toolName); return; } } qDebug("Found %s encoder binary:\n%s\n", toolName, MUTILS_UTF8(fileInfo.first().canonicalFilePath())); //Lock the encoder binaries QScopedPointer<LockedFile> binaries[MAX_FILES]; try { size_t index = 0; for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++) { binaries[index++].reset(new LockedFile(iter->canonicalFilePath())); } } catch(...) { qWarning("Failed to get excluive lock to encoder binary -> %s support will be disabled!", toolName); return; } QProcess process; MUtils::init_process(process, fileInfo.first().absolutePath()); process.start(fileInfo.first().canonicalFilePath(), QStringList() << "-help"); if(!process.waitForStarted()) { qWarning("%s process failed to create!", toolName); qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData()); process.kill(); process.waitForFinished(-1); return; } quint32 toolVersion = 0; bool sigFound = regExpSig.isEmpty() ? true : false; while(process.state() != QProcess::NotRunning) { if(!process.waitForReadyRead()) { if(process.state() == QProcess::Running) { qWarning("%s process time out -> killing!", toolName); process.kill(); process.waitForFinished(-1); return; } } while(process.canReadLine()) { QString line = QString::fromUtf8(process.readLine().constData()).simplified(); if((!sigFound) && regExpSig.lastIndexIn(line) >= 0) { sigFound = true; continue; } if(sigFound && (regExpVer.lastIndexIn(line) >= 0)) { quint32 tmp[8]; if(MUtils::regexp_parse_uint32(regExpVer, tmp, qMin(verDigits, 8U))) { toolVersion = 0; for(quint32 i = 0; i < verDigits; i++) { toolVersion = (toolVersion * verShift) + qBound(0U, tmp[i], (verShift - 1)); } } } } } if(toolVersion <= 0) { qWarning("%s version could not be determined -> Encoding support will be disabled!", toolName); return; } else if(toolVersion < toolMinVersion) { qWarning("%s version is too much outdated (%s) -> Encoding support will be disabled!", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A"))); qWarning("Minimum required %s version currently is: %s\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolMinVersion, "N/A"))); return; } qDebug("Enabled %s encoder %s.\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A"))); size_t index = 0; for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++) { lamexp_tools_register(iter->fileName(), binaries[index++].take(), toolVersion); } }
void MythUIHelper::ClearOldImageCache(void) { QString cachedirname = GetConfDir() + "/themecache/"; d->themecachedir = GetThemeCacheDir(); QDir dir(cachedirname); if (!dir.exists()) dir.mkdir(cachedirname); QString themecachedir = d->themecachedir; d->themecachedir += '/'; dir.setPath(themecachedir); if (!dir.exists()) dir.mkdir(themecachedir); dir.setPath(cachedirname); dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); QFileInfoList list = dir.entryInfoList(); QFileInfoList::const_iterator it = list.begin(); QMap<QDateTime, QString> dirtimes; const QFileInfo *fi; while (it != list.end()) { fi = &(*it++); if (fi->isDir() && !fi->isSymLink()) { if (fi->absoluteFilePath() == themecachedir) continue; dirtimes[fi->lastModified()] = fi->absoluteFilePath(); } } // Cache two themes/resolutions to allow sampling other themes without // incurring a penalty. Especially for those writing new themes or testing // changes of an existing theme. The space used is neglible when compared // against the average video while ((size_t)dirtimes.size() >= 2) { LOG(VB_GUI | VB_FILE, LOG_INFO, LOC + QString("Removing cache dir: %1") .arg(dirtimes.begin().value())); RemoveCacheDir(dirtimes.begin().value()); dirtimes.erase(dirtimes.begin()); } QMap<QDateTime, QString>::const_iterator dit = dirtimes.begin(); for (; dit != dirtimes.end(); ++dit) { LOG(VB_GUI | VB_FILE, LOG_INFO, LOC + QString("Keeping cache dir: %1").arg(*dit)); } }
bool QAudioManager::testLibrary(QAbstractCoder *coder) { setError(QCoder::NoError); QStringList nameFilters; QDir::Filters filters = QDir::Files | QDir::NoDotAndDotDot; QDir dir; QFileInfoList possibles; QStringList fileNames = coder->fileNames(); QStringList fileExtensions = coder->fileExtensions(); for(int j = 0; j < mSearchPaths.size(); ++j) { QString path = mSearchPaths[j]; for(int k = 0; k < fileNames.size(); ++k) { QString fileName = fileNames[k]; for(int h = 0; h < fileNames.size(); ++h) { QString directoryName = fileNames[h]; for(int i = 0; i < fileExtensions.size(); ++i) { if( coder->load(path + fileName + fileExtensions[i]) == QCoder::NoError || coder->load(path + "lib" + fileName + fileExtensions[i]) == QCoder::NoError || coder->load(path + directoryName + QDir::separator() + fileName + fileExtensions[i]) == QCoder::NoError || coder->load(path + directoryName + QDir::separator() + "lib" + fileName + fileExtensions[i]) == QCoder::NoError || coder->load(path + "lib" + directoryName + QDir::separator() + fileName + fileExtensions[i]) == QCoder::NoError || coder->load(path + "lib" + directoryName + QDir::separator() + "lib" + fileName + fileExtensions[i]) == QCoder::NoError) { coder->unload(); add(QAudioManager::Available, coder); return true; } //Check for libraries that end in version number. Eg: libflac.so.8 nameFilters.clear(); possibles.clear(); nameFilters << fileName + fileExtensions[i] + "*"; nameFilters << "lib" + fileName + fileExtensions[i] + "*"; dir.setPath(path); possibles.append(dir.entryInfoList(nameFilters, filters, QDir::Name)); dir.setPath(path + directoryName); possibles.append(dir.entryInfoList(nameFilters, filters, QDir::Name)); dir.setPath(path + "lib" + directoryName); possibles.append(dir.entryInfoList(nameFilters, filters, QDir::Name)); for(int t = 0; t < possibles.size(); ++t) { if(coder->load(possibles[t].absoluteFilePath()) == QCoder::NoError) { coder->unload(); add(QAudioManager::Available, coder); return true; } } } } } } return false; }
QStringList StorageGroup::GetFileInfoList(QString Path) { QStringList files; QString relPath; bool badPath = true; if (Path.isEmpty() || Path == "/") { for (QStringList::Iterator it = m_dirlist.begin(); it != m_dirlist.end(); ++it) files << QString("sgdir::%1").arg(*it); return files; } for (QStringList::Iterator it = m_dirlist.begin(); it != m_dirlist.end(); ++it) { if (Path.startsWith(*it)) { relPath = Path; relPath.replace(*it,""); if (relPath.startsWith("/")) relPath.replace(0,1,""); badPath = false; } } LOG(VB_FILE, LOG_INFO, QString("GetFileInfoList: Reading '%1'").arg(Path)); if (badPath) return files; QDir d(Path); if (!d.exists()) return files; QFileInfoList list = d.entryInfoList(); if (!list.size()) return files; for (QFileInfoList::iterator p = list.begin(); p != list.end(); ++p) { if (p->fileName() == "." || p->fileName() == ".." || p->fileName() == "Thumbs.db") { continue; } QString tmp; if (p->isDir()) tmp = QString("dir::%1::0").arg(p->fileName()); else tmp = QString("file::%1::%2::%3%4").arg(p->fileName()).arg(p->size()) .arg(relPath).arg(p->fileName()); LOG(VB_FILE, LOG_DEBUG, QString("GetFileInfoList: (%1)").arg(tmp)); files.append(tmp); } return files; }
// solaris, not 2.6 void qt_parseEtcLpPrinters(QList<QPrinterDescription> *printers) { QDir lp(QLatin1String("/etc/lp/printers")); QFileInfoList dirs = lp.entryInfoList(); if (dirs.isEmpty()) return; QString tmp; for (int i = 0; i < dirs.size(); ++i) { QFileInfo printer = dirs.at(i); if (printer.isDir()) { tmp.sprintf("/etc/lp/printers/%s/configuration", printer.fileName().toAscii().data()); QFile configuration(tmp); char *line = new char[1025]; QString remote(QLatin1String("Remote:")); QString contentType(QLatin1String("Content types:")); QString printerHost; bool canPrintPostscript = false; if (configuration.open(QIODevice::ReadOnly)) { while (!configuration.atEnd() && configuration.readLine(line, 1024) > 0) { if (QString::fromLatin1(line).startsWith(remote)) { const char *p = line; while (*p != ':') p++; p++; while (isspace((uchar) *p)) p++; printerHost = QString::fromLocal8Bit(p); printerHost = printerHost.simplified(); } else if (QString::fromLatin1(line).startsWith(contentType)) { char *p = line; while (*p != ':') p++; p++; char *e; while (*p) { while (isspace((uchar) *p)) p++; if (*p) { char s; e = p; while (isalnum((uchar) *e)) e++; s = *e; *e = '\0'; if (!qstrcmp(p, "postscript") || !qstrcmp(p, "any")) canPrintPostscript = true; *e = s; if (s == ',') e++; p = e; } } } } if (canPrintPostscript) qt_perhapsAddPrinter(printers, printer.fileName(), printerHost, QLatin1String("")); } delete[] line; } } }
LocalProcess::FileSet LocalProcess::dirFiles(const QString &dir) const { QFileInfoList fil; QDir subdirs(dir, "mergedjob-*", QDir::Name, QDir::Dirs); QFileInfoList mergedjobdirs = subdirs.entryInfoList(); for (QFileInfoList::const_iterator itr = mergedjobdirs.begin(); itr != mergedjobdirs.end(); ++itr) { QDir mergeddir(itr->absoluteFilePath(), "", QDir::Name, QDir::Files); fil.append(mergeddir.entryInfoList()); } QDir d(dir, "", QDir::Name, QDir::Files); fil.append(d.entryInfoList()); QFileInfoList filtered; // Filter out all files that are part of the set of input files. Everything remaining should be an outputfile for (QFileInfoList::const_iterator itr = fil.begin(); itr != fil.end(); ++itr) { bool partofinput = false; for (std::vector<std::pair<openstudio::path, openstudio::path> >::const_iterator itr2 = m_requiredFiles.begin(); itr2 != m_requiredFiles.end(); ++itr2) { QString fileName = itr->fileName(); QString fileName2 = toQString(itr2->second.filename()); if (fileName == fileName2) { partofinput = true; break; } } if (!partofinput) { filtered.push_back(*itr); } } FileSet out; typedef FileInfo (*filetransform)(QFileInfo); try{ std::transform(filtered.begin(), filtered.end(), std::inserter(out, out.end()), static_cast<filetransform>(&RunManager_Util::dirFile)); } catch(openstudio::Exception& e) { LOG_AND_THROW("Exception caught " << e.what()); } return out; }
/** Creates the \c ls command result * * It creates it in the packetData string. * */ void RainbruRPG::Network::Ftp::FtpTransfer::lsResult(){ LOGI("LIST command result :"); packetData=""; unsigned int childs=1; QDir dir(currentDirectory ); dir.setFilter(QDir::Dirs| QDir::Files| QDir::NoSymLinks); dir.setSorting(QDir::Name); QFileInfoList list = dir.entryInfoList(); LOGCATS("Sending "); LOGCATI(list.size()); LOGCATS(" files."); LOGCAT(); for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); // ====== User permissions // Diretory ? if (fileInfo.isDir()){ packetData+="d"; QDir dir2(fileInfo.absoluteFilePath()); childs=dir2.count(); } else{ packetData+="-"; childs=1; } packetData+=filePermissions(fileInfo.isReadable(),fileInfo.isWritable(), fileInfo.isExecutable()); packetData+=filePermissions(fileInfo.permission(QFile::ReadGroup), fileInfo.permission(QFile::WriteGroup), fileInfo.permission(QFile::ExeGroup)); packetData+=filePermissions(fileInfo.permission(QFile::ReadOther), fileInfo.permission(QFile::WriteOther), fileInfo.permission(QFile::ExeOther)); // Child number QString sChild; sChild.setNum(childs); sChild=sChild.rightJustified(5); packetData+=sChild; // Owner and group names packetData+=' '; QString sOwner=fileInfo.owner(); sOwner=sOwner.leftJustified(9); packetData+=sOwner; QString sGroup=fileInfo.group(); sGroup=sGroup.leftJustified(9); packetData+=sGroup; // File size qint64 size=fileInfo.size(); QString sSize=fileSizeToString(size); sSize=sSize.rightJustified(8); packetData+=sSize; // Last modified time packetData+=" "; QDateTime dt=fileInfo.lastModified(); packetData+=dt.toString("yyyy-MM-dd hh:mm"); // File name and EOL packetData+=" "; packetData+=fileInfo.fileName(); packetData+="\n"; } LOGI("PacketData done. LIST result can be sent"); int i= packetData.size(); LOGCATS("PacketData lenght :"); LOGCATI(i); LOGCAT(); }
bool chksysTimer::verificarModulos() { QDir dir(this->cacicFolder + "/temp"); dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Executable); dir.setSorting(QDir::Size | QDir::Reversed); bool serviceUpdate; QFileInfoList list = dir.entryInfoList(); for (int i = 0; i<list.size(); i++){ serviceUpdate = false; //Se o módulo for install-cacic, deverá ficar na pasta "/bin" QFile novoModulo(list.at(i).filePath()); #ifdef Q_OS_WIN if (QFile::exists(this->cacicFolder + "/" + (list.at(i).fileName().contains("install-cacic") ? "bin/" + list.at(i).fileName() : list.at(i).fileName()))){ #else if (QFile::exists(this->cacicFolder + "/" + list.at(i).fileName())){ #endif if (list.at(i).fileName().contains("cacic-service")){ #ifdef Q_OS_WIN ServiceController *service = new ServiceController(QString(CACIC_SERVICE_NAME).toStdWString()); if (service->isRunning()) { log->escrever(LogCacic::InfoLevel, "Serviço rodando.. parando servico"); if (!service->stop()) { std::string info = "Falha ao parar serviço. Info: "; info+= service->getLastError(); log->escrever(LogCacic::ErrorLevel, info.c_str()); } } delete service; service = NULL; #else ConsoleObject console; if (CCacic::findProc("cacic-service")) console("killall -9 \"cacic-service\""); #endif } #ifdef Q_OS_WIN QFile::remove(this->cacicFolder + "/" + (list.at(i).fileName().contains("install-cacic") ? "bin/" + list.at(i).fileName() : list.at(i).fileName())); #else QFile::remove(this->cacicFolder + "/" + list.at(i).fileName()); #endif //Garante a exclusão. às vezes o SO demora a reconhecer, dunno why. QThread::sleep(1); } #ifdef Q_OS_WIN if (!QFile::exists(this->cacicFolder + "/" + (list.at(i).fileName().contains("install-cacic") ? "bin/" + list.at(i).fileName() : list.at(i).fileName()))){ novoModulo.copy(this->cacicFolder + "/" + (list.at(i).fileName().contains("install-cacic") ? "bin/" + list.at(i).fileName() : list.at(i).fileName())); #else if (!QFile::exists(this->cacicFolder + "/" + list.at(i).fileName())){ novoModulo.copy(this->cacicFolder + "/" + list.at(i).fileName()); #endif if (!novoModulo.remove()) log->escrever(LogCacic::ErrorLevel, "Falha ao excluir "+list.at(i).fileName()+" da pasta temporária."); else { log->escrever(LogCacic::InfoLevel, "Módulo \"" + list.at(i).filePath() + "\" atualizado."); if (list.at(i).fileName().contains("cacic-service") && serviceUpdate){ #ifdef Q_OS_WIN ServiceController *service = new ServiceController(QString("cacicdaemon").toStdWString()); if (!service->isRunning()) service->start(); #else ConsoleObject console; if (!CCacic::findProc("cacic-service")) console("/etc/init.d/cacic3 start"); #endif } } } else { log->escrever(LogCacic::ErrorLevel, "Falha ao excluir módulo antigo"+list.at(i).fileName()+" da pasta temporária."); } novoModulo.close(); } list.clear(); return true; }
bool GalleryUtil::LoadDirectory(ThumbList& itemList, const QString& dir, int sortorder, bool recurse, ThumbHash *itemHash, ThumbGenerator* thumbGen) { QString blah = dir; QDir d(blah); QString currDir = d.absolutePath(); bool isGallery; QFileInfoList gList = d.entryInfoList(QStringList("serial*.dat"), QDir::Files); isGallery = (gList.count() != 0); // Create .thumbcache dir if neccesary if (thumbGen) thumbGen->getThumbcacheDir(currDir); QFileInfoList list = d.entryInfoList(GetMediaFilter(), QDir::Files | QDir::AllDirs, (QDir::SortFlag)sortorder); if (list.isEmpty()) return false; QFileInfoList::const_iterator it = list.begin(); const QFileInfo *fi; if (thumbGen) { thumbGen->cancel(); thumbGen->setDirectory(currDir, isGallery); } while (it != list.end()) { fi = &(*it); ++it; if (fi->fileName() == "." || fi->fileName() == "..") continue; // remove these already-resized pictures. if (isGallery && ( (fi->fileName().indexOf(".thumb.") > 0) || (fi->fileName().indexOf(".sized.") > 0) || (fi->fileName().indexOf(".highlight.") > 0))) continue; if (fi->isDir() && recurse) { GalleryUtil::LoadDirectory( itemList, QDir::cleanPath(fi->absoluteFilePath()), sortorder, true, itemHash, thumbGen); } else { ThumbItem *item = new ThumbItem( fi->fileName(), QDir::cleanPath(fi->absoluteFilePath()), fi->isDir()); itemList.append(item); if (itemHash) itemHash->insert(item->GetName(), item); if (thumbGen) thumbGen->addFile(item->GetName()); } } return isGallery; }
bool PackageJobThread::installPackage(const QString &src, const QString &dest, OperationType operation) { QDir root(dest); if (!root.exists()) { QDir().mkpath(dest); if (!root.exists()) { d->errorMessage = i18n("Could not create package root directory: %1", dest); d->errorCode = Package::JobError::RootCreationError; //qWarning() << "Could not create package root directory: " << dest; return false; } } QFileInfo fileInfo(src); if (!fileInfo.exists()) { d->errorMessage = i18n("No such file: %1", src); d->errorCode = Package::JobError::PackageFileNotFoundError; return false; } QString path; QTemporaryDir tempdir; bool archivedPackage = false; if (fileInfo.isDir()) { // we have a directory, so let's just install what is in there path = src; // make sure we end in a slash! if (!path.endsWith('/')) { path.append('/'); } } else { KArchive *archive = 0; QMimeDatabase db; QMimeType mimetype = db.mimeTypeForFile(src); if (mimetype.inherits(QStringLiteral("application/zip"))) { archive = new KZip(src); } else if (mimetype.inherits(QStringLiteral("application/x-compressed-tar")) || mimetype.inherits(QStringLiteral("application/x-tar")) || mimetype.inherits(QStringLiteral("application/x-bzip-compressed-tar")) || mimetype.inherits(QStringLiteral("application/x-xz")) || mimetype.inherits(QStringLiteral("application/x-lzma"))) { archive = new KTar(src); } else { //qWarning() << "Could not open package file, unsupported archive format:" << src << mimetype.name(); d->errorMessage = i18n("Could not open package file, unsupported archive format: %1 %2", src, mimetype.name()); d->errorCode = Package::JobError::UnsupportedArchiveFormatError; return false; } if (!archive->open(QIODevice::ReadOnly)) { //qWarning() << "Could not open package file:" << src; delete archive; d->errorMessage = i18n("Could not open package file: %1", src); d->errorCode = Package::JobError::PackageOpenError; return false; } archivedPackage = true; path = tempdir.path() + '/'; d->installPath = path; const KArchiveDirectory *source = archive->directory(); source->copyTo(path); QStringList entries = source->entries(); if (entries.count() == 1) { const KArchiveEntry *entry = source->entry(entries[0]); if (entry->isDirectory()) { path.append(entry->name()).append("/"); } } delete archive; } QDir packageDir(path); QFileInfoList entries = packageDir.entryInfoList(*metaDataFiles); KPluginMetaData meta; if (!entries.isEmpty()) { const QString metadataFilePath = entries.first().filePath(); if (metadataFilePath.endsWith(QLatin1String(".desktop"))) meta = KPluginMetaData(metadataFilePath); else { QFile f(metadataFilePath); if(!f.open(QIODevice::ReadOnly)){ qWarning() << "Couldn't open metadata file" << src << path; d->errorMessage = i18n("Could not open metadata file: %1", src); d->errorCode = Package::JobError::MetadataFileMissingError; return false; } QJsonObject metadataObject = QJsonDocument::fromJson(f.readAll()).object(); meta = KPluginMetaData(metadataObject, QString(), metadataFilePath); } } if (!meta.isValid()) { qDebug() << "No metadata file in package" << src << path; d->errorMessage = i18n("No metadata file in package: %1", src); d->errorCode = Package::JobError::MetadataFileMissingError; return false; } QString pluginName = meta.pluginId(); qDebug() << "pluginname: " << meta.pluginId(); if (pluginName.isEmpty()) { //qWarning() << "Package plugin name not specified"; d->errorMessage = i18n("Package plugin name not specified: %1", src); d->errorCode = Package::JobError::PluginNameMissingError; return false; } // Ensure that package names are safe so package uninstall can't inject // bad characters into the paths used for removal. QRegExp validatePluginName("^[\\w-\\.]+$"); // Only allow letters, numbers, underscore and period. if (!validatePluginName.exactMatch(pluginName)) { //qDebug() << "Package plugin name " << pluginName << "contains invalid characters"; d->errorMessage = i18n("Package plugin name %1 contains invalid characters", pluginName); d->errorCode = Package::JobError::PluginNameInvalidError; return false; } QString targetName = dest; if (targetName[targetName.size() - 1] != '/') { targetName.append('/'); } targetName.append(pluginName); if (QFile::exists(targetName)) { if (operation == Update) { KPluginMetaData oldMeta(targetName + QLatin1String("/metadata.desktop")); if (oldMeta.serviceTypes() != meta.serviceTypes()) { d->errorMessage = i18n("The new package has a different type from the old version already installed.", meta.version(), meta.pluginId(), oldMeta.version()); d->errorCode = Package::JobError::UpdatePackageTypeMismatchError; } else if (isVersionNewer(oldMeta.version(), meta.version())) { const bool ok = uninstallPackage(targetName); if (!ok) { d->errorMessage = i18n("Impossible to remove the old installation of %1 located at %2. error: %3", pluginName, targetName, d->errorMessage); d->errorCode = Package::JobError::OldVersionRemovalError; } } else { d->errorMessage = i18n("Not installing version %1 of %2. Version %3 already installed.", meta.version(), meta.pluginId(), oldMeta.version()); d->errorCode = Package::JobError::NewerVersionAlreadyInstalledError; } } else { d->errorMessage = i18n("%1 already exists", targetName); d->errorCode = Package::JobError::PackageAlreadyInstalledError; } if (d->errorCode != KJob::NoError) { d->installPath = targetName; return false; } } //install dependencies const QStringList dependencies = KPluginMetaData::readStringList(meta.rawData(), QStringLiteral("X-KPackage-Dependencies")); for(const QString &dep : dependencies) { QUrl depUrl(dep); if (!installDependency(depUrl)) { d->errorMessage = i18n("Could not install dependency: %1", dep); d->errorCode = Package::JobError::PackageCopyError; return false; } } if (archivedPackage) { // it's in a temp dir, so just move it over. const bool ok = copyFolder(path, targetName); removeFolder(path); if (!ok) { //qWarning() << "Could not move package to destination:" << targetName; d->errorMessage = i18n("Could not move package to destination: %1", targetName); d->errorCode = Package::JobError::PackageMoveError; return false; } } else { // it's a directory containing the stuff, so copy the contents rather // than move them const bool ok = copyFolder(path, targetName); if (!ok) { //qWarning() << "Could not copy package to destination:" << targetName; d->errorMessage = i18n("Could not copy package to destination: %1", targetName); d->errorCode = Package::JobError::PackageCopyError; return false; } } if (archivedPackage) { // no need to remove the temp dir (which has been successfully moved if it's an archive) tempdir.setAutoRemove(false); } indexDirectory(dest, QStringLiteral("kpluginindex.json")); d->installPath = targetName; //qWarning() << "Not updating kbuildsycoca4, since that will go away. Do it yourself for now if needed."; return true; }
void MythUIFileBrowser::updateLocalFileList() { QDir d; d.setPath(m_subDirectory); d.setNameFilters(m_nameFilter); d.setFilter(m_typeFilter); d.setSorting(QDir::Name | QDir::DirsFirst | QDir::IgnoreCase); if (!d.exists()) { LOG(VB_GENERAL, LOG_ERR, "MythUIFileBrowser: current directory does not exist!"); m_locationEdit->SetText("/"); m_subDirectory = "/"; d.setPath("/"); } QFileInfoList list = d.entryInfoList(); bool showBackButton = false; if (list.isEmpty()) { MythUIButtonListItem *item = new MythUIButtonListItem(m_fileList, tr("Parent Directory")); item->DisplayState("upfolder", "nodetype"); } else { QFileInfoList::const_iterator it = list.begin(); const QFileInfo *fi; while (it != list.end()) { fi = &(*it); MFileInfo finfo(fi->filePath()); if (finfo.fileName() == ".") { ++it; continue; } QString displayName = finfo.fileName(); QString type; if (displayName == "..") { if (m_subDirectory.endsWith("/")) { ++it; continue; } displayName = tr("Parent"); type = "upfolder"; showBackButton = true; } else if (finfo.isDir()) { type = "folder"; } else if (finfo.isExecutable()) { type = "executable"; } else if (finfo.isFile()) { type = "file"; } MythUIButtonListItem *item = new MythUIButtonListItem(m_fileList, displayName, qVariantFromValue(finfo)); if (IsImage(finfo.suffix())) { item->SetImage(finfo.absoluteFilePath()); type = "image"; } item->SetText(FormatSize(finfo.size()), "filesize"); item->SetText(finfo.absoluteFilePath(), "fullpath"); item->DisplayState(type, "nodetype"); ++it; } } if (m_backButton) m_backButton->SetEnabled(showBackButton); m_locationEdit->SetText(m_subDirectory); }
LocalListingNetworkReply::LocalListingNetworkReply(QObject *parent, const QNetworkRequest &request) : QNetworkReply(parent), m_offset(0) { setRequest(request); open(QIODevice::ReadOnly | QIODevice::Unbuffered); QFile file(QLatin1String(":/files/listing.html")); file.open(QIODevice::ReadOnly | QIODevice::Text); QTextStream stream(&file); stream.setCodec("UTF-8"); QDir directory(request.url().toLocalFile()); const QFileInfoList entries = directory.entryInfoList((QDir::AllEntries | QDir::Hidden), (QDir::Name | QDir::DirsFirst)); const QRegularExpression expression(QLatin1String("^/+")); QStringList navigation; do { navigation.prepend(QStringLiteral("<a href=\"file:///%1\">%2</a>%3").arg(directory.canonicalPath().remove(expression)).arg(directory.dirName().isEmpty() ? QString('/') : directory.dirName()).arg(directory.dirName().isEmpty() ? QString() : QString('/'))); } while (directory.cdUp()); QHash<QString, QString> variables; variables[QLatin1String("title")] = QFileInfo(request.url().toLocalFile()).canonicalFilePath(); variables[QLatin1String("description")] = tr("Directory Contents"); variables[QLatin1String("dir")] = (QGuiApplication::isLeftToRight() ? QLatin1String("ltr") : QLatin1String("rtl")); variables[QLatin1String("navigation")] = navigation.join(QString()); variables[QLatin1String("header_name")] = tr("Name"); variables[QLatin1String("header_type")] = tr("Type"); variables[QLatin1String("header_size")] = tr("Size"); variables[QLatin1String("header_date")] = tr("Date"); variables[QLatin1String("body")] = QString(); const QMimeDatabase database; for (int i = 0; i < entries.count(); ++i) { const QMimeType mimeType = database.mimeTypeForFile(entries.at(i).canonicalFilePath()); QByteArray byteArray; QBuffer buffer(&byteArray); QIcon::fromTheme(mimeType.iconName(), Utils::getIcon(entries.at(i).isDir() ? QLatin1String("inode-directory") : QLatin1String("unknown"))).pixmap(16, 16).save(&buffer, "PNG"); variables[QLatin1String("body")].append(QStringLiteral("<tr>\n<td><a href=\"file:///%1\"><img src=\"data:image/png;base64,%2\" alt=\"\"> %3</a></td>\n<td>%4</td>\n<td>%5</td>\n<td>%6</td>\n</tr>\n").arg(entries.at(i).filePath().remove(expression)).arg(QString(byteArray.toBase64())).arg(entries.at(i).fileName()).arg(mimeType.comment()).arg(entries.at(i).isDir() ? QString() : Utils::formatUnit(entries.at(i).size(), false, 2)).arg(QLocale().toString(entries.at(i).lastModified()))); } QString html = stream.readAll(); QHash<QString, QString>::iterator iterator; for (iterator = variables.begin(); iterator != variables.end(); ++iterator) { html.replace(QStringLiteral("{%1}").arg(iterator.key()), iterator.value()); } m_content = html.toUtf8(); setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html; charset=UTF-8")); setHeader(QNetworkRequest::ContentLengthHeader, QVariant(m_content.size())); QTimer::singleShot(0, this, SIGNAL(readyRead())); QTimer::singleShot(0, this, SIGNAL(finished())); }
// Recursivly add all book files to the list void BookList::addAllBooks (QString dirpath, bool isUserBooks, int parentindex) { QDir cdir(absPath(dirpath)); //Get all .folder or .obk files in the directory QStringList filter; filter << "*.folder" << "*.obk" << "*.pdf" << "*.link" << "*.html" << "*.htm"; QFileInfoList list = cdir.entryInfoList(filter, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDir::Name); //TODO: Add pdf, html, etc' for (int i=0; i<list.size(); i++) { Book::Filetype ft; if (list[i].fileName().endsWith(".folder", Qt::CaseInsensitive)) ft = Book::Dir; else if (list[i].fileName().endsWith(".obk", Qt::CaseInsensitive)) ft = Book::Normal; else if (list[i].fileName().endsWith(".html", Qt::CaseInsensitive) || list[i].fileName().endsWith(".htm", Qt::CaseInsensitive)) ft = Book::Html; else if (list[i].fileName().endsWith(".pdf", Qt::CaseInsensitive)) ft = Book::Pdf; else if (list[i].fileName().endsWith(".link", Qt::CaseInsensitive)) ft = Book::Link; else ft = Book::Unkown; if ( ft != Book::Unkown ) { if ( list[i].fileName().indexOf("Pics") != -1 ) continue; QString Name = list[i].fileName(); if (!isUserBooks) Name.replace(QRegExp("^[0-9 ]*"), "").replace("_", " ").replace(".obk", ""); //Create BookListItem Book *b = new Book(parentindex != -1 ? (*this)[parentindex] : NULL, list[i].absoluteFilePath(), list[i].absoluteFilePath(), Name, ft, isUserBooks); //Tell the parent it has a new child if (b->getParent() != NULL) b->getParent()->add_child(b); //Add this book to the list push_back(b); //Add folder entry, and all files in that folder if (ft == Book::Dir) { //Do the whole thing again for any dir, sending it's index in the list as the // Parents index of all it's children addAllBooks(list[i].absoluteFilePath().replace(".folder", ""), isUserBooks, this->size() - 1); //Add confs for this directory QList <QString> t; t.clear(); if (ReadFileToList(list[i].absoluteFilePath(), t , "UTF-8")) AddBookConfs(b, t); } //Add orayta-book else if ( ft == Book::Normal ) { //Add confs for this book QList <QString> t; t.clear(); if (ReadZipComment(list[i].absoluteFilePath(), t, "UTF-8")) AddBookConfs(b, t); } else if ( ft == Book::Link ) { //Add confs for this book AddBookConfs(b, readfile(b->getPath(), "UTF-8").split("\n")); } else if ( ft == Book::Html ) { //Add confs for this book AddBookConfs(b, readfile(b->getPath().replace(QRegExp("\\.\\w{3,4}$"),".conf"), "UTF-8").split("\n")); } } } /* for (int i=0; i<list.size(); i++) { Book::Filetype ft; // set the file type if (list[i].isDir()) ft = Book::Dir; else if (list[i].fileName().endsWith(".txt", Qt::CaseInsensitive)) ft = Book::Normal; else if (list[i].fileName().endsWith(".html", Qt::CaseInsensitive) || list[i].fileName().endsWith(".htm", Qt::CaseInsensitive)) ft = Book::Html; else if (list[i].fileName().endsWith(".pdf", Qt::CaseInsensitive)) ft = Book::Pdf; else if (list[i].fileName().endsWith(".link", Qt::CaseInsensitive)) ft = Book::Link; else ft = Book::Unkown; if ( ft != Book::Unkown ) { if ( list[i].fileName().indexOf("Pics") != -1 ) continue; QString Name = list[i].fileName(); if (!isUserBooks) Name.replace(QRegExp("^[0-9 ]*"), "").replace("_", " "); //Create BookListItem Book *b = new Book(parentindex != -1 ? (*this)[parentindex] : NULL, list[i].absoluteFilePath(), list[i].absoluteFilePath(), Name, ft, isUserBooks); //Tell the parent it has a new child if (b->getParent() != NULL) b->getParent()->add_child(b); //Add this book to the list push_back(b); if ( ft == Book::Normal ) { //Add confs for this book AddBookConfs(b, b->getPath().replace(".txt",".conf")); } if ( ft == Book::Html ) { //Add confs for this book AddBookConfs(b, b->getPath().replace(QRegExp("\\.\\w{3,4}$"),".conf")); } if ( ft == Book::Link ) { //Add confs for this book AddBookConfs(b, b->getPath()); } if ( isUserBooks ) { //b->setIsInSearch(false); } else { // call this after AddBookConfs b->loadFont(); } if (ft == Book::Dir) { //Do the whole thing again for any dir, sending it's index in the list as the // Parents index of all it's children addAllBooks(list[i].absoluteFilePath(), isUserBooks, this->size() - 1); //Add confs for this directory AddBookConfs(b, b->getPath().append(".conf")); } } } */ }
void MainWindow::transform(const QString& curr_folder,const QString& tar_folder) { QDir dir(curr_folder); if (!dir.exists()) return; dir.setFilter(QDir::Dirs|QDir::Files);// 除了目录或文件,其他的过滤 dir.setSorting(QDir::DirsFirst);// 优先显示目录 QFileInfoList list = dir.entryInfoList();// 获取文件信息列表 int i = 0; bool bIsDir; do{ QFileInfo fileInfo = list.at(i); if(fileInfo.fileName()=="."||fileInfo.fileName()=="..") { i++; continue; } bIsDir = fileInfo.isDir(); if (!bIsDir) { // copy 无关文件 if(!selected_set.contains(fileInfo.suffix())) { if(ui->copyBox->isChecked()) QFile::copy(fileInfo.filePath(),tar_folder + "/" + fileInfo.fileName()); } // 改为指定编码 else { QFile inFile(fileInfo.filePath()); QFile outFile(tar_folder + "/" + fileInfo.fileName()); if (!inFile.open(QIODevice::ReadOnly)) { qDebug() << "Cannot open file for writing: "; qDebug() << fileInfo.filePath(); return; } if (!outFile.open(QIODevice::WriteOnly)) { qDebug() << "Cannot open file for writing: "; qDebug() << tar_folder + "/" + fileInfo.fileName(); return; } QTextStream in(&inFile); QTextStream out(&outFile); in.setCodec("GBK"); out.setCodec("UTF-8"); QString s = in.readAll(); qDebug() << s; out << s; inFile.close(); outFile.close(); } } else { QString tar = tar_folder + "/" + fileInfo.fileName(); QDir dir(tar); if(!dir.exists()) if(!dir.mkdir(tar)) qDebug() << "mkdir " << tar << " failed"; transform(fileInfo.filePath(),tar); } i++; }while(i<list.size()); ui->pushButton_3->setEnabled(true); }