summaryrefslogtreecommitdiffstats
path: root/kded/kded.cpp
blob: 05964b0df8489b51586055293c388e14c8e0b1d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/*  This file is part of the KDE libraries
 *  Copyright (C) 1999 David Faure <faure@kde.org>
 *  Copyright (C) 2000 Waldo Bastian <bastian@kde.org>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License version 2 as published by the Free Software Foundation;
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 **/

#include <tqdir.h>

#include "kded.h"
#include "kdedmodule.h"

#include <kresourcelist.h>
#include <kcrash.h>

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>

#include <tqfile.h>
#include <tqtimer.h>

#include <dcopclient.h>

#include <kuniqueapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kglobal.h>
#include <kprocess.h>
#include <kdebug.h>
#include <kdirwatch.h>
#include <kstandarddirs.h>
#include <kdatastream.h>
#include <kio/global.h>
#include <kservicetype.h>

#ifdef Q_WS_X11
#include <X11/Xlib.h>
#include <fixx11h.h>
#endif

Kded *Kded::_self = 0;

static bool checkStamps = true;
static bool delayedCheck = false;

static void runBuildSycoca(TQObject *callBackObj=0, const char *callBackSlot=0)
{
   TQStringList args;
   args.append("--incremental");
   if(checkStamps)
      args.append("--checkstamps");
   if(delayedCheck)
      args.append("--nocheckfiles");
   else
      checkStamps = false; // useful only during kded startup
   if (callBackObj)
   {
      TQByteArray data;
      TQDataStream dataStream( data, IO_WriteOnly );
      dataStream << TQString("kbuildsycoca") << args;
      TQCString _launcher = KApplication::launcher();

      kapp->dcopClient()->callAsync(_launcher, _launcher, "tdeinit_exec_wait(TQString,TQStringList)", data, callBackObj, callBackSlot);
   }
   else
   {
      KApplication::tdeinitExecWait( "kbuildsycoca", args );
   }
}

static void runKonfUpdate()
{
   KApplication::tdeinitExecWait( "kconf_update", TQStringList(), 0, 0, "0" /*no startup notification*/ );
}

static void runDontChangeHostname(const TQCString &oldName, const TQCString &newName)
{
   TQStringList args;
   args.append(TQFile::decodeName(oldName));
   args.append(TQFile::decodeName(newName));
   KApplication::tdeinitExecWait( "kdontchangethehostname", args );
}

Kded::Kded(bool checkUpdates, bool new_startup)
  : DCOPObject("kbuildsycoca"), DCOPObjectProxy(),
    b_checkUpdates(checkUpdates),
    m_needDelayedCheck(false),
    m_newStartup( new_startup )
{
  _self = this;
  TQCString cPath;
  TQCString ksycoca_env = getenv("KDESYCOCA");
  if (ksycoca_env.isEmpty())
     cPath = TQFile::encodeName(KGlobal::dirs()->saveLocation("tmp")+"ksycoca");
  else
     cPath = ksycoca_env;
  m_pTimer = new TQTimer(this);
  connect(m_pTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(recreate()));

  TQTimer::singleShot(100, this, TQT_SLOT(installCrashHandler()));

  m_pDirWatch = 0;

  m_windowIdList.setAutoDelete(true);

  m_recreateCount = 0;
  m_recreateBusy = false;
}

Kded::~Kded()
{
  _self = 0;
  m_pTimer->stop();
  delete m_pTimer;
  delete m_pDirWatch;
  // We have to delete the modules while we're still able to process incoming
  // DCOP messages, since modules might make DCOP calls in their destructors.
  TQAsciiDictIterator<KDEDModule> it(m_modules);
  while (!it.isEmpty()) 
	delete it.toFirst();
}

bool Kded::process(const TQCString &obj, const TQCString &fun,
                   const TQByteArray &data,
                   TQCString &replyType, TQByteArray &replyData)
{
  if (obj == "ksycoca") return false; // Ignore this one.

  if (m_dontLoad[obj])
     return false;

  KDEDModule *module = loadModule(obj, true);
  if (!module)
     return false;

  module->setCallingDcopClient(kapp->dcopClient());
  return module->process(fun, data, replyType, replyData);
}

