void FileInfo::addRequiredFile(const QUrl &t_url) { addRequiredFile(t_url, toPath(toPath(t_url.toLocalFile()).filename())); }
QString QMLBridge::toLocalFile(QUrl url) { return url.toLocalFile(); }
/** Returns the best match for the given file url in the project directory. The method first checks whether the file inside the project directory exists. If not, the leading directory in the path is stripped, and the - now shorter - path is checked for existence, and so on. Second, it tries to locate the file in the sysroot folder specified. Third, we walk the list of project files, and search for a file name match there. If all fails, it returns the original path from the file url. */ QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const { QString originalPath = fileUrl.toLocalFile(); if (originalPath.isEmpty()) // e.g. qrc:// originalPath = fileUrl.path(); if (originalPath.isEmpty()) { if (success) *success = false; return originalPath; } if (!m_projectDir.isEmpty()) { int prefixToIgnore = -1; const QChar separator = QLatin1Char('/'); if (originalPath.startsWith(m_projectDir + separator)) { #ifdef Q_OS_MAC // starting with the project path is not sufficient if the file was // copied in an insource build, e.g. into MyApp.app/Contents/Resources static const QString appResourcePath = QString::fromLatin1(".app/Contents/Resources"); if (originalPath.contains(appResourcePath)) { // the path is inside the project, but most probably as a resource of an insource build // so ignore that path prefixToIgnore = originalPath.indexOf(appResourcePath) + appResourcePath.length(); } else { #endif if (success) *success = true; return originalPath; #ifdef Q_OS_MAC } #endif } if (m_cache.contains(originalPath)) { // check if cached path is still there QString candidate = m_cache.value(originalPath); QFileInfo candidateInfo(candidate); if (candidateInfo.exists() && candidateInfo.isFile()) { if (success) *success = true; return candidate; } } // Strip directories one by one from the beginning of the path, // and see if the new relative path exists in the build directory. if (prefixToIgnore < 0) { if (!QFileInfo(originalPath).isAbsolute() && !originalPath.startsWith(separator)) { prefixToIgnore = 0; } else { prefixToIgnore = originalPath.indexOf(separator); } } while (prefixToIgnore != -1) { QString candidate = originalPath; candidate.remove(0, prefixToIgnore); candidate.prepend(m_projectDir); QFileInfo candidateInfo(candidate); if (candidateInfo.exists() && candidateInfo.isFile()) { if (success) *success = true; m_cache.insert(originalPath, candidate); return candidate; } prefixToIgnore = originalPath.indexOf(separator, prefixToIgnore + 1); } } // find (solely by filename) in project files const QString fileName = QFileInfo(originalPath).fileName(); foreach (const QString &f, m_projectFiles) { if (QFileInfo(f).fileName() == fileName) { m_cache.insert(originalPath, f); if (success) *success = true; return f; } } // check if absolute path is found in sysroot if (!m_sysroot.isEmpty()) { const QString sysrootPath = m_sysroot + originalPath; if (QFileInfo(sysrootPath).exists() && QFileInfo(sysrootPath).isFile()) { if (success) *success = true; m_cache.insert(originalPath, sysrootPath); return sysrootPath; } } if (success) *success = false; return originalPath; }
KIOExec::KIOExec(const QStringList &args, bool tempFiles, const QString &suggestedFileName) : mExited(false) , mTempFiles(tempFiles) , mSuggestedFileName(suggestedFileName) , expectedCounter(0) , command(args.first()) , jobCounter(0) { qDebug() << "command=" << command << "args=" << args; for ( int i = 1; i < args.count(); i++ ) { const QUrl urlArg = QUrl::fromUserInput(args.value(i)); if (!urlArg.isValid()) { KMessageBox::error( 0L, i18n("Invalid URL: %1", args.value(i)) ); exit(1); } KIO::StatJob* mostlocal = KIO::mostLocalUrl( urlArg ); bool b = mostlocal->exec(); if (!b) { KMessageBox::error( 0L, i18n("File not found: %1", urlArg.toDisplayString())); exit(1); } Q_ASSERT(b); const QUrl url = mostlocal->mostLocalUrl(); //kDebug() << "url=" << url.url() << " filename=" << url.fileName(); // A local file, not an URL ? // => It is not encoded and not shell escaped, too. if ( url.isLocalFile() ) { FileInfo file; file.path = url.toLocalFile(); file.url = url; fileList.append(file); } // It is an URL else { if ( !url.isValid() ) KMessageBox::error( 0L, i18n( "The URL %1\nis malformed" , url.url() ) ); else if ( mTempFiles ) KMessageBox::error( 0L, i18n( "Remote URL %1\nnot allowed with --tempfiles switch" , url.toDisplayString() ) ); else // We must fetch the file { QString fileName = KIO::encodeFileName( url.fileName() ); if ( !suggestedFileName.isEmpty() ) fileName = suggestedFileName; // Build the destination filename, in ~/.kde/cache-*/krun/ // Unlike KDE-1.1, we put the filename at the end so that the extension is kept // (Some programs rely on it) QString krun_writable = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/krun/"; QDir().mkpath(krun_writable); // error handling will be done by the job QString tmp = krun_writable + QStringLiteral("%1_%2_%3").arg(QCoreApplication::applicationPid()).arg(jobCounter++).arg(fileName); FileInfo file; file.path = tmp; file.url = url; fileList.append(file); expectedCounter++; const QUrl dest = QUrl::fromLocalFile(tmp); qDebug() << "Copying" << url << " to" << dest; KIO::Job *job = KIO::file_copy( url, dest ); jobList.append( job ); connect( job, SIGNAL( result( KJob * ) ), SLOT( slotResult( KJob * ) ) ); } } } if ( mTempFiles ) { slotRunApp(); return; } counter = 0; if ( counter == expectedCounter ) slotResult( 0L ); }
// Extract the provider definition from the url bool QgsDelimitedTextFile::setFromUrl( const QUrl &url ) { // Close any existing definition resetDefinition(); // Extract the file name setFileName( url.toLocalFile() ); // Extract the encoding if ( url.hasQueryItem( QStringLiteral( "encoding" ) ) ) { mEncoding = url.queryItemValue( QStringLiteral( "encoding" ) ); } // if ( url.hasQueryItem( QStringLiteral( "watchFile" ) ) ) { mUseWatcher = url.queryItemValue( QStringLiteral( "watchFile" ) ).toUpper().startsWith( 'Y' ); } // The default type is csv, to be consistent with the // previous implementation (except that quoting should be handled properly) QString type( QStringLiteral( "csv" ) ); QString delimiter( QStringLiteral( "," ) ); QString quote = QStringLiteral( "\"" ); QString escape = QStringLiteral( "\"" ); mUseHeader = true; mSkipLines = 0; // Prefer simple "type" for delimiter type, but include delimiterType // as optional name for backwards compatibility if ( url.hasQueryItem( QStringLiteral( "type" ) ) || url.hasQueryItem( QStringLiteral( "delimiterType" ) ) ) { if ( url.hasQueryItem( QStringLiteral( "type" ) ) ) type = url.queryItemValue( QStringLiteral( "type" ) ); else if ( url.hasQueryItem( QStringLiteral( "delimiterType" ) ) ) type = url.queryItemValue( QStringLiteral( "delimiterType" ) ); // Support for previous version of Qgs - plain chars had // quote characters ' or " if ( type == QLatin1String( "plain" ) ) { quote = QStringLiteral( "'\"" ); escape.clear(); } else if ( type == QLatin1String( "regexp " ) ) { delimiter.clear(); quote.clear(); escape.clear(); } } if ( url.hasQueryItem( QStringLiteral( "delimiter" ) ) ) { delimiter = url.queryItemValue( QStringLiteral( "delimiter" ) ); } if ( url.hasQueryItem( QStringLiteral( "quote" ) ) ) { quote = url.queryItemValue( QStringLiteral( "quote" ) ); } if ( url.hasQueryItem( QStringLiteral( "escape" ) ) ) { escape = url.queryItemValue( QStringLiteral( "escape" ) ); } if ( url.hasQueryItem( QStringLiteral( "skipLines" ) ) ) { mSkipLines = url.queryItemValue( QStringLiteral( "skipLines" ) ).toInt(); } if ( url.hasQueryItem( QStringLiteral( "useHeader" ) ) ) { mUseHeader = ! url.queryItemValue( QStringLiteral( "useHeader" ) ).toUpper().startsWith( 'N' ); } if ( url.hasQueryItem( QStringLiteral( "skipEmptyFields" ) ) ) { mDiscardEmptyFields = ! url.queryItemValue( QStringLiteral( "skipEmptyFields" ) ).toUpper().startsWith( 'N' ); } if ( url.hasQueryItem( QStringLiteral( "trimFields" ) ) ) { mTrimFields = ! url.queryItemValue( QStringLiteral( "trimFields" ) ).toUpper().startsWith( 'N' ); } if ( url.hasQueryItem( QStringLiteral( "maxFields" ) ) ) { mMaxFields = url.queryItemValue( QStringLiteral( "maxFields" ) ).toInt(); } QgsDebugMsg( "Delimited text file is: " + mFileName ); QgsDebugMsg( "Encoding is: " + mEncoding ); QgsDebugMsg( "Delimited file type is: " + type ); QgsDebugMsg( "Delimiter is: [" + delimiter + ']' ); QgsDebugMsg( "Quote character is: [" + quote + ']' ); QgsDebugMsg( "Escape character is: [" + escape + ']' ); QgsDebugMsg( "Skip lines: " + QString::number( mSkipLines ) ); QgsDebugMsg( "Maximum number of fields in record: " + QString::number( mMaxFields ) ); QgsDebugMsg( "Use headers: " + QString( mUseHeader ? "Yes" : "No" ) ); QgsDebugMsg( "Discard empty fields: " + QString( mDiscardEmptyFields ? "Yes" : "No" ) ); QgsDebugMsg( "Trim fields: " + QString( mTrimFields ? "Yes" : "No" ) ); // Support for previous version of plain characters if ( type == QLatin1String( "csv" ) || type == QLatin1String( "plain" ) ) { setTypeCSV( delimiter, quote, escape ); } else if ( type == QLatin1String( "whitespace" ) ) { setTypeWhitespace(); } else if ( type == QLatin1String( "regexp" ) ) { setTypeRegexp( delimiter ); } else { return false; } return mDefinitionValid; }
bool QgsMapLayer::writeXML( QDomNode & layer_node, QDomDocument & document ) { // general layer metadata QDomElement maplayer = document.createElement( "maplayer" ); // use scale dependent visibility flag maplayer.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 ); maplayer.setAttribute( "minimumScale", QString::number( minimumScale() ) ); maplayer.setAttribute( "maximumScale", QString::number( maximumScale() ) ); // ID QDomElement layerId = document.createElement( "id" ); QDomText layerIdText = document.createTextNode( id() ); layerId.appendChild( layerIdText ); maplayer.appendChild( layerId ); // data source QDomElement dataSource = document.createElement( "datasource" ); QString src = source(); QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this ); // TODO: what about postgres, mysql and others, they should not go through writePath() if ( vlayer && vlayer->providerType() == "spatialite" ) { QgsDataSourceURI uri( src ); QString database = QgsProject::instance()->writePath( uri.database() ); uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() ); src = uri.uri(); } else if ( vlayer && vlayer->providerType() == "ogr" ) { QStringList theURIParts = src.split( "|" ); theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0] ); src = theURIParts.join( "|" ); } else if ( vlayer && vlayer->providerType() == "delimitedtext" ) { QUrl urlSource = QUrl::fromEncoded( src.toAscii() ); QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile() ) ); urlDest.setQueryItems( urlSource.queryItems() ); src = QString::fromAscii( urlDest.toEncoded() ); } else { src = QgsProject::instance()->writePath( src ); } QDomText dataSourceText = document.createTextNode( src ); dataSource.appendChild( dataSourceText ); maplayer.appendChild( dataSource ); // layer name QDomElement layerName = document.createElement( "layername" ); QDomText layerNameText = document.createTextNode( originalName() ); layerName.appendChild( layerNameText ); // layer title QDomElement layerTitle = document.createElement( "title" ) ; QDomText layerTitleText = document.createTextNode( title() ); layerTitle.appendChild( layerTitleText ); // layer abstract QDomElement layerAbstract = document.createElement( "abstract" ); QDomText layerAbstractText = document.createTextNode( abstract() ); layerAbstract.appendChild( layerAbstractText ); maplayer.appendChild( layerName ); maplayer.appendChild( layerTitle ); maplayer.appendChild( layerAbstract ); // timestamp if supported if ( timestamp() > QDateTime() ) { QDomElement stamp = document.createElement( "timestamp" ); QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) ); stamp.appendChild( stampText ); maplayer.appendChild( stamp ); } maplayer.appendChild( layerName ); // zorder // This is no longer stored in the project file. It is superfluous since the layers // are written and read in the proper order. // spatial reference system id QDomElement mySrsElement = document.createElement( "srs" ); mCRS->writeXML( mySrsElement, document ); maplayer.appendChild( mySrsElement ); // <transparencyLevelInt> QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" ); QDomText transparencyLevelIntText = document.createTextNode( QString::number( getTransparency() ) ); transparencyLevelIntElement.appendChild( transparencyLevelIntText ); maplayer.appendChild( transparencyLevelIntElement ); // now append layer node to map layer node layer_node.appendChild( maplayer ); writeCustomProperties( maplayer, document ); return writeXml( maplayer, document ); } // bool QgsMapLayer::writeXML
QString BazaarUtils::concatenatePath(const QDir& workingCopy, const QUrl& pathInWorkingCopy) { return QFileInfo(workingCopy.absolutePath() + QDir::separator() + pathInWorkingCopy.toLocalFile()).absoluteFilePath(); }
bool AutoDJFeature::dragMoveAccept(QUrl url) { QFileInfo file(url.toLocalFile()); return SoundSourceProxy::isFilenameSupported(file.fileName()); }
void RenamerWindow::rename(const QMimeData *mimeData) { QString currentText = comboBox->currentText(); if (currentText != "None" && mimeData->hasUrls()) { QList<QUrl> urlList = mimeData->urls(); for (int i = 0; i < urlList.size(); ++i) { QUrl url = urlList.at(i); QString localFile = url.toLocalFile(); QFileInfo fileInfo(localFile); QDir dir(localFile); QString filePath = fileInfo.filePath(); QString canonicalPath = fileInfo.canonicalPath(); QString fileName = fileInfo.fileName(); QString baseName = fileInfo.baseName(); QString suffix = fileInfo.suffix(); QString dirName = dir.dirName(); bool isFile = fileInfo.isFile(); bool isDir = fileInfo.isDir(); QString newFilePath = canonicalPath + "/"; if (currentText == "Prepend") { if (isFile) { newFilePath += baseName.prepend(lineEditA->text()).append('.').append(suffix); } else if (isDir) { newFilePath += dirName.prepend(lineEditA->text()); } } else if (currentText == "Append") { if (isFile) { newFilePath += baseName.append(lineEditA->text()).append('.').append(suffix); } else if (isDir) { newFilePath += dirName.append(lineEditA->text()); } } else if (currentText == "Remove") { if (isFile) { newFilePath += baseName.remove(lineEditA->text()).append('.').append(suffix); } else if (isDir) { newFilePath += dirName.remove(lineEditA->text()); } } else if (currentText == "Replace") { if (isFile) { newFilePath += baseName.replace(lineEditA->text(), lineEditB->text()).append('.').append(suffix); } else if (isDir) { newFilePath += dirName.replace(lineEditA->text(), lineEditB->text()); } } dir.rename(filePath, newFilePath); } } }
QString QPlayer::getMedia() { QUrl u = mp->media().canonicalUrl(); return u.isLocalFile() ? u.toLocalFile() : QString(); }
bool QWindowsServices::openDocument(const QUrl &url) { return shellExecute(url.isLocalFile() ? url.toLocalFile() : url.toString()); }
KoRecentDocumentsPane::KoRecentDocumentsPane(QWidget* parent, const QString& header) : KoDetailsPane(parent, header) , d(new KoRecentDocumentsPanePrivate) { setFocusProxy(m_documentList); m_openButton->setText(i18n("Open This Document")); m_openButton->setIcon(koIcon("document-open")); m_alwaysUseCheckBox->hide(); model()->setSortRole(0); // Disable sorting // load list of recent files from config KConfigGroup config(KSharedConfig::openConfig(), "RecentFiles"); QString fileKey; QString fileValue; QUrl url; QString nameValue; KFileItemList fileList; QStandardItem* rootItem = model()->invisibleRootItem(); for (int i = 1; i <= MAX_RECENTFILES_ENTRIES; ++i) { fileValue = config.readPathEntry(QString("File%1").arg(i), QString()); // ignore empty entries if (fileValue.isEmpty()) { continue; } url = QUrl::fromUserInput(fileValue); // ignore entries for files known to no longer exist if (url.isLocalFile() && !QFile::exists(url.toLocalFile())) { continue; } // ignore duplicated entries if (!fileList.findByUrl(url).isNull()) { continue; } nameValue = config.readPathEntry(QString("Name%1").arg(i), QString()); // handle name entries with empty strings if (nameValue.isEmpty()) { nameValue = url.fileName(); } KFileItem fileItem(url); fileList.prepend(fileItem); const QIcon icon = QIcon::fromTheme(fileItem.iconName()); KoFileListItem* item = new KoFileListItem(icon, nameValue, fileItem); item->setEditable(false); rootItem->insertRow(0, item); } //Select the first file QModelIndex firstIndex = model()->indexFromItem(model()->item(0)); m_documentList->selectionModel()->select(firstIndex, QItemSelectionModel::Select); m_documentList->selectionModel()->setCurrentIndex(firstIndex, QItemSelectionModel::Select); QStringList availablePlugins = KIO::PreviewJob::availablePlugins(); KIO::PreviewJob *previewJob = KIO::filePreview(fileList, QSize(IconExtent, IconExtent), &availablePlugins); d->m_previewJobs.append(previewJob); connect(previewJob, SIGNAL(result(KJob*)), SLOT(previewResult(KJob*))); connect(previewJob, SIGNAL(gotPreview(KFileItem,QPixmap)), SLOT(updateIcon(KFileItem,QPixmap))); }
void ImScrollArea::loadFits() { qDebug() << "Loading Fits image(s)..."; newFitsImage = new MyFitsImage(filePathQStr); QVector<MyFitsImage*> fitsSeries; for (long ii = 0; ii < nFrames; ii++) { QUrl fileUrl = urlList.at(ii); filePathQStr = fileUrl.toLocalFile(); fitsSeries << new MyFitsImage(filePathQStr); } this->fitsSeries = fitsSeries; this->naxis1 = newFitsImage->getNaxis1(); this->naxis2 = newFitsImage->getNaxis2(); this->dataMin = newFitsImage->getDataMin(); this->dataMax = newFitsImage->getDataMax(); this->nPixels = naxis1* naxis2; this->keyNames = newFitsImage->getKeyNames(); this->keyValues = newFitsImage->getKeyValues(); this->keyComments = newFitsImage->getKeyComments(); this->nKeys = newFitsImage->getNKeys(); newMin = dataMin; newMax = dataMax; newRange = newMax - newMin; alpha = (float) (255/newRange); beta = (float) (-255 * newMin/newRange); float t = 0.0f; float t1 = 0.0f; int nTests = 50; float tElapsed = 0; // Create the main Image this->matFits = newFitsImage->getMatFits(); UMat gpuMatFits32 = matFits.getUMat( ACCESS_READ ); UMat gpuMatOut8(naxis2, naxis1, CV_8U, Scalar(0)); // cpu-based convertTo() QElapsedTimer timer1; timer1.start(); matFits.convertTo(this->grayMat8, CV_8U, alpha, beta); qDebug()<<"Time for cpu-based convertTo(): " << timer1.elapsed() << "ms"; // GPU-based convertTo() QElapsedTimer timer2; timer2.start(); gpuMatFits32.convertTo(gpuMatOut8, CV_8U, alpha, beta); tElapsed = static_cast<float> (timer2.elapsed()); qDebug()<<"Time for GPU-based convertTo(): " << tElapsed << "ms"; newPaintImage = new QImage(grayMat8.data, naxis1, naxis2, QImage::Format_Grayscale8); //newPaintImage = new QImage((uchar*)image255, naxis1, naxis2, QImage::Format_ARGB32); newPaintWidget = new PaintWidget(newPaintImage, naxis1, naxis2); }
ImScrollArea::ImScrollArea(QList<QUrl> urlList) : image1DLastAction(NULL), newRawImage(NULL), fitsSeries(NULL), image255(NULL), subImage(NULL), newPaintImage(NULL), newPaintWidget(NULL), subPaintImage(NULL), subPaintWidget(NULL), newFitsImage(NULL), sliderHigh(NULL), sliderLow(NULL), sliderGamma(NULL), valueHighLineEdit(NULL), valueLowLineEdit(NULL), valueGammaLineEdit(NULL) { fitsExt = QString("fits"); rgbList = QList<QString>(); rgbList.append("cr2"); // Instantiate an object that hold information on the user's monitor. myScreen = QApplication::primaryScreen(); pixelDensity = 1;//myScreen->devicePixelRatio(); // Process the list of filenames of the dragged file. // Here it processes the name of 1st of the list to know the file type, // but then it actually loads the whole lot! This may change in the future. this->urlList = urlList; nFrames = urlList.size(); QUrl fileUrl = urlList.at(0); filePathQStr = fileUrl.toLocalFile(); QFileInfo fileInfo(filePathQStr); fileName = fileInfo.fileName(); fileExt = fileInfo.suffix().toLower(); // gamma is used for the "gamma-scaling" gamma = 1; if (fileExt == fitsExt || fileExt == QString("fts")) { // Currently we assume FITS to have one 1 channel only, gray scale. // But this will probably change in the future. isBayerImage = false; // loads the whole stack of files and instantiate fitsSeries: a vector of MyFitsImage // This default may/shall change in the future. loadFits(); createHeaderDock(); } else if (rgbList.contains(fileExt)) { isBayerImage = true; // Currently only one raw file is loaded, contrary to the FITS files above. // This default may/shall change in the future. loadRaw(); } // Initialize the properties of the subImage, and variables for holding the cursor positions // The many variables related to the cursor are due to the inverted Y-axis of Qt frame of reference // and also because we the coordinate of the widget are not the same coordinate system as in the image // So, lots of conversion is needed. subNaxis = 36; subNPixels = subNaxis * subNaxis; subOriginX = naxis1/2; subOriginY = naxis2/2; subOrigin = subOriginX - subNaxis/2 + (naxis1 * (subOriginY - subNaxis/2) ); cursorX = 1; cursorY = 1; imageCursor = 0; subRect = QRect(subOriginX - subNaxis/2, subOriginY - subNaxis/2, subNaxis, subNaxis); // String number format parameters if (!isBayerImage) { format = 'g'; precision = 2; } else { format = 'f'; precision = 0; } // Some default resizing occurs so that whole image fits in the screen // The magnification is a modifier on the resizing factor to make the image even bigger or smaller. // For the main Image, currently we stick to the default, but it may change. magnification = 1; // Initialize the intensity value used in the meta-information displayed over the widgets. intensity = 0; valueStr = QString::number(intensity); // Geometry used by the mdi area for sizing this widget. QStyle * wStyle = this->style(); QStyleOptionTitleBar so; so.titleBarState = 1; // kThemeStateActive so.titleBarFlags = Qt::Window; qint32 titleHeight=wStyle->pixelMetric(QStyle::PM_TitleBarHeight , &so, this); qint32 frameWidth = wStyle->pixelMetric(QStyle::PM_MdiSubWindowFrameWidth , &so, this); qDebug()<<"ScrollArea Widget title height="<< titleHeight <<" px"; // We set the size of the ImScrollArea widget slightly larger than the PaintWidget. fitsWidgetWidth = newPaintWidget->getFitsWidgetWidth() + 4 * frameWidth; fitsWidgetHeight = newPaintWidget->getFitsWidgetHeight() + 4 * frameWidth + titleHeight; // QLabel setup QString naxis1Str; QString naxis2Str; naxis1Str.setNum(naxis1); naxis2Str.setNum(naxis2); setWidget(newPaintWidget); windowTitle = QString("%1 [%2 x %3 px]") .arg(fileName) .arg(naxis1) .arg(naxis2); setWindowTitle(windowTitle); createDock(); qDebug()<<"resizeFac newPaintWidget = " << newPaintWidget->getResizeFac(); qDebug()<<"resizeFac subPaintWidget = " << subPaintWidget->getResizeFac(); //subPaintWidget->update(); }
/*! Sets a navigation mode file. Supports the schemes "coin" and "file" \param[in] url Url to the resource */ void QuarterWidget::setNavigationModeFile(const QUrl & url) { QString filename; if (url.scheme()=="coin") { filename = url.path(); //FIXME: This conditional needs to be implemented when the //CoinResources systems if working #if 0 //#if (COIN_MAJOR_VERSION==3) && (COIN_MINOR_VERSION==0) #endif //Workaround for differences between url scheme, and Coin internal //scheme in Coin 3.0. if (filename[0]=='/') { filename.remove(0,1); } #if 0 //#endif #endif filename = url.scheme()+':'+filename; } else if (url.scheme()=="file") filename = url.toLocalFile(); else if (url.isEmpty()) { if (PRIVATE(this)->currentStateMachine) { this->removeStateMachine(PRIVATE(this)->currentStateMachine); delete PRIVATE(this)->currentStateMachine; PRIVATE(this)->currentStateMachine = NULL; PRIVATE(this)->navigationModeFile = url; } return; } else { qDebug()<<url.scheme()<<"is not recognized"; return; } QByteArray filenametmp = filename.toLocal8Bit(); ScXMLStateMachine * stateMachine = NULL; if (filenametmp.startsWith("coin:")){ stateMachine = ScXML::readFile(filenametmp.data()); } else { //Use Qt to read the file in case it is a Qt resource QFile file(filenametmp); if (file.open(QIODevice::ReadOnly)){ QByteArray fileContents = file.readAll(); #if COIN_MAJOR_VERSION >= 4 stateMachine = ScXML::readBuffer(SbByteBuffer(fileContents.size(), fileContents.constData())); #else stateMachine = ScXML::readBuffer(fileContents.constData()); #endif file.close(); } } if (stateMachine && stateMachine->isOfType(SoScXMLStateMachine::getClassTypeId())) { SoScXMLStateMachine * newsm = static_cast<SoScXMLStateMachine *>(stateMachine); if (PRIVATE(this)->currentStateMachine) { this->removeStateMachine(PRIVATE(this)->currentStateMachine); delete PRIVATE(this)->currentStateMachine; } this->addStateMachine(newsm); newsm->initialize(); PRIVATE(this)->currentStateMachine = newsm; } else { if (stateMachine) delete stateMachine; qDebug()<<filename; qDebug()<<"Unable to load"<<url; return; } //If we have gotten this far, we have successfully loaded the //navigation file, so we set the property PRIVATE(this)->navigationModeFile = url; if (QUrl(DEFAULT_NAVIGATIONFILE) == PRIVATE(this)->navigationModeFile ) { // set up default cursors for the examiner navigation states //FIXME: It may be overly restrictive to not do this for arbitrary //navigation systems? - BFG 20090117 this->setStateCursor("interact", Qt::ArrowCursor); this->setStateCursor("idle", Qt::OpenHandCursor); #if QT_VERSION >= 0x040200 this->setStateCursor("rotate", Qt::ClosedHandCursor); #endif this->setStateCursor("pan", Qt::SizeAllCursor); this->setStateCursor("zoom", Qt::SizeVerCursor); this->setStateCursor("dolly", Qt::SizeVerCursor); this->setStateCursor("seek", Qt::CrossCursor); this->setStateCursor("spin", Qt::OpenHandCursor); } }
void Core::Handle (LeechCraft::Entity e) { QUrl url = e.Entity_.toUrl (); if (e.Mime_ == "text/x-opml") { if (url.scheme () == "file") StartAddingOPML (url.toLocalFile ()); else { QString name = LeechCraft::Util::GetTemporaryName (); LeechCraft::Entity e = Util::MakeEntity (url, name, LeechCraft::Internal | LeechCraft::DoNotNotifyUser | LeechCraft::DoNotSaveInHistory | LeechCraft::NotPersistent | LeechCraft::DoNotAnnounceEntity); PendingOPML po = { name }; int id = -1; QObject *pr; emit delegateEntity (e, &id, &pr); if (id == -1) { ErrorNotification (tr ("Import error"), tr ("Could not find plugin to download OPML %1.") .arg (url.toString ())); return; } HandleProvider (pr, id); PendingOPMLs_ [id] = po; } QMap<QString, QVariant> s = e.Additional_; if (s.contains ("ShowTrayIcon")) XmlSettingsManager::Instance ()->setProperty ("ShowIconInTray", s.value ("ShowIconInTray").toBool ()); if (s.contains ("UpdateOnStartup")) XmlSettingsManager::Instance ()->setProperty ("UpdateOnStartup", s.value ("UpdateOnStartup").toBool ()); if (s.contains ("UpdateTimeout")) XmlSettingsManager::Instance ()->setProperty ("UpdateInterval", s.value ("UpdateTimeout").toInt ()); if (s.contains ("MaxArticles")) XmlSettingsManager::Instance ()->setProperty ("ItemsPerChannel", s.value ("MaxArticles").toInt ()); if (s.contains ("MaxAge")) XmlSettingsManager::Instance ()->setProperty ("ItemsMaxAge", s.value ("MaxAge").toInt ()); } else { QString str = url.toString (); if (str.startsWith ("feed://")) str.replace (0, 4, "http"); else if (str.startsWith ("feed:")) str.remove (0, 5); else if (str.startsWith ("itpc://")) str.replace (0, 4, "http"); LeechCraft::Aggregator::AddFeed af (str); if (af.exec () == QDialog::Accepted) AddFeed (af.GetURL (), af.GetTags ()); } }
bool QgsMapLayer::readXML( const QDomNode& layer_node ) { QgsCoordinateReferenceSystem savedCRS; CUSTOM_CRS_VALIDATION savedValidation; bool layerError; QDomElement element = layer_node.toElement(); QDomNode mnl; QDomElement mne; // read provider QString provider; mnl = layer_node.namedItem( "provider" ); mne = mnl.toElement(); provider = mne.text(); // set data source mnl = layer_node.namedItem( "datasource" ); mne = mnl.toElement(); mDataSource = mne.text(); // TODO: this should go to providers if ( provider == "spatialite" ) { QgsDataSourceURI uri( mDataSource ); uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) ); mDataSource = uri.uri(); } else if ( provider == "ogr" ) { QStringList theURIParts = mDataSource.split( "|" ); theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] ); mDataSource = theURIParts.join( "|" ); } else if ( provider == "delimitedtext" ) { QUrl urlSource = QUrl::fromEncoded( mDataSource.toAscii() ); if ( !mDataSource.startsWith( "file:" ) ) { QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( "?" ) ) ); urlSource.setScheme( "file" ); urlSource.setPath( file.path() ); } QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->readPath( urlSource.toLocalFile() ) ); urlDest.setQueryItems( urlSource.queryItems() ); mDataSource = QString::fromAscii( urlDest.toEncoded() ); } else if ( provider == "wms" ) { // >>> BACKWARD COMPATIBILITY < 1.9 // For project file backward compatibility we must support old format: // 1. mode: <url> // example: http://example.org/wms? // 2. mode: tiled=<width>;<height>;<resolution>;<resolution>...,ignoreUrl=GetMap;GetFeatureInfo,featureCount=<count>,username=<name>,password=<password>,url=<url> // example: tiled=256;256;0.703;0.351,url=http://example.org/tilecache? // example: featureCount=10,http://example.org/wms? // example: ignoreUrl=GetMap;GetFeatureInfo,username=cimrman,password=jara,url=http://example.org/wms? // This is modified version of old QgsWmsProvider::parseUri // The new format has always params crs,format,layers,styles and that params // should not appear in old format url -> use them to identify version if ( !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) ) { QgsDebugMsg( "Old WMS URI format detected -> converting to new format" ); QgsDataSourceURI uri; if ( !mDataSource.startsWith( "http:" ) ) { QStringList parts = mDataSource.split( "," ); QStringListIterator iter( parts ); while ( iter.hasNext() ) { QString item = iter.next(); if ( item.startsWith( "username="******"username", item.mid( 9 ) ); } else if ( item.startsWith( "password="******"password", item.mid( 9 ) ); } else if ( item.startsWith( "tiled=" ) ) { // in < 1.9 tiled= may apper in to variants: // tiled=width;height - non tiled mode, specifies max width and max height // tiled=width;height;resolutions-1;resolution2;... - tile mode QStringList params = item.mid( 6 ).split( ";" ); if ( params.size() == 2 ) // non tiled mode { uri.setParam( "maxWidth", params.takeFirst() ); uri.setParam( "maxHeight", params.takeFirst() ); } else if ( params.size() > 2 ) // tiled mode { // resolutions are no more needed and size limit is not used for tiles // we have to tell to the provider however that it is tiled uri.setParam( "tileMatrixSet", "" ); } } else if ( item.startsWith( "featureCount=" ) ) { uri.setParam( "featureCount", item.mid( 13 ) ); } else if ( item.startsWith( "url=" ) ) { uri.setParam( "url", item.mid( 4 ) ); } else if ( item.startsWith( "ignoreUrl=" ) ) { uri.setParam( "ignoreUrl", item.mid( 10 ).split( ";" ) ); } } } else { uri.setParam( "url", mDataSource ); } mDataSource = uri.encodedUri(); // At this point, the URI is obviously incomplete, we add additional params // in QgsRasterLayer::readXml } // <<< BACKWARD COMPATIBILITY < 1.9 } else { mDataSource = QgsProject::instance()->readPath( mDataSource ); } // Set the CRS from project file, asking the user if necessary. // Make it the saved CRS to have WMS layer projected correctly. // We will still overwrite whatever GDAL etc picks up anyway // further down this function. mnl = layer_node.namedItem( "layername" ); mne = mnl.toElement(); QDomNode srsNode = layer_node.namedItem( "srs" ); mCRS->readXML( srsNode ); mCRS->setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) ); mCRS->validate(); savedCRS = *mCRS; // Do not validate any projections in children, they will be overwritten anyway. // No need to ask the user for a projections when it is overwritten, is there? savedValidation = QgsCoordinateReferenceSystem::customSrsValidation(); QgsCoordinateReferenceSystem::setCustomSrsValidation( NULL ); // now let the children grab what they need from the Dom node. layerError = !readXml( layer_node ); // overwrite CRS with what we read from project file before the raster/vector // file readnig functions changed it. They will if projections is specfied in the file. // FIXME: is this necessary? QgsCoordinateReferenceSystem::setCustomSrsValidation( savedValidation ); *mCRS = savedCRS; // Abort if any error in layer, such as not found. if ( layerError ) { return false; } // the internal name is just the data source basename //QFileInfo dataSourceFileInfo( mDataSource ); //internalName = dataSourceFileInfo.baseName(); // set ID mnl = layer_node.namedItem( "id" ); if ( ! mnl.isNull() ) { mne = mnl.toElement(); if ( ! mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz) { mID = mne.text(); } } // use scale dependent visibility flag toggleScaleBasedVisibility( element.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 ); setMinimumScale( element.attribute( "minimumScale" ).toFloat() ); setMaximumScale( element.attribute( "maximumScale" ).toFloat() ); // set name mnl = layer_node.namedItem( "layername" ); mne = mnl.toElement(); setLayerName( mne.text() ); //title QDomElement titleElem = layer_node.firstChildElement( "title" ); if ( !titleElem.isNull() ) { mTitle = titleElem.text(); } //abstract QDomElement abstractElem = layer_node.firstChildElement( "abstract" ); if ( !abstractElem.isNull() ) { mAbstract = abstractElem.text(); } //read transparency level QDomNode transparencyNode = layer_node.namedItem( "transparencyLevelInt" ); if ( ! transparencyNode.isNull() ) { // set transparency level only if it's in project // (otherwise it sets the layer transparent) QDomElement myElement = transparencyNode.toElement(); setTransparency( myElement.text().toInt() ); } readCustomProperties( layer_node ); return true; } // void QgsMapLayer::readXML
QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) { QgsVirtualLayerDefinition def; def.setFilePath( url.toLocalFile() ); // regexp for column name const QString columnNameRx( "[a-zA-Z_\x80-\xFF][a-zA-Z0-9_\x80-\xFF]*" ); QgsFields fields; int layerIdx = 0; QList<QPair<QByteArray, QByteArray> > items = url.encodedQueryItems(); for ( int i = 0; i < items.size(); i++ ) { QString key = items.at( i ).first; QString value = items.at( i ).second; if ( key == "layer_ref" ) { layerIdx++; // layer id, with optional layer_name int pos = value.indexOf( ':' ); QString layerId, vlayerName; if ( pos == -1 ) { layerId = value; vlayerName = QString( "vtab%1" ).arg( layerIdx ); } else { layerId = value.left( pos ); vlayerName = QUrl::fromPercentEncoding( value.mid( pos + 1 ).toUtf8() ); } // add the layer to the list def.addSource( vlayerName, layerId ); } else if ( key == "layer" ) { layerIdx++; // syntax: layer=provider:url_encoded_source_URI(:name(:encoding)?)? int pos = value.indexOf( ':' ); if ( pos != -1 ) { QString providerKey, source, vlayerName, encoding = "UTF-8"; providerKey = value.left( pos ); int pos2 = value.indexOf( ':', pos + 1 ); if ( pos2 - pos == 2 ) pos2 = value.indexOf( ':', pos + 3 ); if ( pos2 != -1 ) { source = QUrl::fromPercentEncoding( value.mid( pos + 1, pos2 - pos - 1 ).toUtf8() ); int pos3 = value.indexOf( ':', pos2 + 1 ); if ( pos3 != -1 ) { vlayerName = QUrl::fromPercentEncoding( value.mid( pos2 + 1, pos3 - pos2 - 1 ).toUtf8() ); encoding = value.mid( pos3 + 1 ); } else { vlayerName = QUrl::fromPercentEncoding( value.mid( pos2 + 1 ).toUtf8() ); } } else { source = QUrl::fromPercentEncoding( value.mid( pos + 1 ).toUtf8() ); vlayerName = QString( "vtab%1" ).arg( layerIdx ); } def.addSource( vlayerName, source, providerKey, encoding ); } } else if ( key == "geometry" ) { // geometry field definition, optional // geometry_column(:wkb_type:srid)? QRegExp reGeom( "(" + columnNameRx + ")(?::([a-zA-Z0-9]+):(\\d+))?" ); int pos = reGeom.indexIn( value ); if ( pos >= 0 ) { def.setGeometryField( reGeom.cap( 1 ) ); if ( reGeom.captureCount() > 1 ) { // not used by the spatialite provider for now ... QgsWKBTypes::Type wkbType = QgsWKBTypes::parseType( reGeom.cap( 2 ) ); if ( wkbType == QgsWKBTypes::Unknown ) { wkbType = static_cast<QgsWKBTypes::Type>( reGeom.cap( 2 ).toLong() ); } def.setGeometryWkbType( wkbType ); def.setGeometrySrid( reGeom.cap( 3 ).toLong() ); } } } else if ( key == "nogeometry" ) { def.setGeometryWkbType( QgsWKBTypes::NoGeometry ); } else if ( key == "uid" ) { def.setUid( value ); } else if ( key == "query" ) { // url encoded query def.setQuery( QUrl::fromPercentEncoding( value.toUtf8() ) ); } else if ( key == "field" ) { // field_name:type (int, real, text) QRegExp reField( "(" + columnNameRx + "):(int|real|text)" ); int pos = reField.indexIn( value ); if ( pos >= 0 ) { QString fieldName( reField.cap( 1 ) ); QString fieldType( reField.cap( 2 ) ); if ( fieldType == "int" ) { fields.append( QgsField( fieldName, QVariant::Int, fieldType ) ); } else if ( fieldType == "real" ) { fields.append( QgsField( fieldName, QVariant::Double, fieldType ) ); } if ( fieldType == "text" ) { fields.append( QgsField( fieldName, QVariant::String, fieldType ) ); } } } } def.setFields( fields ); return def; }
SMPlayer::ExitCode SMPlayer::processArgs(QStringList args) { /*#ifndef DEBUG qDebug("SMPlayer::processArgs: arguments: %d", args.count()); #endif for (int n = 0; n < args.count(); n++) { #ifndef DEBUG qDebug("SMPlayer::processArgs: %d = %s", n, args[n].toUtf8().data()); #endif } */ QString action; // Action to be passed to running instance bool show_help = false; if (!pref->gui.isEmpty()) gui_to_use = pref->gui; bool add_to_playlist = false; /* #ifdef Q_OS_WIN if (args.contains("-uninstall")){ #if USE_ASSOCIATIONS //Called by uninstaller. Will restore old associations. WinFileAssoc RegAssoc; Extensions exts; QStringList regExts; RegAssoc.GetRegisteredExtensions(exts.multimedia(), regExts); RegAssoc.RestoreFileAssociations(regExts); #endif return NoError; } #endif*/ for (int n = 1; n < args.count(); n++) { QString argument = args[n]; if (argument == "-send-action") { if (n+1 < args.count()) { n++; action = args[n]; } else { return ErrorArgument; } } else if (argument == "-actions") { if (n+1 < args.count()) { n++; actions_list = args[n]; } else { return ErrorArgument; } } else if (argument == "-sub") { if (n+1 < args.count()) { n++; QString file = args[n]; if (QFile::exists(file)) { subtitle_file = QFileInfo(file).absoluteFilePath(); } else { } } else { return ErrorArgument; } } else if (argument == "-pos") { if (n+2 < args.count()) { bool ok_x, ok_y; n++; gui_position.setX( args[n].toInt(&ok_x) ); n++; gui_position.setY( args[n].toInt(&ok_y) ); if (ok_x && ok_y) move_gui = true; } else { return ErrorArgument; } } else if (argument == "-size") { if (n+2 < args.count()) { bool ok_width, ok_height; n++; gui_size.setWidth( args[n].toInt(&ok_width) ); n++; gui_size.setHeight( args[n].toInt(&ok_height) ); if (ok_width && ok_height) resize_gui = true; } else { return ErrorArgument; } } else if ((argument == "--help") || (argument == "-help") || (argument == "-h") || (argument == "-?") ) { show_help = true; } else if (argument == "-close-at-end") { close_at_end = 1; } else if (argument == "-no-close-at-end") { close_at_end = 0; } else if (argument == "-fullscreen") { start_in_fullscreen = 1; } else if (argument == "-no-fullscreen") { start_in_fullscreen = 0; } else if (argument == "-add-to-playlist") { add_to_playlist = true; } else if (argument == "-mini" || argument == "-minigui") { gui_to_use = "MiniGui"; } else if (argument == "-mpcgui") { gui_to_use = "MpcGui"; } else if (argument == "-defaultgui") { gui_to_use = "DefaultGui"; } else { // File #if QT_VERSION >= 0x040600 QUrl fUrl = QUrl::fromUserInput(argument); if (fUrl.isValid() && fUrl.scheme().toLower() == "file") { argument = fUrl.toLocalFile(); } #endif if (QFile::exists( argument )) { argument = QFileInfo(argument).absoluteFilePath(); } files_to_play.append( argument ); } } if (show_help) { printf("%s\n", CLHelp::help().toLocal8Bit().data()); return NoError; } /* #ifdef DEBUG qDebug("SMPlayer::processArgs: files_to_play: count: %d", files_to_play.count() ); #endif for (int n=0; n < files_to_play.count(); n++) { #ifdef DEBUG qDebug("SMPlayer::processArgs: files_to_play[%d]: '%s'", n, files_to_play[n].toUtf8().data()); #endif } */ #ifdef SINGLE_INSTANCE if (pref->use_single_instance) { // Single instance MyApplication * a = MyApplication::instance(); if (a->isRunning()) { a->sendMessage("Hello"); if (!action.isEmpty()) { a->sendMessage("action " + action); } else { if (!subtitle_file.isEmpty()) { a->sendMessage("load_sub " + subtitle_file); } if (!files_to_play.isEmpty()) { /* a->sendMessage("open_file " + files_to_play[0]); */ QString command = "open_files"; if (add_to_playlist) command = "add_to_playlist"; a->sendMessage(command +" "+ files_to_play.join(" <<sep>> ")); } } return NoError; } } #endif if (!pref->default_font.isEmpty()) { QFont f; f.fromString(pref->default_font); qApp->setFont(f); } return SMPlayer::NoExit; }
static QString baseDirectory(const QUrl &url) { QString filePath = url.toLocalFile(); return QFileInfo(filePath).absoluteDir().path(); }
QDir BazaarUtils::toQDir(const QUrl& url) { return QDir(url.toLocalFile()); }
void SettingsDialog::chooseStyleSheet() { QUrl url = QUrl::fromEncoded(userStyleSheet->text().toUtf8()); QString fileName = QFileDialog::getOpenFileName(this, tr("Choose CSS File"), url.toLocalFile()); userStyleSheet->setText(QString::fromUtf8(QUrl::fromLocalFile(fileName).toEncoded())); }
void docAttach::sSave() { XSqlQuery newDocass; QString title; QUrl url; //set the purpose if (_docAttachPurpose->currentIndex() == 0) _purpose = "S"; else if (_docAttachPurpose->currentIndex() == 1) _purpose = "A"; else if (_docAttachPurpose->currentIndex() == 2) _purpose = "C"; else if (_docAttachPurpose->currentIndex() == 3) _purpose = "D"; //if then series, type derived from the stack index. e.g. if (_docType->currentIndex() == 1) { _targettype = "T"; _targetid = _cntct->id(); } else if (_docType->currentIndex() == 2) { _targettype = "CRMA"; _targetid = _crmacct->id(); } else if (_docType->currentIndex() == 3) { _targettype = "C"; _targetid = _cust->id(); } else if (_docType->currentIndex() == 4) { _targettype = "EMP"; _targetid = _emp->id(); } else if (_docType->currentIndex() == 5) { if(_file->text().trimmed().isEmpty()) { QMessageBox::warning( this, tr("Must Specify file"), tr("You must specify a file before you may save.") ); return; } _targettype = "URL"; title = _filetitle->text(); url = QUrl(_file->text()); if (url.scheme().isEmpty()) url.setScheme("file"); } else if (_docType->currentIndex() == 6) { _targettype = "IMG"; _targetid = _img->id(); } else if (_docType->currentIndex() == 7) { _targettype = "INCDT"; _targetid = _incdt->id(); } else if (_docType->currentIndex() == 8) { _targettype = "I"; _targetid = _item->id(); } else if (_docType->currentIndex() == 9) { _targettype = "OPP"; _targetid = _opp->id(); } else if (_docType->currentIndex() == 10) { _targettype = "J"; _targetid = _proj->id(); } else if (_docType->currentIndex() == 11) { _targettype = "P"; _targetid = _po->id(); } else if (_docType->currentIndex() == 12) { _targettype = "S"; _targetid = _so->id(); } else if (_docType->currentIndex() == 13) { _targettype = "V"; _targetid = _vend->id(); } else if (_docType->currentIndex() == 14) { if(_url->text().trimmed().isEmpty()) { QMessageBox::warning( this, tr("Must Specify file"), tr("You must specify a file before you may save.") ); return; } _targettype = "URL"; title = _urltitle->text(); url = QUrl(_url->text()); if (url.scheme().isEmpty()) url.setScheme("http"); } else if (_docType->currentIndex() == 15) { _targettype = "W"; _targetid = _wo->id(); } if (_targettype == "IMG") { // First determine if the id is in the image table, and not one of it's inherited versions // if it is not then we will create a copy in the image table to keep the FK's working XSqlQuery qq; qq.prepare("SELECT image_id FROM ONLY image WHERE image_id=:image_id"); qq.bindValue(":image_id", _targetid); if(qq.exec() && !qq.first()) { qq.exec("SELECT nextval(('\"image_image_id_seq\"'::text)::regclass) AS newid;"); if(qq.first()) { int newid = qq.value("newid").toInt(); qq.prepare("INSERT INTO image (image_id, image_name, image_descrip, image_data) " "SELECT :newid, image_name, image_descrip, image_data" " FROM image WHERE image_id=:image_id;"); qq.bindValue(":newid", newid); qq.bindValue(":image_id", _targetid); if(qq.exec()) _targetid = newid; } } // For now images are handled differently because of legacy structures... newDocass.prepare( "INSERT INTO imageass " "( imageass_source, imageass_source_id, imageass_image_id, imageass_purpose ) " "VALUES " "( :docass_source_type, :docass_source_id, :docass_target_id, :docass_purpose );" ); } else if (_targettype == "URL") { if(!url.isValid()) { QMessageBox::warning( this, tr("Must Specify valid path"), tr("You must specify a path before you may save.") ); return; } QByteArray bytarr; QFileInfo fi(url.toLocalFile()); if(_saveDbCheck->isChecked() && (url.scheme()=="file") && (_mode == "new")) { if (!fi.exists()) { QMessageBox::warning( this, tr("File Error"), tr("File %1 was not found and will not be saved.").arg(url.toLocalFile())); return; } QFile sourceFile(url.toLocalFile()); if (!sourceFile.open(QIODevice::ReadOnly)) { QMessageBox::warning( this, tr("File Open Error"), tr("Could not open source file %1 for read.") .arg(url.toLocalFile())); return; } bytarr = sourceFile.readAll(); url.setPath(fi.fileName().remove(" ")); url.setScheme(""); } // TODO: replace use of URL view if (_mode == "new" && bytarr.isNull()) newDocass.prepare( "INSERT INTO url " "( url_source, url_source_id, url_title, url_url, url_stream ) " "VALUES " "( :docass_source_type, :docass_source_id, :title, :url, :stream );" ); else if (_mode == "new") newDocass.prepare( "INSERT INTO url " "( url_source, url_source_id, url_title, url_url, url_stream ) " "VALUES " "( :docass_source_type, :docass_source_id, :title, :url, E:stream );" ); else newDocass.prepare( "UPDATE url SET " " url_title = :title, " " url_url = :url " "WHERE (url_id=:url_id);" ); newDocass.bindValue(":url_id", _urlid); newDocass.bindValue(":title", title); newDocass.bindValue(":url", url.toString()); newDocass.bindValue(":stream", bytarr); } else { newDocass.prepare( "INSERT INTO docass " "( docass_source_type, docass_source_id, docass_target_type, docass_target_id, docass_purpose ) " "VALUES " "( :docass_source_type, :docass_source_id, :docass_target_type, :docass_target_id, :docass_purpose );" ); newDocass.bindValue(":docass_target_type", _targettype); } if (_targettype == Documents::_documentMap[_source].ident && _targetid == _sourceid) { QMessageBox::critical(this,tr("Invalid Selection"), tr("You may not attach a document to itself.")); return; } newDocass.bindValue(":docass_source_type", Documents::_documentMap[_source].ident); newDocass.bindValue(":docass_source_id", _sourceid); newDocass.bindValue(":docass_target_id", _targetid); newDocass.bindValue(":docass_purpose", _purpose); newDocass.exec(); accept(); }
void MixerSettings::loadSettings() { QUrl loadGainsFileUrl; FILE* fp = 0L; MixerContainer settings; loadGainsFileUrl = QFileDialog::getOpenFileUrl(qApp->activeWindow(), i18n("Select Gimp Gains Mixer File to Load"), QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)), QLatin1String("*")); if (loadGainsFileUrl.isEmpty()) { return; } fp = fopen(QFile::encodeName(loadGainsFileUrl.toLocalFile()).constData(), "r"); if (fp) { char buf1[1024]; char buf2[1024]; char buf3[1024]; buf1[0] = '\0'; fgets(buf1, 1023, fp); fscanf(fp, "%*s %256s", buf1); fscanf(fp, "%*s %256s", buf1); // preview flag, preserved for compatibility fscanf(fp, "%*s %256s", buf1); if (strcmp(buf1, "true") == 0) { settings.bMonochrome = true; } else { settings.bMonochrome = false; } fscanf(fp, "%*s %256s", buf1); if (strcmp(buf1, "true") == 0) { settings.bPreserveLum = true; } else { settings.bPreserveLum = false; } fscanf(fp, "%*s %256s %256s %256s", buf1, buf2, buf3); settings.redRedGain = atof(buf1); settings.redGreenGain = atof(buf2); settings.redBlueGain = atof(buf3); fscanf(fp, "%*s %256s %256s %256s", buf1, buf2, buf3); settings.greenRedGain = atof(buf1); settings.greenGreenGain = atof(buf2); settings.greenBlueGain = atof(buf3); fscanf(fp, "%*s %256s %256s %256s", buf1, buf2, buf3); settings.blueRedGain = atof(buf1); settings.blueGreenGain = atof(buf2); settings.blueBlueGain = atof(buf3); fscanf(fp, "%*s %256s %256s %256s", buf1, buf2, buf3); settings.blackRedGain = atof(buf1); settings.blackGreenGain = atof(buf2); settings.blackBlueGain = atof(buf3); fclose(fp); setSettings(settings); } else { QMessageBox::critical(qApp->activeWindow(), qApp->applicationName(), i18n("Cannot load settings from the Gains Mixer text file.")); return; } }
void QMLBridge::sendFile(QUrl url, QString dir) { usblink_queue_put_file(url.toLocalFile().toStdString(), dir.toStdString(), QMLBridge::usblink_progress_changed, this); }
void MixerSettings::saveAsSettings() { QUrl saveGainsFileUrl; FILE* fp = 0L; saveGainsFileUrl = QFileDialog::getSaveFileUrl(qApp->activeWindow(), i18n("Gimp Gains Mixer File to Save"), QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)), QLatin1String("*")); if (saveGainsFileUrl.isEmpty()) { return; } fp = fopen(QFile::encodeName(saveGainsFileUrl.toLocalFile()).constData(), "w"); if (fp) { const char* str = 0L; char buf1[256]; char buf2[256]; char buf3[256]; switch (d->currentChannel) { case RedChannel: str = "RED"; break; case GreenChannel: str = "GREEN"; break; case BlueChannel: str = "BLUE"; break; default: qCWarning(DIGIKAM_DIMG_LOG) << "Unknown Color channel gains"; break; } fprintf(fp, "# Channel Mixer Configuration File\n"); fprintf(fp, "CHANNEL: %s\n", str); fprintf(fp, "PREVIEW: %s\n", "true"); // preserved for compatibility fprintf(fp, "MONOCHROME: %s\n", d->mixerSettings.bMonochrome ? "true" : "false"); fprintf(fp, "PRESERVE_LUMINOSITY: %s\n", d->mixerSettings.bPreserveLum ? "true" : "false"); sprintf(buf1, "%5.3f", d->mixerSettings.redRedGain); sprintf(buf2, "%5.3f", d->mixerSettings.redGreenGain); sprintf(buf3, "%5.3f", d->mixerSettings.redBlueGain); fprintf(fp, "RED: %s %s %s\n", buf1, buf2, buf3); sprintf(buf1, "%5.3f", d->mixerSettings.greenRedGain); sprintf(buf2, "%5.3f", d->mixerSettings.greenGreenGain); sprintf(buf3, "%5.3f", d->mixerSettings.greenBlueGain); fprintf(fp, "GREEN: %s %s %s\n", buf1, buf2, buf3); sprintf(buf1, "%5.3f", d->mixerSettings.blueRedGain); sprintf(buf2, "%5.3f", d->mixerSettings.blueGreenGain); sprintf(buf3, "%5.3f", d->mixerSettings.blueBlueGain); fprintf(fp, "BLUE: %s %s %s\n", buf1, buf2, buf3); sprintf(buf1, "%5.3f", d->mixerSettings.blackRedGain); sprintf(buf2, "%5.3f", d->mixerSettings.blackGreenGain); sprintf(buf3, "%5.3f", d->mixerSettings.blackBlueGain); fprintf(fp, "BLACK: %s %s %s\n", buf1, buf2, buf3); fclose(fp); } else { QMessageBox::critical(qApp->activeWindow(), qApp->applicationName(), i18n("Cannot save settings to the Gains Mixer text file.")); return; } }
Mrl::Mrl(const QUrl &url) { if (url.isLocalFile()) m_loc = _L("file://") % url.toLocalFile(); else m_loc = url.toString(); }
bool AutoDJFeature::dragMoveAccept(QUrl url) { return SoundSourceProxy::isUrlSupported(url) || Parser::isPlaylistFilenameSupported(url.toLocalFile()); }
void ClassicBackgroundRender::setBackgroundImage(const QUrl &url) { mScalingMode = None; qDebug() << Q_FUNC_INFO << url; setBackgroundImage(url.toLocalFile()); }
bool TestHTTPServer::wait(const QUrl &expect, const QUrl &reply, const QUrl &body) { m_state = AwaitingHeader; m_data.clear(); QFile expectFile(expect.toLocalFile()); if (!expectFile.open(QIODevice::ReadOnly)) return false; QFile replyFile(reply.toLocalFile()); if (!replyFile.open(QIODevice::ReadOnly)) return false; m_bodyData = QByteArray(); if (body.isValid()) { QFile bodyFile(body.toLocalFile()); if (!bodyFile.open(QIODevice::ReadOnly)) return false; m_bodyData = bodyFile.readAll(); } const QByteArray serverHostUrl = QByteArrayLiteral("127.0.0.1:")+ QByteArray::number(m_server.serverPort()); QByteArray line; bool headers_done = false; while (!(line = expectFile.readLine()).isEmpty()) { line.replace('\r', ""); if (line.at(0) == '\n') { headers_done = true; continue; } if (headers_done) { m_waitData.body.append(line); } else { line.replace("{{ServerHostUrl}}", serverHostUrl); m_waitData.headers.append(line); } } /* while (waitData.endsWith('\n')) waitData = waitData.left(waitData.count() - 1); */ m_replyData = replyFile.readAll(); if (!m_replyData.endsWith('\n')) m_replyData.append('\n'); m_replyData.append("Content-length: "); m_replyData.append(QByteArray::number(m_bodyData.length())); m_replyData.append("\n\n"); for (int ii = 0; ii < m_replyData.count(); ++ii) { if (m_replyData.at(ii) == '\n' && (!ii || m_replyData.at(ii - 1) != '\r')) { m_replyData.insert(ii, '\r'); ++ii; } } m_replyData.append(m_bodyData); return true; }