• Skip to content
  • Skip to link menu
KDE 4.2 API Reference
  • KDE API Reference
  • kdelibs
  • Sitemap
  • Contact Us
 

KDED

kbuildsycoca.cpp

Go to the documentation of this file.
00001 // -*- c-basic-offset: 3 -*-
00002 /*  This file is part of the KDE libraries
00003  *  Copyright (C) 1999 David Faure <faure@kde.org>
00004  *  Copyright (C) 2002-2003 Waldo Bastian <bastian@kde.org>
00005  *
00006  *  This library is free software; you can redistribute it and/or
00007  *  modify it under the terms of the GNU Library General Public
00008  *  License version 2 as published by the Free Software Foundation;
00009  *
00010  *  This library is distributed in the hope that it will be useful,
00011  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013  *  Library General Public License for more details.
00014  *
00015  *  You should have received a copy of the GNU Library General Public License
00016  *  along with this library; see the file COPYING.LIB.  If not, write to
00017  *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00018  *  Boston, MA 02110-1301, USA.
00019  **/
00020 
00021 #include "kbuildsycoca.h"
00022 #include "kresourcelist.h"
00023 #include "vfolder_menu.h"
00024 
00025 #include <config.h>
00026 
00027 #include <kservice.h>
00028 #include <kmimetype.h>
00029 #include "kbuildservicetypefactory.h"
00030 #include "kbuildmimetypefactory.h"
00031 #include "kbuildservicefactory.h"
00032 #include "kbuildservicegroupfactory.h"
00033 #include "kbuildprotocolinfofactory.h"
00034 #include "kctimefactory.h"
00035 #include <ktemporaryfile.h>
00036 #include <QtCore/QDataStream>
00037 #include <QtCore/QDir>
00038 #include <QtCore/QEventLoop>
00039 #include <QtCore/QFile>
00040 #include <QtCore/QTimer>
00041 #include <QtDBus/QtDBus>
00042 #include <errno.h>
00043 
00044 #include <assert.h>
00045 #include <kapplication.h>
00046 #include <kglobal.h>
00047 #include <kdebug.h>
00048 #include <kdirwatch.h>
00049 #include <kstandarddirs.h>
00050 #include <ksavefile.h>
00051 #include <klocale.h>
00052 #include <kaboutdata.h>
00053 #include <kcmdlineargs.h>
00054 #include <kcrash.h>
00055 #ifdef Q_OS_WIN
00056 #include <kmemfile.h>
00057 #endif
00058 
00059 #ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build
00060                         // GUI version of kbuildsycoca, so-called "kbuildsycocaw".
00061 # include <qlabel.h>
00062 # include <kmessagebox.h>
00063   bool silent;
00064   bool showprogress;
00065 #endif
00066 
00067 #include <stdlib.h>
00068 #include <unistd.h>
00069 #include <time.h>
00070 #include <memory> // auto_ptr
00071 
00072 typedef QHash<QString, KSycocaEntry::Ptr> KBSEntryDict;
00073 typedef QList<KSycocaEntry::List> KSycocaEntryListList;
00074 
00075 static quint32 newTimestamp = 0;
00076 
00077 static KBuildServiceFactory *g_bsf = 0;
00078 static KBuildServiceGroupFactory *g_bsgf = 0;
00079 static KSycocaFactory *g_factory = 0;
00080 static KCTimeInfo *g_ctimeInfo = 0;
00081 static QHash<QString, quint32> *g_ctimeDict = 0;
00082 static QByteArray g_resource = 0;
00083 static KBSEntryDict *g_entryDict = 0;
00084 static KBSEntryDict *g_serviceGroupEntryDict = 0;
00085 static KSycocaEntryListList *g_allEntries = 0;
00086 static QStringList *g_changeList = 0;
00087 static QStringList *g_allResourceDirs = 0;
00088 static bool g_changed = false;
00089 static KSycocaEntry::List g_tempStorage;
00090 static VFolderMenu *g_vfolder = 0;
00091 
00092 static const char *cSycocaPath = 0;
00093 
00094 static bool bGlobalDatabase = false;
00095 static bool bMenuTest = false;
00096 
00097 void crashHandler(int)
00098 {
00099    // If we crash while reading sycoca, we delete the database
00100    // in an attempt to recover.
00101    if (cSycocaPath)
00102       unlink(cSycocaPath);
00103 }
00104 
00105 static QString sycocaPath()
00106 {
00107   return KSycoca::absoluteFilePath(bGlobalDatabase ? KSycoca::GlobalDatabase : KSycoca::LocalDatabase);
00108 }
00109 
00110 KBuildSycoca::KBuildSycoca()
00111   : KSycoca( true )
00112 {
00113 }
00114 
00115 KBuildSycoca::~KBuildSycoca()
00116 {
00117 
00118 }
00119 
00120 KSycocaEntry::Ptr KBuildSycoca::createEntry(const QString &file, bool addToFactory)
00121 {
00122    quint32 timeStamp = g_ctimeInfo->ctime(file);
00123    if (!timeStamp)
00124    {
00125       timeStamp = KGlobal::dirs()->calcResourceHash( g_resource, file,
00126                                                      KStandardDirs::Recursive);
00127    }
00128    KSycocaEntry::Ptr entry;
00129    if (g_allEntries)
00130    {
00131       assert(g_ctimeDict);
00132       quint32 oldTimestamp = g_ctimeDict->value( file, 0 );
00133 
00134       if (timeStamp && (timeStamp == oldTimestamp))
00135       {
00136          // Re-use old entry
00137          if (g_factory == g_bsgf) // Strip .directory from service-group entries
00138          {
00139             entry = g_entryDict->value(file.left(file.length()-10));
00140          } else {
00141             entry = g_entryDict->value(file);
00142          }
00143          // remove from g_ctimeDict; if g_ctimeDict is not empty
00144          // after all files have been processed, it means
00145          // some files were removed since last time
00146          g_ctimeDict->remove( file );
00147       }
00148       else if (oldTimestamp)
00149       {
00150          g_changed = true;
00151          kDebug(7021) << "modified:" << file;
00152       }
00153       else
00154       {
00155          g_changed = true;
00156          kDebug(7021) << "new:" << file;
00157       }
00158    }
00159    g_ctimeInfo->addCTime(file, timeStamp );
00160    if (!entry)
00161    {
00162       // Create a new entry
00163       entry = g_factory->createEntry( file, g_resource );
00164    }
00165    if ( entry && entry->isValid() )
00166    {
00167       if (addToFactory)
00168          g_factory->addEntry(entry);
00169       else
00170          g_tempStorage.append(entry);
00171       return entry;
00172    }
00173    return KSycocaEntry::Ptr();
00174 }
00175 
00176 // Callback for VFolderMenu
00177 void KBuildSycoca::slotCreateEntry(const QString &file, KService::Ptr *service)
00178 {
00179    KSycocaEntry::Ptr entry = createEntry(file, false);
00180    *service = KService::Ptr::staticCast( entry );
00181 }
00182 
00183 // returns false if the database is up to date
00184 bool KBuildSycoca::build()
00185 {
00186   typedef QLinkedList<KBSEntryDict *> KBSEntryDictList;
00187   KBSEntryDictList entryDictList;
00188   KBSEntryDict *serviceEntryDict = 0;
00189 
00190   // Convert for each factory the entryList to a Dict.
00191   int i = 0;
00192   // For each factory
00193   for (KSycocaFactoryList::Iterator factory = factories()->begin();
00194        factory != factories()->end();
00195        ++factory)
00196   {
00197      KBSEntryDict *entryDict = new KBSEntryDict;
00198      if (g_allEntries)
00199      {
00200          const KSycocaEntry::List list = (*g_allEntries)[i++];
00201          for( KSycocaEntry::List::const_iterator it = list.begin();
00202             it != list.end();
00203             ++it)
00204          {
00205             entryDict->insert( (*it)->entryPath(), *it );
00206          }
00207      }
00208      if ((*factory) == g_bsf)
00209         serviceEntryDict = entryDict;
00210      else if ((*factory) == g_bsgf)
00211         g_serviceGroupEntryDict = entryDict;
00212      entryDictList.append(entryDict);
00213   }
00214 
00215   QStringList allResources; // we could use QSet<QString> - does order matter?
00216   // For each factory
00217   for (KSycocaFactoryList::Iterator factory = factories()->begin();
00218        factory != factories()->end();
00219        ++factory)
00220   {
00221     // For each resource the factory deals with
00222     const KSycocaResourceList *list = (*factory)->resourceList();
00223     if (!list) continue;
00224 
00225     for( KSycocaResourceList::ConstIterator it1 = list->begin();
00226          it1 != list->end();
00227          ++it1 )
00228     {
00229       KSycocaResource res = (*it1);
00230       if (!allResources.contains(res.resource))
00231          allResources.append(res.resource);
00232     }
00233   }
00234 
00235   g_ctimeInfo = new KCTimeInfo(); // This is a build factory too, don't delete!!
00236   bool uptodate = true;
00237   // For all resources
00238   for( QStringList::ConstIterator it1 = allResources.begin();
00239        it1 != allResources.end();
00240        ++it1 )
00241   {
00242      g_changed = false;
00243      g_resource = (*it1).toLatin1();
00244 
00245      QStringList relFiles;
00246 
00247      (void) KGlobal::dirs()->findAllResources( g_resource,
00248                                                QString(),
00249                                                KStandardDirs::Recursive |
00250                                                KStandardDirs::NoDuplicates,
00251                                                relFiles);
00252 
00253 
00254      // Now find all factories that use this resource....
00255      // For each factory
00256      KBSEntryDictList::const_iterator ed_it = entryDictList.begin();
00257      const KBSEntryDictList::const_iterator ed_end = entryDictList.end();
00258      KSycocaFactoryList::const_iterator it = factories()->begin();
00259      const KSycocaFactoryList::const_iterator end = factories()->end();
00260      for ( ; it != end; ++it, ++ed_it )
00261      {
00262         g_factory = (*it);
00263         // g_ctimeInfo gets created after the initial loop, so it has no entryDict.
00264         g_entryDict = ed_it == ed_end ? 0 : *ed_it;
00265     // For each resource the factory deals with
00266         const KSycocaResourceList *list = g_factory->resourceList();
00267         if (!list) continue;
00268 
00269         for( KSycocaResourceList::ConstIterator it2 = list->begin();
00270              it2 != list->end();
00271              ++it2 )
00272         {
00273            KSycocaResource res = (*it2);
00274            if (res.resource != (*it1)) continue;
00275 
00276            // For each file in the resource
00277            for( QStringList::ConstIterator it3 = relFiles.begin();
00278                 it3 != relFiles.end();
00279                 ++it3 )
00280            {
00281                // Check if file matches filter
00282                if ((*it3).endsWith(res.extension))
00283                    createEntry(*it3, true);
00284            }
00285         }
00286      }
00287      if (g_changed || !g_allEntries)
00288      {
00289         uptodate = false;
00290         g_changeList->append(g_resource);
00291      }
00292   }
00293 
00294   bool result = !uptodate || (g_ctimeDict && !g_ctimeDict->isEmpty());
00295 
00296   if (result || bMenuTest)
00297   {
00298      g_resource = "apps";
00299      g_factory = g_bsf;
00300      g_entryDict = serviceEntryDict;
00301      g_changed = false;
00302 
00303      g_vfolder = new VFolderMenu;
00304      if (!m_trackId.isEmpty())
00305         g_vfolder->setTrackId(m_trackId);
00306 
00307      connect(g_vfolder, SIGNAL(newService(const QString &, KService::Ptr *)),
00308              this, SLOT(slotCreateEntry(const QString &, KService::Ptr *)));
00309 
00310      VFolderMenu::SubMenu *kdeMenu = g_vfolder->parseMenu("applications.menu", true);
00311 
00312      KServiceGroup::Ptr entry = g_bsgf->addNew("/", kdeMenu->directoryFile, KServiceGroup::Ptr(), false);
00313      entry->setLayoutInfo(kdeMenu->layoutList);
00314      createMenu(QString(), QString(), kdeMenu);
00315 
00316      (void) existingResourceDirs();
00317      *g_allResourceDirs += g_vfolder->allDirectories();
00318 
00319      disconnect(g_vfolder, SIGNAL(newService(const QString &, KService::Ptr *)),
00320                 this, SLOT(slotCreateEntry(const QString &, KService::Ptr *)));
00321 
00322      if (g_changed || !g_allEntries)
00323      {
00324         uptodate = false;
00325         g_changeList->append(g_resource);
00326      }
00327      if (bMenuTest) {
00328          result = false;
00329      }
00330   }
00331 
00332   qDeleteAll(entryDictList);
00333   return result;
00334 }
00335 
00336 void KBuildSycoca::createMenu(const QString &caption_, const QString &name_, VFolderMenu::SubMenu *menu)
00337 {
00338   QString caption = caption_;
00339   QString name = name_;
00340   foreach (VFolderMenu::SubMenu *subMenu, menu->subMenus)
00341   {
00342      QString subName = name+subMenu->name+'/';
00343 
00344      QString directoryFile = subMenu->directoryFile;
00345      if (directoryFile.isEmpty())
00346         directoryFile = subName+".directory";
00347      quint32 timeStamp = g_ctimeInfo->ctime(directoryFile);
00348      if (!timeStamp)
00349      {
00350         timeStamp = KGlobal::dirs()->calcResourceHash( g_resource, directoryFile,
00351                                                        KStandardDirs::Recursive );
00352      }
00353 
00354      KServiceGroup::Ptr entry;
00355      if (g_allEntries)
00356      {
00357         quint32 oldTimestamp = g_ctimeDict->value( directoryFile, 0 );
00358 
00359         if (timeStamp && (timeStamp == oldTimestamp))
00360         {
00361             KSycocaEntry::Ptr group = g_serviceGroupEntryDict->value(subName);
00362             if ( group )
00363             {
00364                 entry = KServiceGroup::Ptr::staticCast( group );
00365                 if (entry->directoryEntryPath() != directoryFile)
00366                     entry = 0; // Can't reuse this one!
00367             }
00368         }
00369      }
00370      g_ctimeInfo->addCTime(directoryFile, timeStamp);
00371 
00372      entry = g_bsgf->addNew(subName, subMenu->directoryFile, entry, subMenu->isDeleted);
00373      entry->setLayoutInfo(subMenu->layoutList);
00374      if (! (bMenuTest && entry->noDisplay()) )
00375         createMenu(caption + entry->caption() + '/', subName, subMenu);
00376   }
00377   if (caption.isEmpty())
00378      caption += '/';
00379   if (name.isEmpty())
00380      name += '/';
00381   foreach (const KService::Ptr &p, menu->items)
00382   {
00383      if (bMenuTest)
00384      {
00385         if (!menu->isDeleted && !p->noDisplay())
00386            printf("%s\t%s\t%s\n", qPrintable( caption ), qPrintable( p->menuId() ), qPrintable( KStandardDirs::locate("apps", p->entryPath() ) ) );
00387      }
00388      else
00389      {
00390         g_bsf->addEntry( KSycocaEntry::Ptr::staticCast( p ) );
00391         g_bsgf->addNewEntryTo( name, p );
00392      }
00393   }
00394 }
00395 
00396 bool KBuildSycoca::recreate()
00397 {
00398   QString path(sycocaPath());
00399 
00400   // KSaveFile first writes to a temp file.
00401   // Upon finalize() it moves the stuff to the right place.
00402   KSaveFile database(path);
00403   bool openedOK = database.open();
00404   if (!openedOK && database.error() == QFile::PermissionsError && QFile::exists(path))
00405   {
00406     QFile::remove( path );
00407     openedOK = database.open();
00408   }
00409   if (!openedOK)
00410   {
00411     fprintf(stderr, "kbuildsycoca4: ERROR creating database '%s'! %s\n",
00412       path.toLocal8Bit().data(), database.errorString().toLocal8Bit().data());
00413 #ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build
00414                         // GUI version of kbuildsycoca, so-called "kbuildsycocaw".
00415     if (!silent)
00416       KMessageBox::error(0, i18n("Error creating database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n", path.toLocal8Bit().data()), i18n("KBuildSycoca"));
00417 #endif
00418     return false;
00419   }
00420 
00421   m_str = new QDataStream ( &database );
00422   m_str->setVersion(QDataStream::Qt_3_1);
00423 
00424   kDebug(7021).nospace() << "Recreating ksycoca file (" << path << ", version " << KSycoca::version() << ")";
00425 
00426   // It is very important to build the servicetype one first
00427   // Both are registered in KSycoca, no need to keep the pointers
00428   KSycocaFactory *stf = new KBuildServiceTypeFactory;
00429   KBuildMimeTypeFactory *mtf = new KBuildMimeTypeFactory;
00430   g_bsgf = new KBuildServiceGroupFactory();
00431   g_bsf = new KBuildServiceFactory(stf, mtf, g_bsgf);
00432   (void) new KBuildProtocolInfoFactory();
00433 
00434   if( build()) // Parse dirs
00435   {
00436     save(); // Save database
00437     if (m_str->status() != QDataStream::Ok) // ######## TODO: does this detect write errors, e.g. disk full?
00438       database.abort(); // Error
00439     delete m_str;
00440     m_str = 0L;
00441     if (!database.finalize())
00442     {
00443       fprintf(stderr, "kbuildsycoca4: ERROR writing database '%s'!\n", database.fileName().toLocal8Bit().data());
00444       fprintf(stderr, "kbuildsycoca4: Disk full?\n");
00445 #ifdef KBUILDSYCOCA_GUI
00446       if (!silent)
00447         KMessageBox::error(0, i18n("Error writing database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n", path.toLocal8Bit().data()), i18n("KBuildSycoca"));
00448 #endif
00449       return false;
00450     }
00451   }
00452   else
00453   {
00454     delete m_str;
00455     m_str = 0L;
00456     database.abort();
00457     if (bMenuTest)
00458        return true;
00459     kDebug(7021) << "Database is up to date";
00460   }
00461 
00462   if (!bGlobalDatabase)
00463   {
00464     // update the timestamp file
00465     QString stamppath = path + "stamp";
00466     QFile ksycocastamp(stamppath);
00467     ksycocastamp.open( QIODevice::WriteOnly );
00468     QDataStream str( &ksycocastamp );
00469     str.setVersion(QDataStream::Qt_3_1);
00470     str << newTimestamp;
00471     str << existingResourceDirs();
00472     if (g_vfolder)
00473         str << g_vfolder->allDirectories(); // Extra resource dirs
00474   }
00475 #ifdef Q_OS_WIN
00476   KMemFile::fileContentsChanged(path);
00477 #endif
00478   return true;
00479 }
00480 
00481 void KBuildSycoca::save()
00482 {
00483    // Write header (#pass 1)
00484    m_str->device()->seek(0);
00485 
00486    (*m_str) << (qint32) KSycoca::version();
00487    KSycocaFactory * servicetypeFactory = 0;
00488    KBuildMimeTypeFactory * mimeTypeFactory = 0;
00489    KBuildServiceFactory * serviceFactory = 0;
00490    for(KSycocaFactoryList::Iterator factory = factories()->begin();
00491        factory != factories()->end();
00492        ++factory)
00493    {
00494       qint32 aId;
00495       qint32 aOffset;
00496       aId = (*factory)->factoryId();
00497       if ( aId == KST_KServiceTypeFactory )
00498          servicetypeFactory = *factory;
00499       else if ( aId == KST_KMimeTypeFactory )
00500          mimeTypeFactory = static_cast<KBuildMimeTypeFactory *>( *factory );
00501       else if ( aId == KST_KServiceFactory )
00502          serviceFactory = static_cast<KBuildServiceFactory *>( *factory );
00503       aOffset = (*factory)->offset();
00504       (*m_str) << aId;
00505       (*m_str) << aOffset;
00506    }
00507    (*m_str) << (qint32) 0; // No more factories.
00508    // Write KDEDIRS
00509    (*m_str) << KGlobal::dirs()->kfsstnd_prefixes();
00510    (*m_str) << newTimestamp;
00511    (*m_str) << KGlobal::locale()->language();
00512    (*m_str) << KGlobal::dirs()->calcResourceHash("services", "update_ksycoca",
00513                                                  KStandardDirs::Recursive );
00514    (*m_str) << (*g_allResourceDirs);
00515 
00516    // Calculate per-servicetype/mimetype data
00517    mimeTypeFactory->parseSubclasses();
00518    serviceFactory->populateServiceTypes();
00519 
00520    // Write factory data....
00521    for(KSycocaFactoryList::Iterator factory = factories()->begin();
00522        factory != factories()->end();
00523        ++factory)
00524    {
00525       (*factory)->save(*m_str);
00526       if (m_str->status() != QDataStream::Ok) // ######## TODO: does this detect write errors, e.g. disk full?
00527          return; // error
00528    }
00529 
00530    int endOfData = m_str->device()->pos();
00531 
00532    // Write header (#pass 2)
00533    m_str->device()->seek(0);
00534 
00535    (*m_str) << (qint32) KSycoca::version();
00536    for(KSycocaFactoryList::Iterator factory = factories()->begin();
00537        factory != factories()->end(); ++factory)
00538    {
00539       qint32 aId;
00540       qint32 aOffset;
00541       aId = (*factory)->factoryId();
00542       aOffset = (*factory)->offset();
00543       (*m_str) << aId;
00544       (*m_str) << aOffset;
00545    }
00546    (*m_str) << (qint32) 0; // No more factories.
00547 
00548    // Jump to end of database
00549    m_str->device()->seek(endOfData);
00550 }
00551 
00552 bool KBuildSycoca::checkDirTimestamps( const QString& dirname, const QDateTime& stamp, bool top )
00553 {
00554    if( top )
00555    {
00556       QFileInfo inf( dirname );
00557       if( inf.lastModified() > stamp ) {
00558          kDebug( 7021 ) << "timestamp changed:" << dirname;
00559          return false;
00560       }
00561    }
00562    QDir dir( dirname );
00563    const QFileInfoList list = dir.entryInfoList( QDir::NoFilter, QDir::Unsorted );
00564    if (list.isEmpty())
00565       return true;
00566 
00567    foreach ( const QFileInfo& fi, list ) {
00568       if( fi.fileName() == "." || fi.fileName() == ".." )
00569          continue;
00570       if( fi.lastModified() > stamp )
00571       {
00572          kDebug( 7201 ) << "timestamp changed:" << fi.filePath();
00573          return false;
00574       }
00575       if( fi.isDir() && !checkDirTimestamps( fi.filePath(), stamp, false ))
00576             return false;
00577    }
00578    return true;
00579 }
00580 
00581 // check times of last modification of all files on which ksycoca depens,
00582 // and also their directories
00583 // if all of them are older than the timestamp in file ksycocastamp, this
00584 // means that there's no need to rebuild ksycoca
00585 bool KBuildSycoca::checkTimestamps( quint32 timestamp, const QStringList &dirs )
00586 {
00587    kDebug( 7021 ) << "checking file timestamps";
00588    QDateTime stamp;
00589    stamp.setTime_t( timestamp );
00590    for( QStringList::ConstIterator it = dirs.begin();
00591         it != dirs.end();
00592         ++it )
00593    {
00594       if( !checkDirTimestamps( *it, stamp, true ))
00595             return false;
00596    }
00597    kDebug( 7021 ) << "timestamps check ok";
00598    return true;
00599 }
00600 
00601 QStringList KBuildSycoca::existingResourceDirs()
00602 {
00603    static QStringList* dirs = NULL;
00604    if( dirs != NULL )
00605        return *dirs;
00606    dirs = new QStringList;
00607    g_allResourceDirs = new QStringList;
00608    // these are all resources cached by ksycoca
00609    QStringList resources;
00610    resources += KBuildServiceTypeFactory::resourceTypes();
00611    resources += KBuildMimeTypeFactory::resourceTypes();
00612    resources += KBuildServiceGroupFactory::resourceTypes();
00613    resources += KBuildServiceFactory::resourceTypes();
00614    resources += KBuildProtocolInfoFactory::resourceTypes();
00615    while( !resources.empty())
00616    {
00617       QString res = resources.front();
00618       *dirs += KGlobal::dirs()->resourceDirs( res.toLatin1());
00619       resources.removeAll( res );
00620    }
00621 
00622    *g_allResourceDirs = *dirs;
00623 
00624    for( QStringList::Iterator it = dirs->begin();
00625         it != dirs->end(); )
00626    {
00627       QFileInfo inf( *it );
00628       if( !inf.exists() || !inf.isReadable() )
00629          it = dirs->erase( it );
00630       else
00631          ++it;
00632    }
00633    return *dirs;
00634 }
00635 
00636 static const char appFullName[] = "org.kde.kbuildsycoca";
00637 static const char appName[] = "kbuildsycoca4";
00638 static const char appVersion[] = "1.1";
00639 
00640 extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
00641 {
00642    KAboutData d(appName, "kdelibs4", ki18n("KBuildSycoca"), appVersion,
00643                 ki18n("Rebuilds the system configuration cache."),
00644                 KAboutData::License_GPL, ki18n("(c) 1999-2002 KDE Developers"));
00645    d.addAuthor(ki18n("David Faure"), ki18n("Author"), "faure@kde.org");
00646    d.addAuthor(ki18n("Waldo Bastian"), ki18n("Author"), "bastian@kde.org");
00647 
00648    KCmdLineOptions options;
00649    options.add("nosignal", ki18n("Do not signal applications to update"));
00650    options.add("noincremental", ki18n("Disable incremental update, re-read everything"));
00651    options.add("checkstamps", ki18n("Check file timestamps"));
00652    options.add("nocheckfiles", ki18n("Disable checking files (dangerous)"));
00653    options.add("global", ki18n("Create global database"));
00654    options.add("menutest", ki18n("Perform menu generation test run only"));
00655    options.add("track <menu-id>", ki18n("Track menu id for debug purposes"));
00656 #ifdef KBUILDSYCOCA_GUI
00657    options.add("silent", ki18n("Silent - work without windows and stderr"));
00658    options.add("showprogress", ki18n("Show progress information (even if 'silent' mode is on)"));
00659 #endif
00660 
00661    KCmdLineArgs::init(argc, argv, &d);
00662    KCmdLineArgs::addCmdLineOptions(options);
00663    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
00664    bGlobalDatabase = args->isSet("global");
00665    bMenuTest = args->isSet("menutest");
00666 
00667    if (bGlobalDatabase)
00668    {
00669      setenv("KDEHOME", "-", 1);
00670      setenv("KDEROOTHOME", "-", 1);
00671    }
00672 
00673 #ifdef KBUILDSYCOCA_GUI
00674    KApplication k;
00675 #else
00676    KApplication k(false);
00677 #endif
00678    k.disableSessionManagement();
00679 
00680 #ifdef KBUILDSYCOCA_GUI
00681    silent = args->isSet("silent");
00682    showprogress = args->isSet("showprogress");
00683    QLabel progress( QString("<p><br><nobr>    %1    </nobr><br>").arg( i18n("Reloading KDE configuration, please wait...") ), 0, "", Qt::WType_Dialog | Qt::WStyle_DialogBorder  | Qt::WStyle_Customize| Qt::WStyle_Title );
00684    QString capt = i18n("KDE Configuration Manager");
00685    if (!silent) {
00686      if (KMessageBox::No == KMessageBox::questionYesNo(0, i18n("Do you want to reload KDE configuration?"), capt, i18nc("Reload KDE configuration messagebox", "Reload"), i18n("Do Not Reload")))
00687        return 0;
00688    }
00689    if (!silent || showprogress) {
00690      progress.setCaption( capt );
00691      progress.show();
00692    }
00693 #endif
00694 
00695    KCrash::setCrashHandler(KCrash::defaultCrashHandler);
00696    KCrash::setEmergencySaveFunction(crashHandler);
00697    KCrash::setApplicationName(QString(appName));
00698 
00699    // force generating of KLocale object. if not, the database will get
00700    // be translated
00701    KGlobal::locale();
00702    KGlobal::dirs()->addResourceType("app-reg", 0, "share/application-registry" );
00703 
00704    while(QDBusConnection::sessionBus().isConnected())
00705    {
00706      // kapp registered already, but with the PID in the name.
00707      // We need to re-register without it, to detect already-running kbuildsycoca instances.
00708      if (QDBusConnection::sessionBus().interface()->registerService(appFullName, QDBusConnectionInterface::QueueService)
00709          != QDBusConnectionInterface::ServiceQueued)
00710      {
00711        break; // Go
00712      }
00713      fprintf(stderr, "Waiting for already running %s to finish.\n", appName);
00714 
00715      QEventLoop eventLoop;
00716      QObject::connect(QDBusConnection::sessionBus().interface(), SIGNAL(serviceRegistered(QString)),
00717                       &eventLoop, SLOT(quit()));
00718      eventLoop.exec( QEventLoop::ExcludeUserInputEvents );
00719    }
00720    fprintf(stderr, "%s running...\n", appName);
00721 
00722    bool checkfiles = bGlobalDatabase || args->isSet("checkfiles");
00723 
00724    bool incremental = !bGlobalDatabase && args->isSet("incremental") && checkfiles;
00725    if (incremental || !checkfiles)
00726    {
00727      KSycoca::self()->disableAutoRebuild(); // Prevent deadlock
00728      QString current_language = KGlobal::locale()->language();
00729      QString ksycoca_language = KSycoca::self()->language();
00730      quint32 current_update_sig = KGlobal::dirs()->calcResourceHash("services", "update_ksycoca",
00731                                                                     KStandardDirs::Recursive );
00732      quint32 ksycoca_update_sig = KSycoca::self()->updateSignature();
00733      QString current_prefixes = KGlobal::dirs()->kfsstnd_prefixes();
00734      QString ksycoca_prefixes = KSycoca::self()->kfsstnd_prefixes();
00735 
00736      if ((current_update_sig != ksycoca_update_sig) ||
00737          (current_language != ksycoca_language) ||
00738          (current_prefixes != ksycoca_prefixes) ||
00739          (KSycoca::self()->timeStamp() == 0))
00740      {
00741         incremental = false;
00742         checkfiles = true;
00743         delete KSycoca::self();
00744      }
00745    }
00746 
00747    g_changeList = new QStringList;
00748 
00749    bool checkstamps = incremental && args->isSet("checkstamps") && checkfiles;
00750    quint32 filestamp = 0;
00751    QStringList oldresourcedirs;
00752    if( checkstamps && incremental )
00753    {
00754        QString path = sycocaPath()+"stamp";
00755        QByteArray qPath = QFile::encodeName(path);
00756        cSycocaPath = qPath.data(); // Delete timestamps on crash
00757        QFile ksycocastamp(path);
00758        if( ksycocastamp.open( QIODevice::ReadOnly ))
00759        {
00760            QDataStream str( &ksycocastamp );
00761            str.setVersion(QDataStream::Qt_3_1);
00762 
00763            if (!str.atEnd())
00764                str >> filestamp;
00765            if (!str.atEnd())
00766            {
00767                str >> oldresourcedirs;
00768                if( oldresourcedirs != KBuildSycoca::existingResourceDirs())
00769                    checkstamps = false;
00770            }
00771            else
00772            {
00773                checkstamps = false;
00774            }
00775            if (!str.atEnd())
00776            {
00777                QStringList extraResourceDirs;
00778                str >> extraResourceDirs;
00779                oldresourcedirs += extraResourceDirs;
00780            }
00781        }
00