void Kded::initModules()
{
     m_dontLoad.clear();
     KConfig *config = kapp->config();
     bool kde_running = !( getenv( "TDE_FULL_SESSION" ) == NULL || getenv( "TDE_FULL_SESSION" )[ 0 ] == '\0' );
    // not the same user like the one running the session (most likely we're run via sudo or something)
    if( getenv( "KDE_SESSION_UID" ) != NULL && uid_t( atoi( getenv( "KDE_SESSION_UID" ))) != getuid())
        kde_running = false;
     // Preload kded modules.
     KService::List kdedModules = KServiceType::offers("KDEDModule");
     TQString version = getenv( "KDE_SESSION_VERSION" );
     TQStringList blacklist;
     if ( version >= "4" )
     {
         kdDebug(7020) << "KDE4 is running." << endl;
         blacklist << "mediamanager" << "medianotifier" << "kmilod" << "kwrited";
     }
     for(KService::List::ConstIterator it = kdedModules.begin(); it != kdedModules.end(); ++it)
     {
         KService::Ptr service = *it;
         bool autoload = service->property("X-KDE-Kded-autoload", TQVariant::Bool).toBool();
         config->setGroup(TQString("Module-%1").arg(service->desktopEntryName()));
         autoload = config->readBoolEntry("autoload", autoload);
         for (TQStringList::Iterator module = blacklist.begin(); module != blacklist.end(); ++module)
         {
            if (service->desktopEntryName() == *module)
            {
               autoload = false;
               break;
            }
         }
         if( m_newStartup )
         {
            // see ksmserver's README for description of the phases
            TQVariant phasev = service->property("X-KDE-Kded-phase", TQVariant::Int );
            int phase = phasev.isValid() ? phasev.toInt() : 2;
            bool prevent_autoload = false;
            switch( phase )
            {
                case 0: // always autoload
                    break;
                case 1: // autoload only in KDE
                    if( !kde_running )
                        prevent_autoload = true;
                    break;
                case 2: // autoload delayed, only in KDE
                default:
                    prevent_autoload = true;
                    break;   
            }
            if (autoload && !prevent_autoload)
               loadModule(service, false);
         }
         else
         {
            if (autoload && kde_running)
               loadModule(service, false);
         }
         bool dontLoad = false;
         TQVariant p = service->property("X-KDE-Kded-load-on-demand", TQVariant::Bool);
         if (p.isValid() && (p.toBool() == false))
            dontLoad = true;
         if (dontLoad)
            noDemandLoad(service->desktopEntryName());

         if (dontLoad && !autoload)
            unloadModule(service->desktopEntryName().latin1());
     }
}

void Kded::loadSecondPhase()
{
     kdDebug(7020) << "Loading second phase autoload" << endl;
     KConfig *config = kapp->config();
     KService::List kdedModules = KServiceType::offers("KDEDModule");
     for(KService::List::ConstIterator it = kdedModules.begin(); it != kdedModules.end(); ++it)
     {
         KService::Ptr service = *it;
         bool autoload = service->property("X-KDE-Kded-autoload", TQVariant::Bool).toBool();
         config->setGroup(TQString("Module-%1").arg(service->desktopEntryName()));
         autoload = config->readBoolEntry("autoload", autoload);
         TQVariant phasev = service->property("X-KDE-Kded-phase", TQVariant::Int );
         int phase = phasev.isValid() ? phasev.toInt() : 2;
         if( phase == 2 && autoload )
            loadModule(service, false);
     }
}

void Kded::noDemandLoad(const TQString &obj)
{
  m_dontLoad.insert(obj.latin1(), this);
}

KDEDModule *Kded::loadModule(const TQCString &obj, bool onDemand)
{
  KDEDModule *module = m_modules.find(obj);
  if (module)
     return module;
  KService::Ptr s = KService::serviceByDesktopPath("kded/"+obj+".desktop");
  return loadModule(s, onDemand);
}

