void RezkonvImporter::parseFile( const QString &filename ) { QFile input( filename ); if ( input.open( QIODevice::ReadOnly ) ) { QTextStream stream( &input ); stream.skipWhiteSpace(); QString line; while ( !stream.atEnd() ) { line = stream.readLine(); if ( line.contains( QRegExp( "^=====.*REZKONV.*", Qt::CaseInsensitive ) ) ) { QStringList raw_recipe; while ( !( line = stream.readLine() ).contains( QRegExp( "^=====\\s*$" ) ) && !stream.atEnd() ) raw_recipe << line; readRecipe( raw_recipe ); } } if ( fileRecipeCount() == 0 ) setErrorMsg( i18n( "No recipes found in this file." ) ); } else setErrorMsg( i18n( "Unable to open file." ) ); }
DrMain* KMLpdManager::loadPrinterDriver(KMPrinter *printer, bool config) { PrintcapEntry *entry = findPrintcapEntry(printer->name()); if (!entry) return NULL; // check for printtool driver (only for configuration) QString sd = entry->arg("sd"), dr(entry->comment(7)); if (QFile::exists(sd+"/postscript.cfg") && config && !dr.isEmpty()) { QMap<QString,QString> map = loadPrinttoolCfgFile(sd+"/postscript.cfg"); PrinttoolEntry *ptentry = findPrinttoolEntry(dr); if (!ptentry) return NULL; DrMain *dr = ptentry->createDriver(); dr->setOptions(map); map = loadPrinttoolCfgFile(sd+"/general.cfg"); dr->setOptions(map); map = loadPrinttoolCfgFile(sd+"/textonly.cfg"); dr->setOptions(map); return dr; } // default if (entry->m_comment.startsWith("##PRINTTOOL3##")) setErrorMsg(i18n("No driver found (raw printer)")); else setErrorMsg(i18n("Printer type not recognized.")); return NULL; }
bool KMLpdManager::enablePrinter(KMPrinter *printer, bool state) { KPipeProcess proc; QString cmd = programName(0); cmd += " "; cmd += state ? "up" : "down"; cmd += " "; cmd += KProcess::quote(printer->printerName()); if (proc.open(cmd)) { QTextStream t(&proc); QString buffer; while (!t.eof()) buffer.append(t.readLine()); if (buffer.startsWith("?Privilege")) { setErrorMsg(i18n("Permission denied: you must be root.")); return false; } return true; } else { setErrorMsg(i18n("Unable to execute command \"%1\".").arg(cmd)); return false; } }
void MX2Importer::parseFile( const QString& filename ) { QFile file( filename ); kDebug() << "loading file: " << filename ; if ( file.open( QIODevice::ReadOnly ) ) { kDebug() << "file opened" ; QDomDocument doc; //hopefully a temporary hack, since MasterCook creates invalid xml declarations QTextStream stream( &file ); QString all_data = stream.readAll(); if ( all_data.startsWith( "<?xml" ) ) all_data.remove( 0, all_data.indexOf( "?>" ) + 2 ); QString error; int line; int column; if ( !doc.setContent( all_data, &error, &line, &column ) ) { kDebug() << QString( "error: \"%1\" at line %2, column %3" ).arg( error ).arg( line ).arg( column ) ; setErrorMsg( i18n( "\"%1\" at line %2, column %3. This may not be a *.mx2 file.", error, line, column ) ); return ; } QDomElement mx2 = doc.documentElement(); // TODO Check if there are changes between versions if ( mx2.tagName() != "mx2" /*|| mx2.attribute("source") != "MasterCook 5.0"*/ ) { setErrorMsg( i18n( "This file does not appear to be a *.mx2 file" ) ); return ; } QDomNodeList l = mx2.childNodes(); for ( int i = 0; i < l.count(); i++ ) { QDomElement el = l.item( i ).toElement(); if ( el.tagName() == "RcpE" ) { Recipe recipe; recipe.title = el.attribute( "name" ); Element author( el.attribute( "author" ) ); recipe.authorList.append( author ); readRecipe( el.childNodes(), &recipe ); add ( recipe ); } } } else setErrorMsg( i18n( "Unable to open file." ) ); }
MacroBase::Status CvVideoInput::onInit() { const std::string& videoFilePath = getParameterValue<std::string>(0); if (videoFilePath.empty()) { setErrorMsg(L"No video file specified in parameters."); return Error; } ptrCapture = new cv::VideoCapture(videoFilePath); if (!ptrCapture || !ptrCapture->isOpened()) { setErrorMsg(L"Failed to open video capture interface."); return Error; } return Ok; }
PrintcapEntry* KMLpdManager::findPrintcapEntry(const QString& name) { PrintcapEntry *ent = m_entries.find(name); if (!ent) setErrorMsg(i18n("Couldn't find printer <b>%1</b> in printcap file.").arg(name)); return ent; }
EwsFolder* EwsFindFolderResponse::readFolder(QXmlStreamReader &reader) { EwsFolder *folder = 0; if (reader.name() == QStringLiteral("Folder") || reader.name() == QStringLiteral("CalendarFolder") || reader.name() == QStringLiteral("ContactsFolder") || reader.name() == QStringLiteral("TasksFolder") || reader.name() == QStringLiteral("SearchFolder")) { folder = new EwsFolder(reader); if (!folder->isValid()) { setErrorMsg(QStringLiteral("Failed to read EWS request - invalid %1 element.") .arg(QStringLiteral("Folder"))); return 0; } QVariant dn = (*folder)[EwsFolderFieldDisplayName]; if (!dn.isNull()) { EwsClient::folderHash[(*folder)[EwsFolderFieldFolderId].value<EwsId>().id()] = dn.toString(); } } else { qCWarning(EWSRES_LOG).noquote() << QStringLiteral("Unsupported folder type %1").arg(reader.name().toString()); reader.skipCurrentElement(); } return folder; }
void MXPImporter::parseFile( const QString &file ) { QFile input( file ); if ( input.open( QIODevice::ReadOnly ) ) { QTextStream stream( &input ); stream.skipWhiteSpace(); QString line; while ( !stream.atEnd() ) { line = stream.readLine().trimmed(); if ( line == "{ Exported from MasterCook Mac }" ) { kDebug() << "detected Mac file"; importMac( stream ); } else if ( line == "@@@@@" ) { kDebug() << "detected generic file"; importGeneric( stream ); } else if ( line.simplified().contains( "Exported from MasterCook" ) ) { kDebug() << "detected MasterCook normal file"; importMXP( stream ); } stream.skipWhiteSpace(); } if ( fileRecipeCount() == 0 ) addWarningMsg( i18n( "No recipes found in this file." ) ); } else setErrorMsg( i18n( "Unable to open file." ) ); }
EwsSyncFolderHierarchyRequest::Response::Response(QXmlStreamReader &reader) : EwsRequest::Response(reader) { if (mClass == EwsResponseParseError) { return; } static const QVector<EwsXml<SyncResponseElementType>::Item> items = { {SyncState, QStringLiteral("SyncState"), &ewsXmlTextReader}, {IncludesLastFolderInRange, QStringLiteral("IncludesLastFolderInRange"), &ewsXmlBoolReader}, {Changes, QStringLiteral("Changes"), &EwsSyncFolderHierarchyRequest::Response::changeReader}, }; static const EwsXml<SyncResponseElementType> staticReader(items); EwsXml<SyncResponseElementType> ewsReader(staticReader); if (!ewsReader.readItems(reader, ewsMsgNsUri, [this](QXmlStreamReader &reader, const QString &) { if (!readResponseElement(reader)) { setErrorMsg(QStringLiteral("Failed to read EWS request - invalid response element.")); return false; } return true; })) { mClass = EwsResponseParseError; return; } QHash<SyncResponseElementType, QVariant> values = ewsReader.values(); mSyncState = values[SyncState].toString(); mIncludesLastFolder = values[IncludesLastFolderInRange].toBool(); mChanges = values[Changes].value<Change::List>(); }
/** * Check if all requiered free arguments are there or not and if * the containing free arguments are allowed. * @param freeArgumentList */ void OptionParser::Private::checkFreeArgumentList(const OptionTable &optionTable) { QStringList freeArgumentList = optionTable.value('?', QVariant()).toStringList(); int count = freeArgumentList.size(); if (count < m_requireFreeParam) { QString error = QString("There are to less free arguments. Found %1 and require %2."); setErrorMsg(error.arg(count).arg(m_requireFreeParam)); } if (count > m_allowedFreeParam) { QString error = QString("Found %1 free arguments but there are only %2 allowed."); setErrorMsg(error.arg(count).arg(m_allowedFreeParam)); for (quint8 index=0; index<count; ++index) { setErrorMsg(freeArgumentList[index]); } } }
MacroBase::Status CannyEdge::onInit() { const lti::channel8* input = accessInput<lti::channel8>(0); if (input == 0) { setErrorMsg(L"Input is not connected."); return Error; } return Ok; }
MacroBase::Status CvCameraInput::onInit() { const int& deviceId= getParameterValue<int>(0); ptrCapture = new cv::VideoCapture(deviceId); if (!ptrCapture || !ptrCapture->isOpened()) { setErrorMsg(L"Failed to open camera capture interface."); return Error; } return Ok; }
PrinttoolEntry* KMLpdManager::findPrinttoolEntry(const QString& name) { if (m_ptentries.count() == 0) loadPrinttoolDb(driverDirectory()+"/printerdb"); PrinttoolEntry *ent = m_ptentries.find(name); if (!ent) setErrorMsg(i18n("Couldn't find driver <b>%1</b> in printtool database.").arg(name)); return ent; }
bool KMLpdManager::writePrinters() { if (!writePrintcapFile(QString::fromLatin1("%1/etc/printcap").arg(lpdprefix))) { setErrorMsg(i18n("Unable to write printcap file.")); return false; } return true; }
bool KMLpdManager::checkGsDriver(const QString& gsdriver) { if (gsdriver == "ppa" || gsdriver == "POSTSCRIPT" || gsdriver == "TEXT") return true; else if (!m_gschecker->checkGsDriver(gsdriver)) { setErrorMsg(i18n("The driver device <b>%1</b> is not compiled in your GhostScript distribution. Check your installation or use another driver.").arg(gsdriver)); return false; } return true; }
void NYCGenericImporter::parseFile( const QString &file ) { first = true; m_recipe.empty(); QFile input( file ); if ( input.open( QIODevice::ReadOnly ) ) { QTextStream stream( &input ); stream.skipWhiteSpace(); if ( !stream.atEnd() && stream.readLine().startsWith( "@@@@@" ) ) importNYCGeneric( stream ); else { setErrorMsg( i18n( "File does not appear to be a valid NYC export." ) ); return ; } } else setErrorMsg( i18n( "Unable to open file." ) ); }
EwsFindFolderResponse::EwsFindFolderResponse(QXmlStreamReader &reader) : EwsRequest::Response(reader) { while (reader.readNextStartElement()) { if (reader.namespaceUri() != ewsMsgNsUri && reader.namespaceUri() != ewsTypeNsUri) { setErrorMsg(QStringLiteral("Unexpected namespace in %1 element: %2") .arg(QStringLiteral("ResponseMessage")).arg(reader.namespaceUri().toString())); return; } if (reader.name() == QStringLiteral("RootFolder")) { if (!parseRootFolder(reader)) { return; } } else if (!readResponseElement(reader)) { setErrorMsg(QStringLiteral("Failed to read EWS request - invalid response element.")); return; } } }
void RecipeMLImporter::parseFile( const QString& file ) { QFile input( file ); if ( input.open( QIODevice::ReadOnly ) ) { QDomDocument doc; QString error; int line; int column; if ( !doc.setContent( &input, &error, &line, &column ) ) { setErrorMsg( i18n( "\"%1\" at line %2, column %3. This may not be a RecipeML file." , error , line , column )); return ; } QDomElement recipeml = doc.documentElement(); if ( recipeml.tagName() != "recipeml" ) { setErrorMsg( i18n( "This file does not appear to be a valid RecipeML archive." ) ); return ; } QDomNodeList l = recipeml.childNodes(); for ( int i = 0 ; i < l.count(); i++ ) { QDomElement el = l.item( i ).toElement(); QString tagName = el.tagName(); if ( tagName == "meta" ) continue; else if ( tagName == "recipe" ) readRecipemlRecipe( el ); else if ( tagName == "menu" ) readRecipemlMenu( el ); else kDebug() << "Unknown tag within <recipeml>: " << tagName ; } } else setErrorMsg( i18n( "Unable to open file." ) ); }
MacroBase::Status CvCameraInput::onApply() { cv::Mat& output = accessOutput<cv::Mat>(0); if (ptrCapture) { if (!ptrCapture->read(output)) { setErrorMsg(L"Failed to read frame from camera capture interface. Was the camera disconnected?"); return Error; } else { return Ok; } } return Error; }
DrMain *KMFoomaticManager::loadPrinterDriver(KMPrinter *printer, bool) { if(printer->option("foomatic") != "1") { setErrorMsg(i18n("This is not a Foomatic printer")); return NULL; } else if(printer->option("driver").isEmpty() || printer->option("printer").isEmpty()) { setErrorMsg(i18n("Some printer information are missing")); return NULL; } QString cmd = "foomatic-combo-xml -p "; cmd += KProcess::quote(printer->option("printer")); cmd += " -d "; cmd += KProcess::quote(printer->option("driver")); KPipeProcess proc(cmd); QDomDocument doc; doc.setContent(&proc); QDomElement docElem = doc.documentElement(); return createDriverFromXML(&docElem); }
void SocketProxy::addSocketPair(int from,int to) { // to simplify shutdown logic, dup any fds already in a socket pair if( fdInUse(from) ) { from = dup(from); } if( fdInUse(to) ) { to = dup(to); } m_socket_pairs.push_front(SocketProxyPair(from,to)); if( !setNonBlocking(from) || !setNonBlocking(to) ) { setErrorMsg("Failed to set socket to non-blocking mode."); } }
bool KMLpdManager::savePrinterDriver(KMPrinter *printer, DrMain *driver) { // To be able to save a printer driver, a printcap entry MUST exist. // We can then retrieve the spool directory from it. QString spooldir; PrintcapEntry *ent = findPrintcapEntry(printer->printerName()); if (!ent) return false; spooldir = ent->arg("sd"); if (driver->get("drtype") == "printtool" && !spooldir.isEmpty()) { QMap<QString,QString> options; driver->getOptions(options,true); // add some standard options options["DESIRED_TO"] = "ps"; options["PRINTER_TYPE"] = ent->comment(2); // get type from printcap entry (works in anycases) options["PS_SEND_EOF"] = "NO"; if (!checkGsDriver(options["GSDEVICE"])) return false; QString resol(options["RESOLUTION"]), color(options["COLOR"]); // update entry comment to make printtool happy and save printcap file ent->m_comment = QString::fromLatin1("##PRINTTOOL3## %1 %2 %3 %4 {} {%5} %6 {}").arg(options["PRINTER_TYPE"]).arg(options["GSDEVICE"]).arg((resol.isEmpty() ? QString::fromLatin1("NAxNA") : resol)).arg(options["PAPERSIZE"]).arg(driver->name()).arg((color.isEmpty() ? QString::fromLatin1("Default") : color.right(color.length()-15))); ent->m_args["if"] = spooldir+QString::fromLatin1("/filter"); if (!writePrinters()) return false; // write various driver files using templates QCString cmd = "cp "; cmd += QFile::encodeName(KProcess::quote(driverDirectory()+"/master-filter")); cmd += " "; cmd += QFile::encodeName(KProcess::quote(spooldir + "/filter")); if (system(cmd.data()) == 0 && savePrinttoolCfgFile(driverDirectory()+"/general.cfg.in",spooldir,options) && savePrinttoolCfgFile(driverDirectory()+"/postscript.cfg.in",spooldir,options) && savePrinttoolCfgFile(driverDirectory()+"/textonly.cfg.in",spooldir,options)) return true; setErrorMsg(i18n("Unable to write driver associated files in spool directory.")); } return false; }
void ContextBase::die(const Record *record, const string str1, const string str2, const string str3) { string msg; setErrorMsg(msg, false, record, str1, str2, str3); cerr << msg << endl; exit(1); }
void ContextBase::warn(const Record *record, const string str1, const string str2, const string str3) { string msg; setErrorMsg(msg, true, record, str1, str2, str3); cerr << msg << endl; }
VError::VError(const char* msg, const int code) { this->ti = (std::type_info*)&typeid(*this); setErrorMsg(msg); setErrorCode(code); }
void SocketProxy::execute() { std::list<SocketProxyPair>::iterator it; Selector selector; while( true ) { selector.reset(); bool has_active_sockets = false; for ( it=m_socket_pairs.begin(); it != m_socket_pairs.end(); ++it ) { if( it->shutdown ) { continue; } has_active_sockets = true; if( it->buf_end > 0 ) { // drain the buffer before reading more selector.add_fd(it->to_socket, Selector::IO_WRITE); } else { selector.add_fd(it->from_socket, Selector::IO_READ); } } if( !has_active_sockets ) { break; } selector.execute(); for ( it=m_socket_pairs.begin(); it != m_socket_pairs.end(); ++it ) { if( it->shutdown ) { continue; } if( it->buf_end > 0 ) { // attempt to drain the buffer if( selector.fd_ready(it->to_socket, Selector::IO_WRITE) ) { int n = write(it->to_socket,&it->buf[it->buf_begin],it->buf_end-it->buf_begin); if( n > 0 ) { it->buf_begin += n; if( it->buf_begin >= it->buf_end ) { it->buf_begin = 0; it->buf_end = 0; } } } } else if( selector.fd_ready(it->from_socket, Selector::IO_READ) ) { int n = read(it->from_socket,it->buf,SOCKET_PROXY_BUFSIZE); if( n > 0 ) { it->buf_end = n; } else if( n == 0 ) { // the socket has closed // WIN32 lacks SHUT_RD=0 and SHUT_WR=1 shutdown(it->from_socket,0); close(it->from_socket); shutdown(it->to_socket,1); close(it->to_socket); it->shutdown = true; } else if( n < 0 ) { MyString error_msg; error_msg.sprintf("Error reading from socket %d: %s\n", it->from_socket, strerror(errno)); setErrorMsg(error_msg.Value()); break; } } } } }
void KreImporter::parseFile( const QString &filename ) { QFile * file = 0; bool unlink = false; kDebug() << "loading file:" << filename ; if ( filename.right( 4 ) == ".kre" ) { file = new QFile( filename ); kDebug() << "file is an archive" ; KTar* kre = new KTar( filename, "application/x-gzip" ); kre->open( QIODevice::ReadOnly ); const KArchiveDirectory* dir = kre->directory(); QString name; QStringList fileList = dir->entries(); for ( QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it ) { if ( ( *it ).right( 6 ) == ".kreml" ) { name = *it; } } if ( name.isEmpty() ) { kDebug() << "error: Archive doesn't contain a valid Krecipes file" ; setErrorMsg( i18n( "Archive does not contain a valid Krecipes file" ) ); return ; } QString tmp_dir = KStandardDirs::locateLocal( "tmp", "" ); dir->copyTo( tmp_dir ); file = new QFile( tmp_dir + name ); kre->close(); unlink = true; //remove file after import } else { file = new QFile( filename ); } if ( file->open( QIODevice::ReadOnly ) ) { kDebug() << "file opened" ; QDomDocument doc; QString error; int line; int column; if ( !doc.setContent( file, &error, &line, &column ) ) { kDebug() << QString( "error: \"%1\" at line %2, column %3" ).arg( error ).arg( line ).arg( column ) ; setErrorMsg( i18n( "\"%1\" at line %2, column %3" , error , line, column ) ); return ; } QDomElement kreml = doc.documentElement(); if ( kreml.tagName() != "krecipes" ) { setErrorMsg( i18n( "This file does not appear to be a *.kreml file" ) ); return ; } // TODO Check if there are changes between versions QString kreVersion = kreml.attribute( "version" ); kDebug() << "KreML version" << kreVersion ; QDomNodeList r = kreml.childNodes(); QDomElement krecipe; for ( int z = 0; z < r.count(); z++ ) { krecipe = r.item( z ).toElement(); QDomNodeList l = krecipe.childNodes(); if ( krecipe.tagName() == "krecipes-recipe" ) { Recipe recipe; for ( int i = 0; i < l.count(); i++ ) { QDomElement el = l.item( i ).toElement(); if ( el.tagName() == "krecipes-description" ) { readDescription( el.childNodes(), &recipe ); } if ( el.tagName() == "krecipes-ingredients" ) { readIngredients( el.childNodes(), &recipe ); } if ( el.tagName() == "krecipes-instructions" ) { recipe.instructions = el.text().trimmed(); } if ( el.tagName() == "krecipes-ratings" ) { readRatings( el.childNodes(), &recipe ); } } add ( recipe ); } else if ( krecipe.tagName() == "krecipes-category-structure" ) { CategoryTree * tree = new CategoryTree; readCategoryStructure( l, tree ); setCategoryStructure( tree ); } } } if ( unlink ) { file->remove (); } }
bool KShortUriFilter::filterUri( KUriFilterData& data ) const { /* * Here is a description of how the shortURI deals with the supplied * data. First it expands any environment variable settings and then * deals with special shortURI cases. These special cases are the "smb:" * URL scheme which is very specific to KDE, "#" and "##" which are * shortcuts for man:/ and info:/ protocols respectively. It then handles * local files. Then it checks to see if the URL is valid and one that is * supported by KDE's IO system. If all the above checks fails, it simply * lookups the URL in the user-defined list and returns without filtering * if it is not found. TODO: the user-defined table is currently only manually * hackable and is missing a config dialog. */ KUrl url = data.uri(); QString cmd = data.typedString(); // WORKAROUND: Allow the use of '@' in the username component of a URL since // other browsers such as firefox in their infinite wisdom allow such blatant // violations of RFC 3986. BR# 69326/118413. if (cmd.count(QLatin1Char('@')) > 1) { const int lastIndex = cmd.lastIndexOf(QLatin1Char('@')); // Percent encode all but the last '@'. QString encodedCmd = QUrl::toPercentEncoding(cmd.left(lastIndex), ":/"); encodedCmd += cmd.mid(lastIndex); KUrl u (encodedCmd); if (u.isValid()) { cmd = encodedCmd; url = u; } } const bool isMalformed = !url.isValid(); QString protocol = url.protocol(); kDebug(7023) << cmd; // Fix misparsing of "foo:80", QUrl thinks "foo" is the protocol and "80" is the path. // However, be careful not to do that for valid hostless URLs, e.g. file:///foo! if (!protocol.isEmpty() && url.host().isEmpty() && !url.path().isEmpty() && cmd.contains(':') && !KProtocolInfo::protocols().contains(protocol)) { protocol.clear(); } //kDebug(7023) << "url=" << url << "cmd=" << cmd << "isMalformed=" << isMalformed; if (!isMalformed && (protocol.length() == 4) && (protocol != QLatin1String("http")) && (protocol[0]=='h') && (protocol[1]==protocol[2]) && (protocol[3]=='p')) { // Handle "encrypted" URLs like: h++p://www.kde.org url.setProtocol( QLatin1String("http")); setFilteredUri( data, url); setUriType( data, KUriFilterData::NetProtocol ); return true; } // TODO: Make this a bit more intelligent for Minicli! There // is no need to make comparisons if the supplied data is a local // executable and only the argument part, if any, changed! (Dawit) // You mean caching the last filtering, to try and reuse it, to save stat()s? (David) const QString starthere_proto = QL1S("start-here:"); if (cmd.indexOf(starthere_proto) == 0 ) { setFilteredUri( data, KUrl("system:/") ); setUriType( data, KUriFilterData::LocalDir ); return true; } // Handle MAN & INFO pages shortcuts... const QString man_proto = QL1S("man:"); const QString info_proto = QL1S("info:"); if( cmd[0] == '#' || cmd.indexOf( man_proto ) == 0 || cmd.indexOf( info_proto ) == 0 ) { if( cmd.left(2) == QL1S("##") ) cmd = QL1S("info:/") + cmd.mid(2); else if ( cmd[0] == '#' ) cmd = QL1S("man:/") + cmd.mid(1); else if ((cmd==info_proto) || (cmd==man_proto)) cmd+='/'; setFilteredUri( data, KUrl( cmd )); setUriType( data, KUriFilterData::Help ); return true; } // Detect UNC style (aka windows SMB) URLs if ( cmd.startsWith( QLatin1String( "\\\\") ) ) { // make sure path is unix style cmd.replace('\\', '/'); cmd.prepend( QLatin1String( "smb:" ) ); setFilteredUri( data, KUrl( cmd )); setUriType( data, KUriFilterData::NetProtocol ); return true; } bool expanded = false; // Expanding shortcut to HOME URL... QString path; QString ref; QString query; QString nameFilter; if (KUrl::isRelativeUrl(cmd) && QDir::isRelativePath(cmd)) { path = cmd; //kDebug(7023) << "path=cmd=" << path; } else { if (url.isLocalFile()) { //kDebug(7023) << "hasRef=" << url.hasRef(); // Split path from ref/query // but not for "/tmp/a#b", if "a#b" is an existing file, // or for "/tmp/a?b" (#58990) if( ( url.hasRef() || !url.query().isEmpty() ) && !url.path().endsWith(QL1S("/")) ) // /tmp/?foo is a namefilter, not a query { path = url.path(); ref = url.ref(); //kDebug(7023) << "isLocalFile set path to " << stringDetails( path ); //kDebug(7023) << "isLocalFile set ref to " << stringDetails( ref ); query = url.query(); if (path.isEmpty() && url.hasHost()) path = '/'; } else { path = cmd; //kDebug(7023) << "(2) path=cmd=" << path; } } } if( path[0] == '~' ) { int slashPos = path.indexOf('/'); if( slashPos == -1 ) slashPos = path.length(); if( slashPos == 1 ) // ~/ { path.replace ( 0, 1, QDir::homePath() ); } else // ~username/ { const QString userName (path.mid( 1, slashPos-1 )); KUser user (userName); if( user.isValid() && !user.homeDir().isEmpty()) { path.replace (0, slashPos, user.homeDir()); } else { if (user.isValid()) { setErrorMsg(data, i18n("<qt><b>%1</b> does not have a home folder.</qt>", userName)); } else { setErrorMsg(data, i18n("<qt>There is no user called <b>%1</b>.</qt>", userName)); } setUriType( data, KUriFilterData::Error ); // Always return true for error conditions so // that other filters will not be invoked !! return true; } } expanded = true; } else if ( path[0] == '$' ) { // Environment variable expansion. if ( sEnvVarExp.indexIn( path ) == 0 ) { QByteArray exp = qgetenv( path.mid( 1, sEnvVarExp.matchedLength() - 1 ).toLocal8Bit().data() ); if(! exp.isNull()) { path.replace( 0, sEnvVarExp.matchedLength(), QString::fromLocal8Bit(exp.constData()) ); expanded = true; } } } if ( expanded || cmd.startsWith( '/' ) ) { // Look for #ref again, after $ and ~ expansion (testcase: $QTDIR/doc/html/functions.html#s) // Can't use KUrl here, setPath would escape it... const int pos = path.indexOf('#'); if ( pos > -1 ) { const QString newPath = path.left( pos ); if ( QFile::exists( newPath ) ) { ref = path.mid( pos + 1 ); path = newPath; //kDebug(7023) << "Extracted ref: path=" << path << " ref=" << ref; } } } bool isLocalFullPath = (!path.isEmpty() && path[0] == '/'); // Checking for local resource match... // Determine if "uri" is an absolute path to a local resource OR // A local resource with a supplied absolute path in KUriFilterData const QString abs_path = data.absolutePath(); const bool canBeAbsolute = (protocol.isEmpty() && !abs_path.isEmpty()); const bool canBeLocalAbsolute = (canBeAbsolute && abs_path[0] =='/' && !isMalformed); bool exists = false; /*kDebug(7023) << "abs_path=" << abs_path << "protocol=" << protocol << "canBeAbsolute=" << canBeAbsolute << "canBeLocalAbsolute=" << canBeLocalAbsolute << "isLocalFullPath=" << isLocalFullPath;*/ KDE_struct_stat buff; if ( canBeLocalAbsolute ) { QString abs = QDir::cleanPath( abs_path ); // combine absolute path (abs_path) and relative path (cmd) into abs_path int len = path.length(); if( (len==1 && path[0]=='.') || (len==2 && path[0]=='.' && path[1]=='.') ) path += '/'; //kDebug(7023) << "adding " << abs << " and " << path; abs = QDir::cleanPath(abs + '/' + path); //kDebug(7023) << "checking whether " << abs << " exists."; // Check if it exists if( KDE::stat( abs, &buff ) == 0 ) { path = abs; // yes -> store as the new cmd exists = true; isLocalFullPath = true; } } if (isLocalFullPath && !exists && !isMalformed) { exists = ( KDE::stat( path, &buff ) == 0 ); if ( !exists ) { // Support for name filter (/foo/*.txt), see also KonqMainWindow::detectNameFilter // If the app using this filter doesn't support it, well, it'll simply error out itself int lastSlash = path.lastIndexOf( '/' ); if ( lastSlash > -1 && path.indexOf( ' ', lastSlash ) == -1 ) // no space after last slash, otherwise it's more likely command-line arguments { QString fileName = path.mid( lastSlash + 1 ); QString testPath = path.left( lastSlash + 1 ); if ( ( fileName.indexOf( '*' ) != -1 || fileName.indexOf( '[' ) != -1 || fileName.indexOf( '?' ) != -1 ) && KDE::stat( testPath, &buff ) == 0 ) { nameFilter = fileName; //kDebug(7023) << "Setting nameFilter to " << nameFilter; path = testPath; exists = true; } } } } //kDebug(7023) << "path =" << path << " isLocalFullPath=" << isLocalFullPath << " exists=" << exists; if( exists ) { KUrl u; u.setPath(path); //kDebug(7023) << "ref=" << stringDetails(ref) << " query=" << stringDetails(query); u.setRef(ref); u.setQuery(query); if (!KAuthorized::authorizeUrlAction( QLatin1String("open"), KUrl(), u)) { // No authorization, we pretend it's a file will get // an access denied error later on. setFilteredUri( data, u ); setUriType( data, KUriFilterData::LocalFile ); return true; } // Can be abs path to file or directory, or to executable with args bool isDir = S_ISDIR( buff.st_mode ); if( !isDir && access ( QFile::encodeName(path).data(), X_OK) == 0 ) { //kDebug(7023) << "Abs path to EXECUTABLE"; setFilteredUri( data, u ); setUriType( data, KUriFilterData::Executable ); return true; } // Open "uri" as file:/xxx if it is a non-executable local resource. if( isDir || S_ISREG( buff.st_mode ) ) { //kDebug(7023) << "Abs path as local file or directory"; if ( !nameFilter.isEmpty() ) u.setFileName( nameFilter ); setFilteredUri( data, u ); setUriType( data, ( isDir ) ? KUriFilterData::LocalDir : KUriFilterData::LocalFile ); return true; } // Should we return LOCAL_FILE for non-regular files too? kDebug(7023) << "File found, but not a regular file nor dir... socket?"; } if( data.checkForExecutables()) { // Let us deal with possible relative URLs to see // if it is executable under the user's $PATH variable. // We try hard to avoid parsing any possible command // line arguments or options that might have been supplied. QString exe = removeArgs( cmd ); //kDebug(7023) << "findExe with" << exe; if (!KStandardDirs::findExe( exe ).isNull() ) { //kDebug(7023) << "EXECUTABLE exe=" << exe; setFilteredUri( data, KUrl::fromPath( exe )); // check if we have command line arguments if( exe != cmd ) setArguments(data, cmd.right(cmd.length() - exe.length())); setUriType( data, KUriFilterData::Executable ); return true; } } // Process URLs of known and supported protocols so we don't have // to resort to the pattern matching scheme below which can possibly // slow things down... if ( !isMalformed && !isLocalFullPath && !protocol.isEmpty() ) { //kDebug(7023) << "looking for protocol " << protocol; if ( KProtocolInfo::isKnownProtocol( protocol ) ) { setFilteredUri( data, url ); if ( protocol == QL1S("man") || protocol == QL1S("help") ) setUriType( data, KUriFilterData::Help ); else setUriType( data, KUriFilterData::NetProtocol ); return true; } } // Short url matches if ( !cmd.contains( ' ' ) ) { // Okay this is the code that allows users to supply custom matches for // specific URLs using Qt's regexp class. This is hard-coded for now. // TODO: Make configurable at some point... Q_FOREACH(const URLHint& hint, m_urlHints) { if (hint.regexp.indexIn(cmd) == 0) { //kDebug(7023) << "match - prepending" << (*it).prepend; const QString cmdStr = hint.prepend + cmd; KUrl url(cmdStr); if (KProtocolInfo::isKnownProtocol(url)) { setFilteredUri( data, url ); setUriType( data, hint.type ); return true; } } } // No protocol and not malformed means a valid short URL such as kde.org or // [email protected]. However, it might also be valid only because it lacks // the scheme component, e.g. www.kde,org (illegal ',' before 'org'). The // check below properly deciphers the difference between the two and sends // back the proper result. if (protocol.isEmpty() && isPotentialShortURL(cmd)) { QString urlStr = data.defaultUrlScheme(); if (urlStr.isEmpty()) urlStr = m_strDefaultUrlScheme; const int index = urlStr.indexOf(QL1C(':')); if (index == -1 || !KProtocolInfo::isKnownProtocol(urlStr.left(index))) urlStr += QL1S("://"); urlStr += cmd; KUrl url (urlStr); if (url.isValid()) { setFilteredUri(data, url); setUriType(data, KUriFilterData::NetProtocol); } else if (KProtocolInfo::isKnownProtocol(url.protocol())) { setFilteredUri(data, data.uri()); setUriType(data, KUriFilterData::Error); } return true; } }
void MXPImporter::importMac( QTextStream & /*stream*/ ) { setErrorMsg( i18n( "MasterCook Mac's Export format is currently not supported. Please write to [email protected] to request support for this format." ) ); //not even sure it this is worth writing... its rather obsolete }
bool KMLpdManager::createPrinter(KMPrinter *printer) { // 1) create the printcap entry PrintcapEntry *ent = findPrintcapEntry(printer->printerName()); if (!ent) { ent = new PrintcapEntry(); ent->m_name = printer->printerName(); } else { if (!printer->driver() && printer->option("kde-driver") != "raw") printer->setDriver(loadPrinterDriver(printer,true)); // remove it from current entries ent = m_entries.take(ent->m_name); ent->m_args.clear(); } // Standard options if (printer->device().protocol() == "lpd") { // remote lpd queue ent->m_args["rm"] = printer->device().host(); ent->m_args["rp"] = printer->device().path().replace("/",QString::fromLatin1("")); ent->m_args["lpd_bounce"] = "true"; ent->m_comment = QString::fromLatin1("##PRINTTOOL3## REMOTE"); } ent->m_args["mx"] = (printer->option("mx").isEmpty() ? "#0" : printer->option("mx")); ent->m_args["sh"] = QString::null; // create spool directory (if necessary) and update PrintcapEntry object if (!createSpooldir(ent)) { setErrorMsg(i18n("Unable to create spool directory %1 for printer %2.").arg(ent->arg("sd")).arg(ent->m_name)); delete ent; return false; } if (!printer->driver() || printer->driver()->get("drtype") == "printtool") if (!createPrinttoolEntry(printer,ent)) { setErrorMsg(i18n("Unable to save information for printer <b>%1</b>.").arg(printer->printerName())); delete ent; return false; } // 2) write the printcap file m_entries.insert(ent->m_name,ent); if (!writePrinters()) return false; // 3) save the printer driver (if any) if (printer->driver()) { if (!savePrinterDriver(printer,printer->driver())) { m_entries.remove(ent->m_name); writePrinters(); return false; } } // 4) change permissions of spool directory QCString cmd = "chmod -R o-rwx,g+rwX "; cmd += QFile::encodeName(KProcess::quote(ent->arg("sd"))); cmd += "&& chown -R lp.lp "; cmd += QFile::encodeName(KProcess::quote(ent->arg("sd"))); if (system(cmd.data()) != 0) { setErrorMsg(i18n("Unable to set correct permissions on spool directory %1 for printer <b>%2</b>.").arg(ent->arg("sd")).arg(ent->m_name)); return false; } return true; }