/********** *返回值:0成功 *1原包名不存在 *2创建包出错 *3目的包名已经存在 *4替换包名过程出错 *5替换app包名出错 ***********/ int PathManager::ReplaceAppPakInSrc(QString &path, QString &oldName, QString &newName) { QVector<QString> dirNames; QDir dir(path); QFileInfoList filst; QFileInfoList::iterator curFi; //初始化 dirNames.clear(); if (dir.exists()){ dirNames << path; } else{ return 0; } bool isTopDir = true; //遍历各级文件夹,并将这些文件夹中的文件删除 for (int i = 0; i<dirNames.size(); ++i) { dir.setPath(dirNames[i]); filst = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::Readable | QDir::Writable | QDir::Hidden | QDir::NoDotAndDotDot , QDir::Name); if (isTopDir){ isTopDir = false; for (int i = 0; i < filst.size(); i++) { if (filst[i].fileName() == "assets" || filst[i].fileName() == "bin" || filst[i].fileName() == "libs"){ filst.removeAt(i); i--; } } } if (filst.size()>0){ curFi = filst.begin(); while (curFi != filst.end()) { //遇到文件夹,则添加至文件夹列表dirs尾部 if (curFi->isDir()){ dirNames.push_back(curFi->filePath()); } else if (curFi->isFile()){ if (curFi->absoluteFilePath().toLower().endsWith(".java")){ if (!ReplaceAppPakNameInJava(path, curFi->absoluteFilePath(), oldName, newName)){ return 1; } } else if (curFi->absoluteFilePath().toLower().endsWith(".xml")){ if (!ReplaceAppPakNameInXml(path, curFi->absoluteFilePath(), oldName, newName)){ return 1; } } } curFi++; }//end of while } } if (!ReplaceAppPakNameInManifest(path, oldName, newName)){ return 5; } return 0; }
void RecordingsModel::scanRecords(const QString &path) { Q_ASSERT(mRecorder); // Current watching directories auto currentDirs = mWatcher->directories(); // Is the recursive search enabled auto recursiveSearch = mRecorder->recursiveSearch(); // Check if directory exists and add or remove it and // its subdirectories to the wathing list QDir dir(path); QStringList paths(path); if (dir.exists()) { // Check for subdirectories that should be added if (recursiveSearch) { QDirIterator it(path, QDir::Dirs, QDirIterator::Subdirectories); while (it.hasNext()) { paths << it.next(); } } mWatcher->addPaths(paths); } else { // Check for subdirectories that should be removed for (auto d: currentDirs) { if (d.startsWith(path)) { paths << d; } } mWatcher->removePaths(paths); } // Scan for updated and removed records for (int row = mData.size() - 1; row > -1; --row) { auto oldFileInfo = mData[row]; // Process entries only of the changed path if (oldFileInfo.absolutePath() != path) { continue; } QFileInfo newFileInfo(oldFileInfo); newFileInfo.refresh(); if (newFileInfo.exists()) { if (newFileInfo.lastModified() != oldFileInfo.lastModified()) { // The record was updated auto index = this->createIndex(row, 0); emit this->dataChanged(index, index, { Modified }); } } else { // The record was removed this->beginRemoveRows(QModelIndex(), row, row); mData.removeAt(row); this->endRemoveRows(); } } // Scan for new records auto flags = recursiveSearch ? QDirIterator::Subdirectories : QDirIterator::NoIteratorFlags; QDirIterator it(path, RecordingsModel::filters, QDir::Files, flags); QFileInfoList newRecords; while (it.hasNext()) { // Add a new record QFileInfo fileInfo(it.next()); if (!mData.contains(fileInfo)) { newRecords << fileInfo; } } if (!newRecords.empty()) { auto pos = mData.size(); this->beginInsertRows(QModelIndex(), pos, pos + newRecords.size() - 1); mData.append(newRecords); this->endInsertRows(); } }
void SelectFile::copyFile(QString path) { QDir dir(path); QFileInfoList list; QDir flash_dir("C:/pic/SWWYL"); // 复制结果文件到程序用户选择的输出目录 switch (m_pt) { case HYFM: // if(m_first_change) { // m_first_change = false; // QMessageBox::warning(0,"PATH",path,QMessageBox::Yes); QThread::sleep(1); copyDirectoryFiles(path, m_outPath, true ); copyDirectoryFiles(path, "C:/pic/HYFM/", true ); // } break; case SWWYL: list = dir.entryInfoList(); qDebug() << list.size(); if (list.size() == 30+2){ QDir::setCurrent(root_path+"/yubao/wenyanliu/"); QThread::sleep(1); copyDirectoryFiles(path, m_outPath, true ); // call qie ge program. QProcess::execute("./QIEGE.exe"); // copy 0,1,2,3,4,5 pic to flash dir. QDir::setCurrent(root_path+"/yubao/wenyanliu/"); copyDirectoryFiles("./3d_qiege/", "C:/pic/SWWYL_3d/", true ); // copyDirectoryFiles("./flash/", "C:/pic/SWWYL_2d/", true ); QDir::setCurrent(root_path); } break; case ZCDW: list = dir.entryInfoList(); qDebug() << list.size(); if (list.size() == 101+2){ QDir::setCurrent(root_path+"/yubao/zcdw/"); QThread::sleep(1); copyDirectoryFiles(path, m_outPath, true ); copyDirectoryFiles(path, "C:/pic/ZCDW/", true ); QDir::setCurrent(root_path); } break; default: break; } }
bool Dymola::compile(QFileInfo moPath,QString modelToConsider,QDir storeFolder,QFileInfo logFile, const QFileInfoList & moDeps, QFileInfoList neededFiles) { // Create Dymola script QString filePath = storeFolder.absoluteFilePath("MOFirstRun.mos"); QFile file(filePath); if(file.exists()) { file.remove(); } file.open(QIODevice::WriteOnly); QString scriptText; QString curPath; // load dependencies and model QFileInfoList moToLoad; moToLoad.append(moDeps); moToLoad.push_back(moPath); LowTools::removeDuplicates(moToLoad); for(int i=0;i<moToLoad.size();i++) { curPath = QDir::fromNativeSeparators(moToLoad.at(i).absoluteFilePath()); scriptText.append("openModel(\""+curPath+"\",false)\n"); } QString strFolder = QDir::fromNativeSeparators(storeFolder.absolutePath()); QString logFilePath = QDir::fromNativeSeparators(logFile.absoluteFilePath()); scriptText.append("cd "+strFolder+"\n"); scriptText.append("experimentSetupOutput(textual=true)\n"); scriptText.append("Advanced.StoreProtectedVariables:=true;\n"); //scriptText.append("checkModel(\""+modelToConsider+"\",simulate=true)\n"); scriptText.append("translateModel(\""+modelToConsider+"\")\n"); scriptText.append("compile()\n"); scriptText.append("savelog(\""+logFilePath+"\")\n"); scriptText.append("exit\n"); QTextStream ts( &file ); ts << scriptText; file.close(); // Copy needed files LowTools::copyFilesInFolder(neededFiles,storeFolder); // Run script QString dymolaPath = MOSettings::value("dymolaExe").toString(); QFileInfo dymolaBin(dymolaPath); if(!dymolaBin.exists()) { InfoSender::instance()->send(Info("Dymola executable not found. Please verify path in Settings",ListInfo::ERROR2)); return false; } else { // delete previous dymosim.exe QFile dymoFile(storeFolder.absoluteFilePath("dymosim.exe")); if(dymoFile.exists()) dymoFile.remove(); // delete previous dsin file QFile dsinFile(storeFolder.absoluteFilePath("dsin.txt")); if(dsinFile.exists()) dsinFile.remove(); // launch script QProcess scriptProcess; QStringList args; args.push_back(filePath); //start process InfoSender::sendCurrentTask("Launching Dymola..."); scriptProcess.start(dymolaPath,args); bool ok = scriptProcess.waitForFinished(-1); if(!ok) { QString msg("CreateProcess failed"); InfoSender::instance()->debug(msg); return false; } //look if it succeed bool success = dymoFile.exists(); InfoSender::eraseCurrentTask(); return success; } }
static PRL_RESULT GetEntryLists( const QString & aVmHomeDir, QList<QPair<QFileInfo, QString> > & dirList, QList<QPair<QFileInfo, QString> > & fileList) { QString VmHomeDir = QFileInfo(aVmHomeDir).absoluteFilePath(); QFileInfo dirInfo; QFileInfoList entryList; QDir dir; QDir startDir(VmHomeDir); int i, j; QFileInfo config, config_backup, log, statlog; config.setFile(VmHomeDir, VMDIR_DEFAULT_VM_CONFIG_FILE); config_backup.setFile(VmHomeDir, VMDIR_DEFAULT_VM_CONFIG_FILE VMDIR_DEFAULT_VM_BACKUP_SUFFIX); log.setFile(VmHomeDir, "parallels.log"); statlog.setFile(VmHomeDir, PRL_VMTIMING_LOGFILENAME); dirInfo.setFile(VmHomeDir); if (!dirInfo.exists()) { WRITE_TRACE(DBG_FATAL, "Directory %s does not exist", QSTR2UTF8(VmHomeDir)); return (PRL_ERR_VMDIR_INVALID_PATH); } dirList.append(qMakePair(dirInfo, QString("."))); for (i = 0; i < dirList.size(); ++i) { /* CDir::absoluteDir() is equal CDir::dir() : return parent directory */ dir.setPath(dirList.at(i).first.absoluteFilePath()); entryList = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs | QDir::Hidden); WRITE_TRACE(DBG_DEBUG, "Directory %s", QSTR2UTF8(dirList.at(i).first.absoluteFilePath())); for (j = 0; j < entryList.size(); ++j) { const QFileInfo& fileInfo = entryList.at(j); if (dirInfo == fileInfo) { WRITE_TRACE(DBG_FATAL, "Infinite recursion in : %s", QSTR2UTF8(dirInfo.absoluteFilePath())); return (PRL_ERR_FAILURE); } if (!fileInfo.absoluteFilePath().startsWith(VmHomeDir)) { WRITE_TRACE(DBG_FATAL, "Path %s does not starts from VM home dir (%s)", QSTR2UTF8(fileInfo.absoluteFilePath()), QSTR2UTF8(VmHomeDir)); return PRL_ERR_FAILURE; } ; if (fileInfo.isDir()) { dirList.append(qMakePair( fileInfo, startDir.relativeFilePath(fileInfo.absoluteFilePath()))); } else { /* skip config & config backup */ if (fileInfo.absoluteFilePath() == config.absoluteFilePath()) continue; if (fileInfo.absoluteFilePath() == config_backup.absoluteFilePath()) continue; /* skip parallels.log */ if (fileInfo.absoluteFilePath() == log.absoluteFilePath()) continue; if (fileInfo.absoluteFilePath() == statlog.absoluteFilePath()) /* will save statistic.log to temporary file */ fileList.append(qMakePair(statlog, QString(PRL_VMTIMING_LOGFILENAME VMDIR_DEFAULT_VM_MIGRATE_SUFFIX))); else fileList.append(qMakePair( fileInfo, startDir.relativeFilePath(fileInfo.absoluteFilePath()))); } WRITE_TRACE(DBG_DEBUG, "%x\t%s.%s\t%s", int(fileInfo.permissions()), QSTR2UTF8(fileInfo.owner()), QSTR2UTF8(fileInfo.group()), QSTR2UTF8(fileInfo.absoluteFilePath())); } entryList.clear(); } /* remove VM home directory */ dirList.removeFirst(); return (PRL_ERR_SUCCESS); }
void CCCITT4Client::UpdateFileList() { QListWidgetItem *pListItem; QDir *pDir; QFileInfoList list; int i, j; bool bFileExists, bItemExists; /* Disconnect the list event while changing the contents */ disconnect(ui->listWidgetFiles, SIGNAL(itemSelectionChanged()), this, SLOT(OnFilesListSelectionChanged())); /* Obtain a list of all the tif files in the selected directory */ pDir = new QDir(ui->lineEditPath->text()); list = pDir->entryInfoList(QStringList("*.tif"), QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::Time); /* Remove list elements of which the corresponding file does not exist anymore */ for(i = 0; i < ui->listWidgetFiles->count(); i++) { pListItem = ui->listWidgetFiles->item(i); /* Verify if the file exists */ bFileExists = false; if(pListItem != NULL) { for(j = 0; (j < list.size()) && (bFileExists == false); j++) { if(list.at(j).fileName().compare(pListItem->text()) == 0) { bFileExists = true; } } } /* Delete the list element if the file doesn't exists */ if(bFileExists == false) { ui->listWidgetFiles->removeItemWidget(pListItem); delete pListItem; pListItem = NULL; i = 0; } } /* Iterate over all the files and add them to the list if they are not contained yet */ for(i = 0; i < list.size(); ++i) { bItemExists = false; for(j = 0; j < ui->listWidgetFiles->count(); j++) { if(list.at(i).fileName().compare(ui->listWidgetFiles->item(j)->text()) == 0) { bItemExists = true; } } if(bItemExists == false) { pListItem = new QListWidgetItem(QIcon(list.at(i).absoluteFilePath()), list.at(i).fileName()); ui->listWidgetFiles->addItem(pListItem); } } /* Alternate the backgroundcolor of the list elements */ for(i = 0; i < ui->listWidgetFiles->count(); i++) { if(i & 0x1) { ui->listWidgetFiles->item(i)->setBackgroundColor(QColor::fromHsv(0,0,240)); } else { ui->listWidgetFiles->item(i)->setBackgroundColor(QColor::fromHsv(0,0,255)); } } delete pDir; /* reconnnect the list event */ connect(ui->listWidgetFiles, SIGNAL(itemSelectionChanged()), this, SLOT(OnFilesListSelectionChanged())); }
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; 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 unsigned 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 == "pbuffer") type = OpenGLPBufferType; #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 == "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 } } 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(fileName)); 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>; qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_filename = files.at(j); qWidget->setWindowTitle(fileinfo.filePath()); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } case ImageWidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>; qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_filename = files.at(j); qWidget->setWindowTitle(fileinfo.filePath()); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } #ifndef QT_NO_OPENGL case OpenGLPBufferType: { QGLPixelBuffer pbuffer(QSize(width, height)); QPainter pt(&pbuffer); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image = pbuffer.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>; qGLWidget->setVerboseMode(verboseMode); qGLWidget->setType(type); qGLWidget->setCheckersBackground(checkers_background); qGLWidget->m_filename = files.at(j); qGLWidget->setWindowTitle(fileinfo.filePath()); qGLWidget->m_commands = content; qGLWidget->resize(width, height); qGLWidget->show(); activeWidget = qGLWidget; break; } #else case OpenGLType: 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(width, height); 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(width, height); 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(width, height, type == ImageMonoType ? QImage::Format_MonoLSB : imageFormat); 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"); #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: { 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()); break; } case PsType: case PdfType: { PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); bool ps = type == PsType; QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); QFileInfo input(files.at(j)); QString file = QString("%1_%2.%3") .arg(input.baseName()) .arg(input.suffix()) .arg(ps ? "ps" : "pdf"); p.setOutputFormat(ps ? QPrinter::PdfFormat : QPrinter::PostScriptFormat); 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)); 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 return 0; }
int main(int argc, char *argv[]) { QString workDir; #ifdef Q_OS_MAC if (QDir(QString()).absolutePath() == "/") { QString first = argc ? QString::fromLocal8Bit(argv[0]) : QString(); if (!first.isEmpty()) { QFileInfo info(first); if (info.exists()) { QDir result(info.absolutePath() + "/../../.."); workDir = result.absolutePath() + '/'; } } } #endif QString remove; int version = 0; QFileInfoList files; for (int i = 0; i < argc; ++i) { if (string("-path") == argv[i] && i + 1 < argc) { QString path = workDir + QString(argv[i + 1]); QFileInfo info(path); files.push_back(info); if (remove.isEmpty()) remove = info.canonicalPath() + "/"; } else if (string("-version") == argv[i] && i + 1 < argc) { version = QString(argv[i + 1]).toInt(); } else if (string("-dev") == argv[i]) { DevChannel = true; } } if (files.isEmpty() || remove.isEmpty() || version <= 1016 || version > 999999) { // not for release =) #ifdef Q_OS_WIN cout << "Usage: Packer.exe -path {file} -version {version} OR Packer.exe -path {dir} -version {version}\n"; #elif defined Q_OS_MAC cout << "Usage: Packer.app -path {file} -version {version} OR Packer.app -path {dir} -version {version}\n"; #endif return -1; } bool hasDirs = true; while (hasDirs) { hasDirs = false; for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { QFileInfo info(*i); QString fullPath = info.canonicalFilePath(); if (info.isDir()) { hasDirs = true; files.erase(i); QDir d = QDir(info.absoluteFilePath()); QString fullDir = d.canonicalPath(); QStringList entries = d.entryList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); files.append(d.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)); break; } else if (!info.isReadable()) { cout << "Can't read: " << info.absoluteFilePath().toUtf8().constData() << "\n"; return -1; } else if (info.isHidden()) { hasDirs = true; files.erase(i); break; } } } for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { QFileInfo info(*i); if (!info.canonicalFilePath().startsWith(remove)) { cout << "Can't find '" << remove.toUtf8().constData() << "' in file '" << info.canonicalFilePath().toUtf8().constData() << "' :(\n"; return -1; } } QByteArray result; { QBuffer buffer(&result); buffer.open(QIODevice::WriteOnly); QDataStream stream(&buffer); stream.setVersion(QDataStream::Qt_5_1); stream << quint32(version); stream << quint32(files.size()); cout << "Found " << files.size() << " file" << (files.size() == 1 ? "" : "s") << "..\n"; for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) { QFileInfo info(*i); QString fullName = info.canonicalFilePath(); QString name = fullName.mid(remove.length()); cout << name.toUtf8().constData() << " (" << info.size() << ")\n"; QFile f(fullName); if (!f.open(QIODevice::ReadOnly)) { cout << "Can't open '" << fullName.toUtf8().constData() << "' for read..\n"; return -1; } QByteArray inner = f.readAll(); stream << name << quint32(inner.size()) << inner; #if defined Q_OS_MAC || defined Q_OS_LINUX stream << (QFileInfo(fullName).isExecutable() ? true : false); #endif } if (stream.status() != QDataStream::Ok) { cout << "Stream status is bad: " << stream.status() << "\n"; return -1; } } int32 resultSize = result.size(); cout << "Compression start, size: " << resultSize << "\n"; QByteArray compressed, resultCheck; #ifdef Q_OS_WIN // use Lzma SDK for win const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size size_t compressedLen = compressed.size() - hSize; size_t outPropsSize = LZMA_PROPS_SIZE; uchar *_dest = (uchar*)(compressed.data() + hSize); size_t *_destLen = &compressedLen; const uchar *_src = (const uchar*)(result.constData()); size_t _srcLen = result.size(); uchar *_outProps = (uchar*)(compressed.data() + hSigLen + hShaLen); int res = LzmaCompress(_dest, _destLen, _src, _srcLen, _outProps, &outPropsSize, 9, 64 * 1024 * 1024, 4, 0, 2, 273, 2); if (res != SZ_OK) { cout << "Error in compression: " << res << "\n"; return -1; } compressed.resize(int(hSize + compressedLen)); memcpy(compressed.data() + hSigLen + hShaLen + hPropsLen, &resultSize, hOriginalSizeLen); cout << "Compressed to size: " << compressedLen << "\n"; cout << "Checking uncompressed..\n"; int32 resultCheckLen; memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen); if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) { cout << "Bad result len: " << resultCheckLen << "\n"; return -1; } resultCheck.resize(resultCheckLen); size_t resultLen = resultCheck.size(); SizeT srcLen = compressedLen; int uncompressRes = LzmaUncompress((uchar*)resultCheck.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE); if (uncompressRes != SZ_OK) { cout << "Uncompress failed: " << uncompressRes << "\n"; return -1; } if (resultLen != size_t(result.size())) { cout << "Uncompress bad size: " << resultLen << ", was: " << result.size() << "\n"; return -1; } #else // use liblzma for others const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size size_t compressedLen = compressed.size() - hSize; lzma_stream stream = LZMA_STREAM_INIT; int preset = 9 | LZMA_PRESET_EXTREME; lzma_ret ret = lzma_easy_encoder(&stream, preset, LZMA_CHECK_CRC64); if (ret != LZMA_OK) { const char *msg; switch (ret) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break; case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error initializing the encoder: " << msg << " (error code " << ret << ")\n"; return -1; } stream.avail_in = resultSize; stream.next_in = (uint8_t*)result.constData(); stream.avail_out = compressedLen; stream.next_out = (uint8_t*)(compressed.data() + hSize); lzma_ret res = lzma_code(&stream, LZMA_FINISH); compressedLen -= stream.avail_out; lzma_end(&stream); if (res != LZMA_OK && res != LZMA_STREAM_END) { const char *msg; switch (res) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_DATA_ERROR: msg = "File size limits exceeded"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error in compression: " << msg << " (error code " << res << ")\n"; return -1; } compressed.resize(int(hSize + compressedLen)); memcpy(compressed.data() + hSigLen + hShaLen, &resultSize, hOriginalSizeLen); cout << "Compressed to size: " << compressedLen << "\n"; cout << "Checking uncompressed..\n"; int32 resultCheckLen; memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen, hOriginalSizeLen); if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) { cout << "Bad result len: " << resultCheckLen << "\n"; return -1; } resultCheck.resize(resultCheckLen); size_t resultLen = resultCheck.size(); stream = LZMA_STREAM_INIT; ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED); if (ret != LZMA_OK) { const char *msg; switch (ret) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break; case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error initializing the decoder: " << msg << " (error code " << ret << ")\n"; return -1; } stream.avail_in = compressedLen; stream.next_in = (uint8_t*)(compressed.constData() + hSize); stream.avail_out = resultLen; stream.next_out = (uint8_t*)resultCheck.data(); res = lzma_code(&stream, LZMA_FINISH); if (stream.avail_in) { cout << "Error in decompression, " << stream.avail_in << " bytes left in _in of " << compressedLen << " whole.\n"; return -1; } else if (stream.avail_out) { cout << "Error in decompression, " << stream.avail_out << " bytes free left in _out of " << resultLen << " whole.\n"; return -1; } lzma_end(&stream); if (res != LZMA_OK && res != LZMA_STREAM_END) { const char *msg; switch (res) { case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break; case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break; case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break; case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break; case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break; default: msg = "Unknown error, possibly a bug"; break; } cout << "Error in decompression: " << msg << " (error code " << res << ")\n"; return -1; } #endif if (memcmp(result.constData(), resultCheck.constData(), resultLen)) { cout << "Data differ :(\n"; return -1; } /**/ result = resultCheck = QByteArray(); cout << "Counting SHA1 hash..\n"; uchar sha1Buffer[20]; memcpy(compressed.data() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, uint32(compressedLen + hPropsLen + hOriginalSizeLen), sha1Buffer), hShaLen); // count sha1 uint32 siglen = 0; cout << "Signing..\n"; RSA *prKey = PEM_read_bio_RSAPrivateKey(BIO_new_mem_buf(const_cast<char*>(DevChannel ? privateDevKey : privateKey), -1), 0, 0, 0); if (!prKey) { cout << "Could not read RSA private key!\n"; return -1; } if (RSA_size(prKey) != hSigLen) { RSA_free(prKey); cout << "Bad private key, size: " << RSA_size(prKey) << "\n"; return -1; } if (RSA_sign(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (uchar*)(compressed.data()), &siglen, prKey) != 1) { // count signature RSA_free(prKey); cout << "Signing failed!\n"; return -1; } RSA_free(prKey); if (siglen != hSigLen) { cout << "Bad signature length: " << siglen << "\n"; return -1; } cout << "Checking signature..\n"; RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(DevChannel ? publicDevKey : publicKey), -1), 0, 0, 0); if (!pbKey) { cout << "Could not read RSA public key!\n"; return -1; } if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), siglen, pbKey) != 1) { // verify signature RSA_free(pbKey); cout << "Signature verification failed!\n"; return -1; } cout << "Signature verified!\n"; RSA_free(pbKey); #ifdef Q_OS_WIN QString outName(QString("tupdate%1").arg(version)); #elif defined Q_OS_MAC QString outName(QString("tmacupd%1").arg(version)); #elif defined Q_OS_LINUX32 QString outName(QString("tlinux32upd%1").arg(version)); #elif defined Q_OS_LINUX64 QString outName(QString("tlinuxupd%1").arg(version)); #else #error Unknown platform! #endif QFile out(outName); if (!out.open(QIODevice::WriteOnly)) { cout << "Can't open '" << outName.toUtf8().constData() << "' for write..\n"; return -1; } out.write(compressed); out.close(); cout << "Update file '" << outName.toUtf8().constData() << "' written successfully!\n"; return 0; }
void get_dir_files (QStringList *input_files, QStringList *input_dirs) { for (NV_INT32 i = 0 ; i < input_dirs->size () ; i++) { QStringList nameFilter; QString type = input_dirs->at (i).section (':', 0, 0); if (type == "GSF") { nameFilter << "*.d\?\?" << "*.gsf"; } else if (type == "WLF") { nameFilter << "*.wlf" << "*.wtf" << "*.whf"; } else if (type == "HAWKEYE") { nameFilter << "*.bin"; } else if (type == "HOF") { nameFilter << "*.hof"; } else if (type == "TOF") { nameFilter << "*.tof"; } else if (type == "UNISIPS") { nameFilter << "*.u"; } else if (type == "YXZ") { nameFilter << "*.yxz" << "*.txt"; } else if (type == "HYPACK") { nameFilter << "*.raw"; } else if (type == "IVS XYZ") { nameFilter << "*.xyz"; } else if (type == "LLZ") { nameFilter << "*.llz"; } else if (type == "CZMIL") { nameFilter << "*.cxy"; } else if (type == "DTED") { nameFilter << "*.dt1" << "*.dt2"; } else if (type == "CHRTR") { nameFilter << "*.fin" << "*.ch2"; } else if (type == "BAG") { nameFilter << "*.bag"; } else { NV_CHAR atype[128]; strcpy (atype, type.toAscii ()); fprintf (stderr, "\n\nUnknown data type %s on [DIR] = field, ignoring!\n\n", atype); continue; } QString file = input_dirs->at (i).section (':', 1, 1).trimmed (); QDir dirs; dirs.cd (file); dirs.setFilter (QDir::Dirs | QDir::Readable); // Get all matching files in this directory. QDir files; files.setFilter (QDir::Files | QDir::Readable); files.setNameFilters (nameFilter); if (files.cd (file)) { QFileInfoList flist = files.entryInfoList (); for (NV_INT32 i = 0 ; i < flist.size () ; i++) { // Don't load HOF timing lines. QString tst = flist.at (i).absoluteFilePath (); if (!nameFilter.contains ("*.hof") || tst.mid (tst.length () - 13, 4) != "_TA_") { input_files->append (tst); } } } // Get all directories in this directory. QFileInfoList dlist = dirs.entryInfoList (); QStringList dirList; for (NV_INT32 i = 0 ; i < dlist.size () ; i++) { if (dlist.at (i).fileName () != "." && dlist.at (i).fileName () != "..") dirList.append (dlist.at (i).absoluteFilePath ()); } // Get all subordinate directories. for (NV_INT32 i = 0 ; i < dirList.size () ; i++) { QString dirName = dirList.at (i); if (dirs.cd (dirName)) { QFileInfoList nlist = dirs.entryInfoList (); for (NV_INT32 i = 0 ; i < nlist.size () ; i++) { if (nlist.at (i).fileName () != "." && nlist.at (i).fileName () != "..") dirList.append (nlist.at (i).absoluteFilePath ()); } } } // Get all matching files in all subordinate directories for (NV_INT32 i = 0 ; i < dirList.size () ; i++) { files.setFilter (QDir::Files | QDir::Readable); files.setNameFilters (nameFilter); QString dirName = dirList.at (i); if (files.cd (dirName)) { QFileInfoList flist = files.entryInfoList (); for (NV_INT32 i = 0 ; i < flist.size () ; i++) { // Don't load HOF timing lines. QString tst = flist.at (i).absoluteFilePath (); if (!nameFilter.contains ("*.hof") || tst.mid (tst.length () - 13, 4) != "_TA_") { input_files->append (tst); } } } } } }
// 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; } } }
// 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); } } }
int init ( ) { BL_FUNC_DEBUG /// Inicializa el sistema de traducciones 'gettext'. setlocale ( LC_ALL, "" ); blBindTextDomain ( "pluginbl_report2ods", g_confpr->value( CONF_DIR_TRADUCCION ).toLatin1().constData() ); PluginBl_Report2ODS *mcont = new PluginBl_Report2ODS; QMenu *pPluginMenu = NULL; /// Buscamos ficheros que tengan el nombre de la tabla QDir dir ( g_confpr->value( CONF_DIR_OPENREPORTS ) ); dir.setFilter ( QDir::Files | QDir::NoSymLinks ); dir.setSorting ( QDir::Size | QDir::Reversed ); /// Hacemos un filtrado de busqueda QStringList filters; filters << "inf_*.pys"; dir.setNameFilters ( filters ); QFileInfoList list = dir.entryInfoList(); for ( int i = 0; i < list.size(); ++i ) { QFileInfo fileInfo = list.at ( i ); QFile file; file.setFileName ( g_confpr->value( CONF_DIR_OPENREPORTS ) + fileInfo.fileName() ); file.open ( QIODevice::ReadOnly ); QTextStream stream ( &file ); QString buff = stream.readAll(); file.close(); /// Buscamos el titulo QString titulo = fileInfo.fileName(); QRegExp rx3 ( "title\\s*=\\s*\"(.*)\"" ); rx3.setMinimal ( true ); if ( rx3.indexIn ( buff, 0 ) != -1 ) { titulo = rx3.cap ( 1 ); } // end if QString pathtitulo = fileInfo.fileName(); QRegExp rx1 ( "pathtitle\\s*=\\s*\"(.*)\"" ); rx1.setMinimal ( true ); if ( rx1.indexIn ( buff, 0 ) != -1 ) { pathtitulo = rx1.cap ( 1 ); } else { pathtitulo = titulo; } // end if /// Buscamos el icono QString icon = ":/Images/template2ods.png"; QRegExp rx4 ( " icon\\s*=\\s*\"(.*)\"" ); rx4.setMinimal ( true ); if ( rx4.indexIn ( buff, 0 ) != -1 ) { icon = rx4.cap ( 1 ); } // end if QMenuBar *menubar =g_pluginbl_report2ods->menuBar(); QMenu *menu = NULL; QStringList path = pathtitulo.split("\\"); if (path.size() > 1) { QList<QMenu *> allPButtons = menubar->findChildren<QMenu *>(); bool encontrado = false; for (int j = 0; j < allPButtons.size(); ++j) { if (allPButtons.at(j)->title() == path[0]) { encontrado = true; menu = allPButtons.at(j); } // end if } // end for if (!encontrado) { //QMenu *pPluginMenu1 = new QMenu ( path[0] , menubar ); //menubar->insertMenu ( pPluginVer->menuAction(), pPluginMenu1 ); /// Miramos si existe un menu Herramientas menu = g_pluginbl_report2ods->newMenu ( path[0], "", "menuHerramientas" ); } // end if } else { if (!pPluginMenu) { pPluginMenu = g_pluginbl_report2ods->newMenu ( _("Informes &ODS"), "menuInfODS", "menuHerramientas" ); } // end if menu = pPluginMenu; } // end if for (int i = 1; i < path.size()-1; ++i) { QList<QMenu *> allPButtons = menu->findChildren<QMenu *>(); bool encontrado = false; for (int j = 0; j < allPButtons.size(); ++j) { if (allPButtons.at(j)->title() == path[i]) { encontrado = true; menu = allPButtons.at(j); } // end if } // end for if (!encontrado) { QMenu *pPluginMenu1 = new QMenu ( path[i] , menu ); menu->addMenu ( pPluginMenu1 ); menu = pPluginMenu1; } // end if } // end for /// Creamos el menú. QAction *accion = new QAction ( path[path.size()-1], 0 ); accion->setIcon(QIcon(icon)); accion->setObjectName ( fileInfo.fileName() ); accion->setStatusTip ( titulo); accion->setWhatsThis ( titulo ); mcont->connect ( accion, SIGNAL ( activated() ), mcont, SLOT ( elslot1() ) ); menu->addAction ( accion ); } // end for return 0; }
/// /// Loads only usable plugins /// std::vector<LadspaFXInfo*> Effects::getPluginList() { if ( m_pluginList.size() != 0 ) { return m_pluginList; } vector<QString> ladspaPathVect = Preferences::get_instance()->getLadspaPath(); INFOLOG( QString( "PATHS: %1" ).arg( ladspaPathVect.size() ) ); for ( vector<QString>::iterator i = ladspaPathVect.begin(); i != ladspaPathVect.end(); i++ ) { QString sPluginDir = *i; INFOLOG( "*** [getPluginList] reading directory: " + sPluginDir ); QDir dir( sPluginDir ); if ( !dir.exists() ) { INFOLOG( "Directory " + sPluginDir + " not found" ); continue; } QFileInfoList list = dir.entryInfoList(); for ( int i = 0; i < list.size(); ++i ) { QString sPluginName = list.at( i ).fileName(); if ( ( sPluginName == "." ) || ( sPluginName == ".." ) ) { continue; } // if the file ends with .so or .dll is a plugin, else... #ifdef WIN32 int pos = sPluginName.indexOf( ".dll" ); #else #ifdef Q_OS_MACX int pos = sPluginName.indexOf( ".dylib" ); #else int pos = sPluginName.indexOf( ".so" ); #endif #endif if ( pos == -1 ) { continue; } //warningLog( "[getPluginList] Loading: " + sPluginName ); QString sAbsPath = QString( "%1/%2" ).arg( sPluginDir ).arg( sPluginName ); QLibrary lib( sAbsPath ); LADSPA_Descriptor_Function desc_func = ( LADSPA_Descriptor_Function )lib.resolve( "ladspa_descriptor" ); if ( desc_func == NULL ) { ERRORLOG( "Error loading the library. (" + sAbsPath + ")" ); continue; } const LADSPA_Descriptor * d; if ( desc_func ) { for ( unsigned i = 0; ( d = desc_func ( i ) ) != NULL; i++ ) { LadspaFXInfo* pFX = new LadspaFXInfo( QString::fromLocal8Bit(d->Name) ); pFX->m_sFilename = sAbsPath; pFX->m_sLabel = QString::fromLocal8Bit(d->Label); pFX->m_sID = QString::number(d->UniqueID); pFX->m_sMaker = QString::fromLocal8Bit(d->Maker); pFX->m_sCopyright = QString::fromLocal8Bit(d->Copyright); //INFOLOG( "Loading: " + pFX->m_sLabel ); for ( unsigned j = 0; j < d->PortCount; j++ ) { LADSPA_PortDescriptor pd = d->PortDescriptors[j]; if ( LADSPA_IS_PORT_INPUT( pd ) && LADSPA_IS_PORT_CONTROL( pd ) ) { pFX->m_nICPorts++; } else if ( LADSPA_IS_PORT_INPUT( pd ) && LADSPA_IS_PORT_AUDIO( pd ) ) { pFX->m_nIAPorts++; } else if ( LADSPA_IS_PORT_OUTPUT( pd ) && LADSPA_IS_PORT_CONTROL( pd ) ) { pFX->m_nOCPorts++; } else if ( LADSPA_IS_PORT_OUTPUT( pd ) && LADSPA_IS_PORT_AUDIO( pd ) ) { pFX->m_nOAPorts++; } else { // string sPortName = d->PortNames[ j ]; QString sPortName; ERRORLOG( QString( "%1::%2 unknown port type" ).arg( pFX->m_sLabel ).arg( sPortName ) ); } } if ( ( pFX->m_nIAPorts == 2 ) && ( pFX->m_nOAPorts == 2 ) ) { // Stereo plugin m_pluginList.push_back( pFX ); } else if ( ( pFX->m_nIAPorts == 1 ) && ( pFX->m_nOAPorts == 1 ) ) { // Mono plugin m_pluginList.push_back( pFX ); } else { // not supported plugin //WARNINGLOG( "Plugin not supported: " + sPluginName ); delete pFX; } } } else { ERRORLOG( "Error loading: " + sPluginName ); } } } INFOLOG( QString( "Loaded %1 LADSPA plugins" ).arg( m_pluginList.size() ) ); std::sort( m_pluginList.begin(), m_pluginList.end(), LadspaFXInfo::alphabeticOrder ); return m_pluginList; }
bool PathManager::CopyDir(const QString &source, const QString &destination, bool isCover) { /* 递归实现 */ /*QDir directory(source); if (!directory.exists()){ return false; } QString srcPath = QDir::toNativeSeparators(source); if (!srcPath.endsWith(QDir::separator())){ srcPath += QDir::separator(); } QString dstPath = QDir::toNativeSeparators(destination); if (!dstPath.endsWith(QDir::separator())){ dstPath += QDir::separator(); } QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden); for (QStringList::size_type i = 0; i != fileNames.size(); ++i) { QString fileName = fileNames.at(i); QString srcFilePath = srcPath + fileName; QString dstFilePath = dstPath + fileName; QFileInfo fileInfo(srcFilePath); if (fileInfo.isFile() || fileInfo.isSymLink()){ if (isCover){ QFile::setPermissions(dstFilePath, QFile::WriteOwner); } if (!QFile::copy(srcFilePath, dstFilePath)){ return false; } } else if (fileInfo.isDir()){ QDir dstDir(dstFilePath); dstDir.mkpath(dstFilePath); if (!CopyDir(srcFilePath, dstFilePath, isCover)){ return false; } } } return true;*/ QVector<QString> dirNames; QVector<QString> fileNames; QDir dir(source); if (!dir.exists()){ return false; } dirNames.clear(); dirNames << source; QFileInfoList filst; QFileInfoList::iterator curFi; for (int i = 0; i < dirNames.size(); ++i) { dir.setPath(dirNames[i]); filst = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::Readable | QDir::Writable | QDir::Hidden | QDir::NoDotAndDotDot , QDir::DirsFirst); if (filst.size() > 0){ curFi = filst.begin(); while (curFi != filst.end()) { if (curFi->isDir()){ dirNames.push_back(curFi->filePath()); } else if (curFi->isFile()){ fileNames.push_back(curFi->absoluteFilePath()); } curFi++; } } } for (QVector<QString>::Iterator ite = dirNames.begin(); ite != dirNames.end(); ite++) { QDir dirSrc(source); QDir dirDest(destination); ite->replace(dirSrc.absolutePath(), dirDest.absolutePath()); QDir dirTmp(*ite); if (!dirTmp.exists() && !dirTmp.mkpath(*ite)){ return false; } } for (QVector<QString>::Iterator ite = fileNames.begin(); ite != fileNames.end(); ite++) { QDir dirSrc(source); QDir dirDest(destination); QString srcPath = *ite; QString tar = ite->replace(dirSrc.absolutePath(), dirDest.absolutePath()); QFile file(tar); if (file.exists()){ if (isCover){ if (!file.remove()){ return false; } } else{ continue; } } if (!QFile::copy(srcPath, tar)){ return false; } } return true; }
void qippda::loadMessages(const QString &path) { QDir dir = path; if(!dir.cd("History")) return; QHash<QString,QString> protocols; protocols[QLatin1String("icq")] = QLatin1String("ICQ"); protocols[QLatin1String("jabber")] = QLatin1String("Jabber"); protocols[QLatin1String("mra")] = QLatin1String("MRIM"); QStringList filters = QStringList() << QLatin1String("*.qhf") << QLatin1String("*.ahf"); QFileInfoList files = dir.entryInfoList(filters, QDir::Files); setMaxValue(files.size()); for(int i = 0; i < files.size(); i++) { setValue(i + 1); QString protocol = files[i].fileName().section("_",0,0); while(!protocol.isEmpty() && protocol.at(protocol.length() - 1).isDigit()) protocol.chop(1); // Old qip pda has only ICQ support and files are named like 1_myuin_hisuin if(protocol.isEmpty()) protocol = QLatin1String("ICQ"); else { protocol = protocols[protocol.toLower()]; if(protocol.isEmpty()) { qWarning("Unknown protocol: \"%s\"", qPrintable(files[i].fileName())); continue; } } setProtocol(protocol); QString account = files[i].fileName().section("_",1,1); setAccount(account); QFile file(files[i].absoluteFilePath()); if(file.open(QFile::ReadOnly)) { QByteArray bytearray = file.readAll(); const uchar *data = (const uchar *)bytearray.constData(); const uchar *end = data + bytearray.size(); if(memcmp(data, "QHF", 3)) continue; uchar version = data[3]; data += 44; QString uin = qipinfium::getString(data, qipinfium::getUInt16(data)); QString name = qipinfium::getString(data, qipinfium::getUInt16(data)); setContact(uin); // continue; while(data < end) { quint16 type = qipinfium::getUInt16(data); quint32 index = qipinfium::getUInt32(data); data += 2; const uchar *next = data + index; if(type == 1) { Message message; message.type = 1; data += 10; message.time = QDateTime::fromTime_t(qipinfium::getUInt32(data)); message.time.setTimeSpec(Qt::LocalTime); if(version == 1) message.time = message.time.toUTC().addDays(2); else message.time = message.time.toUTC(); data += 4; message.in = qipinfium::getUInt8(data) == 0; data += 4; int mes_len = version == 3 ? qipinfium::getUInt32(data) : qipinfium::getUInt16(data); QString text = qipinfium::getString(data, mes_len, version > 1); message.text = Qt::escape(text).replace("\n", "<br/>"); appendMessage(message); } else data = next; } } } }
//----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tFilepathSelector::UpdateList() { m_FilePathList.clear(); m_FriendlyFilepathList.clear(); m_DisplayList.clear(); m_pListWidget->clear(); // First add the NONE option, No need to translate (appears in settings.ini) m_FilePathList << "None"; m_FriendlyFilepathList << "None"; m_DisplayList << "None"; int currentRow = 0; // setCurrentRow to the currentFile // Add files from all locations for (int i = 0; i < m_PathAndDirNameList.size(); ++i) { tPathAndDirname pathAndDirname = m_PathAndDirNameList.at(i); QDir directory(pathAndDirname.Path(), "", m_SortFlags, m_Filters); directory.setNameFilters(m_NameFilters); QFileInfoList fileInfoList = directory.entryInfoList(); for (int j = 0; j < fileInfoList.size(); ++j) { QFileInfo fileInfo = fileInfoList.at(j); // Add the real filepath string to our list m_FilePathList.append(fileInfo.filePath()); // Add the user displayed filepath e.g. "Sonar.sl2 (factory)" const QString dirname = pathAndDirname.DirName(); QString friendlyFilepath; if (dirname.isEmpty()) { friendlyFilepath = fileInfo.fileName(); m_FriendlyFilepathList.append(friendlyFilepath); } else { friendlyFilepath = QString("%1 (%2)").arg(fileInfo.fileName()).arg(dirname); m_FriendlyFilepathList.append(friendlyFilepath); // compare currentFile to path and set currentRow if there is an exact match if (friendlyFilepath.compare(m_CurrentFile) == 0) { currentRow = j + 1; } } if (m_ShowFileSize) { QString item = QString("%1 (%2)").arg(friendlyFilepath).arg(FormatSize(fileInfo.size())); m_DisplayList << item; } else { m_DisplayList << friendlyFilepath; } } } m_pListWidget->addItems(m_DisplayList); if (m_CurrentFile.isEmpty()) { m_pListWidget->setCurrentRow(0); } else { m_pListWidget->setCurrentRow(currentRow); } }
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, LOC + 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, LOC + QString("GetFileInfoList: (%1)").arg(tmp)); files.append(tmp); } return files; }
void MainWindow_M::extractEdgeImage() { QString path = QFileDialog::getExistingDirectory(this, tr("Open Directory"),".\\database", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if(path == "") return; QDir dir(path); if(!dir.exists()) return; QString eifilename = path.section('\\',-1); eifilename = path + "\\" + eifilename + ".xml"; // convert the fileName from QString to char* char file[256]; int len = 0; for(;len < eifilename.length(); len++) { file[len] = (eifilename.at(len)).toAscii(); } file[len] = '\0'; // store this edge image FileStorage fs(file,FileStorage::WRITE); if(!fs.isOpened()) { return; } CSAImageProcess imageProcess; QImage srcImage; QString fileName; dir.setFilter(QDir::Files | QDir::NoSymLinks); QFileInfoList list = dir.entryInfoList(); int i = 0; while(i < list.size()) { QFileInfo fileInfo = list.at(i++); fileName = fileInfo.fileName(); if(fileName.section('.',-1) != "png" && fileName.section('.',-1) != "PNG") continue; fileName = fileInfo.path() + "/"+fileName; // convert the fileName from QString to char* char file[256]; int len = 0; for(;len < fileName.length(); len++) { file[len] = (fileName.at(len)).toAscii(); } file[len] = '\0'; // read the image Mat mat = imread(file,CV_LOAD_IMAGE_COLOR); Mat edgelength,edgeorientation,m,m_n,edgeresponse; imageProcess.edgeextraction(mat,edgelength,edgeorientation,m,m_n,edgeresponse); // save this edge image char name[256]; sprintf(name,"edgeimage_%d",i); fs<<name<<edgelength; } fs.release(); }
/** \param parent **/ EQToolButton::EQToolButton ( QWidget *parent ) : QToolButton ( parent ) { BL_FUNC_DEBUG bool hayElementos = false; /// Buscamos alguna otra instancia y si la hay nos quitamos de enmedio EQToolButton *tool = parent->findChild<EQToolButton *>("EQToolButtonG"); if (tool) { hide(); return; } // end if setObjectName("EQToolButtonG"); connect ( parent, SIGNAL ( pintaMenu ( QMenu * ) ), this, SLOT ( pintaMenu ( QMenu * ) ) ); connect ( parent, SIGNAL ( trataMenu ( QAction * ) ), this, SLOT ( trataMenu ( QAction * ) ) ); m_BlForm = ( BlForm * ) parent; QFrame *plugbotones = m_BlForm->findChild<QFrame *>("mui_plugbotones"); if (plugbotones) { QHBoxLayout *m_hboxLayout1 = plugbotones->findChild<QHBoxLayout *> ( "hboxLayout1" ); if ( !m_hboxLayout1 ) { m_hboxLayout1 = new QHBoxLayout ( plugbotones ); m_hboxLayout1->setSpacing ( 5 ); m_hboxLayout1->setMargin ( 0 ); m_hboxLayout1->setObjectName ( QString::fromUtf8 ( "hboxLayout1" ) ); } // end if m_hboxLayout1->addWidget ( this ); setMinimumSize ( QSize ( 32, 32 ) ); setMaximumSize ( QSize ( 32, 32 ) ); setIcon ( QIcon ( ":/Images/template2rml.png" ) ); setIconSize ( QSize ( 32, 32 ) ); setPopupMode(QToolButton::InstantPopup); /// Creamos el menu QMenu *menu = new QMenu(this); /// Buscamos ficheros que tengan el nombre de la tabla QDir dir ( g_confpr->value( CONF_DIR_OPENREPORTS ) ); dir.setFilter ( QDir::Files | QDir::NoSymLinks ); dir.setSorting ( QDir::Size | QDir::Reversed ); /// Hacemos un filtrado de busqueda QStringList filters; filters << "*impers_" + m_BlForm->tableName() + "*.rml"; dir.setNameFilters ( filters ); QFileInfoList list = dir.entryInfoList(); // Si no hay elementos que mostrar entonces ocultamos el boton ya que no lleva a ninguna parte. if (list.size() != 0) { hayElementos = true; } // end if for ( int i = 0; i < list.size(); ++i ) { QFileInfo fileInfo = list.at ( i ); QFile file; file.setFileName ( g_confpr->value( CONF_DIR_OPENREPORTS ) + fileInfo.fileName() ); file.open ( QIODevice::ReadOnly ); QTextStream stream ( &file ); QString buff = stream.readAll(); file.close(); /// Buscamos Query's por tratar QString titulo = fileInfo.fileName(); QRegExp rx1 ( "title\\s*=\\s*\"(.*)\"" ); rx1.setMinimal ( true ); if ( rx1.indexIn ( buff, 0 ) != -1 ) { titulo = rx1.cap ( 1 ); } // end while /// Buscamos Query's por tratar QString icon = ":/Images/template2rml.png"; QRegExp rx2 ( " icon\\s*=\\s*\"(.*)\"" ); rx2.setMinimal ( true ); if ( rx2.indexIn ( buff, 0 ) != -1 ) { icon = rx2.cap ( 1 ); } // end while QAction *accion = menu->addAction ( titulo ); accion->setObjectName ( fileInfo.fileName() ); accion->setIcon(QIcon(icon)); connect ( accion, SIGNAL ( triggered ( bool ) ), this, SLOT ( trataMenu ( ) ) ); } // end for // Buscamos plantillas TXT que tienen que salir por la ticketera. /// Buscamos ficheros que tengan el nombre de la tabla QDir dir1 ( g_confpr->value( CONF_DIR_OPENREPORTS ) ); dir1.setFilter ( QDir::Files | QDir::NoSymLinks ); dir1.setSorting ( QDir::Size | QDir::Reversed ); /// Hacemos un filtrado de busqueda QStringList filters1; filters1 << "*impers_" + m_BlForm->tableName() + "*.txt"; dir1.setNameFilters ( filters1 ); QFileInfoList list1 = dir1.entryInfoList(); // Si no hay elementos que mostrar entonces ocultamos el boton ya que no lleva a ninguna parte. if (list1.size() != 0) { hayElementos = true; } // end if for ( int i = 0; i < list1.size(); ++i ) { QFileInfo fileInfo = list1.at ( i ); QFile file; file.setFileName ( g_confpr->value( CONF_DIR_OPENREPORTS ) + fileInfo.fileName() ); file.open ( QIODevice::ReadOnly ); QTextStream stream ( &file ); QString buff = stream.readAll(); file.close(); /// Buscamos Query's por tratar QString titulo = fileInfo.fileName(); QRegExp rx1 ( "title\\s*=\\s*\"(.*)\"" ); rx1.setMinimal ( true ); if ( rx1.indexIn ( buff, 0 ) != -1 ) { titulo = rx1.cap ( 1 ); } // end while /// Buscamos Query's por tratar QString icon = ":/Images/template2rml.png"; QRegExp rx2 ( " icon\\s*=\\s*\"(.*)\"" ); rx2.setMinimal ( true ); if ( rx2.indexIn ( buff, 0 ) != -1 ) { icon = rx2.cap ( 1 ); } // end while QAction *accion = menu->addAction ( titulo ); accion->setObjectName ( fileInfo.fileName() ); accion->setIcon(QIcon(icon)); connect ( accion, SIGNAL ( triggered ( bool ) ), this, SLOT ( trataMenu ( ) ) ); } // end for /// Si no hay elementos para mostrar nos ocultamos. if (!hayElementos) { hide(); return; } // end if setMenu(menu); } else {
void Plugin14C::loadRefDatas()//const ProjectSettings& settings) { mRefDatas.clear(); QString calibPath = getRefsPath(); QDir calibDir(calibPath); QFileInfoList files = calibDir.entryInfoList(QStringList(), QDir::Files); for(int i=0; i<files.size(); ++i) { if(files[i].suffix().toLower() == "14c") { QFile file(files[i].absoluteFilePath()); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMap<QString, QMap<double, double> > curves; QMap<double, double> curveG; QMap<double, double> curveG95Sup; QMap<double, double> curveG95Inf; QTextStream stream(&file); while(!stream.atEnd()) { QString line = stream.readLine(); if(!isComment(line)) { QStringList values = line.split(","); if(values.size() >= 3) { int t = 1950 - values[0].toInt(); double g = values[1].toDouble(); double gSup = g + 1.96f * values[2].toDouble(); double gInf = g - 1.96f * values[2].toDouble(); curveG[t] = g; curveG95Sup[t] = gSup; curveG95Inf[t] = gInf; } } } file.close(); // The curves do not have 1-year precision! // We have to interpolate in the blanks double tmin = curveG.firstKey(); double tmax = curveG.lastKey(); for(double t=tmin; t<tmax; ++t)//t+=settings.mStep)//++t) { if(curveG.find(t) == curveG.end()) { // This actually return the iterator with the nearest greater key !!! QMap<double, double>::const_iterator iter = curveG.lowerBound(t); if(iter != curveG.end()) { double t_upper = iter.key(); --iter; //if(iter != curveG.begin()) { double t_under = iter.key(); //qDebug() << t_under << " < " << t << " < " << t_upper; double g_under = curveG[t_under]; double g_upper = curveG[t_upper]; double gsup_under = curveG95Sup[t_under]; double gsup_upper = curveG95Sup[t_upper]; double ginf_under = curveG95Inf[t_under]; double ginf_upper = curveG95Inf[t_upper]; curveG[t] = interpolate(t, t_under, t_upper, g_under, g_upper); curveG95Sup[t] = interpolate(t, t_under, t_upper, gsup_under, gsup_upper); curveG95Inf[t] = interpolate(t, t_under, t_upper, ginf_under, ginf_upper); } /*else { curveG[t] = 0; curveG95Sup[t] = 0; curveG95Inf[t] = 0; }*/ } else { /*curveG[t] = 0; curveG95Sup[t] = 0; curveG95Inf[t] = 0;*/ } } } // Store the resulting curves : curves["G"] = curveG; curves["G95Sup"] = curveG95Sup; curves["G95Inf"] = curveG95Inf; mRefDatas[files[i].fileName().toLower()] = curves; } } } }
bool Dymola::createDsin(QFileInfo moFile,QString modelToConsider,QDir folder, const QFileInfoList & moDeps,QFileInfoList neededFiles) { // Create Dymola script QFile file(folder.absoluteFilePath("MOFirstRun.mos")); if(file.exists()) { file.remove(); } file.open(QIODevice::WriteOnly); QString strFolder = QDir::fromNativeSeparators(folder.absolutePath()); QString scriptText; QString curPath; // load dependencies and model QFileInfoList moToLoad; moToLoad.append(moDeps); moToLoad.push_back(moFile); LowTools::removeDuplicates(moToLoad); for(int i=0;i<moToLoad.size();i++) { curPath = QDir::fromNativeSeparators(moToLoad.at(i).absoluteFilePath()); scriptText.append("openModel(\""+curPath+"\")\n"); } scriptText.append("cd "+strFolder+"\n"); scriptText.append("translateModel(\""+modelToConsider+"\")\n"); scriptText.append("exportInitialDsin(\"dsin.txt\")\n"); scriptText.append("savelog(\"buildlog.txt\")\n"); scriptText.append("exit\n"); QTextStream ts( &file ); ts << scriptText; file.close(); // Copy needed files LowTools::copyFilesInFolder(neededFiles,folder); // Run script QString dymolaPath = MOSettings::value("dymolaExe").toString(); QProcess simProcess; QStringList args; args.push_back(QFileInfo(file).absoluteFilePath()); // delete previous dsin file QFile dsinFile(folder.absoluteFilePath("dsin.txt")); if(dsinFile.exists()) dsinFile.remove(); // launch script InfoSender::instance()->send(Info("Launching Dymola...")); simProcess.start(dymolaPath, args); bool ok = simProcess.waitForFinished(-1); if(!ok) { QString msg("CreateProcess failed"); InfoSender::instance()->debug(msg); return false; } //look if it succeed bool success = dsinFile.exists(); return success; }
//#define TEST_DATA int main(int argc, char** argv) { PagePosition pagePos; //コマンドライン引数の解析。デバッグの時は使わない const string commandArgs = "{@input | | directory including ebook (jpg or png)}" "{position | top | page number position. top or bottom}" ; cv::CommandLineParser parser(argc, argv, commandArgs); string src = parser.get<string>(0); string posStr = parser.get<string>("position"); if (posStr == "top") { pagePos = PagePosition::TOP; cout << "page number top" << endl; } else if (posStr == "bottom") { pagePos = PagePosition::BOTTOM; cout << "page number bottom" << endl; } else { cerr << "error: page position is incorrect. specify top or bottom. specified:" << posStr << endl; return 1; } #ifdef TEST_DATA //string src = TEST_DATA_0; string src = "C:\\Users\\kyokushin\\Pictures\\testData_Top\\"; pagePos = PagePosition::TOP; //string src = "C:\\Users\\kyokushin\\Pictures\\testData_Bottom\\"; //pagePos = PagePosition::BOTTOM; #endif QDir dir(QString::fromLocal8Bit(src.c_str()));//Qt用の文字コードに変換 if (!dir.exists()) { cerr << "error directory not exists. entered directory is \"" << src << "\"" << endl; return 1; } QFileInfo savePath(QString::fromLocal8Bit((src + '/' + "pagenumbers.png").c_str())); if (savePath.exists()) { cerr << "already exists pagenumber result file.:" << savePath.absoluteFilePath().toLocal8Bit().constData() << endl; return 1; } QFileInfoList fileList = dir.entryInfoList(QDir::Files); fileList.size(); cout << "input file:" << src << endl; int waitTime = 10; double rescaleSize = 1500; vector<int> imageHeights; vector<cv::Mat> pageNumbers; for (int i = 0; i < fileList.size(); i++) { cv::Mat rowImage(1, 1, CV_8UC1); string fname(fileList[i].absoluteFilePath().toLocal8Bit().constData()); cout << fname << endl; cv::Mat srcImage; int h = 0; do { srcImage = cv::imread(fname, CV_LOAD_IMAGE_COLOR); if (h++ > 10) { cerr << "failed to read image:" << fname << endl; return 1; } } while (srcImage.empty()); cv::Mat colorImage; if (srcImage.rows > rescaleSize || srcImage.cols > rescaleSize) { double scale = rescaleSize / srcImage.rows; double scaleWidth = rescaleSize / srcImage.cols; if (scale > scaleWidth) scale = scaleWidth; cv::resize(srcImage, colorImage, cv::Size(), scale, scale); cout << "resize:" << srcImage.size() << " -> " << colorImage.size() << endl; } else { colorImage = srcImage; } cv::Mat image; if (colorImage.channels() == 1) { image = colorImage; } else { //画像の読み込み。グレースケール画像として読み込む cv::cvtColor(colorImage, image, CV_BGR2GRAY); } ImageScrap scrapImage(image, ImageScrap::RANGE_ALL); //scrapImage.show(); if (pagePos == PagePosition::TOP) { scrapImage.getRow(0).copyTo(rowImage); } else { scrapImage.getRow(scrapImage.getRows() - 1).copyTo(rowImage); } imageHeights.push_back(rowImage.rows);//ページ番号と思われる領域を保存 pageNumbers.push_back(rowImage); cout << "height:" << rowImage.rows << endl; //showImage(rowImage, waitTime); } vector<int> sortedImageHeights; copy(imageHeights.begin(), imageHeights.end(), back_inserter(sortedImageHeights)); sort(sortedImageHeights.begin(), sortedImageHeights.end()); int start; int acceptHeight = 10; for (start = 0; sortedImageHeights[start] < acceptHeight; start++) { } int heightMed = sortedImageHeights[start + (sortedImageHeights.size() - start) / 2]; int minHeight = heightMed * 0.5; int maxHeight = heightMed * 1.5; cout << "height median:" << heightMed << endl; vector<int> isPageNumber; int totalHeight = 0; int maxWidth = 0; int acceptedNum = 0; for (int i = 0; i < imageHeights.size(); i++) { cout << "height:" << imageHeights[i] << endl; bool accept = minHeight <= imageHeights[i] && imageHeights[i] <= maxHeight; isPageNumber.push_back(accept); if (accept) { totalHeight += imageHeights[i]; acceptedNum++; maxWidth = max(maxWidth, pageNumbers[i].cols); } } cout << "total height:" << totalHeight << endl; const int indexWidth = 100; cv::Mat allPageNumImage(totalHeight + acceptedNum, indexWidth + maxWidth, CV_8UC1); allPageNumImage.setTo(255); int currentTop = 0; stringstream sstr; for (int i = 0; i < isPageNumber.size(); i++) { if (isPageNumber[i]) { cv::Mat &page = pageNumbers[i]; ImageScrap scrap(page, ImageScrap::RANGE_COLS); int numOfWords = scrap.getCols(); vector<cv::Mat> wordImages; int pageImageWidth = 0; for (int h = 0; h < numOfWords; h++) { cv::Mat wordImage = scrap.getCol(h); wordImages.push_back(wordImage); pageImageWidth += wordImage.cols; } cv::Mat wordImage(page.rows, pageImageWidth + 1 * numOfWords, CV_8UC1); wordImage.setTo(255); int currentWidth = 0; for (int h = 0; h < wordImages.size(); h++) { cv::Mat& word = wordImages[h]; word.copyTo(cv::Mat(wordImage, cv::Rect(currentWidth, 0, word.cols, word.rows))); currentWidth += word.cols + 1; } //showImage(wordImage); //showImage(page, waitTime); //cv::Mat tmpImage(allPageNumImage, cv::Rect(indexWidth, currentTop, page.cols, page.rows)); //page.copyTo(tmpImage); cv::Mat tmpImage(allPageNumImage, cv::Rect(indexWidth, currentTop, wordImage.cols, wordImage.rows)); wordImage.copyTo(tmpImage); //cv::circle(allPageNumImage, cv::Point(0, currentTop + page.rows), 100, cv::Scalar(255), -1); sstr.str(""); sstr << i << flush; cv::putText(allPageNumImage, sstr.str(), cv::Point(0, currentTop + page.rows - 2), CV_FONT_HERSHEY_COMPLEX, 0.7, cv::Scalar(0), 2); //cv::putText(allPageNumImage, sstr.str(), cv::Point(0, currentTop ), CV_FONT_HERSHEY_COMPLEX, 0.5, cv::Scalar(0), 1); //showImage(allPageNumImage ); currentTop += page.rows; cv::Mat(allPageNumImage, cv::Rect(0, currentTop, allPageNumImage.cols, 1)).setTo(0); currentTop++; //showImage(tmpImage, waitTime); } else { continue; cv::Mat colorImage = cv::imread(fileList[i].absoluteFilePath().toStdString()); showImage(colorImage); } } cout << "total" << endl; showImage(allPageNumImage); destroyWindow(); cout << "saving pagenumber image" << endl; cv::imwrite(savePath.absoluteFilePath().toLocal8Bit().constData(), allPageNumImage); return 0; }
void KTorrentImportPage::handleAccepted () { QString filename = Ui_.FileLocation_->text (); if (!CheckValidity (filename)) return; Entity e = Util::MakeEntity (QUrl::fromLocalFile (filename), QString (), FromUserInitiated, "x-leechcraft/bittorrent-import"); if (Ui_.ImportSettings_->checkState () == Qt::Checked) { QSettings settings (filename, QSettings::IniFormat); if (settings.status () == QSettings::NoError) { QMap<QString, QVariant> additional; settings.beginGroup ("downloads"); if (settings.contains ("completedDir")) additional ["CompletedDir"] = settings.value ("completedDir"); if (settings.contains ("dhtPort")) additional ["DHTPort"] = settings.value ("dhtPort"); if (settings.contains ("dhtSupport")) additional ["DHTSupport"] = settings.value ("dhtSupport"); if (settings.contains ("lastSaveDir")) additional ["LastSaveDir"] = settings.value ("lastSaveDir"); if (settings.contains ("oldTorrentsImported")) additional ["OldTorrentsImported"] = settings.value ("oldTorrentsImported"); if (settings.contains ("saveDir")) additional ["SaveDir"] = settings.value ("saveDir"); if (settings.contains ("TempDir")) { additional ["TempDir"] = settings.value ("TempDir"); QDir tempDir (settings.value ("TempDir").toString ()); if (tempDir.exists () && tempDir.isReadable ()) { QFileInfoList torrentsDir = tempDir.entryInfoList (QStringList ("tor"), QDir::Dirs | QDir::Readable, QDir::Unsorted); QList<QVariant> list; for (int i = 0; i < torrentsDir.size (); ++i) { QMap<QString, QVariant> map; GetTorrentSettings (torrentsDir.at (i).absoluteFilePath (), map); list << map; } additional ["BitTorrentImportTorrents"] = list; } } else { additional ["TempDir"] = "~/.kde/share/apps/ktorrent"; // TODO later } if (settings.contains ("TorrentCopyDir")) additional ["TorrentCopyDir"] = settings.value ("torrentCopyDir"); settings.endGroup (); e.Additional_ ["BitTorrent/SettingsImportData"] = additional; e.Additional_ ["UserVisibleName"] = tr ("KTorrent settings"); } else QMessageBox::critical (this, "LeechCraft", tr ("Could not access or parse KTorrent settings.")); } emit gotEntity (e); }
QString OptionsWindow::getMaskToConfig(int step) { QString mask; QSettings *GlobalSettings = new QSettings("/root/.WiFiHostapdAP/WiFi_Hostapd_AP.conf",QSettings::NativeFormat); // создание нового объекта QDir dir; QFileInfoList list; QString temp_qstring = "default.conf"; QString path; switch(step) { case 0: dir.cd("/root"); if(!dir.cd(".WiFiHostapdAP")) { dir.mkdir(QString("%1").arg(".WiFiHostapdAP")); dir.cd(".WiFiHostapdAP"); } if(!dir.cd("./Mask/")) { dir.mkdir(QString("%1").arg("Mask")); dir.cd("./Mask/"); } if(!dir.cd("./hostapd/")) { dir.mkdir(QString("%1").arg("hostapd")); dir.cd("./hostapd/"); } dir.setFilter(QDir::Files); list = dir.entryInfoList(); if(list.size()==0) { QFile new_Default_Mask("/root/.WiFiHostapdAP/Mask/hostapd/default.conf"); new_Default_Mask.open(QIODevice::Append | QIODevice::Text); QTextStream out(&new_Default_Mask); out << "#Name:Default\n"; out << "#Type:Hostapd\n"; out << "interface=[INTERFACE]\n"; out << "driver=[DRIVER]\n"; out << "ssid=[SSID]\n"; out << "country_code=[COUNTRY_CODE]\n"; out << "[TYPE_AP]\n"; out << "channel=[CHANNEL]\n"; out << "macaddr_acl=0\n"; out << "[HIDEAP]\n"; out << "[PROTECT]"; new_Default_Mask.close(); list.clear(); dir.setFilter(QDir::Files); list = dir.entryInfoList(); } path = "/root/.WiFiHostapdAP/Mask/hostapd/"; for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if(fileInfo.fileName() == GlobalSettings->value("AP/ConfigMask", "default.conf").toString()) temp_qstring = GlobalSettings->value("AP/ConfigMask", "default.conf").toString(); } path += temp_qstring; break; case 1: dir.cd("/root"); if(!dir.cd(".WiFiHostapdAP")) { dir.mkdir(QString("%1").arg(".WiFiHostapdAP")); dir.cd(".WiFiHostapdAP"); } if(!dir.cd("./Mask/")) { dir.mkdir(QString("%1").arg("Mask")); dir.cd("./Mask/"); } if(!dir.cd("./dnsmasq/")) { dir.mkdir(QString("%1").arg("dnsmasq")); dir.cd("./dnsmasq/"); } dir.setFilter(QDir::Files); list = dir.entryInfoList(); if(list.size()==0) { // If the pattern is not present, create the default template QFile new_Default_Mask("/root/.WiFiHostapdAP/Mask/dnsmasq/default.conf"); new_Default_Mask.open(QIODevice::Append | QIODevice::Text); QTextStream out(&new_Default_Mask); out << "#Name:Default\n"; out << "#Type:DNSMASQ\n"; out << "interface=[INTERFACE]\n"; out << "dhcp-range=[RANGE_1],[RANGE_2],[IP_TIME];\n"; out<< "[OpenDNS]"; new_Default_Mask.close(); list.clear(); dir.setFilter(QDir::Files); list = dir.entryInfoList(); } path = "/root/.WiFiHostapdAP/Mask/dnsmasq/"; for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if(fileInfo.fileName() == GlobalSettings->value("AP/ConfigMask1", "default.conf").toString()) temp_qstring = GlobalSettings->value("AP/ConfigMask1", "default.conf").toString(); } path += temp_qstring; break; } QFile file_mask(path); file_mask.open(QIODevice::ReadOnly); QTextStream in(&file_mask); mask = in.read(10240); QString temp1 = ""; // HOSTAPD mask.replace("[INTERFACE]", GlobalSettings->value("AP/Iface", "wlan0").toString()); mask.replace("[DRIVER]", GlobalSettings->value("AP/drive", "nl80211").toString()); mask.replace("[SSID]", GlobalSettings->value("AP/SSID", "MyWiFI_AP").toString()); mask.replace("[COUNTRY_CODE]", GlobalSettings->value("AP/CountryCode", "RU").toString()); mask.replace("[CHANNEL]", GlobalSettings->value("AP/Channels", "7").toString()); ///////////////////////////////////////////////////////////////////////// // Type AP ///////////////////////////////////////////////////////////////////////// if(GlobalSettings->value("AP/TypeAP", "g").toString()=="ac") { temp1 = "hw_mode=ag\nwme_enabled=1\nieee80211n=1\nht_capab=[HT40+][SHORT-GI-40][DSSS_CCK-40]"; temp1.append("\nieee80211ac=1\nvht_capab=[SHORT-GI-80]\nvht_oper_chwidth=1"); } else if(GlobalSettings->value("AP/TypeAP", "g").toString()=="n") temp1 = "hw_mode=ag\nwme_enabled=1\nieee80211n=1\nht_capab=[HT40+][SHORT-GI-40][DSSS_CCK-40]"; else if(GlobalSettings->value("AP/TypeAP", "g").toString()=="g") temp1 = "hw_mode=g"; //a else temp1 = "\n"; mask.replace("[TYPE_AP]", temp1); temp1.clear(); ///////////////////////////////////////////////////////////////////////// // Разбираемся с защитой ///////////////////////////////////////////////////////////////////////// if(GlobalSettings->value("AP/Protection", "WPA3").toString()=="WPA3") { // Составляем маску для WPA temp1 = "wpa=3\nwpa_key_mgmt=WPA-PSK\nwpa_pairwise=TKIP CCMP\nwpa_passphrase="; temp1.append(GlobalSettings->value("AP/Password", "MyWiFI_AP").toString()); } ///////////////////////////////////////////////////////////////////////// else if(GlobalSettings->value("AP/Protection", "WPA3").toString()=="WEP") { // Составляем маску для WEP temp1 = "wep_default_key=0\nwep_key_len_broadcast=13\nwep_key_len_unicast=13\nwep_rekey_period=300\nwep_key0="; temp1.append(GlobalSettings->value("AP/Password", "MyWiFI_AP").toString()); } else temp1 = ""; mask.replace("[PROTECT]", temp1); if(GlobalSettings->value("AP/ShowSSID", false).toBool()) mask.replace("[HIDEAP]", "ignore_broadcast_ssid=2"); else mask.replace("[HIDEAP]", ""); temp1.clear(); // DNSMASQ mask.replace("[RANGE_1]", GlobalSettings->value("DHCP/IP_CLIENT1", "192.168.0.2").toString()); mask.replace("[RANGE_2]", GlobalSettings->value("DHCP/IP_CLIENT2", "192.168.0.225").toString()); mask.replace("[INTERFACE_INTERNET]", GlobalSettings->value("DHCP/Internet_iface", "eth0").toString()); if(GlobalSettings->value("DHCP/UseOpenDNS", true).toBool()) mask.replace("[OpenDNS]", "server=/www.google.com/8.8.8.8"); else mask.replace("[OpenDNS]", ""); switch(GlobalSettings->value("DHCP/IP_time", 2).toInt()) { case(0): mask.replace("[IP_TIME]", "10m"); break; case(1): mask.replace("[IP_TIME]", "30m"); break; case(2): mask.replace("[IP_TIME]", "1h"); break; case(3): mask.replace("[IP_TIME]", "2h"); break; case(4): mask.replace("[IP_TIME]", "6h"); break; case(5): mask.replace("[IP_TIME]", "12h"); break; } file_mask.close(); delete GlobalSettings; return mask; }
void BasicBundleProvider::mergeBundlesForKit(ProjectExplorer::Kit *kit , QmlJS::QmlLanguageBundles &bundles , const QHash<QString,QString> &replacements) { typedef QmlJS::Document Doc; QHash<QString,QString> myReplacements = replacements; bundles.mergeBundleForLanguage(Doc::QmlQbsLanguage, defaultQbsBundle()); bundles.mergeBundleForLanguage(Doc::QmlTypeInfoLanguage, defaultQmltypesBundle()); bundles.mergeBundleForLanguage(Doc::QmlProjectLanguage, defaultQmlprojectBundle()); QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(kit); if (!qtVersion) { QmlBundle b1(defaultQt4QtQuick1Bundle()); bundles.mergeBundleForLanguage(Doc::QmlLanguage, b1); bundles.mergeBundleForLanguage(Doc::QmlQtQuick1Language, b1); QmlBundle b11(defaultQt5QtQuick1Bundle()); bundles.mergeBundleForLanguage(Doc::QmlLanguage, b11); bundles.mergeBundleForLanguage(Doc::QmlQtQuick1Language, b11); QmlBundle b2(defaultQt5QtQuick2Bundle()); bundles.mergeBundleForLanguage(Doc::QmlLanguage, b2); bundles.mergeBundleForLanguage(Doc::QmlQtQuick2Language, b2); return; } QString qtImportsPath = qtVersion->qmakeProperty("QT_INSTALL_IMPORTS"); QString qtQmlPath = qtVersion->qmakeProperty("QT_INSTALL_QML"); Core::FeatureSet features = qtVersion->availableFeatures(); if (features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK)) || features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1)) || features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1_1))) { myReplacements.insert(QLatin1String("$(CURRENT_DIRECTORY)"), qtImportsPath); QDir qtQuick1Bundles(qtImportsPath); qtQuick1Bundles.setNameFilters(QStringList(QLatin1String("*-bundle.json"))); QmlBundle qtQuick1Bundle; QFileInfoList list = qtQuick1Bundles.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QmlBundle bAtt; QStringList errors; if (!bAtt.readFrom(list.value(i).filePath(), &errors)) qWarning() << "BasicBundleProvider: ERROR reading " << list[i].filePath() << " : " << errors; qtQuick1Bundle.merge(bAtt); } if (!qtQuick1Bundle.supportedImports().contains(QLatin1String("QtQuick 1."), QmlJS::PersistentTrie::Partial)) { if (qtVersion->qtVersion().majorVersion == 4) qtQuick1Bundle.merge(defaultQt4QtQuick1Bundle()); else if (qtVersion->qtVersion().majorVersion > 4) qtQuick1Bundle.merge(defaultQt5QtQuick1Bundle()); } qtQuick1Bundle.replaceVars(myReplacements); bundles.mergeBundleForLanguage(Doc::QmlLanguage, qtQuick1Bundle); bundles.mergeBundleForLanguage(Doc::QmlQtQuick1Language, qtQuick1Bundle); } if (features.contains(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_2))) { myReplacements.insert(QLatin1String("$(CURRENT_DIRECTORY)"), qtQmlPath); QDir qtQuick2Bundles(qtQmlPath); qtQuick2Bundles.setNameFilters(QStringList(QLatin1String("*-bundle.json"))); QmlBundle qtQuick2Bundle; QFileInfoList list = qtQuick2Bundles.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QmlBundle bAtt; QStringList errors; if (!bAtt.readFrom(list.value(i).filePath(), &errors)) qWarning() << "BasicBundleProvider: ERROR reading " << list[i].filePath() << " : " << errors; qtQuick2Bundle.merge(bAtt); } if (!qtQuick2Bundle.supportedImports().contains(QLatin1String("QtQuick 2."), QmlJS::PersistentTrie::Partial)) { qtQuick2Bundle.merge(defaultQt5QtQuick2Bundle()); } qtQuick2Bundle.replaceVars(myReplacements); bundles.mergeBundleForLanguage(Doc::QmlLanguage, qtQuick2Bundle); bundles.mergeBundleForLanguage(Doc::QmlQtQuick2Language, qtQuick2Bundle); } }
void ScanDiskThirdPartyPM::scan(const QString& path, Job* job, int level, QStringList& ignore) const { if (ignore.contains(path)) return; QDir aDir(path); QMap<QString, QString> path2sha1; DBRepository* r = DBRepository::getDefault(); QString err; QList<PackageVersion*> packageVersions = r->getPackageVersionsWithDetectFiles(&err); // qDebug() << "package versions with detect files: " << packageVersions.count(); if (!err.isEmpty()) job->setErrorMessage(err); for (int i = 0; i < packageVersions.count(); i++) { if (!job->shouldProceed()) break; PackageVersion* pv = packageVersions.at(i); if (!pv->installed() && pv->detectFiles.count() > 0) { boolean ok = true; for (int j = 0; j < pv->detectFiles.count(); j++) { bool fileOK = false; DetectFile* df = pv->detectFiles.at(j); if (aDir.exists(df->path)) { QString fullPath = path + "\\" + df->path; QFileInfo f(fullPath); if (f.isFile() && f.isReadable()) { QString sha1 = path2sha1.value(df->path); if (sha1.isEmpty()) { sha1 = WPMUtils::sha1(fullPath); path2sha1[df->path] = sha1; } if (df->sha1 == sha1) { fileOK = true; } } } if (!fileOK) { ok = false; break; } } if (ok) { pv->setPath(path); return; } } } if (job && !job->isCancelled()) { QFileInfoList entries = aDir.entryInfoList( QDir::NoDotAndDotDot | QDir::Dirs); int count = entries.size(); for (int idx = 0; idx < count; idx++) { if (job && job->isCancelled()) break; QFileInfo entryInfo = entries[idx]; QString name = entryInfo.fileName(); if (job) { job->setTitle(name); if (job->isCancelled()) break; } Job* djob; if (level < 2) djob = job->newSubJob(1.0 / count); else djob = 0; scan(path + "\\" + name.toLower(), djob, level + 1, ignore); if (job) { job->setProgress(((double) idx) / count); } } } qDeleteAll(packageVersions); if (job) job->complete(); }
void MainWindow::detectSavePath() { int found = 0; GameFWL game = games[gameidx]; QStringList possiblepaths; QString detectedpath; // We add the possible paths in documents if(!documentspath.isEmpty()) foreach(QString path, game.getPathInDocs()) possiblepaths.push_back(QDir::toNativeSeparators(documentspath + path)); // We add the possible paths in Steam Cloud QString steamcloudpath; if(!steampath.isEmpty() && !game.getPathInSteamCloud().isEmpty()) { steamcloudpath = steampath + QString("userdata") + QDir::separator(); // We look in each Steam user folder QDir userdata(steamcloudpath); QFileInfoList steamusers = userdata.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time); for(int i=0; i<steamusers.size() && !found; ++i) { QString user = QDir::toNativeSeparators(steamusers[i].canonicalFilePath() + QDir::separator()); foreach(QString appid, game.getPathInSteamCloud()) possiblepaths.push_back(QDir::toNativeSeparators(user + appid + QString("/remote"))); } } // We add the possible paths in SteamApps QString steamappspath; if(!steampath.isEmpty()) { steamappspath = steampath + QString("steamapps") + QDir::separator(); foreach(QString path, game.getPathInSteamApps()) possiblepaths.push_back(QDir::toNativeSeparators(steamappspath + path)); } // We add the possible paths in "appdata" if(!appdatapath.isEmpty()) foreach(QString path, game.getPathInAppData()) possiblepaths.push_back(QDir::toNativeSeparators(appdatapath + path)); // We add the possible paths in "local" if(!localpath.isEmpty()) foreach(QString path, game.getPathInLocal()) possiblepaths.push_back(QDir::toNativeSeparators(localpath + path)); // We add the possible paths in "public" if(!publicpath.isEmpty()) foreach(QString path, game.getPathInPublic()) possiblepaths.push_back(QDir::toNativeSeparators(publicpath + path)); // We add the possible paths in "publicdata" if(!publicdatapath.isEmpty()) foreach(QString path, game.getPathInPublicData()) possiblepaths.push_back(QDir::toNativeSeparators(publicdatapath + path)); for(int i=0; i<possiblepaths.size() && found<1; ++i) { QDir folder(possiblepaths[i]); QFileInfoList files = folder.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Time); foreach(QFileInfo file, files) { if(file.completeSuffix() == game.getExtension()) ++found; if(found > 0) detectedpath = folder.canonicalPath(); } if(found == 0) { QFileInfoList subfolders = folder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time); foreach(QFileInfo subfolder, subfolders) { QDir subdir(subfolder.canonicalFilePath()); QFileInfoList subfiles = subdir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Time); foreach(QFileInfo subfile, subfiles) { if(subfile.completeSuffix() == game.getExtension()) ++found; if(found > 0) detectedpath = subdir.canonicalPath(); } } }
bool WPSRun::initialize() { if(work_folder == "") { qDebug()<<"work_folder == """; return false; } ClearDir(work_folder); if(!p_namelist_tool->writeasciiWrf(work_folder)) { qDebug()<<"Ошибка при создании namelist.wps"; return false; } if(!p_namelist_tool->writeasciiWps(work_folder)) { qDebug()<<"Ошибка при создании namelist.input"; return false; } if(!p_namelist_tool->writeasciiOBSPROC(work_folder)) { qDebug()<<"Ошибка при создании namelist.obsproc"; return false; } if(!p_namelist_tool->writeasciiARWPost(work_folder)) { qDebug()<<"Ошибка при создании namelist.ARWPost"; return false; } ///////// WPS QFile::link(wps_root+"geogrid/src/geogrid.exe", work_folder+"geogrid.exe"); QFile::link(wps_root+"geogrid/GEOGRID.TBL.ARW", work_folder+"GEOGRID.TBL"); QFile::link(wps_root+"metgrid/src/metgrid.exe", work_folder+"metgrid.exe"); QFile::link(wps_root+"metgrid/METGRID.TBL.ARW", work_folder+"METGRID.TBL"); QFile::link(wps_root+"ungrib/src/ungrib.exe", work_folder+"ungrib.exe"); QFile::link(wps_root+"ungrib/Variable_Tables/Vtable.GFS", work_folder+"Vtable"); //////////END WPS ///////// WRF QDir dir(wrf_root+"run"); dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); QFile::link(fileInfo.filePath(),work_folder+fileInfo.fileName()); } QFile::link(wrf_root+"main/ndown.exe", work_folder+"ndown.exe"); QFile::link(wrf_root+"main/nup.exe", work_folder+"nup.exe"); QFile::link(wrf_root+"main/real.exe", work_folder+"real.exe"); QFile::link(wrf_root+"main/tc.exe", work_folder+"tc.exe"); QFile::link(wrf_root+"main/wrf.exe", work_folder+"wrf.exe"); //////////END WRF QFile::link(wrf_root+"/MaxTools/mpd.hosts", work_folder+"mpd.hosts"); QFile::link(wrf_root+"/MaxTools/myhosts", work_folder+"myhosts"); // Link NCL files to draw images QFile::link(wrf_root+"/MaxTools/NCLrun.sh", work_folder+"NCLrun.sh"); QFile::link(wrf_root+"/MaxTools/NCLscript.ncl", work_folder+"NCLscript.ncl"); QFile::link(arwpost_root+"src/ARWpost.exe", work_folder+"ARWpost.exe"); GribLink(grib_files,work_folder); //////////WRFDA QFile::link(wrfda_root+"/var/da/da_wrfvar.exe", work_folder+"da_wrfvar.exe"); //Ассимиляция QFile::link(wrfda_root+"/var/run/be.dat.cv3", work_folder+"be.dat"); //link background error statistics as be.dat QFile::link(wrfda_root+"/var/da/da_update_bc.exe", work_folder+"da_update_bc.exe"); //Обновление граничных условий QFile::link(wrf_root+"/MaxTools/parame.in", work_folder+"parame.in"); // namelist для da_update_bc.exe QFile::link(wrfda_root+"/var/obsproc/src/obsproc.exe", work_folder+"obsproc.exe"); //Препроцессинг метеоинформации в LITTLE_R QFile::link(wrfda_root+"/var/obsproc/obserr.txt", work_folder+"obserr.txt"); //Препроцессинг метеоинформации в LITTLE_R QString filename = work_folder + "ob.little_r"; Little_r_fm12* little_r_fm12 = new Little_r_fm12(this); /**< указатель на Класс для записи в Little_r приземных наблюдений*/ little_r_fm12->OpenFile(filename); //Открываем файл для записи QDateTime date = p_namelist_tool->GetDateTimeStart(); for(int index=26001;index<26008;index++) { little_r_fm12->writeRZD_DB_data(index,date); //Пишем станцию } little_r_fm12->CloseFile(); // Закрываем файл //////////END WRFDA return true; }
void SelectFile::callSWWYL() { QString inFile; QString inFile_2d; QString outPath; QDir dir(root_path+"/yubao/wenyanliu/3d_pic/"); QFileInfoList list; QFile file_init("initial.txt"); QTextStream fileOut(&file_init); inFile = ui->lineEdit->text(); outPath = ui->lineEdit_3->text(); QFileInfo fi(inFile); if(inFile.isEmpty() || outPath.isEmpty()){ QMessageBox::warning(0,"Warning",QStringLiteral("请选择输入文件和输出路径"),QMessageBox::Yes);//查看路径 }else { file_date = fi.fileName().mid(12,8); qDebug() << file_date << "1111111"; // return; //载入loading…动画 loadMovie->start(); ui->label_5->show(); // 清空原文件,复制用户选择的文件到程序运行目录,并重命名 // QFile::remove(root_path+"/yubao/wenyanliu/ocean_his_4750.nc"); list = dir.entryInfoList(); for(int i=0; i<list.size(); i++) { // QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes); QFile::remove(list.at(i).filePath()); } // dir = QDir("C:/pic/SWWYL_3d"); // list = dir.entryInfoList(); // for(int i=0; i<list.size(); i++) // { //// QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes); // QFile::remove(list.at(i).filePath()); // } // dir = QDir("C:/pic/SWWYL_2d"); // list = dir.entryInfoList(); // for(int i=0; i<list.size(); i++) // { //// QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes); // QFile::remove(list.at(i).filePath()); // } copyFileToPath(inFile, root_path+"/yubao/wenyanliu/",true); inFile_2d = fi.absolutePath()+"/2d/ecs_new_"+file_date+".nc"; qDebug() << inFile_2d; copyFileToPath(inFile_2d, root_path+"/yubao/wenyanliu/",true); //m_fsw->removePaths(m_fsw->directories()); m_outPath = outPath; m_fsw->addPath( root_path+"/yubao/wenyanliu/3d_pic/"); // 写配置文件 initial1.txt 调用程序 qDebug() << root_path; QDir::setCurrent(root_path+"/yubao/wenyanliu/"); file_init.open(QIODevice::WriteOnly); fileOut << file_date << "\n"; file_init.close(); QProcess::startDetached("swwyl.exe"); // QProcess::execute("swwyl.exe"); // 还原系统路径 QDir::setCurrent(root_path); } }
QTreeWidgetItem * FormMain::processPath( const QString & path, qint64 & dirSize, const QListWidget & exc, int parent_id ) { statusBar()->showMessage( path ); qApp->processEvents(); QDir dir( path ); if ( ! dir.exists() ) return 0; const int dbDirId = dbSaveFolder( dir, parent_id ); if ( dbDirId == -1 ) return 0; QTreeWidgetItem * item = new QTreeWidgetItem(); item->setIcon( 0, QIcon(":/blue.png" ) ); if ( dir.isRoot() ) item->setText( 0, dir.rootPath() ); else item->setText( 0, dir.dirName() ); item->setData( 0, Qt::UserRole, dbDirId ); qint64 dir_size = 0; // folders QFileInfoList list = dir.entryInfoList( QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Drives, QDir::Name ); const int dirCount = list.size(); for ( int i = 0; i < list.size(); ++i ) { /* if ( exclude( list[ i ] ) ) continue; */ bool e = false; for ( int j = 0; j < exc.count(); ++j ) if ( list[ i ].absoluteFilePath() == exc.item( j )->text() ) { e = true; break; } if ( e ) continue; item->addChild( processPath( list[ i ].absoluteFilePath(), dir_size, exc, dbDirId ) ); } // files list = dir.entryInfoList( QDir::Files | QDir::Hidden | QDir::System, QDir::Type ); #ifdef DEBUG qDebug() << "files count: " << dir.dirName() << list.size(); #endif for ( int i = 0; i < list.size(); ++ i ) { dbSaveFile( list[ i ], dbDirId ); dir_size += list[ i ].size(); } // percents QHash< QString, int > counts; for ( int i = 0; i < list.size(); ++i ) { const QString suffix = list[ i ].suffix().toLower(); if ( counts.contains( suffix ) ) counts[ suffix ] += 1; else counts[ suffix ] = 1; } dbSavePercents( counts, dbDirId, dirCount + list.size() ); dbSaveFolderSize( dbDirId, dir_size ); dirSize += dir_size; return item; }