KDEDModule *Kded::loadModule(const KService *s, bool onDemand)
{
  KDEDModule *module = 0;
  if (s && !s->library().isEmpty())
  {
    TQCString obj = s->desktopEntryName().latin1();
    KDEDModule *oldModule = m_modules.find(obj);
    if (oldModule)
       return oldModule;

    if (onDemand)
    {
      TQVariant p = s->property("X-KDE-Kded-load-on-demand", TQVariant::Bool);
      if (p.isValid() && (p.toBool() == false))
      {
         noDemandLoad(s->desktopEntryName());
         return 0;
      }
    }
    // get the library loader instance

    KLibLoader *loader = KLibLoader::self();

    TQVariant v = s->property("X-KDE-FactoryName", TQVariant::String);
    TQString factory = v.isValid() ? v.toString() : TQString::null;
    if (factory.isEmpty())
    {
       // Stay bugward compatible
       v = s->property("X-KDE-Factory", TQVariant::String);
       factory = v.isValid() ? v.toString() : TQString::null;
    }
    if (factory.isEmpty())
      factory = s->library();

    factory = "create_" + factory;
    TQString libname = "kded_"+s->library();

    KLibrary *lib = loader->library(TQFile::encodeName(libname));
    if (!lib)
    {
      kdWarning() << k_funcinfo << "Could not load library. [ "
		  << loader->lastErrorMessage() << " ]" << endl;
      libname.prepend("lib");
      lib = loader->library(TQFile::encodeName(libname));
    }
    if (lib)
    {
      // get the create_ function
      void *create = lib->symbol(TQFile::encodeName(factory));

      if (create)
      {
        // create the module
        KDEDModule* (*func)(const TQCString &);
        func = (KDEDModule* (*)(const TQCString &)) create;
        module = func(obj);
        if (module)
        {
          m_modules.insert(obj, module);
          m_libs.insert(obj, lib);
          connect(module, TQT_SIGNAL(moduleDeleted(KDEDModule *)), TQT_SLOT(slotKDEDModuleRemoved(KDEDModule *)));
          kdDebug(7020) << "Successfully loaded module '" << obj << "'\n";
          return module;
        }
      }
      loader->unloadLibrary(TQFile::encodeName(libname));
    }
    else
    {
	kdWarning() << k_funcinfo << "Could not load library. [ "
		    << loader->lastErrorMessage() << " ]" << endl;
    }
    kdDebug(7020) << "Could not load module '" << obj << "'\n";
  }
  return 0;
}

bool Kded::unloadModule(const TQCString &obj)
{
  KDEDModule *module = m_modules.take(obj);
  if (!module)
     return false;
  kdDebug(7020) << "Unloading module '" << obj << "'\n";
  delete module;
  return true;
}

// DCOP
QCStringList Kded::loadedModules()
{
	QCStringList modules;
	TQAsciiDictIterator<KDEDModule> it( m_modules );
	for ( ; it.current(); ++it)
		modules.append( it.currentKey() );

	return modules;
}

QCStringList Kded::functions()
{
    QCStringList res = DCOPObject::functions();
    res += "ASYNC recreate()";
    return res;
}

void Kded::slotKDEDModuleRemoved(KDEDModule *module)
{
  m_modules.remove(module->objId());
  KLibrary *lib = m_libs.take(module->objId());
  if (lib)
     lib->unload();
}

void Kded::slotApplicationRemoved(const TQCString &appId)
{
  for(TQAsciiDictIterator<KDEDModule> it(m_modules); it.current(); ++it)
  {
     it.current()->removeAll(appId);
  }

  TQValueList<long> *windowIds = m_windowIdList.find(appId);
  if (windowIds)
  {
     for( TQValueList<long>::ConstIterator it = windowIds->begin();
          it != windowIds->end(); ++it)
     {
        long windowId = *it;
        m_globalWindowIdList.remove(windowId);
        for(TQAsciiDictIterator<KDEDModule> it(m_modules); it.current(); ++it)
        {
            emit it.current()->windowUnregistered(windowId);
        }
     }
     m_windowIdList.remove(appId);
  }
}

