void WWidgetNode::setupNodeChildren() { QFileInfo info(m_strPath); if (!info.isDir()) { qDebug() << "[ERROR] Not a directory in WWidgetNode::setupNodeChildren"; } QDir dir(info.absoluteFilePath()); QFileInfo newinfo; QFileInfoList list; WWidgetNode * child; int count = 0; // loop all entries in dir for (int i = 0; i < dir.entryInfoList().count(); i++) { // get entry of this dir newinfo = dir.entryInfoList().at(i); // continue if entry is not a dir if (!newinfo.fileName().compare(".") || !newinfo.fileName().compare("..")) { continue; } // depending on this dir type choose what to do with the cuirrent entry switch (m_intNodeType) { case ROOT: if (newinfo.isDir()) { // create category child QString strTemp = newinfo.absoluteFilePath(); child = new WWidgetNode(CATEGORY, strTemp, count, this); childWWidgetNodes.append(child); count++; } break; case CATEGORY: if (newinfo.isDir()) { list = QDir(newinfo.absoluteFilePath()).entryInfoList(); for (int j = 0; j < list.count(); j++) { // check if selected child dir contains a project file if (list.at(j).filePath().contains(".wtw")) { // create widget child QString strTemp = newinfo.absoluteFilePath(); child = new WWidgetNode(WIDGET, strTemp, count, this); // discirminate some widgets (do not add to WWidgetNode tree but yes to QObject tree) QString strName = child->getName(); if (strName.compare("WTabItem" ) != 0 && strName.compare("WMenuItem" ) != 0 && strName.compare("WPopupItem") != 0) { // append to list of widgets childWWidgetNodes.append(child); count++; } } } } break; case WIDGET: if (newinfo.isFile() && newinfo.fileName().contains(".wtw")) { m_strName = newinfo.baseName(); // must be class name QFile file(newinfo.absoluteFilePath()); if (!file.open(QFile::ReadOnly)) { qDebug() << "[ERROR] Opening file in WWidgetNode::setupNodeChildren : " << newinfo.absoluteFilePath(); } m_byteConfig = file.readAll(); } else if (newinfo.isDir() && QDir(newinfo.absoluteFilePath()).dirName().compare("icon", Qt::CaseInsensitive) == 0) { list = QDir(newinfo.absoluteFilePath()).entryInfoList(); for (int j = 0; j < list.count(); j++) { // check if selected child is icon file if (list.at(j).baseName().compare(dir.dirName()) == 0) { // get icon m_icon = QIcon(list.at(j).absoluteFilePath()); } } } break; default: break; } } if (m_intNodeType == WIDGET) { Icons::GetCache().insert(m_strName, m_icon); } // set name for category if (m_intNodeType == CATEGORY && count > 0) { m_strName = dir.dirName(); } // just in case updateRowNumbers(); }
bool CopyDir::copyDirAndFiles(QString srcDir, QString dstDir, QStringList *nameExcludeFilter, QStringList *nameIncludeFilter, QStringList *srcFileList, QStringList *dstFileList) { if(mExitNow) return false; mutex.lock(); if(mPause) { pauseThreads.wait(&mutex); } mutex.unlock(); bool isFirst = false; if(srcFileList == NULL) { isFirst = true; srcFileList = new QStringList; dstFileList = new QStringList; } QDir rootPath(QDir::toNativeSeparators(srcDir)); QDir destPath(QDir::toNativeSeparators(dstDir)); rootPath.setFilter(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files); QFileInfoList entryList = rootPath.entryInfoList(); QRegExp rx; rx.setPatternSyntax(QRegExp::Wildcard); bool moveOn; QString dirName; for(int i=0; i<entryList.size(); i++) { if(mExitNow) { return false; } QFileInfo entry = entryList.at(i); // we do exclude list checking, a lot easier to exclude a couple file types than list all of the included ones moveOn = false; for(int j=0; j<nameExcludeFilter->size(); j++) { rx.setPattern(nameExcludeFilter->at(j)); QString name = entry.absoluteFilePath(); if(rx.exactMatch(name)) { moveOn = true; // now let's check to make sure this specific file isn't on the include list, that overrides exluded types for(int k=0; k<nameIncludeFilter->size(); k++) { // compare the file to the include file adding the root directory (the include filter should be relative files) QString filePath = QDir::toNativeSeparators(entry.filePath()); QString include = QDir::toNativeSeparators(mRootDir + "/" + nameIncludeFilter->at(k)); if(include.compare(filePath) == 0) { moveOn = false; break; } } break; } } // if we have been matched against the exclude list then lets skip if(moveOn) continue; // now we copy it over if(entry.isDir()) { dirName = entry.fileName(); bool pathCreated = false; QString targetSubPath(QDir::separator() + dirName); if(QDir(destPath.path() + targetSubPath).exists()) { pathCreated = true; } else { pathCreated = destPath.mkdir(dirName); } if(pathCreated) { copyDirAndFiles(srcDir + QDir::separator() + dirName, destPath.path() + QDir::separator() + dirName, nameExcludeFilter, nameIncludeFilter, srcFileList, dstFileList); } } else if(entry.isFile()) { srcFileList->push_back(entry.absoluteFilePath()); dstFileList->push_back(dstDir + QDir::separator() + entry.fileName()); } } if(isFirst) { emit updateFileCount(srcFileList->size()); for(int i=0; i<srcFileList->size(); i++) { if(mExitNow) return false; QFile fileEntry(srcFileList->at(i)); fileEntry.copy(dstFileList->at(i)); mutex.lock(); if(mPause) { pauseThreads.wait(&mutex); } mutex.unlock(); if(mExitNow) return false; emit updateFileProgress(i+1, QFileInfo(fileEntry.fileName()).fileName()); } } return true; }
void ScanFileOrFolder::listFolder(QFileInfo source,QFileInfo destination) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("source: %1 (%2), destination: %3 (%4)").arg(source.absoluteFilePath()).arg(source.isSymLink()).arg(destination.absoluteFilePath()).arg(destination.isSymLink())); if(stopIt) return; destination=resolvDestination(destination); if(stopIt) return; if(fileErrorAction==FileError_Skip) return; //if is same if(source.absoluteFilePath()==destination.absoluteFilePath()) { emit folderAlreadyExists(source,destination,true); waitOneAction.acquire(); QString destinationSuffixPath; switch(folderExistsAction) { case FolderExists_Merge: break; case FolderExists_Skip: return; break; case FolderExists_Rename: ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination before rename: "+destination.absoluteFilePath()); if(newName.isEmpty()) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"pattern: "+folder_isolation.pattern()); //resolv the new name destinationSuffixPath=destination.baseName(); int num=1; do { if(num==1) { if(firstRenamingRule.isEmpty()) destinationSuffixPath=tr("%1 - copy").arg(destination.baseName()); else { destinationSuffixPath=firstRenamingRule; destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName()); } } else { if(otherRenamingRule.isEmpty()) destinationSuffixPath=tr("%1 - copy (%2)").arg(destination.baseName()).arg(num); else { destinationSuffixPath=otherRenamingRule; destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName()); destinationSuffixPath.replace(QStringLiteral("%number%"),QString::number(num)); } } num++; if(destination.completeSuffix().isEmpty()) destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath); else destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath+text_dot+destination.completeSuffix()); } while(destination.exists()); } else { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"use new name: "+newName); destinationSuffixPath = newName; } destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath); ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination after rename: "+destination.absoluteFilePath()); break; default: return; break; } } //check if destination exists if(checkDestinationExists) { if(destination.exists()) { emit folderAlreadyExists(source,destination,false); waitOneAction.acquire(); QString destinationSuffixPath; switch(folderExistsAction) { case FolderExists_Merge: break; case FolderExists_Skip: return; break; case FolderExists_Rename: ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination before rename: "+destination.absoluteFilePath()); if(newName.isEmpty()) { //resolv the new name QFileInfo destinationInfo; int num=1; do { if(num==1) { if(firstRenamingRule.isEmpty()) destinationSuffixPath=tr("%1 - copy").arg(destination.baseName()); else { destinationSuffixPath=firstRenamingRule; destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName()); } } else { if(otherRenamingRule.isEmpty()) destinationSuffixPath=tr("%1 - copy (%2)").arg(destination.baseName()).arg(num); else { destinationSuffixPath=otherRenamingRule; destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName()); destinationSuffixPath.replace(QStringLiteral("%number%"),QString::number(num)); } } destinationInfo.setFile(destinationInfo.absolutePath()+text_slash+destinationSuffixPath); num++; } while(destinationInfo.exists()); } else { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"use new name: "+newName); destinationSuffixPath = newName; } if(destination.completeSuffix().isEmpty()) destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath); else destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath+QStringLiteral(".")+destination.completeSuffix()); ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination after rename: "+destination.absoluteFilePath()); break; default: return; break; } } } //do source check //check of source is readable do { fileErrorAction=FileError_NotSet; if(!source.isReadable() || !source.isExecutable() || !source.exists() || !source.isDir()) { if(!source.isDir()) emit errorOnFolder(source,tr("This is not a folder")); else if(!source.exists()) emit errorOnFolder(source,tr("The folder does exists")); else emit errorOnFolder(source,tr("The folder is not readable")); waitOneAction.acquire(); ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"actionNum: "+QString::number(fileErrorAction)); } } while(fileErrorAction==FileError_Retry); do { QDir tempDir(source.absoluteFilePath()); fileErrorAction=FileError_NotSet; if(!tempDir.isReadable() || !tempDir.exists()) { emit errorOnFolder(source,tr("Problem with name encoding")); waitOneAction.acquire(); ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"actionNum: "+QString::number(fileErrorAction)); } } while(fileErrorAction==FileError_Retry); if(stopIt) return; /// \todo check here if the folder is not readable or not exists QFileInfoList entryList; if(copyListOrder) entryList=QDir(source.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System,QDir::DirsFirst|QDir::Name|QDir::IgnoreCase);//possible wait time here else entryList=QDir(source.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System);//possible wait time here if(stopIt) return; int sizeEntryList=entryList.size(); emit newFolderListing(source.absoluteFilePath()); if(mode!=Ultracopier::Move) emit addToMkPath(source,destination,sizeEntryList); for (int index=0;index<sizeEntryList;++index) { QFileInfo fileInfo=entryList.at(index); if(stopIt) return; if(haveFilters) { if(reloadTheNewFilters) { QMutexLocker lock(&filtersMutex); QCoreApplication::processEvents(QEventLoop::AllEvents); reloadTheNewFilters=false; this->include=this->include_send; this->exclude=this->exclude_send; } QString fileName=fileInfo.fileName(); if(fileInfo.isDir() && !fileInfo.isSymLink()) { bool excluded=false,included=(include.size()==0); int filters_index=0; while(filters_index<exclude.size()) { if(exclude.at(filters_index).apply_on==ApplyOn_folder || exclude.at(filters_index).apply_on==ApplyOn_fileAndFolder) { if(fileName.contains(exclude.at(filters_index).regex)) { excluded=true; break; } } filters_index++; } if(excluded) {} else { filters_index=0; while(filters_index<include.size()) { if(include.at(filters_index).apply_on==ApplyOn_folder || include.at(filters_index).apply_on==ApplyOn_fileAndFolder) { if(fileName.contains(include.at(filters_index).regex)) { included=true; break; } } filters_index++; } if(!included) {} else listFolder(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName()); } } else { bool excluded=false,included=(include.size()==0); int filters_index=0; while(filters_index<exclude.size()) { if(exclude.at(filters_index).apply_on==ApplyOn_file || exclude.at(filters_index).apply_on==ApplyOn_fileAndFolder) { if(fileName.contains(exclude.at(filters_index).regex)) { excluded=true; break; } } filters_index++; } if(excluded) {} else { filters_index=0; while(filters_index<include.size()) { if(include.at(filters_index).apply_on==ApplyOn_file || include.at(filters_index).apply_on==ApplyOn_fileAndFolder) { if(fileName.contains(include.at(filters_index).regex)) { included=true; break; } } filters_index++; } if(!included) {} else #ifndef ULTRACOPIER_PLUGIN_RSYNC emit fileTransfer(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName(),mode); #else { bool sendToTransfer=false; if(!rsync) sendToTransfer=true; else if(!QFile::exists(destination.absoluteFilePath()+"/"+fileInfo.fileName())) sendToTransfer=true; else if(fileInfo.lastModified()!=QFileInfo(destination.absoluteFilePath()+"/"+fileInfo.fileName()).lastModified()) sendToTransfer=true; if(sendToTransfer) emit fileTransfer(fileInfo.absoluteFilePath(),destination.absoluteFilePath()+"/"+fileInfo.fileName(),mode); } #endif } } } else { if(fileInfo.isDir() && !fileInfo.isSymLink())//possible wait time here //listFolder(source,destination,suffixPath+fileInfo.fileName()+QDir::separator()); listFolder(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName());//put unix separator because it's transformed into that's under windows too else #ifndef ULTRACOPIER_PLUGIN_RSYNC emit fileTransfer(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName(),mode); #else { bool sendToTransfer=false; if(!rsync) sendToTransfer=true; else if(!QFile::exists(destination.absoluteFilePath()+"/"+fileInfo.fileName())) sendToTransfer=true; else if(fileInfo.lastModified()!=QFileInfo(destination.absoluteFilePath()+"/"+fileInfo.fileName()).lastModified()) sendToTransfer=true; if(sendToTransfer) emit fileTransfer(fileInfo.absoluteFilePath(),destination.absoluteFilePath()+"/"+fileInfo.fileName(),mode); } #endif } } #ifdef ULTRACOPIER_PLUGIN_RSYNC if(rsync) { //check the reverse path here QFileInfoList entryListDestination; if(copyListOrder) entryListDestination=QDir(destination.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System,QDir::DirsFirst|QDir::Name|QDir::IgnoreCase);//possible wait time here else entryListDestination=QDir(destination.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System);//possible wait time here int sizeEntryListDestination=entryListDestination.size(); int index=0; for (int indexDestination=0;indexDestination<sizeEntryListDestination;++indexDestination) { index=0; while(index<sizeEntryList) { if(entryListDestination.at(indexDestination).fileName()==entryList.at(index).fileName()) break; index++; } if(index==sizeEntryList) { //then not found, need be remove emit addToRmForRsync(entryListDestination.at(indexDestination)); } } return; } #endif if(mode==Ultracopier::Move) { ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"source: "+source.absoluteFilePath()+", sizeEntryList: "+QString::number(sizeEntryList)); emit addToMovePath(source,destination,sizeEntryList); } }
void IconSettings::cmdGetIcon_Click(){ QString fileName, searchPath=this->prefix_path; if ((!txtWorkDir->text().isEmpty()) and (QDir(txtWorkDir->text()).exists())){ searchPath = txtWorkDir->text(); } else { if (QDir(this->prefix_path).exists()){ searchPath=this->prefix_path; } else { searchPath=QDir::homePath(); } } QFileDialog dialog(this); dialog.setFilter(QDir::Dirs | QDir::Files | QDir::Hidden); dialog.setFileMode(QFileDialog::ExistingFile); dialog.setWindowTitle(tr("Open image file")); #if QT_VERSION >= 0x040500 if (CoreLib->getSetting("advanced", "useNativeFileDialog", false, 1)==0){ dialog.setOptions(QFileDialog::DontUseNativeDialog); } #endif if ((!iconPath.isEmpty()) and (QFile(iconPath).exists())){ QStringList list = iconPath.split("/"); searchPath = iconPath.left(iconPath.length() - list.last().length()); } dialog.setDirectory(searchPath); #ifndef WITH_ICOUTILS dialog.setNameFilter(tr("Image files (*.png *.jpg *.gif *.bmp *.xpm)")); #else dialog.setNameFilter(tr("Image and Win32 binary files (*.png *.jpg *.gif *.bmp *.xpm *.exe *.dll);;Image files (*.png *.jpg *.gif *.bmp *.xpm);;Win32 Executable (*.exe);;Win32 Shared libraies (*.dll);;Win32 Executable and Shared libraies (*.exe *.dll)")); #endif //dialog.setSidebarUrls(add_prefix_urls); if (dialog.exec()) fileName = dialog.selectedFiles().first(); if(!fileName.isEmpty()){ if ((fileName.toLower().right(3)!="exe") && (fileName.toLower().right(3)!="dll")){ cmdGetIcon->setIcon (QIcon(fileName)); } else { QStringList args; args << "-x"; args << "-t" << "14"; QString tmpDir=""; QStringList list1 = fileName.split("/"); tmpDir.append(QDir::homePath()); tmpDir.append("/.config/"); tmpDir.append(APP_SHORT_NAME); tmpDir.append("/tmp/"); tmpDir.append(list1.last()); QDir tmp(tmpDir); tmp.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); QFileInfoList list = tmp.entryInfoList(); if (tmp.exists(tmpDir)){ for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if (!tmp.remove(fileInfo.filePath())) qDebug()<<"[EE] - Can't delete files at: "<<fileInfo.filePath(); } } else { if (!tmp.mkdir(tmpDir)){ qDebug()<<"[EE] - Can't create temp directory at: "<<tmpDir; } } args << "-o" << tmpDir; args << fileName; Process exportProcess(args, CoreLib->getSetting("icotool", "wrestool").toString(), QDir::homePath(), tr("Exporting icon from binary file.<br>This can take a while..."), tr("Exporting icon"), FALSE); if (exportProcess.exec()==QDialog::Accepted){ //icotool -x -o ./regedit.png --width=32 --height=32 ./regedit.exe_14_100_0.ico args.clear(); args << "-x"; QDir ico_dir(tmpDir); // Updating file index list = ico_dir.entryInfoList(); //Creating file list for converting for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); qDebug() << fileInfo.fileName(); if (fileInfo.fileName().right(3)=="ico") args << fileInfo.filePath(); } args << "-o" << QString("%1/").arg(tmpDir); //Converting ico files to png //Look here, this function checks is some icons found, or not. 5 -- is default number of arguments, //if more -- then we have some ico file to convert if (args.size()>=4){ Process exportProcess(args, CoreLib->getSetting("icotool", "icotool").toString(), QDir::homePath(), tr("Convering icon from binary file.<br>This can take a while..."), tr("Converting icon"), FALSE); if (exportProcess.exec()==QDialog::Accepted){ IconsView iconsView(tmpDir); if (iconsView.exec()==QDialog::Accepted){ fileName=iconsView.selectedFile; cmdGetIcon->setIcon (QIcon(fileName)); } else { fileName.clear(); } } } else { IconsView iconsView(tmpDir); if (iconsView.exec()==QDialog::Accepted){ fileName=iconsView.selectedFile; cmdGetIcon->setIcon (QIcon(fileName)); } else { fileName.clear(); } } } else { qDebug()<<"wrestool testing Rejected"; fileName.clear(); } //Clearing temp files list = tmp.entryInfoList(); //Creating file list for converting for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if (!QFile::remove(fileInfo.filePath())) qDebug()<<"[EE] - Can't delete files at: "<<fileInfo.filePath(); } if (!tmp.rmdir(tmpDir)) qDebug()<<"[EE] - Can't delete tmp dir: "<<tmpDir; } if (!fileName.isEmpty()) iconPath=fileName; } return; }
void PathProcess::run() { emit Log("jejee"); m_CurrentValue = 0; emit ThreadProcessBar(m_CurrentValue); mConvertProcess = new QProcess(this); connect(mConvertProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput())); connect(mConvertProcess, SIGNAL(finished(int)), this, SLOT(ConvertFinished())); QDir dir(this->path); if (!dir.exists()) { return; } QStringList filters; filters << QString("*.ts") << QString("*.TS"); dir.setFilter(QDir::Files); //设置类型过滤器,只为文件格式 dir.setNameFilters(filters); //设置文件名称过滤器,只为filters格式(后缀为.jpeg等图片格式) QFileInfoList list = dir.entryInfoList(); int file_count = list.count(); if (file_count <= 0) { return; } m_CurrentFile= file_count; emit Log("The path has ts file number:" + QString::number(file_count)); for (int i = 0; i < file_count; i++) { QFileInfo fileInfo = list.at(i); QString mkdir_path = fileInfo.path() + "/" + fileInfo.baseName(); qDebug() << "mkdir_path" + mkdir_path; //mkdir same name dir QDir *dir_mkdir = new QDir; bool exist = dir_mkdir->exists(mkdir_path); if (exist) { } else { bool ok = dir_mkdir->mkdir(mkdir_path); if (ok) { //textEdit->append(mkdir_path + " path create ok"); } } delete dir_mkdir; QString m3u8_name = fileInfo.path() + "/" + fileInfo.baseName()+"/" + fileInfo.baseName() +".m3u8"; QString list_name = fileInfo.path() + "/" + fileInfo.baseName()+"/" + fileInfo.baseName() +"%03d.ts"; QStringList args; args <<"-i"<<fileInfo.absoluteFilePath(); args <<"-c"<<"copy"; args <<"-map"<<"0"; args <<"-f"<<"segment"; args <<"-segment_list"<< m3u8_name; args <<"-segment_time"<<"10"; args <<list_name; qDebug() << args << endl; mConvertProcess->setProcessChannelMode(QProcess::MergedChannels); QString program = QApplication::applicationDirPath() + "/ffmpeg/ffmpeg"; //QString program = "D:/ffmpeg/qtffmpeg/ffmpeghls/ffmpegtosegment/github/ffmpeg-segment/bin/ffmpeg"; mConvertProcess->start(program, args); while (false == mConvertProcess->waitForFinished()) { } } emit Log("Convert Surcessfully\N"); m_CurrentValue=100 ; emit ThreadProcessBar(m_CurrentValue); }
/// /// Loads only usable plugins /// std::vector<LadspaFXInfo*> Effects::getPluginList() { if ( m_pluginList.size() != 0 ) { return m_pluginList; } foreach ( const QString& sPluginDir, Filesystem::ladspa_paths() ) { 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 ); } } }
/** * @brief Apply output parsers, return the next expected model output file name(s). * @param step Step number to search the files for. * @param test_only If true, only tests if the expected output file exists. * @return Vector containing the output file name(s). */ std::vector<std::string> BinaryHandler::_get_data_filenames( int step, bool test_only ) { std::vector<std::string> output_files; QString run_id = QString::number( _toothLife->getID() ); QString run_path = systemTempPath + "/" + run_id + "/"; QDir qdir(run_path); std::string ext = ""; if (_output_style == "PLY" || _output_style == "") { ext = ".ply"; } else if (_output_style == "Matrix") { ext = ".txt"; } else if (_output_style == "Humppa") { ext = ".off"; } else { return output_files; } // // TODO: Imnplement control of output file names. // // Note: allowing for some room in the input file name: int iter = step*stepSize; QString target = QString::number(iter) + "*" + run_id + "*" + QString(ext.c_str()); QStringList filter; filter << target; QFileInfoList files = qdir.entryInfoList( filter, QDir::Files ); if (files.size() == 0) { return output_files; } if (test_only) { for (auto file : files) { output_files.push_back( file.fileName().toStdString() ); } return output_files; } /* std::cout << std::endl; std::cout << "** Running parsers in " << run_path.toStdString() << std::endl; std::cout << "** Parser target " << target.toStdString() << std::endl; std::cout << "** Number of files to be parsed: " << files.size() << std::endl; */ // Apply parsers for (int i=0; i<files.size(); i++) { QString file = files.at(i).fileName(); for (auto& parser : _output_parsers) { QString path_style = "..\bin\\"; #if defined(__linux__) || defined(__APPLE__) path_style = "../bin/"; #endif QString parser_out = "parser_tmp_" + run_id + ".txt"; QString cmd = path_style + parser + " " + file + " " + parser_out; QProcess process; process.start(cmd); if(!process.waitForFinished( PARSER_TIMEOUT )) { // TODO: Add checks for other errors, e.g., does the parser exist. qDebug() << "Error: Parser" << parser << "failed to finish in" << PARSER_TIMEOUT << "msecs on file" << file <<". SKipping."; continue; } // Replace the input file with the parser output if applicable. if (QFile::exists(parser_out)) { QFile::remove(file); QFile::copy(parser_out, file); QFile::remove(parser_out); } } } // Assuming a fixed output file name for now. std::string outfile = std::to_string(iter) + "_" + run_id.toStdString() + ext; output_files.push_back( outfile ); return output_files; }
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 ProjectFileSystemWatcher::slotDirChangedInternal( const QString &dir, KDevelop::ProjectFolderItem* folderItem ) { QDir changedDir( dir ); if( !changedDir.exists() ) { //directory itself deleted // int row = folderItem->row(); // QStandardItem *parent = folderItem->parent(); // parent->removeRow( row ); // // this->removeDirectory( dir ); QList<KDevelop::ProjectFolderItem*> deletedList; QStandardItem *parent = folderItem->parent(); KDevelop::ProjectFolderItem *parentItem = dynamic_cast<KDevelop::ProjectFolderItem*>( parent ); deletedList << folderItem; emit directoriesDeleted( deletedList, parentItem ); return; } else //subdirectory or file is created or deleted. { // retrieve current disk info QFileInfoList fileEntries = changedDir.entryInfoList(QDir::Files); QFileInfoList dirEntries = changedDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs); // convert disk info into QStringList QStringList fileList; for ( int i = 0; i < fileEntries.count(); ++i ) { QFileInfo fileInfo = fileEntries.at( i ); QString absFilePath = fileInfo.absoluteFilePath(); fileList << absFilePath; } QStringList dirList; for ( int i = 0; i < dirEntries.count(); ++i ) { QFileInfo fileInfo = dirEntries.at( i ); QString absFilePath = fileInfo.absoluteFilePath(); dirList << absFilePath; } // retrieve model item info, and convert into QStringList QList<KDevelop::ProjectFileItem*> itemFileList = folderItem->fileList(); QStringList itemFileListString; Q_FOREACH( KDevelop::ProjectFileItem* _item, itemFileList ) { itemFileListString << _item->url().toLocalFile(); } QList<KDevelop::ProjectFolderItem*> itemFolderList = folderItem->folderList(); QStringList itemFolderListString; Q_FOREACH( KDevelop::ProjectFolderItem *_item, itemFolderList ) { itemFolderListString << _item->url().toLocalFile(); } // Compare the difference between disk file and model items // round 1 -- file // KUrl::List deletedFileUrl; QList< KDevelop::ProjectFileItem* > deletedItems; Q_FOREACH( KDevelop::ProjectFileItem* _fileItem, itemFileList ) { if( fileList.contains( _fileItem->url().toLocalFile() ) == false ) { // disk file was deleted, so project file items should be also deleted // ### note: if some file, previously added to watching list, was deleted, // than QFSW::directoryChanged() is not emitted. Rather fileChanged() is emitted. // int row = _fileItem->row(); // folderItem->removeRow( row ); deletedItems << _fileItem; } } if( !deletedItems.isEmpty() ) emit filesDeleted( deletedItems, folderItem ); KUrl::List createdFileUrl; Q_FOREACH( QString diskFile, fileList ) { if( itemFileListString.contains( diskFile ) == false ) { // disk file was created, file items should be also created // KDevelop::ProjectFileItem *newitem = new KDevelop::ProjectFileItem( // folderItem->project(), KUrl(diskFile), folderItem ); // // if Makefile, parse new targets and add to watcher // if( diskFile.endsWith( "/Makefile" ) ) // TODO portable, setting aware // { // QStringList newTargets = parseCustomMakeFile( KUrl(diskFile) ); // Q_FOREACH( QString newTarget, newTargets ) // { // new CustomMakeTargetItem( folderItem->project(), newTarget, folderItem ); // } // cmpi->fsWatcher()->addFile( diskFile, newitem ); // } createdFileUrl << KUrl(diskFile); } } if( !createdFileUrl.isEmpty() ) emit filesCreated( createdFileUrl, folderItem ); // round 2 -- directory // KUrl::List deletedDirs; QList< KDevelop::ProjectFolderItem* > deletedDirs; Q_FOREACH( KDevelop::ProjectFolderItem* _folderItem, itemFolderList ) { if( dirList.contains( _folderItem->url().toLocalFile() ) == false) { // int row = _folderItem->row(); // QString tobeRemovedDir = _folderItem->url().toLocalFile(); // folderItem->removeRow( row ); // // this->removeDirectory( tobeRemovedDir ); deletedDirs << _folderItem; } } if( !deletedDirs.isEmpty() ) emit directoriesDeleted( deletedDirs, folderItem ); KUrl::List createdDirs; Q_FOREACH( QString diskDir, dirList ) { if( itemFolderListString.contains( diskDir ) == false ) { // KDevelop::ProjectBuildFolderItem *newitem =new KDevelop::ProjectBuildFolderItem( // folderItem->project(), KUrl(diskDir), folderItem ); // // this->addDirectory( diskDir, newitem ); // this->parseDirectoryRecursively( newitem, d->m_manager ); createdDirs << KUrl(diskDir); } } if( !createdDirs.isEmpty() ) emit directoriesCreated( createdDirs, folderItem ); } }
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 CBkImages::loadOnScreen(QWidget *parent, double, double, double) ///////////////////////////////////////////////////////////////////// { QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/data/dssfits/", "*.fits"); dir.setFilter(QDir::Files); QFileInfoList list = dir.entryInfoList(); // TODO: pridat dialog pro rescale obrazku QProgressDialog dlg(tr("Please wait..."), tr("Cancel"), 0, list.count() - 1, parent); dlg.setWindowModality(Qt::WindowModal); dlg.setMinimumDuration(0); dlg.show(); for (int i = 0; i < list.count(); i++) { bool memOk; bool found = false; dlg.setValue(i); QApplication::processEvents(); QFileInfo fi = list.at(i); if (dlg.wasCanceled()) { pcMainWnd->updateDSS(); return; } for (int i = 0; i < m_tImgList.count(); i++) { if (!m_tImgList[i].filePath.compare(fi.filePath(), Qt::CaseInsensitive)) { found = true; break; } } if (found) continue; CFits *f = new CFits; if (!f->load(fi.filePath(), memOk, false)) { delete f; } else { if (pcMapView->isRaDecOnScreen(f->m_ra, f->m_dec)) { bkImgItem_t i; delete f; bool memOk; CFits *f = new CFits; if (f->load(fi.filePath(), memOk)) { i.bShow = true; i.filePath = fi.filePath(); //qDebug("%s", qPrintable(i.filePath)); i.byteSize = (int)fi.size(); i.ptr = (void *)f; i.fileName = fi.fileName(); i.type = BKT_DSSFITS; i.rd.Ra = f->m_ra; i.rd.Dec = f->m_dec; i.size = anSep(f->m_cor[0].Ra, f->m_cor[0].Dec, f->m_cor[2].Ra, f->m_cor[2].Dec); i.param.brightness = 0; i.param.contrast = 100; i.param.gamma = 150; i.param.invert = false; i.param.autoAdjust = false; i.param.dlgSize = 0; i.param.useMatrix = false; memset(i.param.matrix, 0, sizeof(i.param.matrix)); i.param.matrix[1][1] = 1; m_totalSize += i.byteSize; m_tImgList.append(i); //pcMainWnd->updateDSS(); } } else { delete f; } } } pcMainWnd->updateDSS(); }
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(); }
//----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- 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); } }
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); } } } } } }
bool PathHelper::deleteThisDirectoryAndEverythingBelow(QString topDirPath) { DLog("-- deleteThisDirectoryAndEverythingBelow: ") << topDirPath; { QDir topDir(topDirPath); if (!topDir.exists()) { WLog(QString("The given topDir does not exists: %1").arg(topDirPath)); return true; } //First delete any files in the current directory + symlinks to anything except directories QFileInfoList files = topDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Hidden | QDir::System | QDir::Drives/* | QDir::NoSymLinks*/); for(int i = 0; i < files.count(); i++) { QString currFileInPath = files.at(i).fileName(); QString currFileFullPath = topDir.filePath(currFileInPath); QFileInfo currFileInfo(currFileFullPath); if( !currFileInfo.isSymLink() && !currFileInfo.isFile() ) { WLog("Not a symlink and not a file! Cannot remove it!") << currFileFullPath; return false; } if( !topDir.remove(currFileInPath) ) { WLog(QString("The specified file cannot be removed: %1 | full path: %2").arg(currFileInPath).arg(files.at(i).absoluteFilePath())); return false; } } // Now recursively delete any child directories QFileInfoList dirs = topDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden); for(int i = 0; i < dirs.count(); i++) { QString currDirAbsolutePath = dirs.at(i).absoluteFilePath(); if(QFileInfo(currDirAbsolutePath).isSymLink()) { // it's a symlink to a dir, simply remove this symlink file DLog(QString("The dir is a symlink file [%1]. Simply remove it.").arg(currDirAbsolutePath)); if(!QDir().remove(currDirAbsolutePath)) { WLog("Failed to remove the symlink file: " << currDirAbsolutePath); return false; } } else if( !PathHelper::deleteThisDirectoryAndEverythingBelow( currDirAbsolutePath ) ) { WLog("Failed to delete subdir: ") << currDirAbsolutePath; return false; } } } //Finally, remove empty top directory if( !QDir().rmdir(topDirPath) ) { WLog(QString("The specified directory cannot be removed: %1. Maybe it's still not empty.").arg(topDirPath)); return false; } return true; }
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())); }
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); } }
/** \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 {
QDomDocument SaveOMOptim::ProjectToXml(Project * project) { // MO file QDomDocument doc("MOProjectXML"); QDomElement root = doc.createElement( "MOProject" ); doc.appendChild( root ); root.setAttribute("Version",Version::version()); // Project info QDir projectDir(project->folder()); QDomElement cBasic = doc.createElement( "Basic" ); cBasic.setAttribute( "name", project->name() ); root.appendChild(cBasic); QString relPath; // Mo files bool useRelativePath; QFileInfoList moFilesPath = project->moFiles(); if(moFilesPath.size()>0) { QDomElement cMoFiles = doc.createElement("MoFiles"); for(int i=0;i<moFilesPath.size();i++) { // if mo file is in project folder, use relative path useRelativePath = (moFilesPath.at(i).absoluteFilePath().indexOf(projectDir.absolutePath())==0); QDomElement cMoFile = doc.createElement("MoFile"); if(useRelativePath) cMoFile.setAttribute("path",projectDir.relativeFilePath(moFilesPath.at(i).absoluteFilePath())); else cMoFile.setAttribute("path",moFilesPath.at(i).absoluteFilePath()); cMoFiles.appendChild(cMoFile); } root.appendChild(cMoFiles); } // Mmo files QFileInfoList mmoFilesPath = project->mmoFiles(); if(mmoFilesPath.size()>0) { QDomElement cMmoFiles = doc.createElement("MmoFiles"); for(int i=0;i<mmoFilesPath.size();i++) { QDomElement cMmoFile = doc.createElement("MmoFile"); relPath = projectDir.relativeFilePath(mmoFilesPath.at(i).filePath()); qDebug(mmoFilesPath.at(i).filePath().toLatin1()); cMmoFile.setAttribute("path",relPath); cMmoFiles.appendChild(cMmoFile); } root.appendChild(cMmoFiles); } // plugins loaded QStringList pluginsPaths = project->pluginsLoaded().values(); if(pluginsPaths.size()>0) { QDomElement cPlugins = doc.createElement("Plugins"); for(int i=0;i<pluginsPaths.size();i++) { QDomElement cPlugin = doc.createElement("Plugin"); cPlugin.setAttribute("path",pluginsPaths.at(i)); cPlugins.appendChild(cPlugin); } root.appendChild(cPlugins); } // Project problems if(project->problems()->size()>0) { QDomElement cOMCases = doc.createElement( "Problems" ); for (int nr=0;nr<project->problems()->size();nr++) { QDomElement cProblem = doc.createElement( "Problem" ); relPath = projectDir.relativeFilePath(project->problems()->at(nr)->entireSavePath()); cProblem.setAttribute("path",relPath); cOMCases.appendChild(cProblem); } root.appendChild(cOMCases); } // Project results if(project->results()->size()>0) { QDomElement cResults = doc.createElement( "Results" ); for (int nr=0;nr<project->results()->size();nr++) { QDomElement cResult = doc.createElement( "Result" ); relPath = projectDir.relativeFilePath(project->results()->at(nr)->entireSavePath()); cResult.setAttribute("path",relPath); cResults.appendChild(cResult); } root.appendChild(cResults); } return doc; }
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; }
const QString DocumentListPrivate::nextFile() { while ( TRUE ) { while ( searchDepth < 0 ) { // go to next base path if ( docPathsSearched >= docPaths.count() ) { // end of base paths return QString::null; } else { QDir dir( docPaths[docPathsSearched] ); // odebug << "now using base path: " << docPaths[docPathsSearched] << "" << oendl; docPathsSearched++; if ( !dir.exists( ".Qtopia-ignore" ) ) { listDirs[0] = new QDir( dir ); lists[0] = listDirs[0]->entryInfoList(); listPositions[0] = 0; searchDepth = 0; } } } const QFileInfoList *fil = lists[searchDepth]; if (!fil) { return QString::null; } QFileInfoList *fl = (QFileInfoList *)fil; unsigned int pos = listPositions[searchDepth]; if ( pos >= fl->count() ) { // go up a depth delete listDirs[searchDepth]; listDirs[searchDepth] = 0; lists[searchDepth] = 0; listPositions[searchDepth] = 0; searchDepth--; } else { const QFileInfo *fi = fl->at(pos); listPositions[searchDepth]++; QString bn = fi->fileName(); if ( bn[0] != '.' ) { if ( fi->isDir() ) { if ( bn != "CVS" && bn != "Qtopia" && bn != "QtPalmtop" && bn != "proc" && bn != "dev" && bn != "bin" && bn != "usr" && bn != "etc" && bn != "lib" && bn != "sbin" && bn != "tmp" && bn != "var") { // go down a depth QDir dir( fi->filePath() ); // odebug << "now going in to path: " << bn << "" << oendl; if ( !dir.exists( ".Qtopia-ignore" ) ) { if ( searchDepth < MAX_SEARCH_DEPTH - 1) { searchDepth++; listDirs[searchDepth] = new QDir( dir ); lists[searchDepth] = listDirs[searchDepth]->entryInfoList(); listPositions[searchDepth] = 0; } } } } else { estimatedPercentScanned(); return fl->at(pos)->filePath(); } } } } return QString::null; }
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; }
void processDirectory(const QString &dir_old, const QString &dir_new, const QString &dir_result, const QStringList &ignoreMasks) { QDir qdir(dir_new, "", QDir::Name | QDir::IgnoreCase, QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); QFileInfoList files = qdir.entryInfoList(); for (int i = 0; i < files.count(); ++i) { //qDebug() << files.at(i).absoluteFilePath(); QFileInfo fi = files.at(i); // check for ignores bool ignore_this_file = false; for (int k = 0; k < ignoreMasks.size(); ++k) { QRegExp rx(ignoreMasks.at(k)); rx.setPatternSyntax(QRegExp::Wildcard); if (rx.exactMatch(fi.fileName())) { ignore_this_file = true; break; } } if (ignore_this_file) continue; if (fi.isFile()) { QDir qdir_old(dir_old); if(!qdir_old.exists(fi.fileName())) { CopyFile(dir_result, fi.absoluteFilePath()); } else // compare crc, if changed then copy { quint16 crc_new = getCrc(fi.absoluteFilePath()); quint16 crc_old = getCrc(qdir_old.absoluteFilePath(fi.fileName())); log(QString("Comparing crc %1 = %2\n").arg(crc_old).arg(crc_new)); if (crc_new == 0 || crc_old == 0) return; if (crc_new != crc_old) { CopyFile(dir_result, fi.absoluteFilePath()); } } } else if (fi.isDir()) { processDirectory(dir_old + "/" + fi.fileName(), dir_new + "/" + fi.fileName(), dir_result + "/" + fi.fileName(), ignoreMasks); //*/ } } }
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; } }
// Open a new file void MainWindow::handleOpenFileEvent(QString filename, QString filter) { // On Windows, we have to remove all three '/' after 'file:', on Linux, we need to leave one of them #ifdef Q_OS_WIN if(filename.startsWith("file:///")) filename = filename.remove(0,8); #else if(filename.startsWith("file://")) filename = filename.remove(0,7); #endif if(filename.trimmed() == "") { QMetaObject::invokeMethod(object, "openFile"); return; } variables->keepLoadingThumbnails = true; setOverrideCursor(); if(variables->verbose) LOG << CURDATE << "handleOpenFileEvent(): Handle response to request to open new file" << NL; // Decode filename QByteArray usethis = QByteArray::fromPercentEncoding(filename.trimmed().toUtf8()); // Store filter variables->openfileFilter = filter; QString file = ""; // Check return file file = usethis; QMetaObject::invokeMethod(object, "alsoIgnoreSystemShortcuts", Q_ARG(QVariant, false)); // Save current directory variables->currentDir = QFileInfo(file).absolutePath(); // Clear loaded thumbnails variables->loadedThumbnails.clear(); // Load direcgtory QFileInfoList l = loadDir->loadDir(file,variables->openfileFilter); if(l.isEmpty()) { QMetaObject::invokeMethod(object, "noResultsFromFilter"); restoreOverrideCursor(); return; } if(!l.contains(QFileInfo(file))) file = l.at(0).filePath(); // Get and store length int l_length = l.length(); settingsPerSession->setValue("countTot",l_length); // Convert QFileInfoList into QStringList and store it QStringList ll; for(int i = 0; i < l_length; ++i) ll.append(l.at(i).absoluteFilePath()); settingsPerSession->setValue("allFileList",ll); // Get and store current position int curPos = l.indexOf(QFileInfo(file)); settingsPerSession->setValue("curPos",curPos); // Setiup thumbnail model QMetaObject::invokeMethod(object, "setupModel", Q_ARG(QVariant, ll), Q_ARG(QVariant, curPos)); // Display current postiion in main image view QMetaObject::invokeMethod(object, "displayImage", Q_ARG(QVariant, curPos)); QVariant centerPos = curPos; if(!QMetaObject::invokeMethod(object, "getCenterPos", Q_RETURN_ARG(QVariant, centerPos))) std::cerr << CURDATE << "handleOpenFileEvent(): ERROR: couldn't get center pos!" << NL; // And handle the thumbnails handleThumbnails(centerPos.toInt()); restoreOverrideCursor(); }
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); }
SoundManager::SoundManager(QString soundDirectory) { QString applicationDirectory; QString completeSoundDirectory; char cwd[PATH_MAX]; // Initialize ALUT. if (alutInit(NULL, NULL) == false) { reportALUTError(alutGetError()); } // Get the complete application directory in which we will load sounds from. // We convert to QString since it is more convenient when working with directories. getcwd(cwd, PATH_MAX); applicationDirectory = QString(cwd); // Append the assets directory and the actual sounds directory name. completeSoundDirectory = applicationDirectory .append("/app/native/assets/") .append(soundDirectory); // Create OpenAL buffers from all files in the sound directory. QDir dir(completeSoundDirectory); if (!dir.exists()) { qDebug() << "Cannot find the sounds directory." << completeSoundDirectory; } else { // Set a filter for file listing, only files should be listed. dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot); // Get a directory listing. QFileInfoList list = dir.entryInfoList(); // Traverse and load all the audio files into buffers. for (int i = 0; i < list.size(); ++i) { // Create a file info for each audio file. QFileInfo fileInfo = list.at(i); const char* path = fileInfo.absoluteFilePath().toStdString().c_str(); ALenum error; // Generate buffers to hold audio data. alGenBuffers(1, &mSoundBuffers[fileInfo.fileName()]); error = alGetError(); if (error != AL_NO_ERROR) { reportOpenALError(error); break; } // Load sound file. FILE* file = fopen(path, "rb"); if (!file) { qDebug() << "Failed to load audio file " << path; break; } // Read the file header char header[12]; ALuint bufferId = mSoundBuffers[fileInfo.fileName()]; if (fread(header, 1, 12, file) != 12) { qDebug() << "Invalid header for audio file " << path; alDeleteBuffers(1, &bufferId); goto cleanup; } // Check the file format & load the buffer with audio data. if (memcmp(header, "RIFF", 4) == 0) { if (!loadWav(file, bufferId)) { qDebug() << "Invalid wav file: " << path; alDeleteBuffers(1, &bufferId); goto cleanup; } } else if (memcmp(header, "OggS", 4) == 0) { if (!loadOgg(file, bufferId)) { qDebug() << "Invalid ogg file: " << path; alDeleteBuffers(1, &bufferId); goto cleanup; } } else { qDebug() << "Unsupported audio file: " << path; goto cleanup; } cleanup: if (file) { fclose(file); } } } // Generate a number of sources used to attach buffers and play. alGenSources(SOUNDMANAGER_MAX_NBR_OF_SOURCES, mSoundSources); ALenum error = alGetError(); if (error != AL_NO_ERROR) { reportOpenALError(error); } }
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); }
// ======================================================== int init1 ( ) { BL_FUNC_DEBUG PluginBl_Report *mcont = new PluginBl_Report; QMenu *pPluginMenu = NULL; /// Miramos si existe un menu Informes pPluginMenu = g_pluginbl_report->menuBar()->findChild<QMenu *> ( "menuInformes" ); QMenu *pPluginVer = g_pluginbl_report->menuBar()->findChild<QMenu *> ( "menuVentana" ); /// Buscamos ficheros adecuados 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_*.txt"; 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 while 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 while /// Buscamos el icono QString icon = ":/Images/template2rml.png"; QRegExp rx6 ( " icon\\s*=\\s*\"(.*)\"" ); rx6.setMinimal ( true ); if ( rx6.indexIn ( buff, 0 ) != -1 ) { icon = rx6.cap ( 1 ); } // end while QMenuBar *menubar =g_pluginbl_report->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 ); menu = pPluginMenu1; } // end if } else { if (!pPluginMenu) { pPluginMenu = new QMenu ( _ ( "Informes" ), g_pluginbl_report->menuBar() ); pPluginMenu->setObjectName ( QString::fromUtf8 ( "menuInformes" ) ); g_pluginbl_report->menuBar()->insertMenu ( pPluginVer->menuAction(), pPluginMenu ); } // 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 ( elslot2() ) ); menu->addAction ( accion ); } // end for return 0; }
// 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); } } }