kbuildsycoca.cpp

00001 /*  This file is part of the KDE libraries
00002  *  Copyright (C) 1999 David Faure <faure@kde.org>
00003  *  Copyright (C) 2002-2003 Waldo Bastian <bastian@kde.org>
00004  *
00005  *  This library is free software; you can redistribute it and/or
00006  *  modify it under the terms of the GNU Library General Public
00007  *  License version 2 as published by the Free Software Foundation;
00008  *
00009  *  This library is distributed in the hope that it will be useful,
00010  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  *  Library General Public License for more details.
00013  *
00014  *  You should have received a copy of the GNU Library General Public License
00015  *  along with this library; see the file COPYING.LIB.  If not, write to
00016  *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00017  *  Boston, MA 02110-1301, USA.
00018  **/
00019 
00020 #include <qdir.h>
00021 #include <qeventloop.h>
00022 #include <config.h>
00023 
00024 #include "kbuildsycoca.h"
00025 #include "kresourcelist.h"
00026 #include "vfolder_menu.h"
00027 
00028 #include <kservice.h>
00029 #include <kmimetype.h>
00030 #include <kbuildservicetypefactory.h>
00031 #include <kbuildservicefactory.h>
00032 #include <kbuildservicegroupfactory.h>
00033 #include <kbuildimageiofactory.h>
00034 #include <kbuildprotocolinfofactory.h>
00035 #include <kctimefactory.h>
00036 #include <kdatastream.h>
00037 
00038 #include <qdatastream.h>
00039 #include <qfile.h>
00040 #include <qtimer.h>
00041 
00042 #include <assert.h>
00043 #include <kapplication.h>
00044 #include <dcopclient.h>
00045 #include <kglobal.h>
00046 #include <kdebug.h>
00047 #include <kdirwatch.h>
00048 #include <kstandarddirs.h>
00049 #include <ksavefile.h>
00050 #include <klocale.h>
00051 #include <kaboutdata.h>
00052 #include <kcmdlineargs.h>
00053 #include <kcrash.h>
00054 
00055 #ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build 
00056                         // GUI version of kbuildsycoca, so-called "kbuildsycocaw".
00057 # include <qlabel.h>
00058 # include <kmessagebox.h>
00059   bool silent;
00060   bool showprogress;
00061 #endif
00062 
00063 #include <stdlib.h>
00064 #include <unistd.h>
00065 #include <time.h>
00066 #include <memory> // auto_ptr
00067 
00068 typedef QDict<KSycocaEntry> KBSEntryDict;
00069 typedef QValueList<KSycocaEntry::List> KSycocaEntryListList;
00070 
00071 static Q_UINT32 newTimestamp = 0;
00072 
00073 static KBuildServiceFactory *g_bsf = 0;
00074 static KBuildServiceGroupFactory *g_bsgf = 0;
00075 static KSycocaFactory *g_factory = 0;
00076 static KCTimeInfo *g_ctimeInfo = 0;
00077 static QDict<Q_UINT32> *g_ctimeDict = 0;
00078 static const char *g_resource = 0;
00079 static KBSEntryDict *g_entryDict = 0;
00080 static KBSEntryDict *g_serviceGroupEntryDict = 0;
00081 static KSycocaEntryListList *g_allEntries = 0;
00082 static QStringList *g_changeList = 0;
00083 static QStringList *g_allResourceDirs = 0;
00084 static bool g_changed = false;
00085 static KSycocaEntry::List g_tempStorage;
00086 static VFolderMenu *g_vfolder = 0;
00087 
00088 static const char *cSycocaPath = 0;
00089 
00090 static bool bGlobalDatabase = false;
00091 static bool bMenuTest = false;
00092 
00093 void crashHandler(int)
00094 {
00095    // If we crash while reading sycoca, we delete the database
00096    // in an attempt to recover.
00097    if (cSycocaPath)
00098       unlink(cSycocaPath);
00099 }
00100 
00101 static QString sycocaPath()
00102 {
00103   QString path;
00104 
00105   if (bGlobalDatabase)
00106   {
00107      path = KGlobal::dirs()->saveLocation("services")+"ksycoca";
00108   }
00109   else
00110   {
00111      QCString ksycoca_env = getenv("KDESYCOCA");
00112      if (ksycoca_env.isEmpty())
00113         path = KGlobal::dirs()->saveLocation("cache")+"ksycoca";
00114      else
00115         path = QFile::decodeName(ksycoca_env);
00116   }
00117 
00118   return path;
00119 }
00120 
00121 static QString oldSycocaPath()
00122 {
00123   QCString ksycoca_env = getenv("KDESYCOCA");
00124   if (ksycoca_env.isEmpty())
00125      return KGlobal::dirs()->saveLocation("tmp")+"ksycoca";
00126 
00127   return QString::null;
00128 }
00129 
00130 KBuildSycoca::KBuildSycoca()
00131   : KSycoca( true )
00132 {
00133 }
00134 
00135 KBuildSycoca::~KBuildSycoca()
00136 {
00137 
00138 }
00139 
00140 void KBuildSycoca::processGnomeVfs()
00141 {
00142    QString file = locate("app-reg", "gnome-vfs.applications");
00143    if (file.isEmpty())
00144    {
00145 //      kdDebug(7021) << "gnome-vfs.applications not found." << endl;
00146       return;
00147    }
00148 
00149    QString app;
00150 
00151    char line[1024*64];
00152 
00153    FILE *f = fopen(QFile::encodeName(file), "r");
00154    while (!feof(f))
00155    {
00156       if (!fgets(line, sizeof(line)-1, f))
00157       {
00158         break;
00159       }
00160 
00161       if (line[0] != '\t')
00162       {
00163           app = QString::fromLatin1(line);
00164           app.truncate(app.length()-1);
00165       }
00166       else if (strncmp(line+1, "mime_types=", 11) == 0)
00167       {
00168           QString mimetypes = QString::fromLatin1(line+12);
00169           mimetypes.truncate(mimetypes.length()-1);
00170           mimetypes.replace(QRegExp("\\*"), "all");
00171           KService *s = g_bsf->findServiceByName(app);
00172           if (!s)
00173              continue;
00174 
00175           QStringList &serviceTypes = s->accessServiceTypes();
00176           if (serviceTypes.count() <= 1)
00177           {
00178              serviceTypes += QStringList::split(',', mimetypes);
00179 //             kdDebug(7021) << "Adding gnome mimetypes for '" << app << "'.\n";
00180 //             kdDebug(7021) << "ServiceTypes=" << s->serviceTypes().join(":") << endl;
00181           }
00182       }
00183    }
00184    fclose( f );
00185 }
00186 
00187 KSycocaEntry *KBuildSycoca::createEntry(const QString &file, bool addToFactory)
00188 {
00189    Q_UINT32 timeStamp = g_ctimeInfo->ctime(file);
00190    if (!timeStamp)
00191    {
00192       timeStamp = KGlobal::dirs()->calcResourceHash( g_resource, file, true);
00193    }
00194    KSycocaEntry* entry = 0;
00195    if (g_allEntries)
00196    {
00197       assert(g_ctimeDict);
00198       Q_UINT32 *timeP = (*g_ctimeDict)[file];
00199       Q_UINT32 oldTimestamp = timeP ? *timeP : 0;
00200 
00201       if (timeStamp && (timeStamp == oldTimestamp))
00202       {
00203          // Re-use old entry
00204          if (g_factory == g_bsgf) // Strip .directory from service-group entries
00205          {
00206             entry = g_entryDict->find(file.left(file.length()-10));
00207          }
00208          else if (g_factory == g_bsf)
00209          {
00210             entry = g_entryDict->find(file);
00211          }
00212          else
00213          {
00214             entry = g_entryDict->find(file);
00215          }
00216          // remove from g_ctimeDict; if g_ctimeDict is not empty
00217          // after all files have been processed, it means
00218          // some files were removed since last time
00219          g_ctimeDict->remove( file );
00220       }
00221       else if (oldTimestamp)
00222       {
00223          g_changed = true;
00224          kdDebug(7021) << "modified: " << file << endl;
00225       }
00226       else
00227       {
00228          g_changed = true;
00229          kdDebug(7021) << "new: " << file << endl;
00230       }
00231    }
00232    g_ctimeInfo->addCTime(file, timeStamp );
00233    if (!entry)
00234    {
00235       // Create a new entry
00236       entry = g_factory->createEntry( file, g_resource );
00237    }
00238    if ( entry && entry->isValid() )
00239    {
00240       if (addToFactory)
00241          g_factory->addEntry( entry, g_resource );
00242       else
00243          g_tempStorage.append(entry);
00244       return entry;
00245    }
00246    return 0;
00247 }
00248 
00249 void KBuildSycoca::slotCreateEntry(const QString &file, KService **service)
00250 {
00251    KSycocaEntry *entry = createEntry(file, false);
00252    *service = dynamic_cast<KService *>(entry);
00253 }
00254 
00255 // returns false if the database is up to date
00256 bool KBuildSycoca::build()
00257 {
00258   typedef QPtrList<KBSEntryDict> KBSEntryDictList;
00259   KBSEntryDictList *entryDictList = 0;
00260   KBSEntryDict *serviceEntryDict = 0;
00261 
00262   entryDictList = new KBSEntryDictList();
00263   // Convert for each factory the entryList to a Dict.
00264   int i = 0;
00265   // For each factory
00266   for (KSycocaFactory *factory = m_lstFactories->first();
00267        factory;
00268        factory = m_lstFactories->next() )
00269   {
00270      KBSEntryDict *entryDict = new KBSEntryDict();
00271      if (g_allEntries)
00272      {
00273          KSycocaEntry::List list = (*g_allEntries)[i++];
00274          for( KSycocaEntry::List::Iterator it = list.begin();
00275             it != list.end();
00276             ++it)
00277          {
00278             entryDict->insert( (*it)->entryPath(), static_cast<KSycocaEntry *>(*it));
00279          }
00280      }
00281      if (factory == g_bsf)
00282         serviceEntryDict = entryDict;
00283      else if (factory == g_bsgf)
00284         g_serviceGroupEntryDict = entryDict;
00285      entryDictList->append(entryDict);
00286   }
00287 
00288   QStringList allResources;
00289   // For each factory
00290   for (KSycocaFactory *factory = m_lstFactories->first();
00291        factory;
00292        factory = m_lstFactories->next() )
00293   {
00294     // For each resource the factory deals with
00295     const KSycocaResourceList *list = factory->resourceList();
00296     if (!list) continue;
00297 
00298     for( KSycocaResourceList::ConstIterator it1 = list->begin();
00299          it1 != list->end();
00300          ++it1 )
00301     {
00302       KSycocaResource res = (*it1);
00303       if (!allResources.contains(res.resource))
00304          allResources.append(res.resource);
00305     }
00306   }
00307 
00308   g_ctimeInfo = new KCTimeInfo(); // This is a build factory too, don't delete!!
00309   bool uptodate = true;
00310   // For all resources
00311   for( QStringList::ConstIterator it1 = allResources.begin();
00312        it1 != allResources.end();
00313        ++it1 )
00314   {
00315      g_changed = false;
00316      g_resource = (*it1).ascii();
00317 
00318      QStringList relFiles;
00319 
00320      (void) KGlobal::dirs()->findAllResources( g_resource,
00321                                                QString::null,
00322                                                true, // Recursive!
00323                                                true, // uniq
00324                                                relFiles);
00325 
00326 
00327      // Now find all factories that use this resource....
00328      // For each factory
00329      g_entryDict = entryDictList->first();
00330      for (g_factory = m_lstFactories->first();
00331           g_factory;
00332           g_factory = m_lstFactories->next(),
00333           g_entryDict = entryDictList->next() )
00334      {
00335         // For each resource the factory deals with
00336         const KSycocaResourceList *list = g_factory->resourceList();
00337         if (!list) continue;
00338 
00339         for( KSycocaResourceList::ConstIterator it2 = list->begin();
00340              it2 != list->end();
00341              ++it2 )
00342         {
00343            KSycocaResource res = (*it2);
00344            if (res.resource != (*it1)) continue;
00345 
00346            // For each file in the resource
00347            for( QStringList::ConstIterator it3 = relFiles.begin();
00348                 it3 != relFiles.end();
00349                 ++it3 )
00350            {
00351                // Check if file matches filter
00352                if ((*it3).endsWith(res.extension))
00353                    createEntry(*it3, true);
00354            }
00355         }
00356         if ((g_factory == g_bsf) && (strcmp(g_resource, "services") == 0))
00357            processGnomeVfs();
00358      }
00359      if (g_changed || !g_allEntries)
00360      {
00361         uptodate = false;
00362         g_changeList->append(g_resource);
00363      }
00364   }
00365 
00366   bool result = !uptodate || !g_ctimeDict->isEmpty();
00367 
00368   if (result || bMenuTest)
00369   {
00370      g_resource = "apps";
00371      g_factory = g_bsf;
00372      g_entryDict = serviceEntryDict;
00373      g_changed = false;
00374 
00375      g_vfolder = new VFolderMenu;
00376      if (!m_trackId.isEmpty())
00377         g_vfolder->setTrackId(m_trackId);
00378 
00379      connect(g_vfolder, SIGNAL(newService(const QString &, KService **)),
00380              this, SLOT(slotCreateEntry(const QString &, KService **)));
00381              
00382      VFolderMenu::SubMenu *kdeMenu;
00383      if ( QFile::exists( "/etc/xdg/menus/kde-applications.menu" ) )
00384         kdeMenu = g_vfolder->parseMenu("kde-applications.menu", true);
00385      else
00386         kdeMenu = g_vfolder->parseMenu("applications.menu", true);
00387 
00388      KServiceGroup *entry = g_bsgf->addNew("/", kdeMenu->directoryFile, 0, false);
00389      entry->setLayoutInfo(kdeMenu->layoutList);
00390      createMenu(QString::null, QString::null, kdeMenu);
00391 
00392      KServiceGroup::Ptr g(entry);
00393 
00394      (void) existingResourceDirs();
00395      *g_allResourceDirs += g_vfolder->allDirectories();
00396 
00397      disconnect(g_vfolder, SIGNAL(newService(const QString &, KService **)),
00398              this, SLOT(slotCreateEntry(const QString &, KService **)));
00399 
00400      if (g_changed || !g_allEntries)
00401      {
00402         uptodate = false;
00403         g_changeList->append(g_resource);
00404      }
00405      if (bMenuTest)
00406         return false;
00407   }
00408 
00409   return result;
00410 }
00411 
00412 void KBuildSycoca::createMenu(QString caption, QString name, VFolderMenu::SubMenu *menu)
00413 {
00414   for(VFolderMenu::SubMenu *subMenu = menu->subMenus.first(); subMenu; subMenu = menu->subMenus.next())
00415   {
00416      QString subName = name+subMenu->name+"/";
00417 
00418      QString directoryFile = subMenu->directoryFile;
00419      if (directoryFile.isEmpty())
00420         directoryFile = subName+".directory";
00421      Q_UINT32 timeStamp = g_ctimeInfo->ctime(directoryFile);
00422      if (!timeStamp)
00423      {
00424         timeStamp = KGlobal::dirs()->calcResourceHash( g_resource, directoryFile, true);
00425      }
00426 
00427      KServiceGroup* entry = 0;
00428      if (g_allEntries)
00429      {
00430         Q_UINT32 *timeP = (*g_ctimeDict)[directoryFile];
00431         Q_UINT32 oldTimestamp = timeP ? *timeP : 0;
00432 
00433         if (timeStamp && (timeStamp == oldTimestamp))
00434         {
00435             entry = dynamic_cast<KServiceGroup *> (g_serviceGroupEntryDict->find(subName));
00436             if (entry && (entry->directoryEntryPath() != directoryFile))
00437                 entry = 0; // Can't reuse this one!
00438         }
00439      }
00440      g_ctimeInfo->addCTime(directoryFile, timeStamp);
00441 
00442      entry = g_bsgf->addNew(subName, subMenu->directoryFile, entry, subMenu->isDeleted);
00443      entry->setLayoutInfo(subMenu->layoutList);
00444      if (! (bMenuTest && entry->noDisplay()) )
00445         createMenu(caption + entry->caption() + "/", subName, subMenu);
00446   }
00447   if (caption.isEmpty())
00448      caption += "/";
00449   if (name.isEmpty())
00450      name += "/";
00451   for(QDictIterator<KService> it(menu->items); it.current(); ++it)
00452   {
00453      if (bMenuTest)
00454      {
00455         if (!menu->isDeleted && !it.current()->noDisplay())
00456           printf("%s\t%s\t%s\n", caption.local8Bit().data(), it.current()->menuId().local8Bit().data(), locate("apps", it.current()->desktopEntryPath()).local8Bit().data());
00457      }
00458      else
00459      {
00460         g_bsf->addEntry( it.current(), g_resource );
00461         g_bsgf->addNewEntryTo(name, it.current());
00462      }
00463   }
00464 }
00465 
00466 bool KBuildSycoca::recreate()
00467 {
00468   QString path(sycocaPath());
00469 #ifdef Q_WS_WIN
00470   printf("kbuildsycoca: path='%s'\n", (const char*)path);
00471 #endif
00472 
00473   // KSaveFile first writes to a temp file.
00474   // Upon close() it moves the stuff to the right place.
00475   std::auto_ptr<KSaveFile> database( new KSaveFile(path) );
00476   if (database->status() == EACCES && QFile::exists(path))
00477   {
00478     QFile::remove( path );
00479     database.reset( new KSaveFile(path) ); // try again
00480   }
00481   if (database->status() != 0)
00482   {
00483     fprintf(stderr, "kbuildsycoca: ERROR creating database '%s'! %s\n", path.local8Bit().data(),strerror(database->status()));
00484 #ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build 
00485                         // GUI version of kbuildsycoca, so-called "kbuildsycocaw".
00486     if (!silent)
00487       KMessageBox::error(0, i18n("Error creating database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n").arg(path.local8Bit().data()), i18n("KBuildSycoca"));
00488 #endif
00489     return false;
00490   }
00491 
00492   m_str = database->dataStream();
00493 
00494   kdDebug(7021) << "Recreating ksycoca file (" << path << ", version " << KSycoca::version() << ")" << endl;
00495 
00496   // It is very important to build the servicetype one first
00497   // Both are registered in KSycoca, no need to keep the pointers
00498   KSycocaFactory *stf = new KBuildServiceTypeFactory;
00499   g_bsgf = new KBuildServiceGroupFactory();
00500   g_bsf = new KBuildServiceFactory(stf, g_bsgf);
00501   (void) new KBuildImageIOFactory();
00502   (void) new KBuildProtocolInfoFactory();
00503 
00504   if( build()) // Parse dirs
00505   {
00506     save(); // Save database
00507     if (m_str->device()->status())
00508       database->abort(); // Error
00509     m_str = 0L;
00510     if (!database->close())
00511     {
00512       fprintf(stderr, "kbuildsycoca: ERROR writing database '%s'!\n", database->name().local8Bit().data());
00513       fprintf(stderr, "kbuildsycoca: Disk full?\n");
00514 #ifdef KBUILDSYCOCA_GUI
00515       if (!silent)
00516         KMessageBox::error(0, i18n("Error writing database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n").arg(path.local8Bit().data()), i18n("KBuildSycoca"));
00517 #endif
00518       return false;
00519     }
00520   }
00521   else
00522   {
00523     m_str = 0L;
00524     database->abort();
00525     if (bMenuTest)
00526        return true;
00527     kdDebug(7021) << "Database is up to date" << endl;
00528   }
00529 
00530   if (!bGlobalDatabase)
00531   {
00532     // update the timestamp file
00533     QString stamppath = path + "stamp";
00534     QFile ksycocastamp(stamppath);
00535     ksycocastamp.open( IO_WriteOnly );
00536     QDataStream str( &ksycocastamp );
00537     str << newTimestamp;
00538     str << existingResourceDirs();
00539     if (g_vfolder)
00540         str << g_vfolder->allDirectories(); // Extra resource dirs
00541   }
00542   return true;
00543 }
00544 
00545 void KBuildSycoca::save()
00546 {
00547    // Write header (#pass 1)
00548    m_str->device()->at(0);
00549 
00550    (*m_str) << (Q_INT32) KSycoca::version();
00551    KSycocaFactory * servicetypeFactory = 0L;
00552    KSycocaFactory * serviceFactory = 0L;
00553    for(KSycocaFactory *factory = m_lstFactories->first();
00554        factory;
00555        factory = m_lstFactories->next())
00556    {
00557       Q_INT32 aId;
00558       Q_INT32 aOffset;
00559       aId = factory->factoryId();
00560       if ( aId == KST_KServiceTypeFactory )
00561          servicetypeFactory = factory;
00562       else if ( aId == KST_KServiceFactory )
00563          serviceFactory = factory;
00564       aOffset = factory->offset();
00565       (*m_str) << aId;
00566       (*m_str) << aOffset;
00567    }
00568    (*m_str) << (Q_INT32) 0; // No more factories.
00569    // Write KDEDIRS
00570    (*m_str) << KGlobal::dirs()->kfsstnd_prefixes();
00571    (*m_str) << newTimestamp;
00572    (*m_str) << KGlobal::locale()->language();
00573    (*m_str) << KGlobal::dirs()->calcResourceHash("services", "update_ksycoca", true);
00574    (*m_str) << (*g_allResourceDirs);
00575 
00576    // Write factory data....
00577    for(KSycocaFactory *factory = m_lstFactories->first();
00578        factory;
00579        factory = m_lstFactories->next())
00580    {
00581       factory->save(*m_str);
00582       if (m_str->device()->status())
00583          return; // error
00584    }
00585 
00586    int endOfData = m_str->device()->at();
00587 
00588    // Write header (#pass 2)
00589    m_str->device()->at(0);
00590 
00591    (*m_str) << (Q_INT32) KSycoca::version();
00592    for(KSycocaFactory *factory = m_lstFactories->first();
00593        factory;
00594        factory = m_lstFactories->next())
00595    {
00596       Q_INT32 aId;
00597       Q_INT32 aOffset;
00598       aId = factory->factoryId();
00599       aOffset = factory->offset();
00600       (*m_str) << aId;
00601       (*m_str) << aOffset;
00602    }
00603    (*m_str) << (Q_INT32) 0; // No more factories.
00604 
00605    // Jump to end of database
00606    m_str->device()->at(endOfData);
00607 }
00608 
00609 bool KBuildSycoca::checkDirTimestamps( const QString& dirname, const QDateTime& stamp, bool top )
00610 {
00611    if( top )
00612    {
00613       QFileInfo inf( dirname );
00614       if( inf.lastModified() > stamp )
00615          {
00616          kdDebug( 7021 ) << "timestamp changed:" << dirname << endl;
00617          return false;
00618          }
00619    }
00620    QDir dir( dirname );
00621    const QFileInfoList *list = dir.entryInfoList( QDir::DefaultFilter, QDir::Unsorted );
00622    if (!list)
00623       return true;
00624 
00625    for( QFileInfoListIterator it( *list );
00626         it.current() != NULL;
00627         ++it )
00628    {
00629       QFileInfo* fi = it.current();
00630       if( fi->fileName() == "." || fi->fileName() == ".." )
00631          continue;
00632       if( fi->lastModified() > stamp )
00633       {
00634          kdDebug( 7201 ) << "timestamp changed:" << fi->filePath() << endl;
00635          return false;
00636       }
00637       if( fi->isDir() && !checkDirTimestamps( fi->filePath(), stamp, false ))
00638             return false;
00639    }
00640    return true;
00641 }
00642 
00643 // check times of last modification of all files on which ksycoca depens,
00644 // and also their directories
00645 // if all of them all older than the timestamp in file ksycocastamp, this
00646 // means that there's no need to rebuild ksycoca
00647 bool KBuildSycoca::checkTimestamps( Q_UINT32 timestamp, const QStringList &dirs )
00648 {
00649    kdDebug( 7021 ) << "checking file timestamps" << endl;
00650    QDateTime stamp;
00651    stamp.setTime_t( timestamp );
00652    for( QStringList::ConstIterator it = dirs.begin();
00653         it != dirs.end();
00654         ++it )
00655    {
00656       if( !checkDirTimestamps( *it, stamp, true ))
00657             return false;
00658    }
00659    kdDebug( 7021 ) << "timestamps check ok" << endl;
00660    return true;
00661 }
00662 
00663 QStringList KBuildSycoca::existingResourceDirs()
00664 {
00665    static QStringList* dirs = NULL;
00666    if( dirs != NULL )
00667        return *dirs;
00668    dirs = new QStringList;
00669    g_allResourceDirs = new QStringList;
00670    // these are all resources cached by ksycoca
00671    QStringList resources;
00672    resources += KBuildServiceTypeFactory::resourceTypes();
00673    resources += KBuildServiceGroupFactory::resourceTypes();
00674    resources += KBuildServiceFactory::resourceTypes();
00675    resources += KBuildImageIOFactory::resourceTypes();
00676    resources += KBuildProtocolInfoFactory::resourceTypes();
00677    while( !resources.empty())
00678    {
00679       QString res = resources.front();
00680       *dirs += KGlobal::dirs()->resourceDirs( res.latin1());
00681       resources.remove( res ); // remove this 'res' and all its duplicates
00682    }
00683 
00684    *g_allResourceDirs = *dirs;
00685 
00686    for( QStringList::Iterator it = dirs->begin();
00687         it != dirs->end(); )
00688    {
00689       QFileInfo inf( *it );
00690       if( !inf.exists() || !inf.isReadable() )
00691          it = dirs->remove( it );
00692       else
00693          ++it;
00694    }
00695    return *dirs;
00696 }
00697 
00698 static KCmdLineOptions options[] = {
00699    { "nosignal", I18N_NOOP("Do not signal applications to update"), 0 },
00700    { "noincremental", I18N_NOOP("Disable incremental update, re-read everything"), 0 },
00701    { "checkstamps", I18N_NOOP("Check file timestamps"), 0 },
00702    { "nocheckfiles", I18N_NOOP("Disable checking files (dangerous)"), 0 },
00703    { "global", I18N_NOOP("Create global database"), 0 },
00704    { "menutest", I18N_NOOP("Perform menu generation test run only"), 0 },
00705    { "track <menu-id>", I18N_NOOP("Track menu id for debug purposes"), 0 },
00706 #ifdef KBUILDSYCOCA_GUI
00707    { "silent", I18N_NOOP("Silent - work without windows and stderr"), 0 },
00708    { "showprogress", I18N_NOOP("Show progress information (even if 'silent' mode is on)"), 0 },
00709 #endif
00710    KCmdLineLastOption
00711 };
00712 
00713 static const char appName[] = "kbuildsycoca";
00714 static const char appVersion[] = "1.1";
00715 
00716 class WaitForSignal : public QObject
00717 {
00718 public:
00719    ~WaitForSignal() { kapp->eventLoop()->exitLoop(); }
00720 };
00721 
00722 extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
00723 {
00724    KLocale::setMainCatalogue("kdelibs");
00725    KAboutData d(appName, I18N_NOOP("KBuildSycoca"), appVersion,
00726                 I18N_NOOP("Rebuilds the system configuration cache."),
00727                 KAboutData::License_GPL, "(c) 1999-2002 KDE Developers");
00728    d.addAuthor("David Faure", I18N_NOOP("Author"), "faure@kde.org");
00729    d.addAuthor("Waldo Bastian", I18N_NOOP("Author"), "bastian@kde.org");
00730 
00731    KCmdLineArgs::init(argc, argv, &d);
00732    KCmdLineArgs::addCmdLineOptions(options);
00733    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
00734    bGlobalDatabase = args->isSet("global");
00735    bMenuTest = args->isSet("menutest");
00736 
00737    if (bGlobalDatabase)
00738    {
00739      setenv("KDEHOME", "-", 1);
00740      setenv("KDEROOTHOME", "-", 1);
00741    }
00742 
00743    KApplication::disableAutoDcopRegistration();
00744 #ifdef KBUILDSYCOCA_GUI
00745    KApplication k;
00746 #else
00747    KApplication k(false, false);
00748 #endif
00749    k.disableSessionManagement();
00750 
00751 #ifdef KBUILDSYCOCA_GUI
00752    silent = args->isSet("silent");
00753    showprogress = args->isSet("showprogress");
00754    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 );
00755    QString capt = i18n("KDE Configuration Manager");
00756    if (!silent) {
00757      if (KMessageBox::No == KMessageBox::questionYesNo(0, i18n("Do you want to reload KDE configuration?"), capt, i18n("Reload"), i18n("Do Not Reload")))
00758        return 0;
00759    }
00760    if (!silent || showprogress) {
00761      progress.setCaption( capt );
00762      progress.show();
00763    }
00764 #endif
00765 
00766    KCrash::setCrashHandler(KCrash::defaultCrashHandler);
00767    KCrash::setEmergencySaveFunction(crashHandler);
00768    KCrash::setApplicationName(QString(appName));
00769 
00770    // this program is in kdelibs so it uses kdelibs as catalog
00771    KLocale::setMainCatalogue("kdelibs");
00772    // force generating of KLocale object. if not, the database will get
00773    // be translated
00774    KGlobal::locale();
00775    KGlobal::dirs()->addResourceType("app-reg", "share/application-registry" );
00776 
00777    DCOPClient *dcopClient = new DCOPClient();
00778 
00779    while(true)
00780    {
00781      QCString registeredName = dcopClient->registerAs(appName, false);
00782      if (registeredName.isEmpty())
00783      {
00784        fprintf(stderr, "Warning: %s is unable to register with DCOP.\n", appName);
00785        break;
00786      }
00787      else if (registeredName == appName)
00788      {
00789        break; // Go
00790      }
00791      fprintf(stderr, "Waiting for already running %s to finish.\n", appName);
00792 
00793      dcopClient->setNotifications( true );
00794      while (dcopClient->isApplicationRegistered(appName))
00795      {
00796        WaitForSignal *obj = new WaitForSignal;
00797        obj->connect(dcopClient, SIGNAL(applicationRemoved(const QCString &)),
00798                SLOT(deleteLater()));
00799        kapp->eventLoop()->enterLoop();
00800      }
00801      dcopClient->setNotifications( false );
00802    }
00803    fprintf(stderr, "%s running...\n", appName);
00804 
00805    bool checkfiles = bGlobalDatabase || args->isSet("checkfiles");
00806 
00807    bool incremental = !bGlobalDatabase && args->isSet("incremental") && checkfiles;
00808    if (incremental || !checkfiles)
00809    {
00810      KSycoca::self()->disableAutoRebuild(); // Prevent deadlock
00811      QString current_language = KGlobal::locale()->language();
00812      QString ksycoca_language = KSycoca::self()->language();
00813      Q_UINT32 current_update_sig = KGlobal::dirs()->calcResourceHash("services", "update_ksycoca", true);
00814      Q_UINT32 ksycoca_update_sig = KSycoca::self()->updateSignature();
00815 
00816      if ((current_update_sig != ksycoca_update_sig) ||
00817          (current_language != ksycoca_language) ||
00818          (KSycoca::self()->timeStamp() == 0))
00819      {
00820         incremental = false;
00821         checkfiles = true;
00822         delete KSycoca::self();
00823      }
00824    }
00825 
00826    g_changeList = new QStringList;
00827 
00828    bool checkstamps = incremental && args->isSet("checkstamps") && checkfiles;
00829    Q_UINT32 filestamp = 0;
00830    QStringList oldresourcedirs;
00831    if( checkstamps && incremental )
00832    {
00833        QString path = sycocaPath()+"stamp";
00834        QCString qPath = QFile::encodeName(path);
00835        cSycocaPath = qPath.data(); // Delete timestamps on crash
00836        QFile ksycocastamp(path);
00837        if( ksycocastamp.open( IO_ReadOnly ))
00838        {
00839            QDataStream str( &ksycocastamp );
00840            if (!str.atEnd())
00841                str >> filestamp;
00842            if (!str.atEnd())
00843            {
00844                str >> oldresourcedirs;
00845                if( oldresourcedirs != KBuildSycoca::existingResourceDirs())
00846                    checkstamps = false;
00847            }
00848            else
00849            {
00850                checkstamps = false;
00851            }
00852            if (!str.atEnd())
00853            {
00854                QStringList extraResourceDirs;
00855                str >> extraResourceDirs;
00856                oldresourcedirs += extraResourceDirs;
00857            }
00858        }
00859        else
00860        {
00861            checkstamps = false;
00862        }
00863        cSycocaPath = 0;
00864    }
00865 
00866    newTimestamp = (Q_UINT32) time(0);
00867 
00868    if( checkfiles && ( !checkstamps || !KBuildSycoca::checkTimestamps( filestamp, oldresourcedirs )))
00869    {
00870       QCString qSycocaPath = QFile::encodeName(sycocaPath());
00871       cSycocaPath = qSycocaPath.data();
00872 
00873       g_allEntries = 0;
00874       g_ctimeDict = 0;
00875       if (incremental)
00876       {
00877          qWarning("Reusing existing ksycoca");
00878          KSycoca *oldSycoca = KSycoca::self();
00879          KSycocaFactoryList *factories = new KSycocaFactoryList;
00880          g_allEntries = new KSycocaEntryListList;
00881          g_ctimeDict = new QDict<Q_UINT32>(523);
00882 
00883          // Must be in same order as in KBuildSycoca::recreate()!
00884          factories->append( new KServiceTypeFactory );
00885          factories->append( new KServiceGroupFactory );
00886          factories->append( new KServiceFactory );
00887          factories->append( new KImageIOFactory );
00888          factories->append( new KProtocolInfoFactory );
00889 
00890          // For each factory
00891          for (KSycocaFactory *factory = factories->first();
00892               factory;
00893               factory = factories->next() )
00894          {
00895              KSycocaEntry::List list;
00896              list = factory->allEntries();
00897              g_allEntries->append( list );
00898          }
00899          delete factories; factories = 0;
00900          KCTimeInfo *ctimeInfo = new KCTimeInfo;
00901          ctimeInfo->fillCTimeDict(*g_ctimeDict);
00902          delete oldSycoca;
00903       }
00904       cSycocaPath = 0;
00905 
00906       KBuildSycoca *sycoca= new KBuildSycoca; // Build data base
00907       if (args->isSet("track"))
00908          sycoca->setTrackId(QString::fromLocal8Bit(args->getOption("track")));
00909       if (!sycoca->recreate()) {
00910 #ifdef KBUILDSYCOCA_GUI
00911         if (!silent || showprogress)
00912           progress.close();
00913 #endif
00914         return -1;
00915       }
00916 
00917       if (bGlobalDatabase)
00918       {
00919         // These directories may have been created with 0700 permission
00920         // better delete them if they are empty
00921         QString applnkDir = KGlobal::dirs()->saveLocation("apps", QString::null, false);
00922         ::rmdir(QFile::encodeName(applnkDir));
00923         QString servicetypesDir = KGlobal::dirs()->saveLocation("servicetypes", QString::null, false);
00924         ::rmdir(QFile::encodeName(servicetypesDir));
00925       }
00926    }
00927 
00928    if (!bGlobalDatabase)
00929    {
00930      // Recreate compatibility symlink
00931      QString oldPath = oldSycocaPath();
00932      if (!oldPath.isEmpty())
00933      {
00934        KTempFile tmp;
00935        if (tmp.status() == 0)
00936        {
00937          QString tmpFile = tmp.name();
00938          tmp.unlink();
00939          symlink(QFile::encodeName(sycocaPath()), QFile::encodeName(tmpFile));
00940          rename(QFile::encodeName(tmpFile), QFile::encodeName(oldPath));
00941        }
00942      }
00943    }
00944 
00945    if (args->isSet("signal"))
00946    {
00947      // Notify ALL applications that have a ksycoca object, using a broadcast
00948      QByteArray data;
00949      QDataStream stream(data, IO_WriteOnly);
00950      stream << *g_changeList;
00951      dcopClient->send( "*", "ksycoca", "notifyDatabaseChanged(QStringList)", data );
00952    }
00953 
00954 #ifdef KBUILDSYCOCA_GUI
00955    if (!silent) {
00956      progress.close();
00957      KMessageBox::information(0, i18n("Configuration information reloaded successfully."), capt);
00958    }
00959 #endif
00960    return 0;
00961 }
00962 
00963 #include "kbuildsycoca.moc"
KDE Home | KDE Accessibility Home | Description of Access Keys