void Kded::updateDirWatch()
{
  if (!b_checkUpdates) return;

  delete m_pDirWatch;
  m_pDirWatch = new KDirWatch;

  TQObject::connect( m_pDirWatch, TQT_SIGNAL(dirty(const TQString&)),
           this, TQT_SLOT(update(const TQString&)));
  TQObject::connect( m_pDirWatch, TQT_SIGNAL(created(const TQString&)),
           this, TQT_SLOT(update(const TQString&)));
  TQObject::connect( m_pDirWatch, TQT_SIGNAL(deleted(const TQString&)),
           this, TQT_SLOT(dirDeleted(const TQString&)));

  // For each resource
  for( TQStringList::ConstIterator it = m_allResourceDirs.begin();
       it != m_allResourceDirs.end();
       ++it )
  {
     readDirectory( *it );
  }
}

void Kded::updateResourceList()
{
  delete KSycoca::self();

  if (!b_checkUpdates) return;

  if (delayedCheck) return;

  TQStringList dirs = KSycoca::self()->allResourceDirs();
  // For each resource
  for( TQStringList::ConstIterator it = dirs.begin();
       it != dirs.end();
       ++it )
  {
     if (m_allResourceDirs.find(*it) == m_allResourceDirs.end())
     {
        m_allResourceDirs.append(*it);
        readDirectory(*it);
     }
  }
}

void Kded::crashHandler(int)
{
   DCOPClient::emergencyClose();
   if (_self) // Don't restart if we were closing down
      system("kded");
qWarning("Last DCOP call before KDED crash was from application '%s'\n"
         "to object '%s', function '%s'.",
         DCOPClient::postMortemSender(),
         DCOPClient::postMortemObject(),
         DCOPClient::postMortemFunction());
}

void Kded::installCrashHandler()
{
   KCrash::setEmergencySaveFunction(crashHandler);
}

void Kded::recreate()
{
   recreate(false);
}

void Kded::runDelayedCheck()
{
   if( m_needDelayedCheck )
      recreate(false);
   m_needDelayedCheck = false;
}

void Kded::recreate(bool initial)
{
   m_recreateBusy = true;
   // Using KLauncher here is difficult since we might not have a
   // database

   if (!initial)
   {
      updateDirWatch(); // Update tree first, to be sure to miss nothing.
      runBuildSycoca(this, TQT_SLOT(recreateDone()));
   }
   else
   {
      if(!delayedCheck)
         updateDirWatch(); // this would search all the directories
      runBuildSycoca();
      recreateDone();
      if(delayedCheck)
      {
         // do a proper ksycoca check after a delay
         TQTimer::singleShot( 60000, this, TQT_SLOT( runDelayedCheck()));
         m_needDelayedCheck = true;
         delayedCheck = false;
      }
      else
         m_needDelayedCheck = false;
   }
}

void Kded::recreateDone()
{
   updateResourceList();

   for(; m_recreateCount; m_recreateCount--)
   {
      TQCString replyType = "void";
      TQByteArray replyData;
      DCOPClientTransaction *transaction = m_recreateRequests.first();
      if (transaction)
         kapp->dcopClient()->endTransaction(transaction, replyType, replyData);
      m_recreateRequests.remove(m_recreateRequests.begin());
   }
   m_recreateBusy = false;

   // Did a new request come in while building?
   if (!m_recreateRequests.isEmpty())
   {
      m_pTimer->start(2000, true /* single shot */ );
      m_recreateCount = m_recreateRequests.count();
   }
}

void Kded::dirDeleted(const TQString& path)
{
  update(path);
}

void Kded::update(const TQString& )
{
  if (!m_recreateBusy)
  {
    m_pTimer->start( 2000, true /* single shot */ );
  }
  else
  {
    m_recreateRequests.append(0);
  }
}

bool Kded::process(const TQCString &fun, const TQByteArray &data,
                           TQCString &replyType, TQByteArray &replyData)
{
  if (fun == "recreate()") {
    if (!m_recreateBusy)
    {
       if (m_recreateRequests.isEmpty())
       {
          m_pTimer->start(0, true /* single shot */ );
          m_recreateCount = 0;
       }
       m_recreateCount++;
    }
    m_recreateRequests.append(kapp->dcopClient()->beginTransaction());
    replyType = "void";
    return true;
  } else {
    return DCOPObject::process(fun, data, replyType, replyData);
  }
}


