bool QlFiles::isDir(const QString &path){ return QFileInfo(path).isDir(); }
bool QtDesignerFormClassCodeGenerator::generateCpp(const FormClassWizardParameters ¶meters, QString *header, QString *source, int indentation) { Internal::FormClassWizardGenerationParameters generationParameters; generationParameters.fromSettings(Core::ICore::settings()); const QString indent = QString(indentation, QLatin1Char(' ')); QString formBaseClass; QString uiClassName; if (!Internal::FormTemplateWizardPage::getUIXmlData(parameters.uiTemplate, &formBaseClass, &uiClassName)) { qWarning("Unable to determine the form base class from %s.", qPrintable(parameters.uiTemplate)); return false; } // Build the ui class (Ui::Foo) name relative to the namespace (which is the same): const QString colonColon = QLatin1String("::"); const int lastSeparator = uiClassName.lastIndexOf(colonColon); if (lastSeparator != -1) uiClassName.remove(0, lastSeparator + colonColon.size()); uiClassName.insert(0, QLatin1String(uiNamespaceC) + colonColon); // Do we have namespaces? QStringList namespaceList = parameters.className.split(colonColon); if (namespaceList.empty()) // Paranoia! return false; const QString unqualifiedClassName = namespaceList.takeLast(); const QString headerLicense = CppTools::AbstractEditorSupport::licenseTemplate(parameters.headerFile, parameters.className); const QString sourceLicense = CppTools::AbstractEditorSupport::licenseTemplate(parameters.sourceFile, parameters.className); // Include guards const QString guard = Utils::headerGuard(parameters.headerFile, namespaceList); QString uiInclude = QLatin1String("ui_"); uiInclude += QFileInfo(parameters.uiFile).completeBaseName(); uiInclude += QLatin1String(".h"); // 1) Header file QTextStream headerStr(header); headerStr << headerLicense << "#ifndef " << guard << "\n#define " << guard << '\n' << '\n'; // Include 'ui_' if (generationParameters.embedding != Internal::PointerAggregatedUiClass) { Utils::writeIncludeFileDirective(uiInclude, false, headerStr); } else { // Todo: Can we obtain the header from the code model for custom widgets? // Alternatively, from Designer. if (formBaseClass.startsWith(QLatin1Char('Q'))) { if (generationParameters.includeQtModule) { if (generationParameters.addQtVersionCheck) { Utils::writeBeginQtVersionCheck(headerStr); Utils::writeIncludeFileDirective(QLatin1String("QtWidgets/") + formBaseClass, true, headerStr); headerStr << "#else\n"; Utils::writeIncludeFileDirective(QLatin1String("QtGui/") + formBaseClass, true, headerStr); headerStr << "#endif\n"; } else { Utils::writeIncludeFileDirective(QLatin1String("QtGui/") + formBaseClass, true, headerStr); } } else { Utils::writeIncludeFileDirective(formBaseClass, true, headerStr); } } } const QString namespaceIndent = Utils::writeOpeningNameSpaces(namespaceList, generationParameters.indentNamespace ? indent : QString(), headerStr); // Forward-declare the UI class if (generationParameters.embedding == Internal::PointerAggregatedUiClass) { headerStr << '\n' << namespaceIndent << "namespace " << uiNamespaceC << " {\n" << namespaceIndent << indent << "class " << Internal::FormTemplateWizardPage::stripNamespaces(uiClassName) << ";\n" << namespaceIndent << "}\n"; } // Class declaration headerStr << '\n' << namespaceIndent << "class " << unqualifiedClassName << " : public " << formBaseClass; if (generationParameters.embedding == Internal::InheritedUiClass) headerStr << ", private " << uiClassName; headerStr << "\n{\n" << namespaceIndent << indent << "Q_OBJECT\n\n" << namespaceIndent << "public:\n" << namespaceIndent << indent << "explicit " << unqualifiedClassName << "(QWidget *parent = 0);\n"; if (generationParameters.embedding == Internal::PointerAggregatedUiClass) headerStr << namespaceIndent << indent << "~" << unqualifiedClassName << "();\n"; // retranslation if (generationParameters.retranslationSupport) headerStr << '\n' << namespaceIndent << "protected:\n" << namespaceIndent << indent << "void changeEvent(QEvent *e);\n"; // Member variable if (generationParameters.embedding != Internal::InheritedUiClass) { headerStr << '\n' << namespaceIndent << "private:\n" << namespaceIndent << indent << uiClassName << ' '; if (generationParameters.embedding == Internal::PointerAggregatedUiClass) headerStr << '*'; headerStr << uiMemberC << ";\n"; } headerStr << namespaceIndent << "};\n\n"; Utils::writeClosingNameSpaces(namespaceList, generationParameters.indentNamespace ? indent : QString(), headerStr); headerStr << "#endif // "<< guard << '\n'; // 2) Source file QTextStream sourceStr(source); sourceStr << sourceLicense; Utils::writeIncludeFileDirective(parameters.headerFile, false, sourceStr); if (generationParameters.embedding == Internal::PointerAggregatedUiClass) Utils::writeIncludeFileDirective(uiInclude, false, sourceStr); // NameSpaces( Utils::writeOpeningNameSpaces(namespaceList, generationParameters.indentNamespace ? indent : QString(), sourceStr); // Constructor with setupUi sourceStr << '\n' << namespaceIndent << unqualifiedClassName << "::" << unqualifiedClassName << "(QWidget *parent) :\n" << namespaceIndent << indent << formBaseClass << "(parent)"; if (generationParameters.embedding == Internal::PointerAggregatedUiClass) sourceStr << ",\n" << namespaceIndent << indent << uiMemberC << "(new " << uiClassName << ")"; sourceStr << '\n' << namespaceIndent << "{\n" << namespaceIndent << indent; writeUiMemberAccess(generationParameters, sourceStr); sourceStr << "setupUi(this);\n" << namespaceIndent << "}\n"; // Deleting destructor for ptr if (generationParameters.embedding == Internal::PointerAggregatedUiClass) { sourceStr << '\n' << namespaceIndent << unqualifiedClassName << "::~" << unqualifiedClassName << "()\n" << namespaceIndent << "{\n" << namespaceIndent << indent << "delete " << uiMemberC << ";\n" << namespaceIndent << "}\n"; } // retranslation if (generationParameters.retranslationSupport) { sourceStr << '\n' << namespaceIndent << "void " << unqualifiedClassName << "::" << "changeEvent(QEvent *e)\n" << namespaceIndent << "{\n" << namespaceIndent << indent << formBaseClass << "::changeEvent(e);\n" << namespaceIndent << indent << "switch (e->type()) {\n" << namespaceIndent << indent << "case QEvent::LanguageChange:\n" << namespaceIndent << indent << indent; writeUiMemberAccess(generationParameters, sourceStr); sourceStr << "retranslateUi(this);\n" << namespaceIndent << indent << indent << "break;\n" << namespaceIndent << indent << "default:\n" << namespaceIndent << indent << indent << "break;\n" << namespaceIndent << indent << "}\n" << namespaceIndent << "}\n"; } Utils::writeClosingNameSpaces(namespaceList, generationParameters.indentNamespace ? indent : QString(), sourceStr); return true; }
QString ImageDisplay::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); }
//MTL PARSER INSPIRED FROM KIXOR.NET "objloader" (http://www.kixor.net/dev/objloader/) bool ccMaterialSet::ParseMTL(QString path, const QString& filename, ccMaterialSet &materials, QStringList& errors) { //open mtl file QString fullPathFilename = path + QString('/') + filename; QFile file(fullPathFilename); if (!file.open(QFile::ReadOnly)) { errors << QString("Error reading file: %1").arg(filename); return false; } //update path (if the input filename has already a relative path) path = QFileInfo(fullPathFilename).absolutePath(); QTextStream stream(&file); QString currentLine = stream.readLine(); unsigned currentLineIndex = 0; ccMaterial::Shared currentMaterial(0); while( !currentLine.isNull() ) { ++currentLineIndex; QStringList tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts); //skip comments & empty lines if( tokens.empty() || tokens.front().startsWith('/',Qt::CaseInsensitive) || tokens.front().startsWith('#',Qt::CaseInsensitive) ) { currentLine = stream.readLine(); continue; } //start material if (tokens.front() == "newmtl") { //push the previous material (if any) if (currentMaterial) { materials.addMaterial(currentMaterial); currentMaterial = ccMaterial::Shared(0); } // get the name QString materialName = currentLine.mid(7).trimmed(); //we must take the whole line! (see OBJ filter) if (materialName.isEmpty()) materialName = "undefined"; currentMaterial = ccMaterial::Shared(new ccMaterial(materialName)); } else if (currentMaterial) //we already have a "current" material { //ambient if (tokens.front() == "Ka") { if (tokens.size() > 3) { ccColor::Rgbaf ambient( tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat(), 1.0f); currentMaterial->setAmbient(ambient); } } //diff else if (tokens.front() == "Kd") { if (tokens.size() > 3) { ccColor::Rgbaf diffuse( tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat(), 1.0f); currentMaterial->setDiffuse(diffuse); } } //specular else if (tokens.front() == "Ks") { if (tokens.size() > 3) { ccColor::Rgbaf specular(tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat(), 1.0f); currentMaterial->setSpecular(specular); } } //shiny else if (tokens.front() == "Ns") { if (tokens.size() > 1) currentMaterial->setShininess(tokens[1].toFloat()); } //transparent else if (tokens.front() == "d" || tokens.front() == "Tr") { if (tokens.size() > 1) currentMaterial->setTransparency(tokens[1].toFloat()); } //reflection else if (tokens.front() == "r") { //ignored //if (tokens.size() > 1) // currentMaterial->reflect = tokens[1].toFloat(); } //glossy else if (tokens.front() == "sharpness") { //ignored //if (tokens.size() > 1) // currentMaterial->glossy = tokens[1].toFloat(); } //refract index else if (tokens.front() == "Ni") { //ignored //if (tokens.size() > 1) // currentMaterial->refract_index = tokens[1].toFloat(); } // illumination type else if (tokens.front() == "illum") { //ignored } // texture map else if (tokens.front() == "map_Ka" || tokens.front() == "map_Kd" || tokens.front() == "map_Ks") { //DGM: in case there's hidden or space characters at the beginning of the line... int shift = currentLine.indexOf("map_K",0); QString textureFilename = (shift + 7 < currentLine.size() ? currentLine.mid(shift+7).trimmed() : QString()); QString fullTexName = path + QString('/') + textureFilename; if (!currentMaterial->loadAndSetTexture(fullTexName)) { errors << QString("Failed to load texture file: %1").arg(fullTexName); } } else { errors << QString("Unknown command '%1' at line %2").arg(tokens.front()).arg(currentLineIndex); } } currentLine = stream.readLine(); } file.close(); //don't forget to push the last material! if (currentMaterial) materials.addMaterial(currentMaterial); return true; }
void qSRA::loadProfile() { assert(m_app); if (!m_app) return; //persistent settings (default import path) QSettings settings; settings.beginGroup("qSRA"); QString path = settings.value("importPath",QApplication::applicationDirPath()).toString(); ProfileImportDlg piDlg(m_app->getMainWindow()); piDlg.setDefaultFilename(path); if (!piDlg.exec()) return; QString filename = piDlg.getFilename(); if (filename.isEmpty()) return; //save current import path to persistent settings settings.setValue("importPath",QFileInfo(filename).absolutePath()); //get the user defined global axis int axisDim = piDlg.getAxisDimension(); //get whether heights are expressed relatively to 0 or to the input center bool ignoreAxisShift = piDlg.ignoreAxisShift(); //load profile as a (2D) polyline ccPolyline* polyline = ProfileLoader::Load(filename,ignoreAxisShift,axisDim,m_app); if (polyline) { //apply a visual transformation to see the polyline in the right place! ccPointCloud* vertices = dynamic_cast<ccPointCloud*>(polyline->getAssociatedCloud()); if (vertices) { const CCVector3d& O = vertices->getGlobalShift(); ccGLMatrix trans; trans.setTranslation(CCVector3::fromArray(O.u)); float* mat = trans.data(); switch(axisDim) { case 0: //X //invert X and Y mat[0] = 0; mat[1] = 1; mat[4] = 1; mat[5] = 0; break; //case 1: //Y case 2: //Z //invert Z and Y mat[5] = 0; mat[6] = 1; mat[9] = 1; mat[10] = 0; break; default: //nothing to do break; } polyline->set2DMode(false); polyline->setGLTransformation(trans); } //add revolution axis as meta-data DistanceMapGenerationTool::SetPoylineAxis(polyline,axisDim); //default destination container ccHObject* defaultContainer = GetDefaultContainer(m_app); if (defaultContainer) defaultContainer->addChild(polyline); m_app->addToDB(polyline,false); m_app->dispToConsole(QString("[qSRA] File '%1' succesfully loaded").arg(filename),ccMainAppInterface::STD_CONSOLE_MESSAGE); } else { m_app->dispToConsole(QString("Failed to load file '%1'!").arg(filename),ccMainAppInterface::ERR_CONSOLE_MESSAGE); } }
bool RazorPluginInfo::load(const QString& fileName) { XdgDesktopFile::load(fileName); mId = QFileInfo(fileName).completeBaseName(); return isValid(); }
QString ModelFileImpl::workPath() const { return QFileInfo(m_fileName).absolutePath(); }
Optimization::Optimization(QDomElement domProblem,Project* project,bool &ok) :Problem((ProjectBase*)project) { // initialization _omProject = project; _algos = OptimAlgoUtils::getNewAlgos(this); // look for modmodelplus ok = !domProblem.isNull(); ok = ok && (domProblem.tagName()==Optimization::className()); if(ok) { QDomElement domInfos = domProblem.firstChildElement("Infos"); this->setName(domInfos.attribute("name", "" )); // compatibility with older saving format (one model, saved in Infos node) if(!domInfos.attribute("model").isEmpty()) { QString modelName = domInfos.attribute("model"); ModModelPlus* model = project->modModelPlus(modelName); // read corresponding controlers QDomElement domCtrls = domProblem.firstChildElement(ModPlusCtrls::className()); ModPlusCtrls* ctrls = new ModPlusCtrls(project,model,domCtrls); // add model this->addModel(domInfos.attribute("model")); } // new format QDomElement domModels = domProblem.firstChildElement("Models"); QDomElement domModel = domModels.firstChildElement("Model"); while(!domModel.isNull()) { QString modelName = domModel.attribute("name"); ModModelPlus* model = project->modModelPlus(modelName); // read corresponding controlers QDomElement domCtrls = domModel.firstChildElement(ModPlusCtrls::className()); ModPlusCtrls* ctrls = new ModPlusCtrls(project,model,domCtrls); // add model and controlers this->addModel(modelName,ctrls); domModel = domModel.nextSiblingElement("Model"); } } //initialize default(otherwise seg fault in destructor) _optimizedVariables = new OptVariables(true); _scannedVariables = new ScannedVariables(true); _overwritedVariables = new Variables(true); _objectives = new OptObjectives(true); // Optimized Variables QDomElement domOptVars = domProblem.firstChildElement("OptimizedVariables"); this->optimizedVariables()->setItems(domOptVars); // Objectives QDomElement domObj = domProblem.firstChildElement("Objectives"); this->objectives()->setItems(domObj); // Scanned Variables QDomElement domScann = domProblem.firstChildElement("ScannedVariables"); this->scannedVariables()->setItems(domScann); // Overvars Variables QDomElement domOverVars = domProblem.firstChildElement("OverwritedVariables"); this->overwritedVariables()->setItems(domOverVars); for(int i=0;i<overwritedVariables()->size();i++) overwritedVariables()->at(i)->setIsEditableField(Variable::VALUE,true); // Files to copy QDomElement cFilesToCopy = domProblem.firstChildElement("FilesToCopy"); QString text = cFilesToCopy.text(); QStringList strList = text.split("\n",QString::SkipEmptyParts); for(int i=0;i<strList.size();i++) this->_filesToCopy.push_back(QFileInfo(strList.at(i))); // BlockSubstitutions QDomElement domBlockSubs = domProblem.firstChildElement("BlockSubstitutions"); _blockSubstitutions = new BlockSubstitutions(project,domBlockSubs); // EA QDomElement domEA = domProblem.firstChildElement("EA"); QDomElement domEAInfos = domEA.firstChildElement("Infos"); if(!domEAInfos.isNull()) { this->setiCurAlgo(domEAInfos.attribute("num", "" ).toInt()); } QDomElement domEAParameters = domEA.firstChildElement("Parameters"); if(!domEAParameters.isNull()) { this->getCurAlgo()->_parameters->update(domEAParameters); } }
QString SoulNote::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); }
QString QlFiles::ext(const QString &path){ return QFileInfo(path).suffix(); }
int main(int argc, char *argv[]) { int i_file, i_v, i_curve; int i_plot; QString fullPath; KAboutData aboutData("kst", I18N_NOOP("Kst"), KSTVERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2000-2007 Barth Netterfield"), 0, "http://kst.kde.org/"); aboutData.addAuthor("Barth Netterfield", I18N_NOOP("Original author and maintainer."), "*****@*****.**", "http://omega.astro.utoronto.ca/"); aboutData.addAuthor("Staikos Computing Services Inc.", I18N_NOOP("Developed for the University of Toronto."), "*****@*****.**", "http://www.staikos.net/"); aboutData.addAuthor("Sumus Technology Limited", I18N_NOOP("Developed for the University of British Columbia"), "*****@*****.**", "http://www.sumusltd.com/"); aboutData.addAuthor("Rick Chern", I18N_NOOP("University of British Columbia"), "", ""); aboutData.addAuthor("Duncan Hanson", I18N_NOOP("University of British Columbia"), "", ""); aboutData.addAuthor("Nicolas Brisset", "", "", ""); aboutData.addAuthor("Matthew Truch", "", "http://matt.truch.net/", "*****@*****.**"); aboutData.addAuthor("Theodore Kisner", "", "*****@*****.**", ""); aboutData.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails")); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KApplication app; KImageIO::registerFormats(); KstDialogs::replaceSelf(new KstGuiDialogs); KstData::replaceSelf(new KstGuiData); KstApp::initialize(); atexit(exitHelper); if (app.isRestored()) { RESTORE(KstApp) } else { KstApp *kst = new KstApp; InType in; QColor color; QCStringList ycolList; QCStringList matrixList; QCStringList yEqList; QCStringList psdList; QCStringList hsList; QCStringList errorList; unsigned int i_ycol; QCStringList::Iterator hs_string; QCStringList::Iterator eq_i; QCStringList::Iterator mat_i; bool showQuickStart = false; bool showDataWizard = false; bool nOK; int n_y = 0; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); CheckForCMDErrors(args); QString wizardfile = args->getOption("w"); QString printfile = args->getOption("print"); QString pngfile = args->getOption("png"); bool print_and_exit = false; if (printfile != "<none>") { print_and_exit = true; } if (pngfile != "<none>") { print_and_exit = true; } if (!print_and_exit) { app.setMainWidget(kst); QRect rect = KGlobalSettings::desktopGeometry(kst); kst->resize(5 * rect.width() / 6, 5 * rect.height() / 6); kst->show(); } // get Y axis columns ycolList = args->getOptionList("y"); matrixList = args->getOptionList("z"); yEqList = args->getOptionList("ye"); psdList = args->getOptionList("p"); hsList = args->getOptionList("h"); errorList = args->getOptionList("e"); // y axis or PSD specified, so the files are data files, not kst files. n_y = ycolList.count() + psdList.count() + hsList.count() + yEqList.count() + matrixList.count(); if (n_y > 0) { QString creatingEquations = i18n("Creating equations"); QString creatingCurves = i18n("Creating curves"); QString creatingPlots = i18n("Creating plots"); int count; int handled; kst->slotUpdateProgress( 0, 0, QString::null ); SetCMDOptions(args, in, n_y); KstTopLevelViewPtr tlv = kst->activeView(); if (!tlv) { // if there was no active view then we create one... kst->newWindow(false); tlv = kst->activeView(); } if (!tlv) { kstdError() << i18n("Can't create a view.") << endl; return 0; } CreatePlots(in, tlv); Kst2DPlotList plist = kstObjectSubList<KstViewObject, Kst2DPlot>(tlv->children()); i_plot = 0; Kst2DPlotPtr plot = *plist.at(i_plot); KstVCurveList vcurves = kstObjectSubList<KstBaseCurve,KstVCurve>(plot->Curves); // make stand alone equations if there are no files if (args->count() < 1) { if (!yEqList.isEmpty()) { QString eqS; double max, min; int n; bool xeq; SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq); if (xeq) { count = yEqList.size(); handled = 0; kst->slotUpdateProgress( count, handled, creatingEquations ); for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) { eqS = *eq_i; if (NoVectorEq(eqS)) { KstEquationPtr eq = new KstEquation(KST::suggestEQName(eqS), eqS, min, max, n); KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(eq->tag(), true), eq->vX(), eq->vY(), 0L, 0L, 0L, 0L, KstColorSequence::next(vcurves,plot->backgroundColor())); KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(eq.data()); KST::dataObjectList.append(vc.data()); KST::dataObjectList.lock().unlock(); plot->addCurve(vc.data()); if (in.sep_plots) { i_plot++; if (i_plot < in.n_plots) { plot = *plist.at(i_plot); } } } handled++; kst->slotUpdateProgress( count, handled, creatingEquations ); } } } } // make the requested curves for each data file count = args->count(); handled = 0; kst->slotUpdateProgress( count, handled, creatingCurves ); for (i_curve = i_v = 0, i_file = 0; i_file < args->count(); i_file++) { // make the file if (QFile::exists(args->arg(i_file))) { fullPath = QFileInfo(args->arg(i_file)).absFilePath(); } else { fullPath = args->arg(i_file); } KstDataSourcePtr file = KstDataSource::loadSource(fullPath); if (file) { if (!file->isValid() || file->isEmpty()) { kstdError() << i18n("No data in file %1. Trying to continue...").arg(args->arg(i_file)) << endl; // The file might get data later! } KST::dataObjectList.lock().writeLock(); KST::dataSourceList.append(file); KST::dataObjectList.lock().unlock(); KstRVectorPtr yvector; KstRVectorPtr evector; KstVCurvePtr curve; KstPSDPtr psd; KstHistogramPtr hs; KstRVectorPtr xvector; if (!ycolList.isEmpty()) { // if there are some xy plots // make the x axis vector xvector = GetOrCreateVector(args->getOption("x"), file, in); if (xvector) { // make the y axis vectors for (i_ycol = 0; i_ycol < ycolList.count(); ++i_ycol ) { yvector = GetOrCreateVector(*(ycolList.at(i_ycol)), file, in); if (yvector) { // make the curves color = KstColorSequence::next(vcurves,plot->backgroundColor()); curve = new KstVCurve(KST::suggestCurveName(yvector->tag(), false), KstVectorPtr(xvector), KstVectorPtr(yvector), 0L, 0L, 0L, 0L, color); if (in.has_points) { curve->setHasPoints(true); curve->setHasLines(false); } if (i_ycol<errorList.count()) { evector = GetOrCreateVector(*(errorList.at(i_ycol)), file, in); if (evector) { curve->setYError(KstVectorPtr(evector)); curve->setYMinusError(KstVectorPtr(evector)); } } KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(curve.data()); KST::dataObjectList.lock().unlock(); plot->addCurve(curve.data()); if (in.sep_plots) { plot->setTagName(curve->tag()); i_plot++; if (i_plot < in.n_plots) { plot = *plist.at(i_plot); } } // end (if they are separate plots) } } // next y col } } // end (if there are some xy plots) if (!yEqList.isEmpty()) { QString eqS; double max, min; int n; bool xeq, eq_ok; SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq); for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) { KstEquationPtr eq; eqS = *eq_i; ProcessEq(eqS, file, in, &eq_ok); if (xeq) { eq = new KstEquation(KST::suggestEQName(eqS), eqS, min,max,n); } else { if (!xvector) { xvector = GetOrCreateVector(args->getOption("x"), file, in); } if (xvector) { eq = new KstEquation(KST::suggestEQName(eqS), eqS, KstVectorPtr(xvector), true); } } if (eq) { KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(eq->tag(), true), eq->vX(), eq->vY(), 0L, 0L, 0L, 0L, KstColorSequence::next(vcurves,plot->backgroundColor())); KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(eq.data()); KST::dataObjectList.append(vc.data()); KST::dataObjectList.lock().unlock(); plot->addCurve(vc.data()); if (in.sep_plots) { plot->setTagName(eq->tag()); i_plot++; if (i_plot <in.n_plots) { plot = *plist.at(i_plot); } } } } } if (psdList.count() > 0) { // if there are some psd plots KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList); for (QCStringList::ConstIterator it = psdList.begin(); it != psdList.end(); ++it) { yvector = GetOrCreateVector(*it, file, in); if (yvector) { color = KstColorSequence::next(vcurves,plot->backgroundColor()); psd = new KstPSD( KST::suggestPSDName(yvector->tag()), // FIXME: this was yvector->field(), is this right? KstVectorPtr(yvector), in.rate, true, in.len, true, true, in.VUnits, in.RUnits, WindowOriginal); KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(psd->tag(), true), psd->vX(), psd->vY(), 0L, 0L, 0L, 0L, color); if (in.has_points) { vc->setHasPoints(true); vc->setHasLines(false); } KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(psd.data()); KST::dataObjectList.append(vc.data()); KST::dataObjectList.lock().unlock(); plot->addCurve(vc.data()); if (in.sep_plots) { plot->setTagName(psd->tag()); i_plot++; if (i_plot <in.n_plots) { plot = *plist.at(i_plot); } } } } // next psd } // end (if there are some psds) if (hsList.count() > 0) { // if there are some histograms double max, min; int N; KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList); for (hs_string = hsList.begin(); hs_string != hsList.end(); ++hs_string) { yvector = GetOrCreateVector(*hs_string, file, in); if (yvector) { color = KstColorSequence::next(vcurves,plot->backgroundColor()); KstHistogram::AutoBin(KstVectorPtr(yvector), &N, &max, &min); hs = new KstHistogram(KST::suggestHistogramName(yvector->tag()), KstVectorPtr(yvector), min, max, N, KST_HS_NUMBER); KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(hs->tag(), true), hs->vX(), hs->vY(), 0L, 0L, 0L, 0L, color); vc->setHasPoints(false); vc->setHasLines(false); vc->setHasBars(true); vc->setBarStyle(1); KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(hs.data()); KST::dataObjectList.append(vc.data()); KST::dataObjectList.lock().unlock(); plot->addCurve(vc.data()); if (in.sep_plots) { plot->setTagName(hs->tag()); i_plot++; if (i_plot < in.n_plots) { plot = *plist.at(i_plot); } } } } // next histogram } // end (if there are some histograms) if (matrixList.count() > 0) { // if there are some matrixes for (mat_i = matrixList.begin(); mat_i != matrixList.end(); ++mat_i) { QString tag_name = KST::suggestMatrixName(*mat_i); if (!file->isValidMatrix(*mat_i)) { startupErrors.append(i18n("Failed to create matrix '%1' from file '%2'.").arg(*mat_i).arg(file->fileName())); } KstRMatrixPtr matrix = new KstRMatrix(file, *mat_i, KstObjectTag(tag_name, file->tag()), 0,0,-1,-1,false,false,0); // xStart, yStart, xNumSteps, yNumSteps, //doAve, doSkip, skip); // Time to create the image from the matrix tag_name = KST::suggestImageName(matrix->tag()); QStringList palList = KPalette::getPaletteList(); QString pal; if (palList.contains("IDL 13 RAINBOW")) { pal = QString("IDL 13 RAINBOW"); } else { pal = QString(*palList.at(0)); } KPalette* newPal = new KPalette(pal); KstImagePtr image = new KstImage(tag_name, KstMatrixPtr(matrix), 0.0, 1.0, true, newPal); plot->addCurve(KstBaseCurvePtr(image)); KST::dataObjectList.lock().writeLock(); KST::dataObjectList.append(image.data()); KST::dataObjectList.lock().unlock(); image = 0L; // drop the reference if (in.sep_plots) { plot->setTagName(matrix->tag()); i_plot++; if (i_plot < in.n_plots) { plot = *plist.at(i_plot); } } } } } else { startupErrors.append(i18n("Failed to load file '%1'.").arg(args->arg(i_file))); } handled++; kst->slotUpdateProgress( count, handled, creatingCurves ); } // next data file count = in.n_plots; handled = 0; kst->slotUpdateProgress( count, handled, creatingPlots ); for (i_plot = 0; i_plot < in.n_plots; i_plot++) { plot = *plist.at(i_plot); plot->generateDefaultLabels(); // if we have only images in a plot then set the scale mode to AUTO (instead of AUTOBORDER) KstImageList images = kstObjectSubList<KstBaseCurve,KstImage>(plot->Curves); if (images.count() == plot->Curves.count()) { plot->setXScaleMode(AUTO); plot->setYScaleMode(AUTO); } if (plot->Curves.count() > 3 || in.dolegend) { KstViewLegendPtr vl = plot->getOrCreateLegend(); vl->resizeFromAspect(0.1, 0.1, 0.2, 0.1); vl->setBorderWidth(2); } handled++; kst->slotUpdateProgress( count, handled, creatingPlots ); } kst->slotUpdateProgress( 0, 0, QString::null ); } else if (args->count() > 0) { // open a kst file // some of the options can be overridden kst->openDocumentFile(args->arg(0), args->getOption("F"), // override FileName args->getOption("n").toInt(&nOK), // override number of frames args->getOption("f").toInt(&nOK), // override starting frame args->getOption("s").toInt(&nOK), // override skip args->isSet("a"), // add averaging !print_and_exit); // delayed } else { //kst->openDocumentFile(); showQuickStart = true; } if (args->isSet("nq")) { showQuickStart = false; } if (args->isSet("w")) { showDataWizard = true; showQuickStart = false; } if (printfile != "<none>") { kst->forceUpdate(); kst->immediatePrintToFile(printfile, false); } if (pngfile != "<none>") { kst->forceUpdate(); kst->immediatePrintToPng(pngfile); } kst->document()->setModified(false); if (print_and_exit) { delete kst; return 0; } else { kst->updateDialogs(); if (showQuickStart) { kst->showQuickStartDialog(); } if (showDataWizard) { kst->showDataWizardWithFile(wizardfile); } for (size_t i = 0; i < startupErrors.size(); ++i) { KstDebug::self()->log(startupErrors[i], KstDebug::Error); } startupErrors.clear(); } // LEAVE THIS HERE - causes crashes otherwise! int rc = app.exec(); delete kst; return rc; } return app.exec(); }
QString QlFiles::name(const QString &path){ return QFileInfo(path).fileName(); }
QString QlFiles::path(const QString &path){ return QFileInfo(path).path(); }
qint64 QlFiles::size(const QString &path){ return QFileInfo(path).size(); }
CC_FILE_ERROR PovFilter::saveToFile(ccHObject* entity, const char* filename) { if (!entity || !filename) return CC_FERR_BAD_ARGUMENT; ccHObject::Container hClouds; entity->filterChildren(hClouds,false,CC_POINT_CLOUD); if (hClouds.empty()) return CC_FERR_NO_SAVE; unsigned i; std::vector<ccGBLSensor*> sensors; std::vector<ccGenericPointCloud*> clouds; for (i=0;hClouds.size();++i) { ccHObject::Container cloudSensors; hClouds[i]->filterChildren(cloudSensors,false,CC_GBL_SENSOR); if (!cloudSensors.empty()) { clouds.push_back(ccHObjectCaster::ToGenericPointCloud(hClouds[i])); if (cloudSensors.size()>1) ccLog::Warning(QString("Found more than one ground-based LIDAR sensor associated to entity '%1'. Only the first will be saved!").arg(hClouds[i]->getName())); sensors.push_back(static_cast<ccGBLSensor*>(cloudSensors[0])); } } assert(sensors.size() == clouds.size()); if (sensors.empty()) return CC_FERR_NO_SAVE; //FIXME //the first GLS sensor will be used as reference! (ugly) ccGBLSensor* firstGls = sensors.front(); if (sensors.size()>1) ccLog::Warning("Assuming all sensors are equivalent..."); //we extract the body of the filename (without extension) QString fullBaseName = QFileInfo(filename).completeBaseName(); //main file (.POV) FILE* mainFile = fopen(filename,"wt"); if (!mainFile) return CC_FERR_WRITING; if (fprintf(mainFile,"#CC_POVS_FILE\n")<0) { fclose(mainFile); return CC_FERR_WRITING; }; if (fprintf(mainFile,"SENSOR_TYPE = %s\n",CC_SENSOR_ROTATION_ORDER_NAMES[firstGls->getRotationOrder()])<0) { fclose(mainFile); return CC_FERR_WRITING; }; if (fprintf(mainFile,"SENSOR_BASE = %f\n",firstGls->getSensorBase())<0) { fclose(mainFile); return CC_FERR_WRITING; }; if (fprintf(mainFile,"UNITS = IGNORED\n")<0) { fclose(mainFile); return CC_FERR_WRITING; }; if (fprintf(mainFile,"#END_HEADER\n")<0) { fclose(mainFile); return CC_FERR_WRITING; }; for (i=0;i<clouds.size();++i) { QString thisFilename = fullBaseName + QString("_%1.bin").arg(i); CC_FILE_ERROR error = FileIOFilter::SaveToFile(clouds[i],qPrintable(thisFilename),BIN); if (error != CC_FERR_NO_ERROR) { fclose(mainFile); return error; } ccGBLSensor* gls = sensors[i]; //il faut ecrire le nom du fichier relatif et non absolu ! int result = fprintf(mainFile,"\n#POV %i\nF %s\nT ASC\n",i,qPrintable(QFileInfo(thisFilename).fileName())); if (result>0) { CCVector3 C = gls->getSensorCenter(); result = fprintf(mainFile,"C %f %f %f\n",C[0],C[1],C[2]); if (result>0) { const float* mat = gls->getOrientationMatrix().data(); result = fprintf(mainFile,"X %f %f %f\n",mat[0],mat[4],mat[8]); result = fprintf(mainFile,"Y %f %f %f\n",mat[1],mat[5],mat[9]); result = fprintf(mainFile,"Z %f %f %f\n",mat[2],mat[6],mat[10]); } if (result>0) result = fprintf(mainFile,"A %f %f\n",gls->getDeltaPhi(),gls->getDeltaTheta()); if (result>0) result = fprintf(mainFile,"#END_POV\n"); } /*if (++n==palier) { //cancel requested if (pwin->isCancelRequested()) result=-1; percent += 1.0; pwin->update(percent); n = 0; } //*/ } //delete pwin; fclose(mainFile); return CC_FERR_NO_ERROR; }
void QrcEditor::resolveLocationIssues(QStringList &files) { const QDir dir = QFileInfo(m_treeview->fileName()).absoluteDir(); const QString dotdotSlash = QLatin1String("../"); int i = 0; int count = files.count(); // Find first troublesome file for (; i < count; i++) { QString const &file = files.at(i); const QString relativePath = dir.relativeFilePath(file); if (relativePath.startsWith(dotdotSlash)) break; } // All paths fine -> no interaction needed if (i == count) { return; } // Interact with user from now on bool abort = false; for (; i < count; i++) { // Path fine -> skip file QString const &file = files.at(i); QString const relativePath = dir.relativeFilePath(file); if (!relativePath.startsWith(dotdotSlash)) { continue; } // Path troublesome and aborted -> remove file if (abort) { files.removeAt(i); count--; i--; continue; } else { // Path troublesome -> query user QMessageBox message(this); message.setWindowTitle(tr("Invalid file")); message.setIcon(QMessageBox::Warning); QPushButton * const continueButton = message.addButton(tr("Add anyway"), QMessageBox::AcceptRole); QPushButton * const copyButton = message.addButton(tr("Copy"), QMessageBox::ActionRole); QPushButton * const skipButton = message.addButton(tr("Don't add"), QMessageBox::DestructiveRole); QPushButton * const abortButton = message.addButton(tr("Abort"), QMessageBox::RejectRole); message.setDefaultButton(copyButton); message.setEscapeButton(skipButton); message.setText(tr("The file %1 is not in a subdirectory of the resource file. Continuing will result in an invalid resource file.") .arg(QDir::toNativeSeparators(file))); message.exec(); if (message.clickedButton() == continueButton) { continue; } else if (message.clickedButton() == skipButton) { files.removeAt(i); count--; i--; // Compensate i++ } else if (message.clickedButton() == copyButton) { const QFileInfo fi(file); const QFileInfo suggestion(dir, fi.fileName()); const QString copyName = QFileDialog::getSaveFileName(this, tr("Choose copy location"), suggestion.absoluteFilePath()); if (!copyName.isEmpty()) { if (QFile::exists(copyName)) { if (!QFile::remove(copyName)) { QMessageBox::critical(this, tr("Overwrite failed"), tr("Could not overwrite file %1.") .arg(QDir::toNativeSeparators(copyName))); // Remove file files.removeAt(i); count--; i--; // Compensate i++ continue; } } if (!QFile::copy(file, copyName)) { QMessageBox::critical(this, tr("Copying failed"), tr("Could not copy the file to %1.") .arg(QDir::toNativeSeparators(copyName))); // Remove file files.removeAt(i); count--; i--; // Compensate i++ continue; } files[i] = copyName; } else { // Remove file files.removeAt(i); count--; i--; // Compensate i++ } } else if (message.clickedButton() == abortButton) { abort = true; files.removeAt(i); count--; i--; // Compensate i++ } } } }
bool RemotePlugin::init( const QString &pluginExecutable, bool waitForInitDoneMsg ) { lock(); if( m_failed ) { #ifdef SYNC_WITH_SHM_FIFO reset( new shmFifo(), new shmFifo() ); #endif m_failed = false; } QString exec = QFileInfo(QDir("plugins:"), pluginExecutable).absoluteFilePath(); #ifdef LMMS_BUILD_APPLE // search current directory first QString curDir = QCoreApplication::applicationDirPath() + "/" + pluginExecutable; if( QFile( curDir ).exists() ) { exec = curDir; } #endif #ifdef LMMS_BUILD_WIN32 if( ! exec.endsWith( ".exe", Qt::CaseInsensitive ) ) { exec += ".exe"; } #endif if( ! QFile( exec ).exists() ) { qWarning( "Remote plugin '%s' not found.", exec.toUtf8().constData() ); m_failed = true; invalidate(); unlock(); return failed(); } QStringList args; #ifdef SYNC_WITH_SHM_FIFO // swap in and out for bidirectional communication args << QString::number( out()->shmKey() ); args << QString::number( in()->shmKey() ); #else args << m_socketFile; #endif #ifndef DEBUG_REMOTE_PLUGIN m_process.setProcessChannelMode( QProcess::ForwardedChannels ); m_process.setWorkingDirectory( QCoreApplication::applicationDirPath() ); m_process.start( exec, args ); m_watcher.start( QThread::LowestPriority ); #else qDebug() << exec << args; #endif connect( &m_process, SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( processFinished( int, QProcess::ExitStatus ) ) ); #ifndef SYNC_WITH_SHM_FIFO struct pollfd pollin; pollin.fd = m_server; pollin.events = POLLIN; switch ( poll( &pollin, 1, 30000 ) ) { case -1: qWarning( "Unexpected poll error." ); break; case 0: qWarning( "Remote plugin did not connect." ); break; default: m_socket = accept( m_server, NULL, NULL ); if ( m_socket == -1 ) { qWarning( "Unexpected socket error." ); } } #endif resizeSharedProcessingMemory(); if( waitForInitDoneMsg ) { waitForInitDone(); } unlock(); return failed(); }
void ScribusQApp::parseCommandLine() { showSplash=!neverSplashExists(); QString arg(""); bool usage=false; bool header=false; bool availlangs=false; bool version=false; bool runUpgradeCheck=false; showFontInfo=false; showProfileInfo=false; swapDialogButtonOrder=false; //Parse for command line information options, and lang for(int i = 1; i < argc(); i++) { arg = argv()[i]; if ((arg == ARG_LANG || arg == ARG_LANG_SHORT) && (++i < argc())) { lang = argv()[i]; } else if (arg == ARG_VERSION || arg == ARG_VERSION_SHORT) { header=true; version=true; } else if (arg == ARG_HELP || arg == ARG_HELP_SHORT) { header=true; usage=true; } else if (arg == ARG_AVAILLANG || arg == ARG_AVAILLANG_SHORT) { header=true; availlangs=true; } else if (arg == ARG_UPGRADECHECK || arg == ARG_UPGRADECHECK_SHORT) { header=true; runUpgradeCheck=true; } } //Init translations initLang(); //Show command line help if (header) showHeader(); if (version) showVersion(); if (availlangs) showAvailLangs(); if (usage) showUsage(); if (runUpgradeCheck) { UpgradeChecker uc; uc.fetch(); } //Dont run the GUI init process called from main.cpp, and return if (!header) useGUI=true; else return; //We are going to run something other than command line help for(int i = 1; i < argc(); i++) { arg = argv()[i]; if ((arg == ARG_LANG || arg == ARG_LANG_SHORT) && (++i < argc())) { continue; } else if ( arg == ARG_CONSOLE || arg == ARG_CONSOLE_SHORT ) { continue; } else if (arg == ARG_NOSPLASH || arg == ARG_NOSPLASH_SHORT) { showSplash = false; } else if (arg == ARG_NEVERSPLASH || arg == ARG_NEVERSPLASH_SHORT) { showSplash = false; neverSplash(true); } else if (arg == ARG_NOGUI || arg == ARG_NOGUI_SHORT) { useGUI=false; } else if (arg == ARG_FONTINFO || arg == ARG_FONTINFO_SHORT) { showFontInfo=true; } else if (arg == ARG_PROFILEINFO || arg == ARG_PROFILEINFO_SHORT) { showProfileInfo=true; } else if (arg == ARG_SWAPDIABUTTONS || arg == ARG_SWAPDIABUTTONS_SHORT) { swapDialogButtonOrder=true; } else if ((arg == ARG_DISPLAY || arg==ARG_DISPLAY_SHORT || arg==ARG_DISPLAY_QT) && ++i < argc()) { // allow setting of display, QT expect the option -display <display_name> so we discard the // last argument. FIXME: Qt only understands -display not --display and -d , we need to work // around this. } else if (arg == ARG_PREFS || arg == ARG_PREFS_SHORT) { prefsUserFile = QFile::decodeName(argv()[i + 1]); if (!QFileInfo(prefsUserFile).exists()) { showHeader(); if (fileName.left(1) == "-" || fileName.left(2) == "--") { std::cout << tr("Invalid argument: ").toLocal8Bit().data() << fileName.toLocal8Bit().data() << std::endl; } else { std::cout << tr("File %1 does not exist, aborting.").arg(fileName).toLocal8Bit().data() << std::endl; } showUsage(); useGUI=false; return; } else { ++i; } } else if (strncmp(arg.toLocal8Bit().data(),"-psn_",4) == 0) { // Andreas Vox: Qt/Mac has -psn_blah flags that must be accepted. } else { fileName = QFile::decodeName(argv()[i]); if (!QFileInfo(fileName).exists()) { showHeader(); if (fileName.left(1) == "-" || fileName.left(2) == "--") { std::cout << tr("Invalid argument: %1").arg(fileName).toLocal8Bit().data() << std::endl; } else { std::cout << tr("File %1 does not exist, aborting.").arg(fileName).toLocal8Bit().data() << std::endl; } showUsage(); useGUI=false; return; } else { filesToLoad.append(fileName); } } } }
int main(int argc, char **argv) { #ifdef CONSOLE_APPLICATION QApplication app(argc, argv, QApplication::Tty); #else QApplication app(argc, argv); #endif #ifdef DO_QWS_DEBUGGING qt_show_painter_debug_output = false; #endif DeviceType type = WidgetType; bool checkers_background = true; QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied; QLocale::setDefault(QLocale::c()); QStringList files; bool interactive = false; bool printdlg = false; bool highres = false; bool show_cmp = false; int width = 800, height = 800; int scaledWidth = width, scaledHeight = height; qreal scalefactor = 1.0; bool verboseMode = false; #ifndef QT_NO_OPENGL QGLFormat f = QGLFormat::defaultFormat(); f.setSampleBuffers(true); f.setStencil(true); f.setAlpha(true); f.setAlphaBufferSize(8); QGLFormat::setDefaultFormat(f); #endif char *arg; for (int i=1; i<argc; ++i) { arg = argv[i]; if (*arg == '-') { QString option = QString(arg + 1).toLower(); if (option == "widget") type = WidgetType; else if (option == "bitmap") type = BitmapType; else if (option == "pixmap") type = PixmapType; else if (option == "image") type = ImageType; else if (option == "imageformat") { Q_ASSERT_X(i + 1 < argc, "main", "-imageformat must be followed by a value"); QString format = QString(argv[++i]).toLower(); imageFormat = QImage::Format_Invalid; static const int formatCount = sizeof(imageFormats) / sizeof(imageFormats[0]); for (int ff = 0; ff < formatCount; ++ff) { if (QLatin1String(imageFormats[ff].name) == format) { imageFormat = imageFormats[ff].format; break; } } if (imageFormat == QImage::Format_Invalid) { printf("Invalid image format. Available formats are:\n"); for (int ff = 0; ff < formatCount; ++ff) printf("\t%s\n", imageFormats[ff].name); return -1; } } else if (option == "imagemono") type = ImageMonoType; else if (option == "imagewidget") type = ImageWidgetType; #ifndef QT_NO_OPENGL else if (option == "opengl") type = OpenGLType; else if (option == "glbuffer") type = OpenGLBufferType; #endif #ifdef USE_CUSTOM_DEVICE else if (option == "customdevice") type = CustomDeviceType; else if (option == "customwidget") type = CustomWidgetType; #endif else if (option == "pdf") type = PdfType; else if (option == "ps") type = PsType; else if (option == "picture") type = PictureType; else if (option == "printer") type = PrinterType; else if (option == "highres") { type = PrinterType; highres = true; } else if (option == "printdialog") { type = PrinterType; printdlg = true; } else if (option == "grab") type = GrabType; else if (option == "i") interactive = true; else if (option == "v") verboseMode = true; else if (option == "commands") { displayCommands(); return 0; } else if (option == "w") { Q_ASSERT_X(i + 1 < argc, "main", "-w must be followed by a value"); width = atoi(argv[++i]); } else if (option == "h") { Q_ASSERT_X(i + 1 < argc, "main", "-h must be followed by a value"); height = atoi(argv[++i]); } else if (option == "scalefactor") { Q_ASSERT_X(i + 1 < argc, "main", "-scalefactor must be followed by a value"); scalefactor = atof(argv[++i]); } else if (option == "cmp") { show_cmp = true; } else if (option == "bg-white") { checkers_background = false; } } else { #if defined (Q_WS_WIN) QString input = QString::fromLocal8Bit(argv[i]); if (input.indexOf('*') >= 0) { QFileInfo info(input); QDir dir = info.dir(); QFileInfoList infos = dir.entryInfoList(QStringList(info.fileName())); for (int ii=0; ii<infos.size(); ++ii) files.append(infos.at(ii).absoluteFilePath()); } else { files.append(input); } #else files.append(QString(argv[i])); #endif } } scaledWidth = width * scalefactor; scaledHeight = height * scalefactor; PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); QWidget *activeWidget = 0; if (interactive) { runInteractive(); if (!files.isEmpty()) interactive_widget->load(files.at(0)); } else if (files.isEmpty()) { printHelp(); return 0; } else { for (int j=0; j<files.size(); ++j) { const QString &fileName = files.at(j); QStringList content; QFile file(fileName); QFileInfo fileinfo(file); if (file.open(QIODevice::ReadOnly)) { QTextStream textFile(&file); QString script = textFile.readAll(); content = script.split("\n", QString::SkipEmptyParts); } else { printf("failed to read file: '%s'\n", qPrintable(fileinfo.absoluteFilePath())); continue; } pcmd.setContents(content); if (show_cmp) { QString pmFile = QString(files.at(j)).replace(".qps", "_qps") + ".png"; qDebug() << pmFile << QFileInfo(pmFile).exists(); QPixmap pixmap(pmFile); if (!pixmap.isNull()) { QLabel *label = createLabel(); label->setWindowTitle("VERIFY: " + pmFile); label->setPixmap(pixmap); label->show(); } } switch (type) { case WidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } case ImageWidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } #ifndef QT_NO_OPENGL case OpenGLBufferType: { QWindow win; win.setSurfaceType(QSurface::OpenGLSurface); win.create(); QOpenGLFramebufferObjectFormat fmt; fmt.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); fmt.setSamples(4); QOpenGLContext ctx; ctx.create(); ctx.makeCurrent(&win); QOpenGLFramebufferObject fbo(width, height, fmt); fbo.bind(); QOpenGLPaintDevice pdev(width, height); QPainter pt(&pdev); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image = fbo.toImage(); QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case OpenGLType: { OnScreenWidget<QGLWidget> *qGLWidget = new OnScreenWidget<QGLWidget>(files.at(j)); qGLWidget->setVerboseMode(verboseMode); qGLWidget->setType(type); qGLWidget->setCheckersBackground(checkers_background); qGLWidget->m_commands = content; qGLWidget->resize(width, height); qGLWidget->show(); activeWidget = qGLWidget; break; } #else case OpenGLType: case OpenGLBufferType: { printf("OpenGL type not supported in this Qt build\n"); break; } #endif #ifdef USE_CUSTOM_DEVICE case CustomDeviceType: { CustomPaintDevice custom(width, height); QPainter pt; pt.begin(&custom); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage *img = custom.image(); if (img) { QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(*img)); label->resize(label->sizeHint()); label->show(); activeWidget = label; img->save("custom_output_pixmap.png", "PNG"); } else { custom.save("custom_output_pixmap.png", "PNG"); } break; } case CustomWidgetType: { OnScreenWidget<CustomWidget> *cWidget = new OnScreenWidget<CustomWidget>; cWidget->setVerboseMode(verboseMode); cWidget->setType(type); cWidget->setCheckersBackground(checkers_background); cWidget->m_filename = files.at(j); cWidget->setWindowTitle(fileinfo.filePath()); cWidget->m_commands = content; cWidget->resize(width, height); cWidget->show(); activeWidget = cWidget; break; } #endif case PixmapType: { QPixmap pixmap(scaledWidth, scaledHeight); pixmap.setDevicePixelRatio(scalefactor); pixmap.fill(Qt::white); QPainter pt(&pixmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); pixmap.save("output_pixmap.png", "PNG"); break; } case BitmapType: { QBitmap bitmap(scaledWidth, scaledHeight); bitmap.setDevicePixelRatio(scalefactor); QPainter pt(&bitmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); bitmap.save("output_bitmap.png", "PNG"); QLabel *label = createLabel(); label->setPixmap(bitmap); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case ImageMonoType: case ImageType: { qDebug() << "Creating image"; QImage image(scaledWidth, scaledHeight, type == ImageMonoType ? QImage::Format_MonoLSB : imageFormat); image.setDevicePixelRatio(scalefactor); image.fill(0); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); image.convertToFormat(QImage::Format_ARGB32).save("output_image.png", "PNG"); image.setDevicePixelRatio(1.0); // reset scale factor: display "large" image. #ifndef CONSOLE_APPLICATION QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; #endif break; } case PictureType: { QPicture pic; QPainter pt(&pic); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(0); pt.begin(&image); pt.drawPicture(0, 0, pic); pt.end(); QLabel *label = createLabel(); label->setWindowTitle(fileinfo.absolutePath()); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case PrinterType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QString file = QString(files.at(j)).replace(".", "_") + ".ps"; QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); if (printdlg) { QPrintDialog printDialog(&p, 0); if (printDialog.exec() != QDialog::Accepted) break; } else { p.setOutputFileName(file); } QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); if (!printdlg) { printf("wrote file: %s\n", qPrintable(file)); } Q_ASSERT(!p.paintingActive()); #endif break; } case PsType: case PdfType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); QFileInfo input(files.at(j)); const QString file = input.baseName() + QLatin1Char('_') + input.suffix() + QStringLiteral(".pdf"); p.setOutputFormat(QPrinter::PdfFormat); p.setOutputFileName(file); p.setPageSize(QPrinter::A4); QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); printf("write file: %s\n", qPrintable(file)); #endif break; } case GrabType: { QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(QColor(Qt::white).rgb()); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image1(width, height, QImage::Format_RGB32); image1.fill(QColor(Qt::white).rgb()); QPainter pt1(&image1); pt1.drawImage(QPointF(0, 0), image); pt1.end(); QString filename = QString(files.at(j)).replace(".qps", "_qps") + ".png"; image1.save(filename, "PNG"); printf("%s grabbed to %s\n", qPrintable(files.at(j)), qPrintable(filename)); break; } default: break; } } } #ifndef CONSOLE_APPLICATION if (activeWidget || interactive) { QObject::connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit())); app.exec(); } delete activeWidget; #endif delete interactive_widget; return 0; }
QStringList ScribusQApp::getLang(QString lang) { QStringList langs; // read the locales if (!lang.isEmpty()) langs.push_back(lang); //add in user preferences lang, only overridden by lang command line option QString Pff = QDir::toNativeSeparators(ScPaths::getApplicationDataDir()); QFileInfo Pffi = QFileInfo(Pff); if (Pffi.exists()) { QString PrefsPfad; if (Pffi.isDir()) PrefsPfad = Pff; else PrefsPfad = QDir::homePath(); QString prefsXMLFile=QDir::toNativeSeparators(PrefsPfad + "/prefs140.xml"); QFileInfo infoPrefsFile(prefsXMLFile); if (infoPrefsFile.exists()) { PrefsFile* prefsFile = new PrefsFile(prefsXMLFile); if (prefsFile) { PrefsContext* userprefsContext = prefsFile->getContext("user_preferences"); if (userprefsContext) { QString prefslang = userprefsContext->get("gui_language",""); if (!prefslang.isEmpty()) langs.push_back(prefslang); } } delete prefsFile; } } if (!(lang = ::getenv("LC_ALL")).isEmpty()) langs.push_back(lang); if (!(lang = ::getenv("LC_MESSAGES")).isEmpty()) langs.push_back(lang); if (!(lang = ::getenv("LANG")).isEmpty()) langs.push_back(lang); #if defined(_WIN32) wchar_t out[256]; QString language, sublanguage; LCID lcIdo = GetUserDefaultLCID(); WORD sortId = SORTIDFROMLCID(lcIdo); LANGID langId = GetUserDefaultUILanguage(); LCID lcIdn = MAKELCID(langId, sortId); if ( GetLocaleInfoW(lcIdn, LOCALE_SISO639LANGNAME , out, 255) ) { language = QString::fromUtf16( (ushort*)out ); if ( GetLocaleInfoW(lcIdn, LOCALE_SISO3166CTRYNAME, out, 255) ) { sublanguage = QString::fromUtf16( (ushort*)out ).toLower(); lang = language; if ( sublanguage != language && !sublanguage.isEmpty() ) lang += "_" + sublanguage.toUpper(); langs.push_back(lang); } } #endif langs.push_back(QString(QLocale::system().name())); // remove duplicate entries... QStringList::Iterator it = langs.end(); while (it != langs.begin()) { --it; if (langs.count(*it) > 1) it = langs.erase(it); } return langs; }
bool lcApplication::Initialize(int argc, char* argv[], const char* LibraryInstallPath, const char* LDrawPath, const char* LibraryCachePath) { char* LibPath = LIBPATH_DEFAULT; // Image output options. bool SaveImage = false; bool SaveWavefront = false; bool Save3DS = false; // bool ImageHighlight = false; int ImageWidth = lcGetProfileInt(LC_PROFILE_IMAGE_WIDTH); int ImageHeight = lcGetProfileInt(LC_PROFILE_IMAGE_HEIGHT); lcStep ImageStart = 0; lcStep ImageEnd = 0; char* ImageName = NULL; char* ProjectName = NULL; char* SaveWavefrontName = NULL; char* Save3DSName = NULL; // Parse the command line arguments. for (int i = 1; i < argc; i++) { char* Param = argv[i]; if (Param[0] == '-') { if ((strcmp(Param, "-l") == 0) || (strcmp(Param, "--libpath") == 0)) { ParseStringArgument(&i, argc, argv, &LibPath); } else if ((strcmp(Param, "-i") == 0) || (strcmp(Param, "--image") == 0)) { SaveImage = true; if ((argc > (i+1)) && (argv[i+1][0] != '-')) { i++; ImageName = argv[i]; } } else if ((strcmp(Param, "-w") == 0) || (strcmp(Param, "--width") == 0)) { ParseIntegerArgument(&i, argc, argv, &ImageWidth); } else if ((strcmp(Param, "-h") == 0) || (strcmp(Param, "--height") == 0)) { ParseIntegerArgument(&i, argc, argv, &ImageHeight); } else if ((strcmp(Param, "-f") == 0) || (strcmp(Param, "--from") == 0)) { int Step; ParseIntegerArgument(&i, argc, argv, &Step); ImageStart = Step; } else if ((strcmp(Param, "-t") == 0) || (strcmp(Param, "--to") == 0)) { int Step; ParseIntegerArgument(&i, argc, argv, &Step); ImageEnd = Step; } // else if (strcmp(Param, "--highlight") == 0) // ImageHighlight = true; else if ((strcmp(Param, "-wf") == 0) || (strcmp(Param, "--export-wavefront") == 0)) { SaveWavefront = true; if ((argc > (i+1)) && (argv[i+1][0] != '-')) { i++; SaveWavefrontName = argv[i]; } } else if ((strcmp(Param, "-3ds") == 0) || (strcmp(Param, "--export-3ds") == 0)) { Save3DS = true; if ((argc > (i+1)) && (argv[i+1][0] != '-')) { i++; Save3DSName = argv[i]; } } else if ((strcmp(Param, "-v") == 0) || (strcmp(Param, "--version") == 0)) { printf("LeoCAD Version " LC_VERSION_TEXT "\n"); printf("Compiled " __DATE__ "\n"); return false; } else if ((strcmp(Param, "-?") == 0) || (strcmp(Param, "--help") == 0)) { printf("Usage: leocad [options] [file]\n"); printf(" [options] can be:\n"); printf(" -l, --libpath <path>: Loads the Pieces Library from path.\n"); printf(" -i, --image <outfile.ext>: Saves a picture in the format specified by ext.\n"); printf(" -w, --width <width>: Sets the picture width.\n"); printf(" -h, --height <height>: Sets the picture height.\n"); printf(" -f, --from <time>: Sets the first frame or step to save pictures.\n"); printf(" -t, --to <time>: Sets the last frame or step to save pictures.\n"); // printf(" --highlight: Highlight pieces in the steps they appear.\n"); printf(" -wf, --export-wavefront <outfile.obj>: Exports the model to Wavefront format.\n"); printf(" -3ds, --export-3ds <outfile.3ds>: Exports the model to 3DS format.\n"); printf(" \n"); return false; } else printf("Unknown parameter: %s\n", Param); } else { ProjectName = Param; } } gMainWindow = new lcMainWindow(); lcLoadDefaultKeyboardShortcuts(); if (!LoadPiecesLibrary(LibPath, LibraryInstallPath, LDrawPath, LibraryCachePath)) { if (SaveImage || SaveWavefront || Save3DS) { fprintf(stderr, "ERROR: Cannot load pieces library."); return false; } if (mLibrary->LoadBuiltinPieces()) QMessageBox::information(gMainWindow, tr("LeoCAD"), tr("LeoCAD could not find a compatible Parts Library so only a small number of parts will be available.\n\n" "Please visit http://www.leocad.org for information on how to download and install a library.")); else QMessageBox::information(gMainWindow, tr("LeoCAD"), tr("LeoCAD could not load Parts Library.\n\n" "Please visit http://www.leocad.org for information on how to download and install a library.")); } gMainWindow->CreateWidgets(); // Create a new project. Project* NewProject = new Project(); SetProject(NewProject); // Load project. if (ProjectName && gMainWindow->OpenProject(ProjectName)) { if (SaveImage) { QString FileName; if (ImageName) FileName = ImageName; else FileName = ProjectName; QString Extension = QFileInfo(FileName).suffix().toLower(); if (Extension.isEmpty()) { FileName += lcGetProfileString(LC_PROFILE_IMAGE_EXTENSION); } else if (Extension != "bmp" && Extension != "jpg" && Extension != "jpeg" && Extension != "png") { FileName = FileName.left(FileName.length() - Extension.length() - 1); FileName += lcGetProfileString(LC_PROFILE_IMAGE_EXTENSION); } if (ImageEnd < ImageStart) ImageEnd = ImageStart; else if (ImageStart > ImageEnd) ImageStart = ImageEnd; if ((ImageStart == 0) && (ImageEnd == 0)) { ImageStart = ImageEnd = mProject->GetActiveModel()->GetCurrentStep(); } else if ((ImageStart == 0) && (ImageEnd != 0)) { ImageStart = ImageEnd; } else if ((ImageStart != 0) && (ImageEnd == 0)) { ImageEnd = ImageStart; } if (ImageStart > 255) ImageStart = 255; if (ImageEnd > 255) ImageEnd = 255; QString Frame; if (ImageStart != ImageEnd) { QString Extension = QFileInfo(FileName).suffix(); Frame = FileName.left(FileName.length() - Extension.length() - 1) + QLatin1String("%1.") + Extension; } else Frame = FileName; lcGetActiveModel()->SaveStepImages(Frame, ImageWidth, ImageHeight, ImageStart, ImageEnd); } if (SaveWavefront) { QString FileName; if (SaveWavefrontName) FileName = SaveWavefrontName; else FileName = ProjectName; QString Extension = QFileInfo(FileName).suffix().toLower(); if (Extension.isEmpty()) { FileName += ".obj"; } else if (Extension != "obj") { FileName = FileName.left(FileName.length() - Extension.length() - 1); FileName += ".obj"; } mProject->ExportWavefront(FileName); } if (Save3DS) { QString FileName; if (Save3DSName) FileName = Save3DSName; else FileName = ProjectName; QString Extension = QFileInfo(FileName).suffix().toLower(); if (Extension.isEmpty()) { FileName += ".3ds"; } else if (Extension != "3ds") { FileName = FileName.left(FileName.length() - Extension.length() - 1); FileName += ".3ds"; } mProject->Export3DStudio(FileName); } } if (SaveImage || SaveWavefront || Save3DS) return false; return true; }
bool ScribusQApp::neverSplashExists() { return QFileInfo(ScPaths::getApplicationDataDir() + ".neversplash").exists(); }
void sf2Instrument::openFile( const QString & _sf2File, bool updateTrackName ) { emit fileLoading(); // Used for loading file char * sf2Ascii = qstrdup( qPrintable( SampleBuffer::tryToMakeAbsolute( _sf2File ) ) ); QString relativePath = SampleBuffer::tryToMakeRelative( _sf2File ); // free reference to soundfont if one is selected freeFont(); m_synthMutex.lock(); s_fontsMutex.lock(); // Increment Reference if( s_fonts.contains( relativePath ) ) { qDebug() << "Using existing reference to " << relativePath; m_font = s_fonts[ relativePath ]; m_font->refCount++; m_fontId = fluid_synth_add_sfont( m_synth, m_font->fluidFont ); } // Add to map, if doesn't exist. else { m_fontId = fluid_synth_sfload( m_synth, sf2Ascii, true ); if( fluid_synth_sfcount( m_synth ) > 0 ) { // Grab this sf from the top of the stack and add to list m_font = new sf2Font( fluid_synth_get_sfont( m_synth, 0 ) ); s_fonts.insert( relativePath, m_font ); } else { // TODO: Couldn't load file! } } s_fontsMutex.unlock(); m_synthMutex.unlock(); if( m_fontId >= 0 ) { // Don't reset patch/bank, so that it isn't cleared when // someone resolves a missing file //m_patchNum.setValue( 0 ); //m_bankNum.setValue( 0 ); m_filename = relativePath; emit fileChanged(); } delete[] sf2Ascii; if( updateTrackName || instrumentTrack()->displayName() == displayName() ) { instrumentTrack()->setName( QFileInfo( _sf2File ).baseName() ); } }
void OpenProjectDialog::validateOpenUrl( const QUrl& url_ ) { bool isDir = false; QString extension; bool isValid = false; const QUrl url = url_.adjusted(QUrl::StripTrailingSlash); if( url.isLocalFile() ) { QFileInfo info( url.toLocalFile() ); isValid = info.exists(); if ( isValid ) { isDir = info.isDir(); extension = info.suffix(); } } else if ( url.isValid() ) { KIO::StatJob* statJob = KIO::stat( url, KIO::HideProgressInfo ); KJobWidgets::setWindow(statJob, Core::self()->uiControllerInternal()->defaultMainWindow() ); isValid = statJob->exec(); // TODO: do this asynchronously so that the user isn't blocked while typing every letter of the hostname in sftp://hostname if ( isValid ) { KIO::UDSEntry entry = statJob->statResult(); isDir = entry.isDir(); extension = QFileInfo( entry.stringValue( KIO::UDSEntry::UDS_NAME ) ).suffix(); } } if ( isValid ) { // reset header openPage->setHeader(i18n("Open \"%1\" as project", url.fileName())); } else { // report error KColorScheme scheme(palette().currentColorGroup()); const QString errorMsg = i18n("Selected URL is invalid"); openPage->setHeader(QStringLiteral("<font color='%1'>%2</font>") .arg(scheme.foreground(KColorScheme::NegativeText).color().name(), errorMsg) ); setAppropriate( projectInfoPage, false ); setAppropriate( openPage, true ); setValid( openPage, false ); return; } if( isDir || extension != ShellExtension::getInstance()->projectFileExtension() ) { setAppropriate( projectInfoPage, true ); m_url = url; if( !isDir ) { m_url = m_url.adjusted(QUrl::StripTrailingSlash | QUrl::RemoveFilename); } ProjectInfoPage* page = qobject_cast<ProjectInfoPage*>( projectInfoPage->widget() ); if( page ) { page->setProjectName( m_url.fileName() ); OpenProjectPage* page2 = qobject_cast<OpenProjectPage*>( openPage->widget() ); if( page2 ) { // Default manager page->setProjectManager( QStringLiteral("Generic Project Manager") ); // clear the filelist m_fileList.clear(); if( isDir ) { // If a dir was selected fetch all files in it KIO::ListJob* job = KIO::listDir( m_url ); connect( job, &KIO::ListJob::entries, this, &OpenProjectDialog::storeFileList); KJobWidgets::setWindow(job, Core::self()->uiController()->activeMainWindow()); job->exec(); } else { // Else we'lll just take the given file m_fileList << url.fileName(); } // Now find a manager for the file(s) in our filelist. bool managerFound = false; foreach( const QString& manager, page2->projectFilters().keys() ) { foreach( const QString& filterexp, page2->projectFilters().value(manager) ) { if( !m_fileList.filter( QRegExp( filterexp, Qt::CaseSensitive, QRegExp::Wildcard ) ).isEmpty() ) { managerFound = true; break; } } if( managerFound ) { page->setProjectManager( manager ); break; } } } } m_url.setPath( m_url.path() + '/' + m_url.fileName() + '.' + ShellExtension::getInstance()->projectFileExtension() ); } else
/*! Loads a thumbnail representation of \a content. The thumbnail will be scaled to \a size according to the given aspect ratio mode. */ QImage QContentStore::thumbnail(const QContent &content, const QSize &size, Qt::AspectRatioMode mode) { QImage thumbnail; QString thumbPath = thumbnailPath(content.fileName()); QFileInfo thumbInfo(thumbPath); if (thumbInfo.exists()) { if (thumbInfo.lastModified() > content.lastUpdated()) thumbnail = readThumbnail(thumbPath, size, mode); } else { thumbnail = QContentFactory::thumbnail(content, size, mode); } if (thumbnail.isNull()) { if (QIODevice *device = content.open()) { QImageReader reader(device); if (reader.canRead()) { QSize scaledSize = reader.size(); reader.setQuality(25); if (scaledSize.width() > 128 || scaledSize.height() > 128) { scaledSize.scale(QSize(128, 128), Qt::KeepAspectRatio); reader.setQuality( 49 ); // Otherwise Qt smooth scales reader.setScaledSize(scaledSize); reader.read(&thumbnail); if (!thumbnail.isNull()) { QImageWriter writer(thumbPath, QByteArray::fromRawData("PNG", 3)); writer.setQuality(25); writer.write(thumbnail); if (size.isValid()) thumbnail = thumbnail.scaled(size, mode); } } else { if (size.isValid()) { scaledSize.scale(size, mode); reader.setQuality( 49 ); // Otherwise Qt smooth scales reader.setScaledSize(scaledSize); } reader.read(&thumbnail); } } delete device; } } if (thumbnail.isNull() && content.type().startsWith(m_audioPrefix)) { QDir dir = QFileInfo(content.fileName()).absoluteDir(); foreach (const QString &fileName, m_folderThumbnails) { if (dir.exists(fileName)) { thumbnail = readThumbnail(dir.absoluteFilePath(fileName), size, mode); break; } } }
bool FolderWizardSourcePage::isComplete() const { QFileInfo selFile( QDir::fromNativeSeparators(_ui.localFolderLineEdit->text()) ); QString userInput = selFile.canonicalFilePath(); QString warnString; bool isOk = selFile.isDir(); if( !isOk ) { warnString = tr("No local folder selected!"); } if (isOk && !selFile.isWritable()) { isOk = false; warnString += tr("You have no permission to write to the selected folder!"); } // check if the local directory isn't used yet in another ownCloud sync Folder::Map map = _folderMap; if( isOk ) { Folder::Map::const_iterator i = map.constBegin(); while( isOk && i != map.constEnd() ) { Folder *f = static_cast<Folder*>(i.value()); QString folderDir = QDir( f->path() ).canonicalPath(); if( folderDir.isEmpty() ) { isOk = true; qDebug() << "Absolute path for folder: " << f->path() << " doesn't exist. Skipping."; i++; continue; } if( ! folderDir.endsWith(QLatin1Char('/')) ) folderDir.append(QLatin1Char('/')); qDebug() << "Checking local path: " << folderDir << " <-> " << userInput; if( QFileInfo( f->path() ) == userInput ) { isOk = false; warnString.append( tr("The local path %1 is already an upload folder.<br/>Please pick another one!") .arg(QDir::toNativeSeparators(userInput)) ); } if( isOk && folderDir.startsWith( userInput )) { qDebug() << "A already configured folder is child of the current selected"; warnString.append( tr("An already configured folder is contained in the current entry.")); isOk = false; } if( isOk && userInput.startsWith( folderDir ) ) { qDebug() << "An already configured folder is parent of the current selected"; warnString.append( tr("An already configured folder contains the currently entered directory.")); isOk = false; } i++; } } // check if the alias is unique. QString alias = _ui.aliasLineEdit->text(); if( alias.isEmpty() ) { warnString.append( tr("The alias can not be empty. Please provide a descriptive alias word.") ); isOk = false; } Folder::Map::const_iterator i = map.constBegin(); bool goon = true; while( goon && i != map.constEnd() ) { Folder *f = i.value(); qDebug() << "Checking local alias: " << f->alias(); if( f ) { if( f->alias() == alias ) { warnString.append( tr("<br/>The alias <i>%1</i> is already in use. Please pick another alias.").arg(alias) ); isOk = false; goon = false; } } i++; } if( isOk ) { _ui.warnLabel->hide(); _ui.warnLabel->setText( QString::null ); } else { _ui.warnLabel->show(); _ui.warnLabel->setText( warnString ); } return isOk; }
/* Init our module */ void Pulsars::init() { upgradeConfigIni(); try { StelFileMgr::makeSureDirExistsAndIsWritable(StelFileMgr::getUserDir()+"/modules/Pulsars"); // If no settings in the main config file, create with defaults if (!conf->childGroups().contains("Pulsars")) { qDebug() << "[Pulsars] No Pulsars section exists in main config file - creating with defaults"; restoreDefaultConfigIni(); } // populate settings from main config file. readSettingsFromConfig(); jsonCatalogPath = StelFileMgr::findFile("modules/Pulsars", (StelFileMgr::Flags)(StelFileMgr::Directory|StelFileMgr::Writable)) + "/pulsars.json"; if (jsonCatalogPath.isEmpty()) return; texPointer = StelApp::getInstance().getTextureManager().createTexture(StelFileMgr::getInstallationDir()+"/textures/pointeur2.png"); Pulsar::markerTexture = StelApp::getInstance().getTextureManager().createTexture(":/Pulsars/pulsar.png"); // key bindings and other actions addAction("actionShow_Pulsars", N_("Pulsars"), N_("Show pulsars"), "pulsarsVisible", "Ctrl+Alt+P"); addAction("actionShow_Pulsars_ConfigDialog", N_("Pulsars"), N_("Pulsars configuration window"), configDialog, "visible"); GlowIcon = new QPixmap(":/graphicGui/glow32x32.png"); OnIcon = new QPixmap(":/Pulsars/btPulsars-on.png"); OffIcon = new QPixmap(":/Pulsars/btPulsars-off.png"); setFlagShowPulsars(getEnableAtStartup()); setFlagShowPulsarsButton(flagShowPulsarsButton); } catch (std::runtime_error &e) { qWarning() << "[Pulsars] init error:" << e.what(); return; } // A timer for hiding alert messages messageTimer = new QTimer(this); messageTimer->setSingleShot(true); // recurring check for update messageTimer->setInterval(9000); // 6 seconds should be enough time messageTimer->stop(); connect(messageTimer, SIGNAL(timeout()), this, SLOT(messageTimeout())); // If the json file does not already exist, create it from the resource in the Qt resource if(QFileInfo(jsonCatalogPath).exists()) { if (!checkJsonFileFormat() || getJsonFileFormatVersion()<CATALOG_FORMAT_VERSION) { restoreDefaultJsonFile(); } } else { qDebug() << "[Pulsars] pulsars.json does not exist - copying default file to" << QDir::toNativeSeparators(jsonCatalogPath); restoreDefaultJsonFile(); } qDebug() << "[Pulsars] Loading catalog file:" << QDir::toNativeSeparators(jsonCatalogPath); readJsonFile(); // Set up download manager and the update schedule downloadMgr = new QNetworkAccessManager(this); connect(downloadMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(updateDownloadComplete(QNetworkReply*))); updateState = CompleteNoUpdates; updateTimer = new QTimer(this); updateTimer->setSingleShot(false); // recurring check for update updateTimer->setInterval(13000); // check once every 13 seconds to see if it is time for an update connect(updateTimer, SIGNAL(timeout()), this, SLOT(checkForUpdate())); updateTimer->start(); GETSTELMODULE(StelObjectMgr)->registerStelObjectMgr(this); }
CC_FILE_ERROR PovFilter::loadFile(const char* filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, double* coordinatesShift/*=0*/) { assert(!filename); //opening file FILE* fp = fopen(filename, "rt"); if (!fp) return CC_FERR_READING; //read buffer char line[MAX_ASCII_FILE_LINE_LENGTH]; //header if (!fgets(line, MAX_ASCII_FILE_LINE_LENGTH, fp)) { fclose(fp); return CC_FERR_READING; } if (strcmp(line,"#CC_POVS_FILE\n")!=0) { fclose(fp); return CC_FERR_READING; } char sensorType[12]; if (fscanf(fp,"SENSOR_TYPE = %s\n",sensorType)<0) { fclose(fp); return CC_FERR_READING; } ccGBLSensor::ROTATION_ORDER rotationOrder; if (strcmp(sensorType,CC_SENSOR_ROTATION_ORDER_NAMES[ccGBLSensor::PHI_THETA])==0) rotationOrder = ccGBLSensor::PHI_THETA; else if (strcmp(sensorType,CC_SENSOR_ROTATION_ORDER_NAMES[ccGBLSensor::THETA_PHI])==0) rotationOrder = ccGBLSensor::THETA_PHI; else { fclose(fp); return CC_FERR_READING; } float base=0.0f; if (fscanf(fp,"SENSOR_BASE = %f\n",&base)<0) { fclose(fp); return CC_FERR_READING; } //units: ignored in this version char unitsType[3]; if (fscanf(fp,"UNITS = %s\n",unitsType)<0) { fclose(fp); return CC_FERR_READING; } if (!fgets(line, MAX_ASCII_FILE_LINE_LENGTH, fp)) { fclose(fp); return CC_FERR_READING; } if (strcmp(line,"#END_HEADER\n")!=0) { fclose(fp); return CC_FERR_READING; } ccLog::Print("[PovFilter::loadFile] POV FILE [Type %s - base=%f - unit: %s}\n",sensorType,base,unitsType); //on extrait le chemin relatif QString path = QFileInfo(filename).absolutePath(); char subFileName[256]; char subFileType[12]; while (fgets(line, MAX_ASCII_FILE_LINE_LENGTH, fp)) { if ((line[0]=='#')&&(line[1]=='P')) { ccLog::Print("%s",line); if (fscanf(fp,"F %s\n",subFileName)<0) { ccLog::PrintDebug("[PovFilter::loadFile] Read error (F) !\n"); fclose(fp); return CC_FERR_READING; } if (fscanf(fp,"T %s\n",subFileType)<0) { ccLog::PrintDebug("[PovFilter::loadFile] Read error (T) !\n"); fclose(fp); return CC_FERR_READING; } //chargement du fichier (potentiellement plusieurs listes) correspondant au point de vue en cours CC_FILE_TYPES fType = FileIOFilter::GuessFileFormatFromExtension(subFileType); ccHObject* loadedLists = FileIOFilter::LoadFromFile(qPrintable(QString("%0/%1").arg(path).arg(subFileName)),fType); if (loadedLists) { ccGBLSensor* gls = new ccGBLSensor(rotationOrder); //ne pas oublier la base du scanner (SOISIC) gls->setSensorBase(base); ccGLMatrix rot; rot.toIdentity(); while (fgets(line, MAX_ASCII_FILE_LINE_LENGTH, fp)) { if (line[0]=='#') break; else if (line[0]=='C') { float C[3]; sscanf(line,"C %f %f %f\n",C,C+1,C+2); gls->setSensorCenter(C); } else if (line[0]=='X' || line[0]=='Y' || line[0]=='Z') { float V[3]; sscanf(line+2,"%f %f %f\n",V,V+1,V+2); uchar col = uchar(line[0])-88; float* mat = rot.data(); mat[col+0] = V[0]; mat[col+4] = V[1]; mat[col+8] = V[2]; } else if (line[0]=='A') { float dPhi,dTheta; sscanf(line,"A %f %f\n",&dPhi,&dTheta); gls->setDeltaPhi(dPhi); gls->setDeltaTheta(dTheta); } } gls->setOrientationMatrix(rot); int errorCode; ccHObject::Container clouds; if (loadedLists->isKindOf(CC_POINT_CLOUD)) clouds.push_back(loadedLists); else loadedLists->filterChildren(clouds,true,CC_POINT_CLOUD); for (unsigned i=0;i<clouds.size();++i) { ccGenericPointCloud* theCloud = ccHObjectCaster::ToGenericPointCloud(clouds[i]); CCLib::GenericIndexedCloud* projectedList = gls->project(theCloud,errorCode,true); switch (errorCode) { case -1: ccLog::Print(QString("[PovFilter::loadFile] Error on cloud #%1 (%2): nothing to project?! Must be a bug, sorry ;)").arg(i).arg(theCloud->getName())); break; case -2: ccLog::Print(QString("[PovFilter::loadFile] Error on cloud #%1 (%2): the resulting depth map seems much too big! Check parameters, or reduce angular steps ...").arg(i).arg(theCloud->getName())); break; case -3: ccLog::Print(QString("[PovFilter::loadFile] Error on cloud #%1 (%2): the resulting depth map is void (too small)! Check parameters and input, or increase angular steps ...").arg(i).arg(theCloud->getName())); break; case -4: ccLog::Print(QString("[PovFilter::loadFile] Error on cloud #%1 (%2): not enough memory!").arg(i).arg(theCloud->getName())); break; } if (projectedList) { delete projectedList; projectedList=0; theCloud->addChild(gls); } else { delete gls; gls=0; } theCloud->setName(subFileName); container.addChild(theCloud); } } else { ccLog::Print("[PovFilter::loadFile] File (%s) not found or empty!\n",subFileName); } } } fclose(fp); return CC_FERR_NO_ERROR; }
QList<QgsOgrDbLayerInfo *> QgsOgrLayerItem::subLayers( const QString &path, const QString &driver ) { QList<QgsOgrDbLayerInfo *> children; // Vector layers QgsVectorLayer layer( path, QStringLiteral( "ogr_tmp" ), QStringLiteral( "ogr" ) ); if ( ! layer.isValid( ) ) { QgsDebugMsgLevel( QStringLiteral( "Layer is not a valid %1 Vector layer %2" ).arg( path ), 3 ); } else { // Collect mixed-geom layers QMultiMap<int, QStringList> subLayersMap; QgsOgrProvider *ogrProvider = qobject_cast<QgsOgrProvider *>( layer.dataProvider() ); const QStringList subLayersList( ogrProvider->subLayersWithoutFeatureCount( ) ); QMap< QString, int > mapLayerNameToCount; bool uniqueNames = true; int prevIdx = -1; for ( const QString &descriptor : subLayersList ) { QStringList pieces = descriptor.split( QgsDataProvider::SUBLAYER_SEPARATOR ); int idx = pieces[0].toInt(); subLayersMap.insert( idx, pieces ); if ( pieces.count() >= 4 && idx != prevIdx ) { QString layerName = pieces[1]; int count = ++mapLayerNameToCount[layerName]; if ( count > 1 || layerName.isEmpty() ) uniqueNames = false; } prevIdx = idx; } prevIdx = -1; const auto subLayerKeys = subLayersMap.keys( ); for ( const int &idx : subLayerKeys ) { if ( idx == prevIdx ) { continue; } prevIdx = idx; QList<QStringList> values = subLayersMap.values( idx ); for ( int i = 0; i < values.size(); ++i ) { QStringList pieces = values.at( i ); QString layerId = pieces[0]; QString name = pieces[1]; // QString featuresCount = pieces[2]; // Not used QString geometryType = pieces[3]; QString geometryColumn = pieces[4]; QgsLayerItem::LayerType layerType; layerType = QgsOgrLayerItem::layerTypeFromDb( geometryType ); // example URI for mixed-geoms geoms: '/path/gdal_sample_v1.2_no_extensions.gpkg|layerid=7|geometrytype=Point' // example URI for mixed-geoms attr table: '/path/gdal_sample_v1.2_no_extensions.gpkg|layername=MyLayer|layerid=7' // example URI for single geoms: '/path/gdal_sample_v1.2_no_extensions.gpkg|layerid=6' QString uri; if ( layerType != QgsLayerItem::LayerType::NoType ) { if ( geometryType.contains( QStringLiteral( "Collection" ), Qt::CaseInsensitive ) ) { QgsDebugMsgLevel( QStringLiteral( "Layer %1 is a geometry collection: skipping %2" ).arg( name, path ), 3 ); } else { if ( uniqueNames ) uri = QStringLiteral( "%1|layername=%2" ).arg( path, name ); else uri = QStringLiteral( "%1|layerid=%2" ).arg( path, layerId ); if ( values.size() > 1 ) { uri += QStringLiteral( "|geometrytype=" ) + geometryType; } QgsDebugMsgLevel( QStringLiteral( "Adding %1 Vector item %2 %3 %4" ).arg( driver, name, uri, geometryType ), 3 ); children.append( new QgsOgrDbLayerInfo( path, uri, name, geometryColumn, geometryType, layerType ) ); } } else { QgsDebugMsgLevel( QStringLiteral( "Layer type is not a supported %1 Vector layer %2" ).arg( driver, path ), 3 ); uri = QStringLiteral( "%1|layerid=%2|layername=%3" ).arg( path, layerId, name ); children.append( new QgsOgrDbLayerInfo( path, uri, name, geometryColumn, geometryType, QgsLayerItem::LayerType::TableLayer ) ); } QgsDebugMsgLevel( QStringLiteral( "Adding %1 Vector item %2 %3 %4" ).arg( driver, name, uri, geometryType ), 3 ); } } } // Raster layers QgsRasterLayer::LayerOptions options; options.loadDefaultStyle = false; QgsRasterLayer rlayer( path, QStringLiteral( "gdal_tmp" ), QStringLiteral( "gdal" ), options ); if ( !rlayer.dataProvider()->subLayers( ).empty() ) { const QStringList layers( rlayer.dataProvider()->subLayers( ) ); for ( const QString &uri : layers ) { // Split on ':' since this is what comes out from the provider QStringList pieces = uri.split( ':' ); QString name = pieces.value( pieces.length() - 1 ); QgsDebugMsgLevel( QStringLiteral( "Adding GeoPackage Raster item %1 %2 %3" ).arg( name, uri ), 3 ); children.append( new QgsOgrDbLayerInfo( path, uri, name, QString(), QStringLiteral( "Raster" ), QgsLayerItem::LayerType::Raster ) ); } } else if ( rlayer.isValid( ) ) { // Get the identifier GDALAllRegister(); // do not print errors, but write to debug CPLPushErrorHandler( CPLQuietErrorHandler ); CPLErrorReset(); gdal::dataset_unique_ptr hDS( GDALOpen( path.toUtf8().constData(), GA_ReadOnly ) ); CPLPopErrorHandler(); if ( ! hDS ) { QgsDebugMsg( QStringLiteral( "GDALOpen error # %1 : %2 " ).arg( CPLGetLastErrorNo() ).arg( CPLGetLastErrorMsg() ) ); } else { QString uri( QStringLiteral( "%1:%2" ).arg( driver, path ) ); QString name = GDALGetMetadataItem( hDS.get(), "IDENTIFIER", nullptr ); hDS.reset(); // Fallback: will not be able to delete the table if ( name.isEmpty() ) { name = QFileInfo( path ).fileName(); } else { uri += QStringLiteral( ":%1" ).arg( name ); } QgsDebugMsgLevel( QStringLiteral( "Adding %1 Raster item %2 %3" ).arg( driver, name, path ), 3 ); children.append( new QgsOgrDbLayerInfo( path, uri, name, QString(), QStringLiteral( "Raster" ), QgsLayerItem::LayerType::Raster ) ); } } return children; }
bool QlFiles::exists(const QString &path){ return QFileInfo(path).exists(); }