kstandarddirs.cpp

来自「konqueror3 embedded版本, KDE环境下的当家浏览器的嵌入式版」· C++ 代码 · 共 1,677 行 · 第 1/3 页

CPP
1,677
字号
       if (slash < 0)	   rest = relpath.left(relpath.length() - 1);       else {	   path = relpath.left(slash);	   rest = relpath.mid(slash + 1);       }    }    if (prefix.isEmpty()) //for sanity      return;#ifdef Q_WS_WIN    assert(prefix.at(prefix.length() - 1) == '/' || prefix.at(prefix.length() - 1) == '\\');#else    assert(prefix.at(prefix.length() - 1) == '/');#endif    KDE_struct_stat buff;    if (path.contains('*') || path.contains('?')) {	QRegExp pathExp(path, true, true);	DIR *dp = opendir( QFile::encodeName(prefix) );	if (!dp) {	    return;	}	struct dirent *ep;        QString _dot(".");        QString _dotdot("..");	while( ( ep = readdir( dp ) ) != 0L )	    {		QString fn( QFile::decodeName(ep->d_name));		if (fn == _dot || fn == _dotdot || fn.at(fn.length() - 1) == '~')		    continue;		if ( !pathExp.exactMatch(fn) )		    continue; // No match		QString rfn = relPart+fn;		fn = prefix + fn;		if ( KDE_stat( QFile::encodeName(fn), &buff ) != 0 ) {		    kdDebug() << "Error statting " << fn << " : " << perror << endl;		    continue; // Couldn't stat (e.g. no permissions)		}		if ( S_ISDIR( buff.st_mode ))		    lookupPrefix(fn + '/', rest, rfn + '/', regexp, list, relList, recursive, unique);	    }	closedir( dp );    } else {        // Don't stat, if the dir doesn't exist we will find out        // when we try to open it.        lookupPrefix(prefix + path + '/', rest,                     relPart + path + '/', regexp, list,                     relList, recursive, unique);    }}QStringListKStandardDirs::findAllResources( const char *type,			         const QString& filter,				 bool recursive,			         bool unique,                                 QStringList &relList) const{    QStringList list;    QString filterPath;    QString filterFile;    if (filter.length())    {       int slash = filter.findRev('/');       if (slash < 0)	   filterFile = filter;       else {	   filterPath = filter.left(slash + 1);	   filterFile = filter.mid(slash + 1);       }    }    checkConfig();    QStringList candidates;	if (!QDir::isRelativePath(filter)) // absolute path    {#ifdef Q_OS_WIN        candidates << filterPath.left(3); //e.g. "C:\"        filterPath = filterPath.mid(3);#else        candidates << "/";        filterPath = filterPath.mid(1);#endif    }    else    {        if (d && d->restrictionsActive && (strcmp(type, "data")==0))            applyDataRestrictions(filter);        candidates = resourceDirs(type);    }    if (filterFile.isEmpty())	filterFile = "*";    QRegExp regExp(filterFile, true, true);    for (QStringList::ConstIterator it = candidates.begin();         it != candidates.end(); ++it)    {        lookupPrefix(*it, filterPath, "", regExp, list,                     relList, recursive, unique);    }    return list;}QStringListKStandardDirs::findAllResources( const char *type,			         const QString& filter,				 bool recursive,			         bool unique) const{    QStringList relList;    return findAllResources(type, filter, recursive, unique, relList);}QStringKStandardDirs::realPath(const QString &dirname){    char realpath_buffer[MAXPATHLEN + 1];    memset(realpath_buffer, 0, MAXPATHLEN + 1);    /* If the path contains symlinks, get the real name */    if (realpath( QFile::encodeName(dirname).data(), realpath_buffer) != 0) {        // succes, use result from realpath        int len = strlen(realpath_buffer);        realpath_buffer[len] = '/';        realpath_buffer[len+1] = 0;        return QFile::decodeName(realpath_buffer);    }    return dirname;}QStringKStandardDirs::realFilePath(const QString &filename){    char realpath_buffer[MAXPATHLEN + 1];    memset(realpath_buffer, 0, MAXPATHLEN + 1);    /* If the path contains symlinks, get the real name */    if (realpath( QFile::encodeName(filename).data(), realpath_buffer) != 0) {        // succes, use result from realpath        return QFile::decodeName(realpath_buffer);    }    return filename;}void KStandardDirs::createSpecialResource(const char *type){   char hostname[256];   hostname[0] = 0;   gethostname(hostname, 255);   QString dir = QString("%1%2-%3").arg(localkdedir()).arg(type).arg(hostname);   char link[1024];   link[1023] = 0;   int result = readlink(QFile::encodeName(dir).data(), link, 1023);   bool relink = (result == -1) && (errno == ENOENT);   if (result > 0)   {      link[result] = 0;      if (!QDir::isRelativePath(link))      {         KDE_struct_stat stat_buf;         int res = KDE_lstat(link, &stat_buf);         if ((res == -1) && (errno == ENOENT))         {            relink = true;         }         else if ((res == -1) || (!S_ISDIR(stat_buf.st_mode)))         {            fprintf(stderr, "Error: \"%s\" is not a directory.\n", link);            relink = true;         }         else if (stat_buf.st_uid != getuid())         {            fprintf(stderr, "Error: \"%s\" is owned by uid %d instead of uid %d.\n", link, stat_buf.st_uid, getuid());            relink = true;         }      }   }#ifdef Q_WS_WIN   if (relink)   {      if (!makeDir(dir, 0700))         fprintf(stderr, "failed to create \"%s\"", dir.latin1());      else         result = readlink(QFile::encodeName(dir).data(), link, 1023);   }#else //UNIX   if (relink)   {      QString srv = findExe(QString::fromLatin1("lnusertemp"), kfsstnd_defaultbindir());      if (srv.isEmpty())         srv = findExe(QString::fromLatin1("lnusertemp"));      if (!srv.isEmpty())      {         system(QFile::encodeName(srv)+" "+type);         result = readlink(QFile::encodeName(dir).data(), link, 1023);      }   }   if (result > 0)   {      link[result] = 0;      if (link[0] == '/')         dir = QFile::decodeName(link);      else         dir = QDir::cleanDirPath(dir+QFile::decodeName(link));   }#endif   addResourceDir(type, dir+'/');}QStringList KStandardDirs::resourceDirs(const char *type) const{    QStringList *candidates = dircache.find(type);    if (!candidates) { // filling cache        if (strcmp(type, "socket") == 0)           const_cast<KStandardDirs *>(this)->createSpecialResource(type);        else if (strcmp(type, "tmp") == 0)           const_cast<KStandardDirs *>(this)->createSpecialResource(type);        else if (strcmp(type, "cache") == 0)           const_cast<KStandardDirs *>(this)->createSpecialResource(type);        QDir testdir;        candidates = new QStringList();        QStringList *dirs;        bool restrictionActive = false;        if (d && d->restrictionsActive)        {           if (d->dataRestrictionActive)              restrictionActive = true;           else if (d->restrictions["all"])              restrictionActive = true;           else if (d->restrictions[type])              restrictionActive = true;           d->dataRestrictionActive = false; // Reset        }        dirs = relatives.find(type);        if (dirs)        {            bool local = true;            const QStringList *prefixList = 0;            if (strncmp(type, "xdgdata-", 8) == 0)                prefixList = &(d->xdgdata_prefixes);            else if (strncmp(type, "xdgconf-", 8) == 0)                prefixList = &(d->xdgconf_prefixes);            else                prefixList = &prefixes;            for (QStringList::ConstIterator pit = prefixList->begin();                 pit != prefixList->end();                 ++pit)            {                for (QStringList::ConstIterator it = dirs->begin();                     it != dirs->end(); ++it) {                    QString path = realPath(*pit + *it);                    testdir.setPath(path);                    if (local && restrictionActive)                       continue;                    if ((local || testdir.exists()) && !candidates->contains(path))                        candidates->append(path);                }                local = false;            }        }        dirs = absolutes.find(type);        if (dirs)            for (QStringList::ConstIterator it = dirs->begin();                 it != dirs->end(); ++it)            {                testdir.setPath(*it);                if (testdir.exists())                {                    QString filename = realPath(*it);                    if (!candidates->contains(filename))                        candidates->append(filename);                }            }        dircache.insert(type, candidates);    }#if 0    kdDebug() << "found dirs for resource " << type << ":" << endl;    for (QStringList::ConstIterator pit = candidates->begin();	 pit != candidates->end();	 pit++)    {	fprintf(stderr, "%s\n", (*pit).latin1());    }#endif  return *candidates;}QStringList KStandardDirs::systemPaths( const QString& pstr ){    QStringList tokens;    QString p = pstr;    if( p.isNull() )    {	p = getenv( "PATH" );    }    QString delimiters(QChar(KPATH_SEPARATOR));    delimiters += "\b";    tokenize( tokens, p, delimiters );    QStringList exePaths;    // split path using : or \b as delimiters    for( unsigned i = 0; i < tokens.count(); i++ )    {	p = tokens[ i ];        if ( p[ 0 ] == '~' )        {            int len = p.find( '/' );            if ( len == -1 )                len = p.length();            if ( len == 1 )            {                p.replace( 0, 1, QDir::homeDirPath() );            }            else            {                QString user = p.mid( 1, len - 1 );                struct passwd *dir = getpwnam( user.local8Bit().data() );                if ( dir && strlen( dir->pw_dir ) )                    p.replace( 0, len, QString::fromLocal8Bit( dir->pw_dir ) );            }        }	exePaths << p;    }    return exePaths;}QString KStandardDirs::findExe( const QString& appname,				const QString& pstr, bool ignore){#ifdef Q_WS_WIN    QString real_appname = appname + ".exe";#else    QString real_appname = appname;#endif    QFileInfo info;    // absolute path ?    if (!QDir::isRelativePath(real_appname))    {        info.setFile( real_appname );        if( info.exists() && ( ignore || info.isExecutable() )            && info.isFile() ) {            return real_appname;        }        return QString::null;    }    QString p = QString("%1/%2").arg(kfsstnd_defaultbindir()).arg(real_appname);    info.setFile( p );    if( info.exists() && ( ignore || info.isExecutable() )         && ( info.isFile() || info.isSymLink() )  ) {         return p;    }    QStringList exePaths = systemPaths( pstr );    for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); ++it)    {	p = (*it) + "/";	p += real_appname;	// Check for executable in this tokenized path	info.setFile( p );	if( info.exists() && ( ignore || info.isExecutable() )           && ( info.isFile() || info.isSymLink() )  ) {	    return p;	}    }    // If we reach here, the executable wasn't found.    // So return empty string.    return QString::null;}int KStandardDirs::findAllExe( QStringList& list, const QString& appname,			const QString& pstr, bool ignore ){#ifdef Q_WS_WIN    QString real_appname = appname + ".exe";#else    QString real_appname = appname;#endif    QFileInfo info;    QString p;    list.clear();    QStringList exePaths = systemPaths( pstr );    for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); ++it)    {	p = (*it) + "/";	p += real_appname;	info.setFile( p );	if( info.exists() && (ignore || info.isExecutable())	    && info.isFile() ) {	    list.append( p );	}    }    return list.count();}static int tokenize( QStringList& tokens, const QString& str,		     const QString& delim ){    int len = str.length();    QString token = "";    for( int index = 0; index < len; index++)    {	if ( delim.find( str[ index ] ) >= 0 )	{	    tokens.append( token );	    token = "";	}	else	{	    token += str[ index ];	}    }    if ( token.length() > 0 )    {	tokens.append( token );    }    return tokens.count();}QString KStandardDirs::kde_default(const char *type) {    if (!strcmp(type, "data"))	return "share/apps/";    if (!strcmp(type, "html"))	return "share/doc/HTML/";    if (!strcmp(type, "icon"))	return "share/icons/";    if (!strcmp(type, "config"))	return "share/config/";    if (!strcmp(type, "pixmap"))	return "share/pixmaps/";    if (!strcmp(type, "apps"))	return "share/applnk/";    if (!strcmp(type, "sound"))	return "share/sounds/";    if (!strcmp(type, "locale"))	return "share/locale/";    if (!strcmp(type, "services"))	return "share/services/";    if (!strcmp(type, "servicetypes"))	return "share/servicetypes/";    if (!strcmp(type, "mime"))	return "share/mimelnk/";    if (!strcmp(type, "cgi"))	return "cgi-bin/";    if (!strcmp(type, "wallpaper"))	return "share/wallpapers/";    if (!strcmp(type, "templates"))	return "share/templates/";    if (!strcmp(type, "exe"))	return "bin/";    if (!strcmp(type, "lib"))	return "lib" KDELIBSUFF "/";    if (!strcmp(type, "module"))	return "lib" KDELIBSUFF "/kde3/";    if (!strcmp(type, "qtplugins"))        return "lib" KDELIBSUFF "/kde3/plugins";    if (!strcmp(type, "xdgdata-apps"))        return "applications/";    if (!strcmp(type, "xdgdata-dirs"))        return "desktop-directories/";    if (!strcmp(type, "xdgconf-menu"))        return "menus/";    if (!strcmp(type, "kcfg"))	return "share/config.kcfg";    if (!strcmp(type, "emoticons"))			return "share/emoticons";    qFatal("unknown resource type %s", type);    return QString::null;}QString KStandardDirs::saveLocation(const char *type,				    const QString& suffix,				    bool create) const{    checkConfig();    QString *pPath = savelocations.find(type);    if (!pPath)    {       QStringList *dirs = relatives.find(type);       if (!dirs && (                     (strcmp(type, "socket") == 0) ||                     (strcmp(type, "tmp") == 0) ||                     (strcmp(type, "cache") == 0) ))       {          (void) resourceDirs(type); // Generate socket|tmp|cache resource.          dirs = relatives.find(type); // Search again.       }       if (dirs)       {          // Check for existence of typed directory + suffix          if (strncmp(type, "xdgdata-", 8) == 0)             pPath = new QString(realPath(localxdgdatadir() + dirs->last()));          else if (strncmp(type, "xdgconf-", 8) == 0)             pPath = new QString(realPath(localxdgconfdir() + dirs->last()));          else             pPath = new QString(realPath(localkdedir() + dirs->last()));       }       else {          dirs = absolutes.find(type);          if (!dirs)             qFatal("KStandardDirs: The resource type %s is not registered", type);          pPath = new QString(realPath(dirs->last()));       }       savelocations.insert(type, pPath);    }    QString fullPath = *pPath + (pPath->endsWith("/") ? "" : "/") + suffix;    KDE_struct_stat st;    if (KDE_stat(QFile::encodeName(fullPath), &st) != 0 || !(S_ISDIR(st.st_mode))) {	if(!create) {#ifndef NDEBUG	    kdDebug() << QString("save location %1 doesn't exist").arg(fullPath) << endl;#endif	    return fullPath;	}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?