void Kded::readDirectory( const TQString& _path )
{
  TQString path( _path );
  if ( path.right(1) != "/" )
    path += "/";

  if ( m_pDirWatch->contains( path ) ) // Already seen this one?
     return;

  TQDir d( _path, TQString::null, TQDir::Unsorted, TQDir::Readable | TQDir::Executable | TQDir::Dirs | TQDir::Hidden );
  // set TQDir ...


  //************************************************************************
  //                           Setting dirs
  //************************************************************************

  m_pDirWatch->addDir(path);          // add watch on this dir

  if ( !d.exists() )                            // exists&isdir?
  {
    kdDebug(7020) << TQString(TQString("Does not exist! (%1)").arg(_path)) << endl;
    return;                             // return false
  }

  // Note: If some directory is gone, dirwatch will delete it from the list.

  //************************************************************************
  //                               Reading
  //************************************************************************
  TQString file;
  unsigned int i;                           // counter and string length.
  unsigned int count = d.count();
  for( i = 0; i < count; i++ )                        // check all entries
  {
     if (d[i] == "." || d[i] == ".." || d[i] == "magic")
       continue;                          // discard those ".", "..", "magic"...

     file = path;                           // set full path
     file += d[i];                          // and add the file name.

     readDirectory( file );      // yes, dive into it.
  }
}

bool Kded::isWindowRegistered(long windowId)
{
  return m_globalWindowIdList.find(windowId) != 0;

}

// DCOP
void Kded::registerWindowId(long windowId)
{
  m_globalWindowIdList.replace(windowId, &windowId);
  TQCString sender = callingDcopClient()->senderId();
  if( sender.isEmpty()) // local call
      sender = callingDcopClient()->appId();
  TQValueList<long> *windowIds = m_windowIdList.find(sender);
  if (!windowIds)
  {
    windowIds = new TQValueList<long>;
    m_windowIdList.insert(sender, windowIds);
  }
  windowIds->append(windowId);


  for(TQAsciiDictIterator<KDEDModule> it(m_modules); it.current(); ++it)
  {
     emit it.current()->windowRegistered(windowId);
  }
}

// DCOP
void Kded::unregisterWindowId(long windowId)
{
  m_globalWindowIdList.remove(windowId);
  TQCString sender = callingDcopClient()->senderId();
  if( sender.isEmpty()) // local call
      sender = callingDcopClient()->appId();
  TQValueList<long> *windowIds = m_windowIdList.find(sender);
  if (windowIds)
  {
     windowIds->remove(windowId);
     if (windowIds->isEmpty())
        m_windowIdList.remove(sender);
  }

  for(TQAsciiDictIterator<KDEDModule> it(m_modules); it.current(); ++it)
  {
    emit it.current()->windowUnregistered(windowId);
  }
}


static void sighandler(int /*sig*/)
{
    if (kapp)
       kapp->quit();
}

KUpdateD::KUpdateD()
{
    m_pDirWatch = new KDirWatch;
    m_pTimer = new TQTimer;
    connect(m_pTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(runKonfUpdate()));
    TQObject::connect( m_pDirWatch, TQT_SIGNAL(dirty(const TQString&)),
           this, TQT_SLOT(slotNewUpdateFile()));

    TQStringList dirs = KGlobal::dirs()->findDirs("data", "kconf_update");
    for( TQStringList::ConstIterator it = dirs.begin();
         it != dirs.end();
         ++it )
    {
       TQString path = *it;
       if (path[path.length()-1] != '/')
          path += "/";

       if (!m_pDirWatch->contains(path))
          m_pDirWatch->addDir(path);
    }
}

KUpdateD::~KUpdateD()
{
    delete m_pDirWatch;
    delete m_pTimer;
}

void KUpdateD::runKonfUpdate()
{
    ::runKonfUpdate();
}

void KUpdateD::slotNewUpdateFile()
{
    m_pTimer->start( 500, true /* single shot */ );
}

KHostnameD::KHostnameD(int pollInterval)
{
    m_Timer.start(pollInterval, false /* repetitive */ );
    connect(&m_Timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(checkHostname()));
    checkHostname();
}

KHostnameD::~KHostnameD()
{
    // Empty
}

void KHostnameD::checkHostname()
{
    char buf[1024+1];
    if (gethostname(buf, 1024) != 0)
       return;
    buf[sizeof(buf)-1] = '\0';

    if (m_hostname.isEmpty())
    {
       m_hostname = buf;
       return;
    }

    if (m_hostname == buf)
       return;

    TQCString newHostname = buf;

    runDontChangeHostname(m_hostname, newHostname);
    m_hostname = newHostname;
}


static KCmdLineOptions options[] =
{
  { "check", I18N_NOOP("Check Sycoca database only once"), 0 },
  { "new-startup", "Internal", 0 },
  KCmdLineLastOption
};

class KDEDQtDCOPObject : public DCOPObject
{
public:
  KDEDQtDCOPObject() : DCOPObject("qt/kded") { }

  virtual bool process(const TQCString &fun, const TQByteArray &data,
                       TQCString& replyType, TQByteArray &replyData)
    {
      if ( kapp && (fun == "quit()") )
      {
        kapp->quit();
        replyType = "void";
        return true;
      }
      return DCOPObject::process(fun, data, replyType, replyData);
    }

  QCStringList functions()
    {
       QCStringList res = DCOPObject::functions();
       res += "void quit()";
       return res;
    }
};

class KDEDApplication : public KUniqueApplication
{
public:
  KDEDApplication() : KUniqueApplication( )
    {
       startup = true;
       dcopClient()->connectDCOPSignal( "DCOPServer", "", "terminateKDE()",
                                        objId(), "quit()", false );
    }

  int newInstance()
    {
       if (startup) {
          startup = false;
          if( Kded::self()->newStartup())
             Kded::self()->initModules();
          else
	     TQTimer::singleShot(500, Kded::self(), TQT_SLOT(initModules()));
       } else 
          runBuildSycoca();

       return 0;
    }

  QCStringList functions()
    {
       QCStringList res = KUniqueApplication::functions();
       res += "bool loadModule(TQCString)";
       res += "bool unloadModule(TQCString)";
       res += "void registerWindowId(long int)";
       res += "void unregisterWindowId(long int)";
       res += "QCStringList loadedModules()";
       res += "void reconfigure()";
       res += "void loadSecondPhase()";
       res += "void quit()";
       return res;
    }

  bool process(const TQCString &fun, const TQByteArray &data,
               TQCString &replyType, TQByteArray &replyData)
  {
    if (fun == "loadModule(TQCString)") {
      TQCString module;
      TQDataStream arg( data, IO_ReadOnly );
      arg >> module;
      bool result = (Kded::self()->loadModule(module, false) != 0);
      replyType = "bool";
      TQDataStream _replyStream( replyData, IO_WriteOnly );
      _replyStream << result;
      return true;
    }
    else if (fun == "unloadModule(TQCString)") {
      TQCString module;
      TQDataStream arg( data, IO_ReadOnly );
      arg >> module;
      bool result = Kded::self()->unloadModule(module);
      replyType = "bool";
      TQDataStream _replyStream( replyData, IO_WriteOnly );
      _replyStream << result;
      return true;
    }
    else if (fun == "registerWindowId(long int)") {
      long windowId;
      TQDataStream arg( data, IO_ReadOnly );
      arg >> windowId;
      Kded::self()->setCallingDcopClient(callingDcopClient());
      Kded::self()->registerWindowId(windowId);
      replyType = "void";
      return true;
    }
     else if (fun == "unregisterWindowId(long int)") {
      long windowId;
      TQDataStream arg( data, IO_ReadOnly );
      arg >> windowId;
      Kded::self()->setCallingDcopClient(callingDcopClient());
      Kded::self()->unregisterWindowId(windowId);
      replyType = "void";
      return true;
    }
    else if (fun == "loadedModules()") {
      replyType = "QCStringList";
      TQDataStream _replyStream(replyData, IO_WriteOnly);
      _replyStream << Kded::self()->loadedModules();
      return true;
    }
    else if (fun == "reconfigure()") {
      config()->reparseConfiguration();
      Kded::self()->initModules();
      replyType = "void";
      return true;
    }
    else if (fun == "loadSecondPhase()") {
      Kded::self()->loadSecondPhase();
      replyType = "void";
      return true;
    }
    else if (fun == "quit()") {
      quit();
      replyType = "void";
      return true;
    }
    return KUniqueApplication::process(fun, data, replyType, replyData);
  }

  bool startup;
  KDEDQtDCOPObject kdedQtDcopObject;
};

extern "C" KDE_EXPORT int kdemain(int argc, char *argv[])
{
     KAboutData aboutData( "kded", I18N_NOOP("KDE Daemon"),
        "$Id$",
        I18N_NOOP("KDE Daemon - triggers Sycoca database updates when needed"));

     KApplication::installSigpipeHandler();

     KCmdLineArgs::init(argc, argv, &aboutData);

     KUniqueApplication::addCmdLineOptions();

     KCmdLineArgs::addCmdLineOptions( options );

     // this program is in tdelibs so it uses tdelibs as catalog
     KLocale::setMainCatalogue("tdelibs");

     // WABA: Make sure not to enable session management.
     putenv(strdup("SESSION_MANAGER="));

     // Parse command line before checking DCOP
     KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

     // Check DCOP communication.
     {
        DCOPClient testDCOP;
        TQCString dcopName = testDCOP.registerAs("kded", false);
        if (dcopName.isEmpty())
        {
           kdFatal() << "DCOP communication problem!" << endl;
           return 1;
        }
     }

     KInstance *instance = new KInstance(&aboutData);
     KConfig *config = instance->config(); // Enable translations.

     if (args->isSet("check"))
     {
        config->setGroup("General");
        checkStamps = config->readBoolEntry("CheckFileStamps", true);
        runBuildSycoca();
        runKonfUpdate();
        exit(0);
     }

     if (!KUniqueApplication::start())
     {
        fprintf(stderr, "KDE Daemon (kded) already running.\n");
        exit(0);
     }

     KUniqueApplication::dcopClient()->setQtBridgeEnabled(false);

     config->setGroup("General");
     int HostnamePollInterval = config->readNumEntry("HostnamePollInterval", 5000);
     bool bCheckSycoca = config->readBoolEntry("CheckSycoca", true);
     bool bCheckUpdates = config->readBoolEntry("CheckUpdates", true);
     bool bCheckHostname = config->readBoolEntry("CheckHostname", true);
     checkStamps = config->readBoolEntry("CheckFileStamps", true);
     delayedCheck = config->readBoolEntry("DelayedCheck", false);

     Kded *kded = new Kded(bCheckSycoca, args->isSet("new-startup")); // Build data base

     signal(SIGTERM, sighandler);
     signal(SIGHUP, sighandler);
     KDEDApplication k;

     kded->recreate(true); // initial

     if (bCheckUpdates)
        (void) new KUpdateD; // Watch for updates

     runKonfUpdate(); // Run it once.

     if (bCheckHostname)
        (void) new KHostnameD(HostnamePollInterval); // Watch for hostname changes

     DCOPClient *client = kapp->dcopClient();
     TQObject::connect(client, TQT_SIGNAL(applicationRemoved(const TQCString&)),
             kded, TQT_SLOT(slotApplicationRemoved(const TQCString&)));
     client->setNotifications(true);
     client->setDaemonMode( true );

     // During startup kdesktop waits for KDED to finish.
     // Send a notifyDatabaseChanged signal even if the database hasn't
     // changed.
     // If the database changed, kbuildsycoca's signal didn't go anywhere
     // anyway, because it was too early, so let's send this signal
     // unconditionnally (David)
     TQByteArray data;
     client->send( "*", "ksycoca", "notifyDatabaseChanged()", data );
     client->send( "ksplash", "", "upAndRunning(TQString)",  TQString("kded"));
#ifdef Q_WS_X11
     XEvent e;
     e.xclient.type = ClientMessage;
     e.xclient.message_type = XInternAtom( qt_xdisplay(), "_KDE_SPLASH_PROGRESS", False );
     e.xclient.display = qt_xdisplay();
     e.xclient.window = qt_xrootwin();
     e.xclient.format = 8;
     strcpy( e.xclient.data.b, "kded" );
     XSendEvent( qt_xdisplay(), qt_xrootwin(), False, SubstructureNotifyMask, &e );
#endif
     int result = k.exec(); // keep running

     delete kded;
     delete instance; // Deletes config as well

     return result;
}

#include "kded.moc"