• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • kdecore
 

kdecore

  • kdecore
kapplication.cpp
1 /* This file is part of the KDE libraries
2  Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
3  Copyright (C) 1998, 1999, 2000 KDE Team
4 
5  This library is free software; you can redistribute it and/or
6  modify it under the terms of the GNU Library General Public
7  License as published by the Free Software Foundation; either
8  version 2 of the License, or (at your option) any later version.
9 
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  Library General Public License for more details.
14 
15  You should have received a copy of the GNU Library General Public License
16  along with this library; see the file COPYING.LIB. If not, write to
17  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  Boston, MA 02110-1301, USA.
19  */
20 
21 #include "config.h"
22 
23 #ifdef HAVE_XCOMPOSITE
24 #define COMPOSITE
25 #endif
26 
27 // #ifdef QTRANSLATOR_H
28 // #error qtranslator.h was already included
29 // #endif // QTRANSLATOR_H
30 //
31 // #ifdef TQTRANSLATOR_H
32 // #error tqtranslator.h was already included
33 // #endif // TQTRANSLATOR_H
34 
35 #undef QT_NO_TRANSLATION
36 #undef TQT_NO_TRANSLATION
37 #include <tqtranslator.h>
38 
39 // FIXME
40 // FOR BINARY COMPATIBILITY ONLY
41 // REMOVE WHEN PRACTICAL!
42 #define TDEAPPLICATION_BINARY_COMPAT_HACK 1
43 #include "kapplication.h"
44 #undef TDEAPPLICATION_BINARY_COMPAT_HACK
45 
46 #define QT_NO_TRANSLATION
47 #define TQT_NO_TRANSLATION
48 #include <tqdir.h>
49 #include <tqptrcollection.h>
50 #include <tqwidgetlist.h>
51 #include <tqstrlist.h>
52 #include <tqfile.h>
53 #include <tqmessagebox.h>
54 #include <tqtextstream.h>
55 #include <tqregexp.h>
56 #include <tqlineedit.h>
57 #include <tqtextedit.h>
58 #include <tqsessionmanager.h>
59 #include <tqptrlist.h>
60 #include <tqtimer.h>
61 #include <tqstylesheet.h>
62 #include <tqpixmapcache.h>
63 #include <tqtooltip.h>
64 #include <tqstylefactory.h>
65 #include <tqmetaobject.h>
66 #include <tqimage.h>
67 #ifndef QT_NO_SQL
68 #include <tqsqlpropertymap.h>
69 #endif
70 
71 #include <kglobal.h>
72 #include <kstandarddirs.h>
73 #include <kdebug.h>
74 #include <klocale.h>
75 #include <kstyle.h>
76 #include <kiconloader.h>
77 #include <kclipboard.h>
78 #include <kconfig.h>
79 #include <ksimpleconfig.h>
80 #include <kcmdlineargs.h>
81 #include <kaboutdata.h>
82 #include <kglobalsettings.h>
83 #include <kcrash.h>
84 #include <kdatastream.h>
85 #include <klibloader.h>
86 #include <kmimesourcefactory.h>
87 #include <kstdaccel.h>
88 #include <kaccel.h>
89 #include "kcheckaccelerators.h"
90 #include <tqptrdict.h>
91 #include <kmacroexpander.h>
92 #include <kshell.h>
93 #include <kprotocolinfo.h>
94 #include <kkeynative.h>
95 #include <kmdcodec.h>
96 #include <kglobalaccel.h>
97 
98 #if defined Q_WS_X11
99 #include <kstartupinfo.h>
100 #endif
101 
102 #include <dcopclient.h>
103 #include <dcopref.h>
104 
105 #include <sys/types.h>
106 #ifdef HAVE_SYS_STAT_H
107 #include <sys/stat.h>
108 #endif
109 #include <sys/wait.h>
110 #include <grp.h>
111 #include <sys/types.h>
112 
113 #ifndef Q_WS_WIN
114 #include "kwin.h"
115 #endif
116 
117 #include <fcntl.h>
118 #include <stdlib.h> // getenv(), srand(), rand()
119 #include <signal.h>
120 #include <unistd.h>
121 #include <time.h>
122 #include <sys/time.h>
123 #include <errno.h>
124 #include <string.h>
125 #include <netdb.h>
126 #if defined Q_WS_X11
127 //#ifndef Q_WS_QWS //FIXME(E): NetWM should talk to QWS...
128 #include <netwm.h>
129 #endif
130 
131 #include "kprocctrl.h"
132 
133 #ifdef HAVE_PATHS_H
134 #include <paths.h>
135 #endif
136 
137 #ifdef Q_WS_X11
138 #include <X11/Xlib.h>
139 #ifdef COMPOSITE
140 #include <X11/extensions/Xrender.h>
141 #include <X11/extensions/Xcomposite.h>
142 #include <dlfcn.h>
143 #endif
144 #include <X11/Xutil.h>
145 #include <X11/Xatom.h>
146 #include <X11/SM/SMlib.h>
147 #include <fixx11h.h>
148 #endif
149 
150 #include <pwd.h>
151 
152 #ifndef Q_WS_WIN
153 #include <KDE-ICE/ICElib.h>
154 #else
155 typedef void* IceIOErrorHandler;
156 #include <windows.h>
157 //KDE4: remove
158 #define Button1Mask (1<<8)
159 #define Button2Mask (1<<9)
160 #define Button3Mask (1<<10)
161 #endif
162 
163 #ifdef Q_WS_X11
164 #define DISPLAY "DISPLAY"
165 #elif defined(Q_WS_QWS)
166 #define DISPLAY "QWS_DISPLAY"
167 #endif
168 
169 #if defined Q_WS_X11
170 #include <kipc.h>
171 #endif
172 
173 #ifdef Q_WS_MACX
174 #include <Carbon/Carbon.h>
175 #include <tqimage.h>
176 #endif
177 
178 #include "kappdcopiface.h"
179 
180 // exported for kdm kfrontend
181 KDE_EXPORT bool kde_have_kipc = true; // magic hook to disable kipc in kdm
182 bool kde_kiosk_exception = false; // flag to disable kiosk restrictions
183 bool kde_kiosk_admin = false;
184 
185 KApplication* KApplication::KApp = 0L;
186 bool KApplication::loadedByKdeinit = false;
187 DCOPClient *KApplication::s_DCOPClient = 0L;
188 bool KApplication::s_dcopClientNeedsPostInit = false;
189 
190 #ifdef Q_WS_X11
191 static Atom atom_DesktopWindow;
192 static Atom atom_NetSupported;
193 #endif
194 
195 #if defined(Q_WS_X11) && defined(COMPOSITE)
196 static int composite_event, composite_error, composite_opcode;
197 static bool x11_composite_error_generated;
198 static int x11_error(Display *dpy, XErrorEvent *ev) {
199  if (ev->request_code == composite_opcode && ev->minor_code == X_CompositeRedirectSubwindows)
200  {
201  x11_composite_error_generated = true;
202  return 0;
203  }
204 }
205 #endif
206 
207 // duplicated from patched Qt, so that there won't be unresolved symbols if Qt gets
208 // replaced by unpatched one
209 KDECORE_EXPORT bool qt_qclipboard_bailout_hack = false;
210 
211 template class TQPtrList<KSessionManaged>;
212 
213 #ifdef Q_WS_X11
214 extern "C" {
215 static int kde_xio_errhandler( Display * dpy )
216 {
217  return kapp->xioErrhandler( dpy );
218 }
219 
220 static int kde_x_errhandler( Display *dpy, XErrorEvent *err )
221 {
222  return kapp->xErrhandler( dpy, err );
223 }
224 
225 }
226 
227 extern "C" {
228 static void kde_ice_ioerrorhandler( IceConn conn )
229 {
230  if(kapp)
231  kapp->iceIOErrorHandler( conn );
232  // else ignore the error for now
233 }
234 }
235 #endif
236 
237 #ifdef Q_WS_WIN
238 void KApplication_init_windows(bool GUIenabled);
239 
240 class QAssistantClient;
241 #endif
242 
243 /*
244  Private data to make keeping binary compatibility easier
245  */
246 class KApplicationPrivate
247 {
248 public:
249  KApplicationPrivate()
250  : actionRestrictions( false ),
251  refCount( 1 ),
252  oldIceIOErrorHandler( 0 ),
253  checkAccelerators( 0 ),
254  overrideStyle( TQString::null ),
255  startup_id( "0" ),
256  app_started_timer( NULL ),
257  m_KAppDCOPInterface( 0L ),
258  session_save( false )
259 #ifdef Q_WS_X11
260  ,oldXErrorHandler( NULL )
261  ,oldXIOErrorHandler( NULL )
262 #elif defined Q_WS_WIN
263  ,qassistantclient( 0 )
264 #endif
265  {
266  }
267 
268  ~KApplicationPrivate()
269  {
270 #ifdef Q_WS_WIN
271  delete qassistantclient;
272 #endif
273  }
274 
275 
276  bool actionRestrictions : 1;
277  bool guiEnabled : 1;
284  int refCount;
285  IceIOErrorHandler oldIceIOErrorHandler;
286  KCheckAccelerators* checkAccelerators;
287  TQString overrideStyle;
288  TQString geometry_arg;
289  TQCString startup_id;
290  TQTimer* app_started_timer;
291  KAppDCOPInterface *m_KAppDCOPInterface;
292  bool session_save;
293 #ifdef Q_WS_X11
294  int (*oldXErrorHandler)(Display*,XErrorEvent*);
295  int (*oldXIOErrorHandler)(Display*);
296 #elif defined Q_WS_WIN
297  QAssistantClient* qassistantclient;
298 #endif
299 
300  class URLActionRule
301  {
302  public:
303 #define checkExactMatch(s, b) \
304  if (s.isEmpty()) b = true; \
305  else if (s[s.length()-1] == '!') \
306  { b = false; s.truncate(s.length()-1); } \
307  else b = true;
308 #define checkStartWildCard(s, b) \
309  if (s.isEmpty()) b = true; \
310  else if (s[0] == '*') \
311  { b = true; s = s.mid(1); } \
312  else b = false;
313 #define checkEqual(s, b) \
314  b = (s == "=");
315 
316  URLActionRule(const TQString &act,
317  const TQString &bProt, const TQString &bHost, const TQString &bPath,
318  const TQString &dProt, const TQString &dHost, const TQString &dPath,
319  bool perm)
320  : action(act),
321  baseProt(bProt), baseHost(bHost), basePath(bPath),
322  destProt(dProt), destHost(dHost), destPath(dPath),
323  permission(perm)
324  {
325  checkExactMatch(baseProt, baseProtWildCard);
326  checkStartWildCard(baseHost, baseHostWildCard);
327  checkExactMatch(basePath, basePathWildCard);
328  checkExactMatch(destProt, destProtWildCard);
329  checkStartWildCard(destHost, destHostWildCard);
330  checkExactMatch(destPath, destPathWildCard);
331  checkEqual(destProt, destProtEqual);
332  checkEqual(destHost, destHostEqual);
333  }
334 
335  bool baseMatch(const KURL &url, const TQString &protClass)
336  {
337  if (baseProtWildCard)
338  {
339  if ( !baseProt.isEmpty() && !url.protocol().startsWith(baseProt) &&
340  (protClass.isEmpty() || (protClass != baseProt)) )
341  return false;
342  }
343  else
344  {
345  if ( (url.protocol() != baseProt) &&
346  (protClass.isEmpty() || (protClass != baseProt)) )
347  return false;
348  }
349  if (baseHostWildCard)
350  {
351  if (!baseHost.isEmpty() && !url.host().endsWith(baseHost))
352  return false;
353  }
354  else
355  {
356  if (url.host() != baseHost)
357  return false;
358  }
359  if (basePathWildCard)
360  {
361  if (!basePath.isEmpty() && !url.path().startsWith(basePath))
362  return false;
363  }
364  else
365  {
366  if (url.path() != basePath)
367  return false;
368  }
369  return true;
370  }
371 
372  bool destMatch(const KURL &url, const TQString &protClass, const KURL &base, const TQString &baseClass)
373  {
374  if (destProtEqual)
375  {
376  if ( (url.protocol() != base.protocol()) &&
377  (protClass.isEmpty() || baseClass.isEmpty() || protClass != baseClass) )
378  return false;
379  }
380  else if (destProtWildCard)
381  {
382  if ( !destProt.isEmpty() && !url.protocol().startsWith(destProt) &&
383  (protClass.isEmpty() || (protClass != destProt)) )
384  return false;
385  }
386  else
387  {
388  if ( (url.protocol() != destProt) &&
389  (protClass.isEmpty() || (protClass != destProt)) )
390  return false;
391  }
392  if (destHostWildCard)
393  {
394  if (!destHost.isEmpty() && !url.host().endsWith(destHost))
395  return false;
396  }
397  else if (destHostEqual)
398  {
399  if (url.host() != base.host())
400  return false;
401  }
402  else
403  {
404  if (url.host() != destHost)
405  return false;
406  }
407  if (destPathWildCard)
408  {
409  if (!destPath.isEmpty() && !url.path().startsWith(destPath))
410  return false;
411  }
412  else
413  {
414  if (url.path() != destPath)
415  return false;
416  }
417  return true;
418  }
419 
420  TQString action;
421  TQString baseProt;
422  TQString baseHost;
423  TQString basePath;
424  TQString destProt;
425  TQString destHost;
426  TQString destPath;
427  bool baseProtWildCard : 1;
428  bool baseHostWildCard : 1;
429  bool basePathWildCard : 1;
430  bool destProtWildCard : 1;
431  bool destHostWildCard : 1;
432  bool destPathWildCard : 1;
433  bool destProtEqual : 1;
434  bool destHostEqual : 1;
435  bool permission;
436  };
437  TQPtrList<URLActionRule> urlActionRestrictions;
438 
439  TQString sessionKey;
440  TQString pSessionConfigFile;
441 };
442 
443 
444 static TQPtrList<TQWidget>*x11Filter = 0;
445 static bool autoDcopRegistration = true;
446 
447 void KApplication::installX11EventFilter( TQWidget* filter )
448 {
449  if ( !filter )
450  return;
451  if (!x11Filter)
452  x11Filter = new TQPtrList<TQWidget>;
453  connect ( filter, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( x11FilterDestroyed() ) );
454  x11Filter->append( filter );
455 }
456 
457 void KApplication::x11FilterDestroyed()
458 {
459  removeX11EventFilter( static_cast< const TQWidget* >( sender()));
460 }
461 
462 void KApplication::removeX11EventFilter( const TQWidget* filter )
463 {
464  if ( !x11Filter || !filter )
465  return;
466  x11Filter->removeRef( filter );
467  if ( x11Filter->isEmpty() ) {
468  delete x11Filter;
469  x11Filter = 0;
470  }
471 }
472 
473 // FIXME: remove this when we've get a better method of
474 // customizing accelerator handling -- hopefully in Qt.
475 // For now, this is set whenever an accelerator is overridden
476 // in KAccelEventHandler so that the AccelOverride isn't sent twice. -- ellis, 19/10/02
477 extern bool kde_g_bKillAccelOverride;
478 
479 bool KApplication::notify(TQObject *receiver, TQEvent *event)
480 {
481  TQEvent::Type t = event->type();
482  if (kde_g_bKillAccelOverride)
483  {
484  kde_g_bKillAccelOverride = false;
485  // Indicate that the accelerator has been overridden.
486  if (t == TQEvent::AccelOverride)
487  {
488  TQT_TQKEYEVENT(event)->accept();
489  return true;
490  }
491  else
492  kdWarning(125) << "kde_g_bKillAccelOverride set, but received an event other than AccelOverride." << endl;
493  }
494 
495  if ((t == TQEvent::AccelOverride) || (t == TQEvent::KeyPress))
496  {
497  static const KShortcut& _selectAll = KStdAccel::selectAll();
498  TQLineEdit *edit = ::tqqt_cast<TQLineEdit *>(receiver);
499  if (edit)
500  {
501  // We have a keypress for a lineedit...
502  TQKeyEvent *kevent = TQT_TQKEYEVENT(event);
503  KKey key(kevent);
504  if (_selectAll.contains(key))
505  {
506  if (t == TQEvent::KeyPress)
507  {
508  edit->selectAll();
509  return true;
510  }
511  else
512  {
513  kevent->accept();
514  }
515  }
516  // Ctrl-U deletes from start of line.
517  if (key == KKey(Qt::CTRL + Qt::Key_U))
518  {
519  if (t == TQEvent::KeyPress)
520  {
521  if (!edit->isReadOnly())
522  {
523  TQString t(edit->text());
524  t = t.mid(edit->cursorPosition());
525  edit->validateAndSet(t, 0, 0, 0);
526  }
527  return true;
528  }
529  else
530  {
531  kevent->accept();
532  }
533 
534  }
535  }
536  TQTextEdit *medit = ::tqqt_cast<TQTextEdit *>(receiver);
537  if (medit)
538  {
539  // We have a keypress for a multilineedit...
540  TQKeyEvent *kevent = TQT_TQKEYEVENT(event);
541  if (_selectAll.contains(KKey(kevent)))
542  {
543  if (t == TQEvent::KeyPress)
544  {
545  medit->selectAll();
546  return true;
547  }
548  else
549  {
550  kevent->accept();
551  }
552  }
553  }
554  }
555  if( t == TQEvent::Show && receiver->isWidgetType())
556  {
557  TQWidget* w = TQT_TQWIDGET( receiver );
558 #if defined Q_WS_X11
559  if( w->isTopLevel() && !startupId().isEmpty() && !TQT_TQSHOWEVENT(event)->spontaneous()) // TODO better done using window group leader?
560  KStartupInfo::setWindowStartupId( w->winId(), startupId());
561 #endif
562  if( w->isTopLevel() && !w->testWFlags( WX11BypassWM ) && !w->isPopup() && !event->spontaneous())
563  {
564  if( d->app_started_timer == NULL )
565  {
566  d->app_started_timer = new TQTimer( this, "app_started_timer" );
567  connect( d->app_started_timer, TQT_SIGNAL( timeout()), TQT_SLOT( checkAppStartedSlot()));
568  }
569  if( !d->app_started_timer->isActive())
570  d->app_started_timer->start( 0, true );
571  }
572  if( w->isTopLevel() && ( w->icon() == NULL || w->icon()->isNull()))
573  {
574  // icon() cannot be null pixmap, it'll be the "unknown" icon - so check if there is this application icon
575  static TQPixmap* ic = NULL;
576  if( ic == NULL )
577  ic = new TQPixmap( KGlobal::iconLoader()->loadIcon( iconName(),
578  KIcon::NoGroup, 0, KIcon::DefaultState, NULL, true ));
579  if( !ic->isNull())
580  {
581  w->setIcon( *ic );
582 #if defined Q_WS_X11
583  KWin::setIcons( w->winId(), *ic, miniIcon());
584 #endif
585  }
586  }
587  }
588  return TQApplication::notify(receiver, event);
589 }
590 
591 void KApplication::checkAppStartedSlot()
592 {
593 #if defined Q_WS_X11
594  KStartupInfo::handleAutoAppStartedSending();
595 #endif
596 }
597 
598 // the help class for session management communication
599 static TQPtrList<KSessionManaged>* sessionClients()
600 {
601  static TQPtrList<KSessionManaged>* session_clients = 0L;
602  if ( !session_clients )
603  session_clients = new TQPtrList<KSessionManaged>;
604  return session_clients;
605 }
606 
607 /*
608  Auxiliary function to calculate a a session config name used for the
609  instance specific config object.
610  Syntax: "session/<appname>_<sessionId>"
611  */
612 TQString KApplication::sessionConfigName() const
613 {
614  TQString sessKey = sessionKey();
615  if ( sessKey.isEmpty() && !d->sessionKey.isEmpty() )
616  sessKey = d->sessionKey;
617  return TQString("session/%1_%2_%3").arg(name()).arg(sessionId()).arg(sessKey);
618 }
619 
620 #ifdef Q_WS_X11
621 static SmcConn mySmcConnection = 0;
622 static SmcConn tmpSmcConnection = 0;
623 #else
624 // FIXME(E): Implement for Qt Embedded
625 // Possibly "steal" XFree86's libSM?
626 #endif
627 static TQTime* smModificationTime = 0;
628 
629 KApplication::KApplication( int& argc, char** argv, const TQCString& rAppName,
630  bool allowStyles, bool GUIenabled, bool SMenabled ) :
631  TQApplication( argc, argv, GUIenabled, SMenabled ), KInstance(rAppName),
632 #ifdef Q_WS_X11
633  display(0L),
634  argb_visual(false),
635 #endif
636  d (new KApplicationPrivate())
637 {
638  aIconPixmap.pm.icon = 0L;
639  aIconPixmap.pm.miniIcon = 0L;
640  read_app_startup_id();
641  if (!GUIenabled)
642  allowStyles = false;
643  useStyles = allowStyles;
644  Q_ASSERT (!rAppName.isEmpty());
645  setName(rAppName);
646 
647  installSigpipeHandler();
648  KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
649  parseCommandLine( );
650  init(GUIenabled);
651  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
652 }
653 
654 // FIXME
655 // FOR BINARY COMPATIBILITY ONLY
656 // REMOVE WHEN PRACTICAL!
657 KApplication::KApplication( int& argc, char** argv, const TQCString& rAppName,
658  bool allowStyles, bool GUIenabled ) :
659  TQApplication( argc, argv, GUIenabled ), KInstance(rAppName),
660 #ifdef Q_WS_X11
661  display(0L),
662  argb_visual(false),
663 #endif
664  d (new KApplicationPrivate())
665 {
666  aIconPixmap.pm.icon = 0L;
667  aIconPixmap.pm.miniIcon = 0L;
668  read_app_startup_id();
669  if (!GUIenabled)
670  allowStyles = false;
671  useStyles = allowStyles;
672  Q_ASSERT (!rAppName.isEmpty());
673  setName(rAppName);
674 
675  installSigpipeHandler();
676  KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
677  parseCommandLine( );
678  init(GUIenabled);
679  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
680 }
681 
682 KApplication::KApplication( bool allowStyles, bool GUIenabled, bool SMenabled ) :
683 // TQApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(), TRUE ), // Qt4 requires that there always be a GUI
684  TQApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(), GUIenabled, SMenabled ), // We need to be able to run command line apps
685  KInstance( KCmdLineArgs::about),
686 #ifdef Q_WS_X11
687  display(0L),
688  argb_visual(false),
689 #endif
690  d (new KApplicationPrivate)
691 {
692  aIconPixmap.pm.icon = 0L;
693  aIconPixmap.pm.miniIcon = 0L;
694  read_app_startup_id();
695  if (!GUIenabled)
696  allowStyles = false;
697  useStyles = allowStyles;
698  setName( instanceName() );
699 
700  installSigpipeHandler();
701  parseCommandLine( );
702  init(GUIenabled);
703  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
704 }
705 
706 // FIXME
707 // FOR BINARY COMPATIBILITY ONLY
708 // REMOVE WHEN PRACTICAL!
709 KApplication::KApplication( bool allowStyles, bool GUIenabled ) :
710 // TQApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(), TRUE ), // Qt4 requires that there always be a GUI
711  TQApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(), GUIenabled ), // We need to be able to run command line apps
712  KInstance( KCmdLineArgs::about),
713 #ifdef Q_WS_X11
714  display(0L),
715  argb_visual(false),
716 #endif
717  d (new KApplicationPrivate)
718 {
719  aIconPixmap.pm.icon = 0L;
720  aIconPixmap.pm.miniIcon = 0L;
721  read_app_startup_id();
722  if (!GUIenabled)
723  allowStyles = false;
724  useStyles = allowStyles;
725  setName( instanceName() );
726 
727  installSigpipeHandler();
728  parseCommandLine( );
729  init(GUIenabled);
730  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
731 }
732 
733 #ifdef Q_WS_X11
734 KApplication::KApplication( Display *dpy, bool allowStyles ) :
735  TQApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
736  getX11RGBAVisual(dpy), getX11RGBAColormap(dpy) ),
737  KInstance( KCmdLineArgs::about), display(0L), d (new KApplicationPrivate)
738 {
739  aIconPixmap.pm.icon = 0L;
740  aIconPixmap.pm.miniIcon = 0L;
741  read_app_startup_id();
742  useStyles = allowStyles;
743  setName( instanceName() );
744  installSigpipeHandler();
745  parseCommandLine( );
746  init( true );
747  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
748 }
749 
750 KApplication::KApplication( Display *dpy, bool disable_argb, Qt::HANDLE visual, Qt::HANDLE colormap, bool allowStyles ) :
751  TQApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
752  disable_argb?visual:getX11RGBAVisual(dpy), disable_argb?colormap:getX11RGBAColormap(dpy) ),
753  KInstance( KCmdLineArgs::about), display(0L), d (new KApplicationPrivate)
754 {
755  aIconPixmap.pm.icon = 0L;
756  aIconPixmap.pm.miniIcon = 0L;
757  read_app_startup_id();
758  useStyles = allowStyles;
759  if (disable_argb) argb_visual = false;
760  setName( instanceName() );
761  installSigpipeHandler();
762  parseCommandLine( );
763  init( true );
764  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
765 }
766 
767 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
768  bool allowStyles ) :
769  TQApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
770  visual?visual:getX11RGBAVisual(dpy), colormap?colormap:getX11RGBAColormap(dpy) ),
771  KInstance( KCmdLineArgs::about), display(0L), d (new KApplicationPrivate)
772 {
773  if ((visual) && (colormap))
774  getX11RGBAInformation(dpy);
775  aIconPixmap.pm.icon = 0L;
776  aIconPixmap.pm.miniIcon = 0L;
777  read_app_startup_id();
778  useStyles = allowStyles;
779  setName( instanceName() );
780  installSigpipeHandler();
781  parseCommandLine( );
782  init( true );
783  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
784 }
785 
786 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
787  bool allowStyles, KInstance * _instance ) :
788  TQApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
789  visual?visual:getX11RGBAVisual(dpy), colormap?colormap:getX11RGBAColormap(dpy) ),
790  KInstance( _instance ), display(0L), d (new KApplicationPrivate)
791 {
792  if ((visual) && (colormap))
793  getX11RGBAInformation(dpy);
794  aIconPixmap.pm.icon = 0L;
795  aIconPixmap.pm.miniIcon = 0L;
796  read_app_startup_id();
797  useStyles = allowStyles;
798  setName( instanceName() );
799  installSigpipeHandler();
800  parseCommandLine( );
801  init( true );
802  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
803 }
804 #endif
805 
806 KApplication::KApplication( bool allowStyles, bool GUIenabled, KInstance* _instance ) :
807  TQApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
808  GUIenabled ),
809  KInstance( _instance ),
810 #ifdef Q_WS_X11
811  display(0L),
812 #endif
813  argb_visual(false),
814  d (new KApplicationPrivate)
815 {
816  aIconPixmap.pm.icon = 0L;
817  aIconPixmap.pm.miniIcon = 0L;
818  read_app_startup_id();
819  if (!GUIenabled)
820  allowStyles = false;
821  useStyles = allowStyles;
822  setName( instanceName() );
823 
824  installSigpipeHandler();
825  parseCommandLine( );
826  init(GUIenabled);
827  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
828 }
829 
830 #ifdef Q_WS_X11
831 KApplication::KApplication(Display *display, int& argc, char** argv, const TQCString& rAppName,
832  bool allowStyles, bool GUIenabled ) :
833  TQApplication( display ), KInstance(rAppName),
834  display(0L),
835  argb_visual(false),
836  d (new KApplicationPrivate())
837 {
838  aIconPixmap.pm.icon = 0L;
839  aIconPixmap.pm.miniIcon = 0L;
840  read_app_startup_id();
841  if (!GUIenabled)
842  allowStyles = false;
843  useStyles = allowStyles;
844 
845  Q_ASSERT (!rAppName.isEmpty());
846  setName(rAppName);
847 
848  installSigpipeHandler();
849  KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
850  parseCommandLine( );
851  init(GUIenabled);
852  d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
853 }
854 #endif
855 
856 int KApplication::xioErrhandler( Display* dpy )
857 {
858  if(kapp)
859  {
860  emit shutDown();
861 #ifdef Q_WS_X11
862  d->oldXIOErrorHandler( dpy );
863 #else
864  Q_UNUSED(dpy);
865 #endif
866  }
867  exit( 1 );
868  return 0;
869 }
870 
871 int KApplication::xErrhandler( Display* dpy, void* err_ )
872 { // no idea how to make forward decl. for XErrorEvent
873 #ifdef Q_WS_X11
874  XErrorEvent* err = static_cast< XErrorEvent* >( err_ );
875  if(kapp)
876  {
877  // add KDE specific stuff here
878  d->oldXErrorHandler( dpy, err );
879  }
880 #endif
881  return 0;
882 }
883 
884 void KApplication::iceIOErrorHandler( _IceConn *conn )
885 {
886  emit shutDown();
887 
888 #ifdef Q_WS_X11
889  if ( d->oldIceIOErrorHandler != NULL )
890  (*d->oldIceIOErrorHandler)( conn );
891 #endif
892  exit( 1 );
893 }
894 
895 class KDETranslator : public TQTranslator
896 {
897 public:
898  KDETranslator(TQObject *parent) : TQTranslator(parent, "kdetranslator") {}
899  virtual TQTranslatorMessage findMessage(const char* context,
900  const char *sourceText,
901  const char* message) const
902  {
903  TQTranslatorMessage res;
904  res.setTranslation(KGlobal::locale()->translateQt(context, sourceText, message));
905  return res;
906  }
907 };
908 
909 void KApplication::init(bool GUIenabled)
910 {
911  d->guiEnabled = GUIenabled;
912  if ((getuid() != geteuid()) ||
913  (getgid() != getegid()) )
914  {
915  // man permissions are not exploitable and better than
916  // world writable directories
917  struct group *man = getgrnam("man");
918  if ( !man || man->gr_gid != getegid() ){
919  fprintf(stderr, "The KDE libraries are not designed to run with suid privileges.\n");
920  ::exit(127);
921  }
922  }
923 
924  KProcessController::ref();
925 
926  (void) KClipboardSynchronizer::self();
927 
928  TQApplication::setDesktopSettingsAware( false );
929 
930  KApp = this;
931 
932 
933 #ifdef Q_WS_X11 //FIXME(E)
934  // create all required atoms in _one_ roundtrip to the X server
935  if ( GUIenabled ) {
936  const int max = 20;
937  Atom* atoms[max];
938  char* names[max];
939  Atom atoms_return[max];
940  int n = 0;
941 
942  atoms[n] = &kipcCommAtom;
943  names[n++] = (char *) "KIPC_COMM_ATOM";
944 
945  atoms[n] = &atom_DesktopWindow;
946  names[n++] = (char *) "KDE_DESKTOP_WINDOW";
947 
948  atoms[n] = &atom_NetSupported;
949  names[n++] = (char *) "_NET_SUPPORTED";
950 
951  XInternAtoms( qt_xdisplay(), names, n, false, atoms_return );
952 
953  for (int i = 0; i < n; i++ )
954  *atoms[i] = atoms_return[i];
955  }
956 #endif
957 
958  dcopAutoRegistration();
959  dcopClientPostInit();
960 
961  smw = 0;
962 
963  // Initial KIPC event mask.
964 #if defined Q_WS_X11
965  kipcEventMask = (1 << KIPC::StyleChanged) | (1 << KIPC::PaletteChanged) |
966  (1 << KIPC::FontChanged) | (1 << KIPC::BackgroundChanged) |
967  (1 << KIPC::ToolbarStyleChanged) | (1 << KIPC::SettingsChanged) |
968  (1 << KIPC::ClipboardConfigChanged) | (1 << KIPC::BlockShortcuts);
969 #endif
970 
971  // Trigger creation of locale.
972  (void) KGlobal::locale();
973 
974  KConfig* config = KGlobal::config();
975  d->actionRestrictions = config->hasGroup("KDE Action Restrictions" ) && !kde_kiosk_exception;
976  // For brain-dead configurations where the user's local config file is not writable.
977  // * We use kdialog to warn the user, so we better not generate warnings from
978  // kdialog itself.
979  // * Don't warn if we run with a read-only $HOME
980  TQCString readOnly = getenv("KDE_HOME_READONLY");
981  if (readOnly.isEmpty() && (tqstrcmp(name(), "kdialog") != 0))
982  {
983  KConfigGroupSaver saver(config, "KDE Action Restrictions");
984  if (config->readBoolEntry("warn_unwritable_config",true))
985  config->checkConfigFilesWritable(true);
986  }
987 
988  if (GUIenabled)
989  {
990 #ifdef Q_WS_X11
991  // this is important since we fork() to launch the help (Matthias)
992  fcntl(ConnectionNumber(qt_xdisplay()), F_SETFD, FD_CLOEXEC);
993  // set up the fancy (=robust and error ignoring ) KDE xio error handlers (Matthias)
994  d->oldXErrorHandler = XSetErrorHandler( kde_x_errhandler );
995  d->oldXIOErrorHandler = XSetIOErrorHandler( kde_xio_errhandler );
996 #endif
997 
998  connect( this, TQT_SIGNAL( aboutToQuit() ), this, TQT_SIGNAL( shutDown() ) );
999 
1000 #ifdef Q_WS_X11 //FIXME(E)
1001  display = desktop()->x11Display();
1002 #endif
1003 
1004  {
1005  TQStringList plugins = KGlobal::dirs()->resourceDirs( "qtplugins" );
1006  TQStringList::Iterator it = plugins.begin();
1007  while (it != plugins.end()) {
1008  addLibraryPath( *it );
1009  ++it;
1010  }
1011 
1012  }
1013  kdisplaySetStyle();
1014  kdisplaySetFont();
1015 // kdisplaySetPalette(); done by kdisplaySetStyle
1016  propagateSettings(SETTINGS_QT);
1017 
1018  // Set default mime-source factory
1019  // XXX: This is a hack. Make our factory the default factory, but add the
1020  // previous default factory to the list of factories. Why? When the default
1021  // factory can't resolve something, it iterates in the list of factories.
1022  // But it TQWhatsThis only uses the default factory. So if there was already
1023  // a default factory (which happens when using an image library using uic),
1024  // we prefer KDE's factory and so we put that old default factory in the
1025  // list and use KDE as the default. This may speed up things as well.
1026  TQMimeSourceFactory* oldDefaultFactory = TQMimeSourceFactory::takeDefaultFactory();
1027  TQMimeSourceFactory::setDefaultFactory( mimeSourceFactory() );
1028  if ( oldDefaultFactory ) {
1029  TQMimeSourceFactory::addFactory( oldDefaultFactory );
1030  }
1031 
1032  d->checkAccelerators = new KCheckAccelerators( TQT_TQOBJECT(this) );
1033  }
1034 
1035 #ifdef Q_WS_MACX
1036  if (GUIenabled) {
1037  TQPixmap pixmap = KGlobal::iconLoader()->loadIcon( KCmdLineArgs::appName(),
1038  KIcon::NoGroup, KIcon::SizeLarge, KIcon::DefaultState, 0L, false );
1039  if (!pixmap.isNull()) {
1040  TQImage i = pixmap.convertToImage().convertDepth(32).smoothScale(40, 40);
1041  for(int y = 0; y < i.height(); y++) {
1042  uchar *l = i.scanLine(y);
1043  for(int x = 0; x < i.width(); x+=4)
1044  *(l+x) = 255;
1045  }
1046  CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
1047  CGDataProviderRef dp = CGDataProviderCreateWithData(NULL,
1048  i.bits(), i.numBytes(), NULL);
1049  CGImageRef ir = CGImageCreate(i.width(), i.height(), 8, 32, i.bytesPerLine(),
1050  cs, kCGImageAlphaNoneSkipFirst, dp,
1051  0, 0, kCGRenderingIntentDefault);
1052  //cleanup
1053  SetApplicationDockTileImage(ir);
1054  CGImageRelease(ir);
1055  CGColorSpaceRelease(cs);
1056  CGDataProviderRelease(dp);
1057  }
1058  }
1059 #endif
1060 
1061 
1062  // save and restore the RTL setting, as installTranslator calls qt_detectRTLLanguage,
1063  // which makes it impossible to use the -reverse cmdline switch with KDE apps
1064  bool rtl = reverseLayout();
1065  installTranslator(new KDETranslator(TQT_TQOBJECT(this)));
1066  setReverseLayout( rtl );
1067  if (i18n( "_: Dear Translator! Translate this string to the string 'LTR' in "
1068  "left-to-right languages (as english) or to 'RTL' in right-to-left "
1069  "languages (such as Hebrew and Arabic) to get proper widget layout." ) == "RTL")
1070  setReverseLayout( !rtl );
1071 
1072  // install appdata resource type
1073  KGlobal::dirs()->addResourceType("appdata", KStandardDirs::kde_default("data")
1074  + TQString::fromLatin1(name()) + '/');
1075  pSessionConfig = 0L;
1076  bSessionManagement = true;
1077 
1078 #ifdef Q_WS_X11
1079  // register a communication window for desktop changes (Matthias)
1080  if (GUIenabled && kde_have_kipc )
1081  {
1082  smw = new TQWidget(0,0);
1083  long data = 1;
1084  XChangeProperty(qt_xdisplay(), smw->winId(),
1085  atom_DesktopWindow, atom_DesktopWindow,
1086  32, PropModeReplace, (unsigned char *)&data, 1);
1087  }
1088  d->oldIceIOErrorHandler = IceSetIOErrorHandler( kde_ice_ioerrorhandler );
1089 #elif defined(Q_WS_WIN)
1090  KApplication_init_windows(GUIenabled);
1091 #else
1092  // FIXME(E): Implement for Qt Embedded
1093 #endif
1094 }
1095 
1096 static int my_system (const char *command) {
1097  int pid, status;
1098 
1099  pid = fork();
1100  if (pid == -1)
1101  return -1;
1102  if (pid == 0) {
1103  const char* shell = "/bin/sh";
1104  execl(shell, shell, "-c", command, (void *)0);
1105  ::_exit(127);
1106  }
1107  do {
1108  if (waitpid(pid, &status, 0) == -1) {
1109  if (errno != EINTR)
1110  return -1;
1111  } else
1112  return status;
1113  } while(1);
1114 }
1115 
1116 
1117 DCOPClient *KApplication::dcopClient()
1118 {
1119  if (s_DCOPClient)
1120  return s_DCOPClient;
1121 
1122  s_DCOPClient = new DCOPClient();
1123  KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
1124  if (args && args->isSet("dcopserver"))
1125  {
1126  s_DCOPClient->setServerAddress( args->getOption("dcopserver"));
1127  }
1128  if( kapp ) {
1129  connect(s_DCOPClient, TQT_SIGNAL(attachFailed(const TQString &)),
1130  kapp, TQT_SLOT(dcopFailure(const TQString &)));
1131  connect(s_DCOPClient, TQT_SIGNAL(blockUserInput(bool) ),
1132  kapp, TQT_SLOT(dcopBlockUserInput(bool)) );
1133  }
1134  else
1135  s_dcopClientNeedsPostInit = true;
1136 
1137  DCOPClient::setMainClient( s_DCOPClient );
1138  return s_DCOPClient;
1139 }
1140 
1141 void KApplication::dcopClientPostInit()
1142 {
1143  if( s_dcopClientNeedsPostInit )
1144  {
1145  s_dcopClientNeedsPostInit = false;
1146  connect(s_DCOPClient, TQT_SIGNAL(blockUserInput(bool) ),
1147  TQT_SLOT(dcopBlockUserInput(bool)) );
1148  s_DCOPClient->bindToApp(); // Make sure we get events from the DCOPClient.
1149  }
1150 }
1151 
1152 void KApplication::dcopAutoRegistration()
1153 {
1154  if (autoDcopRegistration)
1155  {
1156  ( void ) dcopClient();
1157  if( dcopClient()->appId().isEmpty())
1158  dcopClient()->registerAs(name());
1159  }
1160 }
1161 
1162 void KApplication::disableAutoDcopRegistration()
1163 {
1164  autoDcopRegistration = false;
1165 }
1166 
1167 KConfig* KApplication::sessionConfig()
1168 {
1169  if (pSessionConfig)
1170  return pSessionConfig;
1171 
1172  // create an instance specific config object
1173  pSessionConfig = new KConfig( sessionConfigName(), false, false);
1174  return pSessionConfig;
1175 }
1176 
1177 void KApplication::ref()
1178 {
1179  d->refCount++;
1180  //kdDebug() << "[kdecore-kapplication] KApplication::ref() : refCount = " << d->refCount << endl;
1181 }
1182 
1183 void KApplication::deref()
1184 {
1185  d->refCount--;
1186  //kdDebug() << "[kdecore-kapplication] KApplication::deref() : refCount = " << d->refCount << endl;
1187  if ( d->refCount <= 0 )
1188  quit();
1189 }
1190 
1191 KSessionManaged::KSessionManaged()
1192 {
1193  sessionClients()->remove( this );
1194  sessionClients()->append( this );
1195 }
1196 
1197 KSessionManaged::~KSessionManaged()
1198 {
1199  sessionClients()->remove( this );
1200 }
1201 
1202 bool KSessionManaged::saveState(TQSessionManager&)
1203 {
1204  return true;
1205 }
1206 
1207 bool KSessionManaged::commitData(TQSessionManager&)
1208 {
1209  return true;
1210 }
1211 
1212 
1213 void KApplication::disableSessionManagement() {
1214  bSessionManagement = false;
1215 }
1216 
1217 void KApplication::enableSessionManagement() {
1218  bSessionManagement = true;
1219 #ifdef Q_WS_X11
1220  // Session management support in Qt/KDE is awfully broken.
1221  // If konqueror disables session management right after its startup,
1222  // and enables it later (preloading stuff), it won't be properly
1223  // saved on session shutdown.
1224  // I'm not actually sure why it doesn't work, but saveState()
1225  // doesn't seem to be called on session shutdown, possibly
1226  // because disabling session management after konqueror startup
1227  // disabled it somehow. Forcing saveState() here for this application
1228  // seems to fix it.
1229  if( mySmcConnection ) {
1230  SmcRequestSaveYourself( mySmcConnection, SmSaveLocal, False,
1231  SmInteractStyleAny,
1232  False, False );
1233 
1234  // flush the request
1235  IceFlush(SmcGetIceConnection(mySmcConnection));
1236  }
1237 #endif
1238 }
1239 
1240 
1241 bool KApplication::requestShutDown(
1242  ShutdownConfirm confirm, ShutdownType sdtype, ShutdownMode sdmode )
1243 {
1244 #ifdef Q_WS_X11
1245  TQApplication::syncX();
1246  /* use ksmserver's dcop interface if necessary */
1247  if ( confirm == ShutdownConfirmYes ||
1248  sdtype != ShutdownTypeDefault ||
1249  sdmode != ShutdownModeDefault )
1250  {
1251  TQByteArray data;
1252  TQDataStream arg(data, IO_WriteOnly);
1253  arg << (int)confirm << (int)sdtype << (int)sdmode;
1254  return dcopClient()->send( "ksmserver", "ksmserver",
1255  "logout(int,int,int)", data );
1256  }
1257 
1258  if ( mySmcConnection ) {
1259  // we already have a connection to the session manager, use it.
1260  SmcRequestSaveYourself( mySmcConnection, SmSaveBoth, True,
1261  SmInteractStyleAny,
1262  confirm == ShutdownConfirmNo, True );
1263 
1264  // flush the request
1265  IceFlush(SmcGetIceConnection(mySmcConnection));
1266  return true;
1267  }
1268 
1269  // open a temporary connection, if possible
1270 
1271  propagateSessionManager();
1272  TQCString smEnv = ::getenv("SESSION_MANAGER");
1273  if (smEnv.isEmpty())
1274  return false;
1275 
1276  if (! tmpSmcConnection) {
1277  char cerror[256];
1278  char* myId = 0;
1279  char* prevId = 0;
1280  SmcCallbacks cb;
1281  tmpSmcConnection = SmcOpenConnection( 0, 0, 1, 0,
1282  0, &cb,
1283  prevId,
1284  &myId,
1285  255,
1286  cerror );
1287  ::free( myId ); // it was allocated by C
1288  if (!tmpSmcConnection )
1289  return false;
1290  }
1291 
1292  SmcRequestSaveYourself( tmpSmcConnection, SmSaveBoth, True,
1293  SmInteractStyleAny, False, True );
1294 
1295  // flush the request
1296  IceFlush(SmcGetIceConnection(tmpSmcConnection));
1297  return true;
1298 #else
1299  // FIXME(E): Implement for Qt Embedded
1300  return false;
1301 #endif
1302 }
1303 
1304 void KApplication::propagateSessionManager()
1305 {
1306 #ifdef Q_WS_X11
1307  TQCString fName = TQFile::encodeName(locateLocal("socket", "KSMserver"));
1308  TQCString display = ::getenv(DISPLAY);
1309  // strip the screen number from the display
1310  display.replace(TQRegExp("\\.[0-9]+$"), "");
1311  int i;
1312  while( (i = display.find(':')) >= 0)
1313  display[i] = '_';
1314 
1315  fName += "_"+display;
1316  TQCString smEnv = ::getenv("SESSION_MANAGER");
1317  bool check = smEnv.isEmpty();
1318  if ( !check && smModificationTime ) {
1319  TQFileInfo info( fName );
1320  TQTime current = TQT_TQTIME_OBJECT(info.lastModified().time());
1321  check = current > *smModificationTime;
1322  }
1323  if ( check ) {
1324  delete smModificationTime;
1325  TQFile f( fName );
1326  if ( !f.open( IO_ReadOnly ) )
1327  return;
1328  TQFileInfo info ( f );
1329  smModificationTime = new TQTime( TQT_TQTIME_OBJECT(info.lastModified().time()) );
1330  TQTextStream t(&f);
1331  t.setEncoding( TQTextStream::Latin1 );
1332  TQString s = t.readLine();
1333  f.close();
1334  ::setenv( "SESSION_MANAGER", s.latin1(), true );
1335  }
1336 #endif
1337 }
1338 
1339 void KApplication::commitData( TQSessionManager& sm )
1340 {
1341  d->session_save = true;
1342  bool canceled = false;
1343  for (KSessionManaged* it = sessionClients()->first();
1344  it && !canceled;
1345  it = sessionClients()->next() ) {
1346  canceled = !it->commitData( sm );
1347  }
1348  if ( canceled )
1349  sm.cancel();
1350 
1351  if ( sm.allowsInteraction() ) {
1352  TQWidgetList done;
1353  TQWidgetList *list = TQApplication::topLevelWidgets();
1354  bool canceled = false;
1355  TQWidget* w = list->first();
1356  while ( !canceled && w ) {
1357  if ( !w->testWState( WState_ForceHide ) && !w->inherits("KMainWindow") ) {
1358  TQCloseEvent e;
1359  sendEvent( w, &e );
1360  canceled = !e.isAccepted();
1361  if ( !canceled )
1362  done.append( w );
1363  delete list; // one never knows...
1364  list = TQApplication::topLevelWidgets();
1365  w = list->first();
1366  } else {
1367  w = list->next();
1368  }
1369  while ( w && done.containsRef( w ) )
1370  w = list->next();
1371  }
1372  delete list;
1373  }
1374 
1375 
1376  if ( !bSessionManagement )
1377  sm.setRestartHint( TQSessionManager::RestartNever );
1378  else
1379  sm.setRestartHint( TQSessionManager::RestartIfRunning );
1380  d->session_save = false;
1381 }
1382 
1383 static void checkRestartVersion( TQSessionManager& sm )
1384 {
1385  Display* dpy = qt_xdisplay();
1386  Atom type;
1387  int format;
1388  unsigned long nitems, after;
1389  unsigned char* data;
1390  if( XGetWindowProperty( dpy, RootWindow( dpy, 0 ), XInternAtom( dpy, "TDE_FULL_SESSION", False ),
1391  0, 1, False, AnyPropertyType, &type, &format, &nitems, &after, &data ) == Success ) {
1392  if( data != NULL )
1393  XFree( data );
1394  if( type == XA_STRING && format == 8 ) { // session set, check if KDE_SESSION_VERSION is not set (meaning KDE3)
1395  if( XGetWindowProperty( dpy, RootWindow( dpy, 0 ), XInternAtom( dpy, "KDE_SESSION_VERSION", False ),
1396  0, 1, False, AnyPropertyType, &type, &format, &nitems, &after, &data ) == Success ) {
1397  if( data != NULL )
1398  XFree( data ); // KDE4 or newer
1399  if( type == None )
1400  return; // we run in our native session, no need to wrap
1401  } else {
1402  return; // we run in our native session, no need to wrap
1403  }
1404  }
1405  }
1406  TQString wrapper = KStandardDirs::findExe( "trinity" );
1407  TQStringList restartCommand = sm.restartCommand();
1408  restartCommand.prepend( wrapper );
1409  sm.setRestartCommand( restartCommand );
1410 }
1411 
1412 void KApplication::saveState( TQSessionManager& sm )
1413 {
1414  d->session_save = true;
1415 #ifdef Q_WS_X11
1416  static bool firstTime = true;
1417  mySmcConnection = (SmcConn) sm.handle();
1418 
1419  if ( !bSessionManagement ) {
1420  sm.setRestartHint( TQSessionManager::RestartNever );
1421  d->session_save = false;
1422  return;
1423  }
1424  else
1425  sm.setRestartHint( TQSessionManager::RestartIfRunning );
1426 
1427  if ( firstTime ) {
1428  firstTime = false;
1429  d->session_save = false;
1430  return; // no need to save the state.
1431  }
1432 
1433  // remove former session config if still existing, we want a new
1434  // and fresh one. Note that we do not delete the config file here,
1435  // this is done by the session manager when it executes the
1436  // discard commands. In fact it would be harmful to remove the
1437  // file here, as the session might be stored under a different
1438  // name, meaning the user still might need it eventually.
1439  if ( pSessionConfig ) {
1440  delete pSessionConfig;
1441  pSessionConfig = 0;
1442  }
1443 
1444  // tell the session manager about our new lifecycle
1445  TQStringList restartCommand = sm.restartCommand();
1446 
1447  TQCString multiHead = getenv("KDE_MULTIHEAD");
1448  if (multiHead.lower() == "true") {
1449  // if multihead is enabled, we save our -display argument so that
1450  // we are restored onto the correct head... one problem with this
1451  // is that the display is hard coded, which means we cannot restore
1452  // to a different display (ie. if we are in a university lab and try,
1453  // try to restore a multihead session, our apps could be started on
1454  // someone else's display instead of our own)
1455  TQCString displayname = getenv(DISPLAY);
1456  if (! displayname.isNull()) {
1457  // only store the command if we actually have a DISPLAY
1458  // environment variable
1459  restartCommand.append("-display");
1460  restartCommand.append(displayname);
1461  }
1462  sm.setRestartCommand( restartCommand );
1463  }
1464 
1465  checkRestartVersion( sm );
1466 
1467  // finally: do session management
1468  emit saveYourself(); // for compatibility
1469  bool canceled = false;
1470  for (KSessionManaged* it = sessionClients()->first();
1471  it && !canceled;
1472  it = sessionClients()->next() ) {
1473  canceled = !it->saveState( sm );
1474  }
1475 
1476  // if we created a new session config object, register a proper discard command
1477  if ( pSessionConfig ) {
1478  pSessionConfig->sync();
1479  TQStringList discard;
1480  discard << "rm" << locateLocal("config", sessionConfigName());
1481  sm.setDiscardCommand( discard );
1482  } else {
1483  sm.setDiscardCommand( TQStringList("") );
1484  }
1485 
1486  if ( canceled )
1487  sm.cancel();
1488 #else
1489  // FIXME(E): Implement for Qt Embedded
1490 #endif
1491  d->session_save = false;
1492 }
1493 
1494 bool KApplication::sessionSaving() const
1495 {
1496  return d->session_save;
1497 }
1498 
1499 void KApplication::startKdeinit()
1500 {
1501 #ifndef Q_WS_WIN //TODO
1502  KInstance inst( "startkdeinitlock" );
1503  KLockFile lock( locateLocal( "tmp", "startkdeinitlock", &inst ));
1504  if( lock.lock( KLockFile::LockNoBlock ) != KLockFile::LockOK ) {
1505  lock.lock();
1506  DCOPClient cl;
1507  if( cl.attach())
1508  return; // whoever held the lock has already started dcopserver
1509  }
1510  // Try to launch kdeinit.
1511  TQString srv = KStandardDirs::findExe(TQString::fromLatin1("kdeinit"));
1512  if (srv.isEmpty())
1513  srv = KStandardDirs::findExe(TQString::fromLatin1("kdeinit"), KGlobal::dirs()->kfsstnd_defaultbindir());
1514  if (srv.isEmpty())
1515  return;
1516  if (kapp && (Tty != kapp->type()))
1517  setOverrideCursor( tqwaitCursor );
1518  my_system(TQFile::encodeName(srv)+" --suicide"+" --new-startup");
1519  if (kapp && (Tty != kapp->type()))
1520  restoreOverrideCursor();
1521 #endif
1522 }
1523 
1524 void KApplication::dcopFailure(const TQString &msg)
1525 {
1526  static int failureCount = 0;
1527  failureCount++;
1528  if (failureCount == 1)
1529  {
1530  startKdeinit();
1531  return;
1532  }
1533  if (failureCount == 2)
1534  {
1535 #ifdef Q_WS_WIN
1536  KGlobal::config()->setGroup("General");
1537  if (KGlobal::config()->readBoolEntry("ignoreDCOPFailures", false))
1538  return;
1539 #endif
1540  TQString msgStr(i18n("There was an error setting up inter-process "
1541  "communications for KDE. The message returned "
1542  "by the system was:\n\n"));
1543  msgStr += msg;
1544  msgStr += i18n("\n\nPlease check that the \"dcopserver\" program is running!");
1545 
1546  if (Tty != kapp->type())
1547  {
1548  TQMessageBox::critical
1549  (
1550  kapp->mainWidget(),
1551  i18n("DCOP communications error (%1)").arg(kapp->caption()),
1552  msgStr,
1553  i18n("&OK")
1554  );
1555  }
1556  else
1557  {
1558  fprintf(stderr, "%s\n", msgStr.local8Bit().data());
1559  }
1560 
1561  return;
1562  }
1563 }
1564 
1565 static const KCmdLineOptions qt_options[] =
1566 {
1567  //FIXME: Check if other options are specific to Qt/X11
1568 #ifdef Q_WS_X11
1569  { "display <displayname>", I18N_NOOP("Use the X-server display 'displayname'"), 0},
1570 #else
1571  { "display <displayname>", I18N_NOOP("Use the QWS display 'displayname'"), 0},
1572 #endif
1573  { "session <sessionId>", I18N_NOOP("Restore the application for the given 'sessionId'"), 0},
1574  { "cmap", I18N_NOOP("Causes the application to install a private color\nmap on an 8-bit display"), 0},
1575  { "ncols <count>", I18N_NOOP("Limits the number of colors allocated in the color\ncube on an 8-bit display, if the application is\nusing the TQApplication::ManyColor color\nspecification"), 0},
1576  { "nograb", I18N_NOOP("tells Qt to never grab the mouse or the keyboard"), 0},
1577  { "dograb", I18N_NOOP("running under a debugger can cause an implicit\n-nograb, use -dograb to override"), 0},
1578  { "sync", I18N_NOOP("switches to synchronous mode for debugging"), 0},
1579  { "fn", 0, 0},
1580  { "font <fontname>", I18N_NOOP("defines the application font"), 0},
1581  { "bg", 0, 0},
1582  { "background <color>", I18N_NOOP("sets the default background color and an\napplication palette (light and dark shades are\ncalculated)"), 0},
1583  { "fg", 0, 0},
1584  { "foreground <color>", I18N_NOOP("sets the default foreground color"), 0},
1585  { "btn", 0, 0},
1586  { "button <color>", I18N_NOOP("sets the default button color"), 0},
1587  { "name <name>", I18N_NOOP("sets the application name"), 0},
1588  { "title <title>", I18N_NOOP("sets the application title (caption)"), 0},
1589 #ifdef Q_WS_X11
1590  { "visual TrueColor", I18N_NOOP("forces the application to use a TrueColor visual on\nan 8-bit display"), 0},
1591  { "inputstyle <inputstyle>", I18N_NOOP("sets XIM (X Input Method) input style. Possible\nvalues are onthespot, overthespot, offthespot and\nroot"), 0 },
1592  { "im <XIM server>", I18N_NOOP("set XIM server"),0},
1593  { "noxim", I18N_NOOP("disable XIM"), 0 },
1594 #endif
1595 #ifdef Q_WS_QWS
1596  { "qws", I18N_NOOP("forces the application to run as QWS Server"), 0},
1597 #endif
1598  { "reverse", I18N_NOOP("mirrors the whole layout of widgets"), 0},
1599  KCmdLineLastOption
1600 };
1601 
1602 static const KCmdLineOptions kde_options[] =
1603 {
1604  { "caption <caption>", I18N_NOOP("Use 'caption' as name in the titlebar"), 0},
1605  { "icon <icon>", I18N_NOOP("Use 'icon' as the application icon"), 0},
1606  { "miniicon <icon>", I18N_NOOP("Use 'icon' as the icon in the titlebar"), 0},
1607  { "config <filename>", I18N_NOOP("Use alternative configuration file"), 0},
1608  { "dcopserver <server>", I18N_NOOP("Use the DCOP Server specified by 'server'"), 0},
1609  { "nocrashhandler", I18N_NOOP("Disable crash handler, to get core dumps"), 0},
1610  { "waitforwm", I18N_NOOP("Waits for a WM_NET compatible windowmanager"), 0},
1611  { "style <style>", I18N_NOOP("sets the application GUI style"), 0},
1612  { "geometry <geometry>", I18N_NOOP("sets the client geometry of the main widget - see man X for the argument format"), 0},
1613  { "smkey <sessionKey>", 0, 0}, // this option is obsolete and exists only to allow smooth upgrades from sessions
1614  // saved under Qt 3.0.x -- Qt 3.1.x includes the session key now automatically in
1615  // the session id (Simon)
1616  KCmdLineLastOption
1617 };
1618 
1619 void
1620 KApplication::addCmdLineOptions()
1621 {
1622  KCmdLineArgs::addCmdLineOptions(qt_options, "Qt", "qt");
1623  KCmdLineArgs::addCmdLineOptions(kde_options, "KDE", "kde");
1624 }
1625 
1626 void KApplication::parseCommandLine( )
1627 {
1628  KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
1629 
1630  if ( !args ) return;
1631 
1632  if (args->isSet("config"))
1633  {
1634  TQString config = TQString::fromLocal8Bit(args->getOption("config"));
1635  setConfigName(config);
1636  }
1637 
1638  if (args->isSet("style"))
1639  {
1640 
1641  TQStringList plugins = KGlobal::dirs()->resourceDirs( "qtplugins" );
1642  TQStringList::Iterator itp = plugins.begin();
1643  while (itp != plugins.end()) {
1644  addLibraryPath( *itp );
1645  ++itp;
1646  }
1647 
1648  TQStringList styles = TQStyleFactory::keys();
1649  TQString reqStyle(args->getOption("style").lower());
1650 
1651  TQStringList list = libraryPaths();
1652  TQStringList::Iterator it = list.begin();
1653  while( it != list.end() ) {
1654  ++it;
1655  }
1656 
1657  for (TQStringList::ConstIterator it = styles.begin(); it != styles.end(); ++it) {
1658  if ((*it).lower() == reqStyle)
1659  {
1660  d->overrideStyle = *it;
1661  break;
1662  }
1663  }
1664 
1665  if (d->overrideStyle.isEmpty())
1666  fprintf(stderr, "%s", TQString(i18n("The style %1 was not found\n").arg(reqStyle)).local8Bit().data());
1667  }
1668 
1669  if (args->isSet("caption"))
1670  {
1671  aCaption = TQString::fromLocal8Bit(args->getOption("caption"));
1672  }
1673 
1674  if (args->isSet("miniicon"))
1675  {
1676  const char *tmp = args->getOption("miniicon");
1677  if (!aIconPixmap.pm.miniIcon) {
1678  aIconPixmap.pm.miniIcon = new TQPixmap;
1679  }
1680  *aIconPixmap.pm.miniIcon = SmallIcon(tmp);
1681  aMiniIconName = tmp;
1682  }
1683 
1684  if (args->isSet("icon"))
1685  {
1686  const char *tmp = args->getOption("icon");
1687  if (!aIconPixmap.pm.icon) {
1688  aIconPixmap.pm.icon = new TQPixmap;
1689  }
1690  *aIconPixmap.pm.icon = DesktopIcon( tmp );
1691  aIconName = tmp;
1692  if (!aIconPixmap.pm.miniIcon) {
1693  aIconPixmap.pm.miniIcon = new TQPixmap;
1694  }
1695  if (aIconPixmap.pm.miniIcon->isNull())
1696  {
1697  *aIconPixmap.pm.miniIcon = SmallIcon( tmp );
1698  aMiniIconName = tmp;
1699  }
1700  }
1701 
1702  bool nocrashhandler = (getenv("KDE_DEBUG") != NULL);
1703  if (!nocrashhandler && args->isSet("crashhandler"))
1704  {
1705  // set default crash handler / set emergency save function to nothing
1706  KCrash::setCrashHandler(KCrash::defaultCrashHandler);
1707  KCrash::setEmergencySaveFunction(NULL);
1708 
1709  KCrash::setApplicationName(TQString(args->appName()));
1710  }
1711 
1712 #ifdef Q_WS_X11
1713  if ( args->isSet( "waitforwm" ) ) {
1714  Atom type;
1715  (void) desktop(); // trigger desktop creation, we need PropertyNotify events for the root window
1716  int format;
1717  unsigned long length, after;
1718  unsigned char *data;
1719  while ( XGetWindowProperty( qt_xdisplay(), qt_xrootwin(), atom_NetSupported,
1720  0, 1, false, AnyPropertyType, &type, &format,
1721  &length, &after, &data ) != Success || !length ) {
1722  if ( data )
1723  XFree( data );
1724  XEvent event;
1725  XWindowEvent( qt_xdisplay(), qt_xrootwin(), PropertyChangeMask, &event );
1726  }
1727  if ( data )
1728  XFree( data );
1729  }
1730 #else
1731  // FIXME(E): Implement for Qt Embedded
1732 #endif
1733 
1734  if (args->isSet("geometry"))
1735  {
1736  d->geometry_arg = args->getOption("geometry");
1737  }
1738 
1739  if (args->isSet("smkey"))
1740  {
1741  d->sessionKey = args->getOption("smkey");
1742  }
1743 
1744 }
1745 
1746 TQString KApplication::geometryArgument() const
1747 {
1748  return d->geometry_arg;
1749 }
1750 
1751 TQPixmap KApplication::icon() const
1752 {
1753  if( !aIconPixmap.pm.icon) {
1754  aIconPixmap.pm.icon = new TQPixmap;
1755  }
1756  if( aIconPixmap.pm.icon->isNull()) {
1757  *aIconPixmap.pm.icon = DesktopIcon( instanceName() );
1758  }
1759  return *aIconPixmap.pm.icon;
1760 }
1761 
1762 TQString KApplication::iconName() const
1763 {
1764  return aIconName.isNull() ? (TQString)instanceName() : aIconName;
1765 }
1766 
1767 TQPixmap KApplication::miniIcon() const
1768 {
1769  if (!aIconPixmap.pm.miniIcon) {
1770  aIconPixmap.pm.miniIcon = new TQPixmap;
1771  }
1772  if (aIconPixmap.pm.miniIcon->isNull()) {
1773  *aIconPixmap.pm.miniIcon = SmallIcon( instanceName() );
1774  }
1775  return *aIconPixmap.pm.miniIcon;
1776 }
1777 
1778 TQString KApplication::miniIconName() const
1779 {
1780  return aMiniIconName.isNull() ? (TQString)instanceName() : aMiniIconName;
1781 }
1782 
1783 extern void kDebugCleanup();
1784 
1785 KApplication::~KApplication()
1786 {
1787  delete aIconPixmap.pm.miniIcon;
1788  aIconPixmap.pm.miniIcon = 0L;
1789  delete aIconPixmap.pm.icon;
1790  aIconPixmap.pm.icon = 0L;
1791  delete d->m_KAppDCOPInterface;
1792 
1793  // First call the static deleters and then call KLibLoader::cleanup()
1794  // The static deleters may delete libraries for which they need KLibLoader.
1795  // KLibLoader will take care of the remaining ones.
1796  KGlobal::deleteStaticDeleters();
1797  KLibLoader::cleanUp();
1798 
1799  delete smw;
1800 
1801  // close down IPC
1802  delete s_DCOPClient;
1803  s_DCOPClient = 0L;
1804 
1805  KProcessController::deref();
1806 
1807 #ifdef Q_WS_X11
1808  if ( d->oldXErrorHandler != NULL )
1809  XSetErrorHandler( d->oldXErrorHandler );
1810  if ( d->oldXIOErrorHandler != NULL )
1811  XSetIOErrorHandler( d->oldXIOErrorHandler );
1812  if ( d->oldIceIOErrorHandler != NULL )
1813  IceSetIOErrorHandler( d->oldIceIOErrorHandler );
1814 #endif
1815 
1816  delete d;
1817  KApp = 0;
1818 
1819 #ifdef Q_WS_X11
1820  mySmcConnection = 0;
1821  delete smModificationTime;
1822  smModificationTime = 0;
1823 
1824  // close the temporary smc connection
1825  if (tmpSmcConnection) {
1826  SmcCloseConnection( tmpSmcConnection, 0, 0 );
1827  tmpSmcConnection = 0;
1828  }
1829 #else
1830  // FIXME(E): Implement for Qt Embedded
1831 #endif
1832 }
1833 
1834 
1835 #ifdef Q_WS_X11
1836 class KAppX11HackWidget: public QWidget
1837 {
1838 public:
1839  bool publicx11Event( XEvent * e) { return x11Event( e ); }
1840 };
1841 #endif
1842 
1843 #if defined(Q_WS_X11) && defined(COMPOSITE)
1844 bool KApplication::isCompositionManagerAvailable() {
1845  bool have_manager = false;
1846  const char *home;
1847  struct passwd *p;
1848  p = getpwuid(getuid());
1849  if (p)
1850  home = p->pw_dir;
1851  else
1852  home = getenv("HOME");
1853 
1854  char *filename;
1855  const char *configfile = "/.kompmgr.available";
1856  int n = strlen(home)+strlen(configfile)+1;
1857  filename = (char*)malloc(n*sizeof(char));
1858  memset(filename,0,n);
1859  strcat(filename, home);
1860  strcat(filename, configfile);
1861 
1862  // Now that we did all that by way of introduction...read the file!
1863  FILE *pFile;
1864  pFile = fopen(filename, "r");
1865  if (pFile) {
1866  have_manager = true;
1867  fclose(pFile);
1868  }
1869 
1870  free(filename);
1871  filename = NULL;
1872 
1873  return have_manager;
1874 }
1875 
1876 bool KApplication::detectCompositionManagerAvailable(bool force_available, bool available) {
1877  bool compositing_manager_available;
1878  if (force_available) {
1879  compositing_manager_available = available;
1880  }
1881  else {
1882  // See if compositing has been enabled
1883  KCmdLineArgs *qtargs = KCmdLineArgs::parsedArgs("qt");
1884  char *displayname = 0;
1885  if ( qtargs->isSet("display"))
1886  displayname = qtargs->getOption( "display" ).data();
1887 
1888  Display *dpy = XOpenDisplay( displayname );
1889 
1890  x11_composite_error_generated = false;
1891  compositing_manager_available = false;
1892  XSetErrorHandler(x11_error);
1893  if (!XQueryExtension (dpy, COMPOSITE_NAME, &composite_opcode, &composite_event, &composite_error)) {
1894  XSetErrorHandler(NULL);
1895  compositing_manager_available = false;
1896  }
1897  else {
1898  if (available) { // FIXME This variable does double duty to avoid breaking the ABI for R14.0. In reality it should be called perform_deep_check
1899  Window root_window = XDefaultRootWindow(dpy);
1900  XCompositeRedirectSubwindows(dpy, root_window, CompositeRedirectManual);
1901  XSync(dpy, false);
1902  if (x11_composite_error_generated == true) {
1903  compositing_manager_available = true;
1904  }
1905  else {
1906  XCompositeUnredirectSubwindows(dpy, root_window, CompositeRedirectManual);
1907  compositing_manager_available = false;
1908  }
1909  XSetErrorHandler(NULL);
1910  XCloseDisplay(dpy);
1911  }
1912  else {
1913  compositing_manager_available = true;
1914  }
1915  }
1916  }
1917 
1918  const char *home;
1919  struct passwd *p;
1920  p = getpwuid(getuid());
1921  if (p)
1922  home = p->pw_dir;
1923  else
1924  home = getenv("HOME");
1925 
1926  char *filename;
1927  const char *configfile = "/.kompmgr.available";
1928  int n = strlen(home)+strlen(configfile)+1;
1929  filename = (char*)malloc(n*sizeof(char));
1930  memset(filename,0,n);
1931  strcat(filename, home);
1932  strcat(filename, configfile);
1933 
1934  /* now that we did all that by way of introduction...create or remove the file! */
1935  if (compositing_manager_available) {
1936  FILE *pFile;
1937  char buffer[255];
1938  sprintf(buffer, "available");
1939  pFile = fopen(filename, "w");
1940  if (pFile) {
1941  fwrite(buffer,1,strlen(buffer), pFile);
1942  fclose(pFile);
1943  }
1944  }
1945  else {
1946  unlink(filename);
1947  }
1948 
1949  free(filename);
1950  filename = NULL;
1951 
1952  return compositing_manager_available;
1953 }
1954 
1955 Display* KApplication::openX11RGBADisplay() {
1956  KCmdLineArgs *qtargs = KCmdLineArgs::parsedArgs("qt");
1957  char *display = 0;
1958  if ( qtargs->isSet("display"))
1959  display = qtargs->getOption( "display" ).data();
1960 
1961  Display *dpy = XOpenDisplay( display );
1962  if ( !dpy ) {
1963  kdError() << "cannot connect to X server " << display << endl;
1964  exit( 1 );
1965  }
1966 
1967  return dpy;
1968 }
1969 
1970 Qt::HANDLE KApplication::getX11RGBAVisual(Display *dpy) {
1971  getX11RGBAInformation(dpy);
1972  if (KApplication::isCompositionManagerAvailable() == true) {
1973  return argb_x11_visual;
1974  }
1975  else {
1976  return (Qt::HANDLE)NULL;
1977  }
1978 }
1979 
1980 Qt::HANDLE KApplication::getX11RGBAColormap(Display *dpy) {
1981  getX11RGBAInformation(dpy);
1982  if (KApplication::isCompositionManagerAvailable() == true) {
1983  return argb_x11_colormap;
1984  }
1985  else {
1986  return (Qt::HANDLE)NULL;
1987  }
1988 }
1989 
1990 bool KApplication::isX11CompositionAvailable() {
1991  return (argb_visual & isCompositionManagerAvailable());
1992 }
1993 
1994 void KApplication::getX11RGBAInformation(Display *dpy) {
1995  if ( !dpy ) {
1996  argb_visual = false;
1997  return;
1998  }
1999 
2000  int screen = DefaultScreen( dpy );
2001  Colormap colormap = 0;
2002  Visual *visual = 0;
2003  int event_base, error_base;
2004 
2005  if ( XRenderQueryExtension( dpy, &event_base, &error_base ) ) {
2006  int nvi;
2007  XVisualInfo templ;
2008  templ.screen = screen;
2009  templ.depth = 32;
2010  templ.c_class = TrueColor;
2011  XVisualInfo *xvi = XGetVisualInfo( dpy, VisualScreenMask | VisualDepthMask
2012  | VisualClassMask, &templ, &nvi );
2013 
2014  for ( int i = 0; i < nvi; i++ ) {
2015  XRenderPictFormat *format = XRenderFindVisualFormat( dpy, xvi[i].visual );
2016  if ( format->type == PictTypeDirect && format->direct.alphaMask ) {
2017  visual = xvi[i].visual;
2018  colormap = XCreateColormap( dpy, RootWindow( dpy, screen ), visual, AllocNone );
2019  kdDebug() << "[kdecore-kapplication] Found visual with alpha support" << endl;
2020  argb_visual = true;
2021  break;
2022  }
2023  }
2024  }
2025 
2026  if( argb_visual ) {
2027  argb_x11_visual = Qt::HANDLE( visual );
2028  argb_x11_colormap = Qt::HANDLE( colormap );
2029  argb_visual = true;
2030  return;
2031  }
2032  argb_visual = false;
2033  return;
2034 }
2035 #else
2036 void KApplication::getX11RGBAInformation(Display *dpy) {
2037 }
2038 
2039 bool KApplication::isCompositionManagerAvailable() {
2040  return false;
2041 }
2042 
2043 bool KApplication::detectCompositionManagerAvailable(bool force_available, bool available) {
2044  const char *home;
2045  struct passwd *p;
2046  p = getpwuid(getuid());
2047  if (p)
2048  home = p->pw_dir;
2049  else
2050  home = getenv("HOME");
2051 
2052  char *filename;
2053  const char *configfile = "/.kompmgr.available";
2054  int n = strlen(home)+strlen(configfile)+1;
2055  filename = (char*)malloc(n*sizeof(char));
2056  memset(filename,0,n);
2057  strcat(filename, home);
2058  strcat(filename, configfile);
2059 
2060  /* now that we did all that by way of introduction...create or remove the file! */
2061  if (force_available) {
2062  FILE *pFile;
2063  char buffer[255];
2064  sprintf(buffer, "available");
2065  pFile = fopen(filename, "w");
2066  if (pFile) {
2067  fwrite(buffer,1,strlen(buffer), pFile);
2068  fclose(pFile);
2069  }
2070  }
2071  else {
2072  unlink(filename);
2073  }
2074 
2075  free(filename);
2076  filename = NULL;
2077 
2078  return false;
2079 }
2080 
2081 Display* KApplication::openX11RGBADisplay() {
2082  return 0;
2083 }
2084 
2085 Qt::HANDLE KApplication::getX11RGBAVisual(Display *dpy) {
2086  return 0;
2087 }
2088 
2089 Qt::HANDLE KApplication::getX11RGBAColormap(Display *dpy) {
2090  return 0;
2091 }
2092 
2093 bool KApplication::isX11CompositionAvailable() {
2094  return false;
2095 }
2096 #endif
2097 
2098 static bool kapp_block_user_input = false;
2099 
2100 void KApplication::dcopBlockUserInput( bool b )
2101 {
2102  kapp_block_user_input = b;
2103 }
2104 
2105 #ifdef Q_WS_X11
2106 bool KApplication::x11EventFilter( XEvent *_event )
2107 {
2108  if ( kapp_block_user_input ) {
2109  switch ( _event->type ) {
2110  case ButtonPress:
2111  case ButtonRelease:
2112  case XKeyPress:
2113  case XKeyRelease:
2114  case MotionNotify:
2115  case EnterNotify:
2116  case LeaveNotify:
2117  return true;
2118  default:
2119  break;
2120  }
2121  }
2122 
2123  if (x11Filter) {
2124  for (TQWidget *w=x11Filter->first(); w; w=x11Filter->next()) {
2125  if (((KAppX11HackWidget*) w)->publicx11Event(_event))
2126  return true;
2127  }
2128  }
2129 
2130  if ((_event->type == ClientMessage) &&
2131  (_event->xclient.message_type == kipcCommAtom))
2132  {
2133  XClientMessageEvent *cme = (XClientMessageEvent *) _event;
2134 
2135  int id = cme->data.l[0];
2136  int arg = cme->data.l[1];
2137  if ((id < 32) && (kipcEventMask & (1 << id)))
2138  {
2139  switch (id)
2140  {
2141  case KIPC::StyleChanged:
2142  KGlobal::config()->reparseConfiguration();
2143  kdisplaySetStyle();
2144  break;
2145 
2146  case KIPC::ToolbarStyleChanged:
2147  KGlobal::config()->reparseConfiguration();
2148  if (useStyles)
2149  emit toolbarAppearanceChanged(arg);
2150  break;
2151 
2152  case KIPC::PaletteChanged:
2153  KGlobal::config()->reparseConfiguration();
2154  kdisplaySetPalette();
2155  break;
2156 
2157  case KIPC::FontChanged:
2158  KGlobal::config()->reparseConfiguration();
2159  KGlobalSettings::rereadFontSettings();
2160  kdisplaySetFont();
2161  break;
2162 
2163  case KIPC::BackgroundChanged:
2164  emit backgroundChanged(arg);
2165  break;
2166 
2167  case KIPC::SettingsChanged:
2168  KGlobal::config()->reparseConfiguration();
2169  if (arg == SETTINGS_PATHS)
2170  KGlobalSettings::rereadPathSettings();
2171  else if (arg == SETTINGS_MOUSE)
2172  KGlobalSettings::rereadMouseSettings();
2173  propagateSettings((SettingsCategory)arg);
2174  break;
2175 
2176  case KIPC::IconChanged:
2177  TQPixmapCache::clear();
2178  KGlobal::config()->reparseConfiguration();
2179  KGlobal::instance()->newIconLoader();
2180  emit updateIconLoaders();
2181  emit iconChanged(arg);
2182  break;
2183 
2184  case KIPC::ClipboardConfigChanged:
2185  KClipboardSynchronizer::newConfiguration(arg);
2186  break;
2187 
2188  case KIPC::BlockShortcuts:
2189  KGlobalAccel::blockShortcuts(arg);
2190  emit kipcMessage(id, arg); // some apps may do additional things
2191  break;
2192  }
2193  }
2194  else if (id >= 32)
2195  {
2196  emit kipcMessage(id, arg);
2197  }
2198  return true;
2199  }
2200  return false;
2201 }
2202 #endif // Q_WS_X11
2203 
2204 void KApplication::updateUserTimestamp( unsigned long time )
2205 {
2206 #if defined Q_WS_X11
2207  Display *display = qt_xdisplay();
2208  if (!display) {
2209  return;
2210  }
2211  if( time == 0 )
2212  { // get current X timestamp
2213  Window w = XCreateSimpleWindow( display, qt_xrootwin(), 0, 0, 1, 1, 0, 0, 0 );
2214  XSelectInput( qt_xdisplay(), w, PropertyChangeMask );
2215  unsigned char data[ 1 ];
2216  XChangeProperty( display, w, XA_ATOM, XA_ATOM, 8, PropModeAppend, data, 1 );
2217  XEvent ev;
2218  XWindowEvent( display, w, PropertyChangeMask, &ev );
2219  time = ev.xproperty.time;
2220  XDestroyWindow( display, w );
2221  }
2222  if( GET_QT_X_USER_TIME() == 0
2223  || NET::timestampCompare( time, GET_QT_X_USER_TIME() ) > 0 ) // check time > qt_x_user_time
2224  SET_QT_X_USER_TIME(time);
2225 #endif
2226 }
2227 
2228 unsigned long KApplication::userTimestamp() const
2229 {
2230 #if defined Q_WS_X11
2231  return GET_QT_X_USER_TIME();
2232 #else
2233  return 0;
2234 #endif
2235 }
2236 
2237 void KApplication::updateRemoteUserTimestamp( const TQCString& dcopId, unsigned long time )
2238 {
2239 #if defined Q_WS_X11
2240  if( time == 0 )
2241  time = GET_QT_X_USER_TIME();
2242  DCOPRef( dcopId, "MainApplication-Interface" ).call( "updateUserTimestamp", time );
2243 #endif
2244 }
2245 
2246 void KApplication::invokeEditSlot( const char *slot )
2247 {
2248  TQObject *object = TQT_TQOBJECT(focusWidget());
2249  if( !object )
2250  return;
2251 
2252  TQMetaObject *meta = object->metaObject();
2253 
2254  int idx = meta->findSlot( slot + 1, true );
2255  if( idx < 0 )
2256  return;
2257 
2258  object->qt_invoke( idx, 0 );
2259 }
2260 
2261 void KApplication::addKipcEventMask(int id)
2262 {
2263  if (id >= 32)
2264  {
2265  kdDebug(101) << "[kdecore-kapplication] Cannot use KIPC event mask for message IDs >= 32\n";
2266  return;
2267  }
2268  kipcEventMask |= (1 << id);
2269 }
2270 
2271 void KApplication::removeKipcEventMask(int id)
2272 {
2273  if (id >= 32)
2274  {
2275  kdDebug(101) << "[kdecore-kapplication] Cannot use KIPC event mask for message IDs >= 32\n";
2276  return;
2277  }
2278  kipcEventMask &= ~(1 << id);
2279 }
2280 
2281 void KApplication::enableStyles()
2282 {
2283  if (!useStyles)
2284  {
2285  useStyles = true;
2286  applyGUIStyle();
2287  }
2288 }
2289 
2290 void KApplication::disableStyles()
2291 {
2292  useStyles = false;
2293 }
2294 
2295 void KApplication::applyGUIStyle()
2296 {
2297  if ( !useStyles ) return;
2298 
2299  KConfigGroup pConfig (KGlobal::config(), "General");
2300  TQString defaultStyle = KStyle::defaultStyle();
2301  TQString styleStr = pConfig.readEntry("widgetStyle", defaultStyle);
2302 
2303  if (d->overrideStyle.isEmpty()) {
2304  // ### add check whether we already use the correct style to return then
2305  // (workaround for Qt misbehavior to avoid double style initialization)
2306 
2307  TQStyle* sp = TQStyleFactory::create( styleStr );
2308 
2309  // If there is no default style available, try falling back any available style
2310  if ( !sp && styleStr != defaultStyle)
2311  sp = TQStyleFactory::create( defaultStyle );
2312  if ( !sp )
2313  sp = TQStyleFactory::create( *(TQStyleFactory::keys().begin()) );
2314  setStyle(sp);
2315  }
2316  else
2317  setStyle(d->overrideStyle);
2318  // Reread palette from config file.
2319  kdisplaySetPalette();
2320 }
2321 
2322 TQString KApplication::caption() const
2323 {
2324  // Caption set from command line ?
2325  if( !aCaption.isNull() )
2326  return aCaption;
2327  else
2328  // We have some about data ?
2329  if ( KGlobal::instance()->aboutData() )
2330  return KGlobal::instance()->aboutData()->programName();
2331  else
2332  // Last resort : application name
2333  return name();
2334 }
2335 
2336 
2337 //
2338 // 1999-09-20: Espen Sand
2339 // An attempt to simplify consistent captions.
2340 //
2341 TQString KApplication::makeStdCaption( const TQString &userCaption,
2342  bool withAppName, bool modified ) const
2343 {
2344  TQString s = userCaption.isEmpty() ? caption() : userCaption;
2345 
2346  // If the document is modified, add '[modified]'.
2347  if (modified)
2348  s += TQString::fromUtf8(" [") + i18n("modified") + TQString::fromUtf8("]");
2349 
2350  if ( !userCaption.isEmpty() ) {
2351  // Add the application name if:
2352  // User asked for it, it's not a duplication and the app name (caption()) is not empty
2353  if ( withAppName && !caption().isNull() && !userCaption.endsWith(caption()) )
2354  s += TQString::fromUtf8(" - ") + caption();
2355  }
2356 
2357  return s;
2358 }
2359 
2360 TQPalette KApplication::createApplicationPalette()
2361 {
2362  KConfig *config = KGlobal::config();
2363  KConfigGroupSaver saver( config, "General" );
2364  return createApplicationPalette( config, KGlobalSettings::contrast() );
2365 }
2366 
2367 TQPalette KApplication::createApplicationPalette( KConfig *config, int contrast_ )
2368 {
2369  TQColor trinity4Background( 239, 239, 239 );
2370  TQColor trinity4Blue( 103,141,178 );
2371 
2372  TQColor trinity4Button;
2373  if ( TQPixmap::defaultDepth() > 8 )
2374  trinity4Button.setRgb( 221, 223, 228 );
2375  else
2376  trinity4Button.setRgb( 220, 220, 220 );
2377 
2378  TQColor trinity4Link( 0, 0, 238 );
2379  TQColor trinity4VisitedLink( 82, 24, 139 );
2380 
2381  TQColor background = config->readColorEntry( "background", &trinity4Background );
2382  TQColor foreground = config->readColorEntry( "foreground", tqblackptr );
2383  TQColor button = config->readColorEntry( "buttonBackground", &trinity4Button );
2384  TQColor buttonText = config->readColorEntry( "buttonForeground", tqblackptr );
2385  TQColor highlight = config->readColorEntry( "selectBackground", &trinity4Blue );
2386  TQColor highlightedText = config->readColorEntry( "selectForeground", tqwhiteptr );
2387  TQColor base = config->readColorEntry( "windowBackground", tqwhiteptr );
2388  TQColor baseText = config->readColorEntry( "windowForeground", tqblackptr );
2389  TQColor link = config->readColorEntry( "linkColor", &trinity4Link );
2390  TQColor visitedLink = config->readColorEntry( "visitedLinkColor", &trinity4VisitedLink );
2391 
2392  int highlightVal, lowlightVal;
2393  highlightVal = 100 + (2*contrast_+4)*16/10;
2394  lowlightVal = 100 + (2*contrast_+4)*10;
2395 
2396  TQColor disfg = foreground;
2397 
2398  int h, s, v;
2399  disfg.hsv( &h, &s, &v );
2400  if (v > 128)
2401  // dark bg, light fg - need a darker disabled fg
2402  disfg = disfg.dark(lowlightVal);
2403  else if (disfg != Qt::black)
2404  // light bg, dark fg - need a lighter disabled fg - but only if !black
2405  disfg = disfg.light(highlightVal);
2406  else
2407  // black fg - use darkgray disabled fg
2408  disfg = Qt::darkGray;
2409 
2410 
2411  TQColorGroup disabledgrp(disfg, background,
2412  background.light(highlightVal),
2413  background.dark(lowlightVal),
2414  background.dark(120),
2415  background.dark(120), base);
2416 
2417  TQColorGroup colgrp(foreground, background, background.light(highlightVal),
2418  background.dark(lowlightVal),
2419  background.dark(120),
2420  baseText, base);
2421 
2422  int inlowlightVal = lowlightVal-25;
2423  if(inlowlightVal < 120)
2424  inlowlightVal = 120;
2425 
2426  colgrp.setColor(TQColorGroup::Highlight, highlight);
2427  colgrp.setColor(TQColorGroup::HighlightedText, highlightedText);
2428  colgrp.setColor(TQColorGroup::Button, button);
2429  colgrp.setColor(TQColorGroup::ButtonText, buttonText);
2430  colgrp.setColor(TQColorGroup::Midlight, background.light(110));
2431  colgrp.setColor(TQColorGroup::Link, link);
2432  colgrp.setColor(TQColorGroup::LinkVisited, visitedLink);
2433 
2434  disabledgrp.setColor(TQColorGroup::Button, button);
2435 
2436  TQColor disbtntext = buttonText;
2437  disbtntext.hsv( &h, &s, &v );
2438  if (v > 128)
2439  // dark button, light buttonText - need a darker disabled buttonText
2440  disbtntext = disbtntext.dark(lowlightVal);
2441  else if (disbtntext != Qt::black)
2442  // light buttonText, dark button - need a lighter disabled buttonText - but only if !black
2443  disbtntext = disbtntext.light(highlightVal);
2444  else
2445  // black button - use darkgray disabled buttonText
2446  disbtntext = Qt::darkGray;
2447 
2448  disabledgrp.setColor(TQColorGroup::ButtonText, disbtntext);
2449  disabledgrp.setColor(TQColorGroup::Midlight, background.light(110));
2450  disabledgrp.setColor(TQColorGroup::Highlight, highlight.dark(120));
2451  disabledgrp.setColor(TQColorGroup::Link, link);
2452  disabledgrp.setColor(TQColorGroup::LinkVisited, visitedLink);
2453 
2454  return TQPalette(colgrp, disabledgrp, colgrp);
2455 }
2456 
2457 
2458 void KApplication::kdisplaySetPalette()
2459 {
2460 #ifdef Q_WS_MACX
2461  //Can I have this on other platforms, please!? --Sam
2462  {
2463  KConfig *config = KGlobal::config();
2464  KConfigGroupSaver saver( config, "General" );
2465  bool do_not_set_palette = FALSE;
2466  if(config->readBoolEntry("nopaletteChange", &do_not_set_palette))
2467  return;
2468  }
2469 #endif
2470  TQApplication::setPalette( createApplicationPalette(), true);
2471  emit kdisplayPaletteChanged();
2472  emit appearanceChanged();
2473 }
2474 
2475 
2476 void KApplication::kdisplaySetFont()
2477 {
2478  TQApplication::setFont(KGlobalSettings::generalFont(), true);
2479  TQApplication::setFont(KGlobalSettings::menuFont(), true, TQMENUBAR_OBJECT_NAME_STRING);
2480  TQApplication::setFont(KGlobalSettings::menuFont(), true, TQPOPUPMENU_OBJECT_NAME_STRING);
2481  TQApplication::setFont(KGlobalSettings::menuFont(), true, "KPopupTitle");
2482 
2483  // "patch" standard TQStyleSheet to follow our fonts
2484  TQStyleSheet* sheet = TQStyleSheet::defaultSheet();
2485  sheet->item ("pre")->setFontFamily (KGlobalSettings::fixedFont().family());
2486  sheet->item ("code")->setFontFamily (KGlobalSettings::fixedFont().family());
2487  sheet->item ("tt")->setFontFamily (KGlobalSettings::fixedFont().family());
2488 
2489  emit kdisplayFontChanged();
2490  emit appearanceChanged();
2491 }
2492 
2493 
2494 void KApplication::kdisplaySetStyle()
2495 {
2496  if (useStyles)
2497  {
2498  applyGUIStyle();
2499  emit kdisplayStyleChanged();
2500  emit appearanceChanged();
2501  }
2502 }
2503 
2504 
2505 void KApplication::propagateSettings(SettingsCategory arg)
2506 {
2507  KConfigBase* config = KGlobal::config();
2508  KConfigGroupSaver saver( config, "KDE" );
2509 
2510 #ifdef QT_HAVE_MAX_IMAGE_SIZE
2511  TQSize maxImageSize(4096, 4096);
2512  maxImageSize = config->readSizeEntry("MaxImageSize", &maxImageSize);
2513  TQImage::setMaxImageSize(maxImageSize);
2514 #endif
2515 
2516  int num = config->readNumEntry("CursorBlinkRate", TQApplication::cursorFlashTime());
2517  if ((num != 0) && (num < 200))
2518  num = 200;
2519  if (num > 2000)
2520  num = 2000;
2521  TQApplication::setCursorFlashTime(num);
2522  num = config->readNumEntry("DoubleClickInterval", TQApplication::doubleClickInterval());
2523  TQApplication::setDoubleClickInterval(num);
2524  num = config->readNumEntry("StartDragTime", TQApplication::startDragTime());
2525  TQApplication::setStartDragTime(num);
2526  num = config->readNumEntry("StartDragDist", TQApplication::startDragDistance());
2527  TQApplication::setStartDragDistance(num);
2528  num = config->readNumEntry("WheelScrollLines", TQApplication::wheelScrollLines());
2529  TQApplication::setWheelScrollLines(num);
2530 
2531  bool b = config->readBoolEntry("EffectAnimateMenu", false);
2532  TQApplication::setEffectEnabled( Qt::UI_AnimateMenu, b);
2533  b = config->readBoolEntry("EffectFadeMenu", false);
2534  TQApplication::setEffectEnabled( Qt::UI_FadeMenu, b);
2535  b = config->readBoolEntry("EffectAnimateCombo", false);
2536  TQApplication::setEffectEnabled( Qt::UI_AnimateCombo, b);
2537  b = config->readBoolEntry("EffectAnimateTooltip", false);
2538  TQApplication::setEffectEnabled( Qt::UI_AnimateTooltip, b);
2539  b = config->readBoolEntry("EffectFadeTooltip", false);
2540  TQApplication::setEffectEnabled( Qt::UI_FadeTooltip, b);
2541  b = !config->readBoolEntry("EffectNoTooltip", false);
2542  TQToolTip::setGloballyEnabled( b );
2543 
2544  emit settingsChanged(arg);
2545 }
2546 
2547 void KApplication::installKDEPropertyMap()
2548 {
2549 #ifndef QT_NO_SQL
2550  static bool installed = false;
2551  if (installed) return;
2552  installed = true;
2559  // TQSqlPropertyMap takes ownership of the new default map.
2560  TQSqlPropertyMap *kdeMap = new TQSqlPropertyMap;
2561  kdeMap->insert( "KColorButton", "color" );
2562  kdeMap->insert( "KComboBox", "currentItem" );
2563  kdeMap->insert( "KDatePicker", "date" );
2564  kdeMap->insert( "KDateWidget", "date" );
2565  kdeMap->insert( "KDateTimeWidget", "dateTime" );
2566  kdeMap->insert( "KEditListBox", "items" );
2567  kdeMap->insert( "KFontCombo", "family" );
2568  kdeMap->insert( "KFontRequester", "font" );
2569  kdeMap->insert( "KFontChooser", "font" );
2570  kdeMap->insert( "KHistoryCombo", "currentItem" );
2571  kdeMap->insert( "KListBox", "currentItem" );
2572  kdeMap->insert( "KLineEdit", "text" );
2573  kdeMap->insert( "KRestrictedLine", "text" );
2574  kdeMap->insert( "KSqueezedTextLabel", "text" );
2575  kdeMap->insert( "KTextBrowser", "source" );
2576  kdeMap->insert( "KTextEdit", "text" );
2577  kdeMap->insert( "KURLRequester", "url" );
2578  kdeMap->insert( "KPasswordEdit", "password" );
2579  kdeMap->insert( "KIntNumInput", "value" );
2580  kdeMap->insert( "KIntSpinBox", "value" );
2581  kdeMap->insert( "KDoubleNumInput", "value" );
2582  // Temp til fixed in QT then enable ifdef with the correct version num
2583  kdeMap->insert( TQGROUPBOX_OBJECT_NAME_STRING, "checked" );
2584  kdeMap->insert( TQTABWIDGET_OBJECT_NAME_STRING, "currentPage" );
2585  TQSqlPropertyMap::installDefaultMap( kdeMap );
2586 #endif
2587 }
2588 
2589 void KApplication::invokeHelp( const TQString& anchor,
2590  const TQString& _appname) const
2591 {
2592  return invokeHelp( anchor, _appname, "" );
2593 }
2594 
2595 #ifndef Q_WS_WIN
2596 // for win32 we're using simple help tools like Qt Assistant,
2597 // see kapplication_win.cpp
2598 void KApplication::invokeHelp( const TQString& anchor,
2599  const TQString& _appname,
2600  const TQCString& startup_id ) const
2601 {
2602  TQString url;
2603  TQString appname;
2604  if (_appname.isEmpty())
2605  appname = name();
2606  else
2607  appname = _appname;
2608 
2609  if (!anchor.isEmpty())
2610  url = TQString("help:/%1?anchor=%2").arg(appname).arg(anchor);
2611  else
2612  url = TQString("help:/%1/index.html").arg(appname);
2613 
2614  TQString error;
2615  if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
2616  {
2617  if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, startup_id, false))
2618  {
2619  if (Tty != kapp->type())
2620  TQMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
2621  i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
2622  else
2623  kdWarning() << "Could not launch help:\n" << error << endl;
2624  return;
2625  }
2626  }
2627  else
2628  DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url, startup_id );
2629 }
2630 #endif
2631 
2632 void KApplication::invokeHTMLHelp( const TQString& _filename, const TQString& topic ) const
2633 {
2634  kdWarning() << "invoking HTML help is deprecated! use docbook and invokeHelp!\n";
2635 
2636  TQString filename;
2637 
2638  if( _filename.isEmpty() )
2639  filename = TQString(name()) + "/index.html";
2640  else
2641  filename = _filename;
2642 
2643  TQString url;
2644  if (!topic.isEmpty())
2645  url = TQString("help:/%1#%2").arg(filename).arg(topic);
2646  else
2647  url = TQString("help:/%1").arg(filename);
2648 
2649  TQString error;
2650  if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
2651  {
2652  if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, "", false))
2653  {
2654  if (Tty != kapp->type())
2655  TQMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
2656  i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
2657  else
2658  kdWarning() << "Could not launch help:\n" << error << endl;
2659  return;
2660  }
2661  }
2662  else
2663  DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url );
2664 }
2665 
2666 
2667 void KApplication::invokeMailer(const TQString &address, const TQString &subject)
2668 {
2669  return invokeMailer(address,subject,"");
2670 }
2671 
2672 void KApplication::invokeMailer(const TQString &address, const TQString &subject, const TQCString& startup_id)
2673 {
2674  invokeMailer(address, TQString::null, TQString::null, subject, TQString::null, TQString::null,
2675  TQStringList(), startup_id );
2676 }
2677 
2678 void KApplication::invokeMailer(const KURL &mailtoURL)
2679 {
2680  return invokeMailer( mailtoURL, "" );
2681 }
2682 
2683 void KApplication::invokeMailer(const KURL &mailtoURL, const TQCString& startup_id )
2684 {
2685  return invokeMailer( mailtoURL, startup_id, false);
2686 }
2687 
2688 void KApplication::invokeMailer(const KURL &mailtoURL, const TQCString& startup_id, bool allowAttachments )
2689 {
2690  TQString address = KURL::decode_string(mailtoURL.path()), subject, cc, bcc, body;
2691  TQStringList queries = TQStringList::split('&', mailtoURL.query().mid(1));
2692  TQStringList attachURLs;
2693  for (TQStringList::Iterator it = queries.begin(); it != queries.end(); ++it)
2694  {
2695  TQString q = (*it).lower();
2696  if (q.startsWith("subject="))
2697  subject = KURL::decode_string((*it).mid(8));
2698  else
2699  if (q.startsWith("cc="))
2700  cc = cc.isEmpty()? KURL::decode_string((*it).mid(3)): cc + ',' + KURL::decode_string((*it).mid(3));
2701  else
2702  if (q.startsWith("bcc="))
2703  bcc = bcc.isEmpty()? KURL::decode_string((*it).mid(4)): bcc + ',' + KURL::decode_string((*it).mid(4));
2704  else
2705  if (q.startsWith("body="))
2706  body = KURL::decode_string((*it).mid(5));
2707  else
2708  if (allowAttachments && q.startsWith("attach="))
2709  attachURLs.push_back(KURL::decode_string((*it).mid(7)));
2710  else
2711  if (allowAttachments && q.startsWith("attachment="))
2712  attachURLs.push_back(KURL::decode_string((*it).mid(11)));
2713  else
2714  if (q.startsWith("to="))
2715  address = address.isEmpty()? KURL::decode_string((*it).mid(3)): address + ',' + KURL::decode_string((*it).mid(3));
2716  }
2717 
2718  invokeMailer( address, cc, bcc, subject, body, TQString::null, attachURLs, startup_id );
2719 }
2720 
2721 void KApplication::invokeMailer(const TQString &to, const TQString &cc, const TQString &bcc,
2722  const TQString &subject, const TQString &body,
2723  const TQString & messageFile, const TQStringList &attachURLs)
2724 {
2725  return invokeMailer(to,cc,bcc,subject,body,messageFile,attachURLs,"");
2726 }
2727 
2728 #ifndef Q_WS_WIN
2729 // on win32, for invoking browser we're using win32 API
2730 // see kapplication_win.cpp
2731 
2732 static TQStringList splitEmailAddressList( const TQString & aStr )
2733 {
2734  // This is a copy of KPIM::splitEmailAddrList().
2735  // Features:
2736  // - always ignores quoted characters
2737  // - ignores everything (including parentheses and commas)
2738  // inside quoted strings
2739  // - supports nested comments
2740  // - ignores everything (including double quotes and commas)
2741  // inside comments
2742 
2743  TQStringList list;
2744 
2745  if (aStr.isEmpty())
2746  return list;
2747 
2748  TQString addr;
2749  uint addrstart = 0;
2750  int commentlevel = 0;
2751  bool insidequote = false;
2752 
2753  for (uint index=0; index<aStr.length(); index++) {
2754  // the following conversion to latin1 is o.k. because
2755  // we can safely ignore all non-latin1 characters
2756  switch (aStr[index].latin1()) {
2757  case '"' : // start or end of quoted string
2758  if (commentlevel == 0)
2759  insidequote = !insidequote;
2760  break;
2761  case '(' : // start of comment
2762  if (!insidequote)
2763  commentlevel++;
2764  break;
2765  case ')' : // end of comment
2766  if (!insidequote) {
2767  if (commentlevel > 0)
2768  commentlevel--;
2769  else {
2770  //kdDebug() << "[kdecore-kapplication] Error in address splitting: Unmatched ')'"
2771  // << endl;
2772  return list;
2773  }
2774  }
2775  break;
2776  case '\\' : // quoted character
2777  index++; // ignore the quoted character
2778  break;
2779  case ',' :
2780  if (!insidequote && (commentlevel == 0)) {
2781  addr = aStr.mid(addrstart, index-addrstart);
2782  if (!addr.isEmpty())
2783  list += addr.simplifyWhiteSpace();
2784  addrstart = index+1;
2785  }
2786  break;
2787  }
2788  }
2789  // append the last address to the list
2790  if (!insidequote && (commentlevel == 0)) {
2791  addr = aStr.mid(addrstart, aStr.length()-addrstart);
2792  if (!addr.isEmpty())
2793  list += addr.simplifyWhiteSpace();
2794  }
2795  //else
2796  // kdDebug() << "[kdecore-kapplication] Error in address splitting: "
2797  // << "Unexpected end of address list"
2798  // << endl;
2799 
2800  return list;
2801 }
2802 
2803 void KApplication::invokeMailer(const TQString &_to, const TQString &_cc, const TQString &_bcc,
2804  const TQString &subject, const TQString &body,
2805  const TQString & /*messageFile TODO*/, const TQStringList &attachURLs,
2806  const TQCString& startup_id )
2807 {
2808  KConfig config("emaildefaults");
2809 
2810  config.setGroup("Defaults");
2811  TQString group = config.readEntry("Profile","Default");
2812 
2813  config.setGroup( TQString("PROFILE_%1").arg(group) );
2814  TQString command = config.readPathEntry("EmailClient");
2815 
2816  TQString to, cc, bcc;
2817  if (command.isEmpty() || command == TQString::fromLatin1("kmail")
2818  || command.endsWith("/kmail"))
2819  {
2820  command = TQString::fromLatin1("kmail --composer -s %s -c %c -b %b --body %B --attach %A -- %t");
2821  if ( !_to.isEmpty() )
2822  {
2823  // put the whole address lists into RFC2047 encoded blobs; technically
2824  // this isn't correct, but KMail understands it nonetheless
2825  to = TQString( "=?utf8?b?%1?=" )
2826  .arg( QString(KCodecs::base64Encode( _to.utf8(), false )) );
2827  }
2828  if ( !_cc.isEmpty() )
2829  cc = TQString( "=?utf8?b?%1?=" )
2830  .arg( QString(KCodecs::base64Encode( _cc.utf8(), false )) );
2831  if ( !_bcc.isEmpty() )
2832  bcc = TQString( "=?utf8?b?%1?=" )
2833  .arg( QString(KCodecs::base64Encode( _bcc.utf8(), false )) );
2834  } else {
2835  to = _to;
2836  cc = _cc;
2837  bcc = _bcc;
2838  if( !command.contains( '%' ))
2839  command += " %u";
2840  }
2841 
2842  if (config.readBoolEntry("TerminalClient", false))
2843  {
2844  KConfigGroup confGroup( KGlobal::config(), "General" );
2845  TQString preferredTerminal = confGroup.readPathEntry("TerminalApplication", "konsole");
2846  command = preferredTerminal + " -e " + command;
2847  }
2848 
2849  TQStringList cmdTokens = KShell::splitArgs(command);
2850  TQString cmd = cmdTokens[0];
2851  cmdTokens.remove(cmdTokens.begin());
2852 
2853  KURL url;
2854  TQStringList qry;
2855  if (!to.isEmpty())
2856  {
2857  TQStringList tos = splitEmailAddressList( to );
2858  url.setPath( tos.first() );
2859  tos.remove( tos.begin() );
2860  for (TQStringList::ConstIterator it = tos.begin(); it != tos.end(); ++it)
2861  qry.append( "to=" + KURL::encode_string( *it ) );
2862  }
2863  const TQStringList ccs = splitEmailAddressList( cc );
2864  for (TQStringList::ConstIterator it = ccs.begin(); it != ccs.end(); ++it)
2865  qry.append( "cc=" + KURL::encode_string( *it ) );
2866  const TQStringList bccs = splitEmailAddressList( bcc );
2867  for (TQStringList::ConstIterator it = bccs.begin(); it != bccs.end(); ++it)
2868  qry.append( "bcc=" + KURL::encode_string( *it ) );
2869  for (TQStringList::ConstIterator it = attachURLs.begin(); it != attachURLs.end(); ++it)
2870  qry.append( "attach=" + KURL::encode_string( *it ) );
2871  if (!subject.isEmpty())
2872  qry.append( "subject=" + KURL::encode_string( subject ) );
2873  if (!body.isEmpty())
2874  qry.append( "body=" + KURL::encode_string( body ) );
2875  url.setQuery( qry.join( "&" ) );
2876  if ( ! (to.isEmpty() && qry.isEmpty()) )
2877  url.setProtocol("mailto");
2878 
2879  TQMap<TQChar, TQString> keyMap;
2880  keyMap.insert('t', to);
2881  keyMap.insert('s', subject);
2882  keyMap.insert('c', cc);
2883  keyMap.insert('b', bcc);
2884  keyMap.insert('B', body);
2885  keyMap.insert('u', url.url());
2886 
2887  TQString attachlist = attachURLs.join(",");
2888  attachlist.prepend('\'');
2889  attachlist.append('\'');
2890  keyMap.insert('A', attachlist);
2891 
2892  for (TQStringList::Iterator it = cmdTokens.begin(); it != cmdTokens.end(); )
2893  {
2894  if (*it == "%A")
2895  {
2896  if (it == cmdTokens.begin()) // better safe than sorry ...
2897  continue;
2898  TQStringList::ConstIterator urlit = attachURLs.begin();
2899  TQStringList::ConstIterator urlend = attachURLs.end();
2900  if ( urlit != urlend )
2901  {
2902  TQStringList::Iterator previt = it;
2903  --previt;
2904  *it = *urlit;
2905  ++it;
2906  while ( ++urlit != urlend )
2907  {
2908  cmdTokens.insert( it, *previt );
2909  cmdTokens.insert( it, *urlit );
2910  }
2911  } else {
2912  --it;
2913  it = cmdTokens.remove( cmdTokens.remove( it ) );
2914  }
2915  } else {
2916  *it = KMacroExpander::expandMacros(*it, keyMap);
2917  ++it;
2918  }
2919  }
2920 
2921  TQString error;
2922  // TODO this should check if cmd has a .desktop file, and use data from it, together
2923  // with sending more ASN data
2924  if (kdeinitExec(cmd, cmdTokens, &error, NULL, startup_id )) {
2925  if (Tty != kapp->type()) {
2926  TQMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Mail Client"),
2927  i18n("Could not launch the mail client:\n\n%1").arg(error), i18n("&OK"));
2928  }
2929  else {
2930  kdWarning() << "Could not launch mail client:\n" << error << endl;
2931  }
2932  }
2933 }
2934 #endif
2935 
2936 void KApplication::invokeBrowser( const TQString &url )
2937 {
2938  return invokeBrowser( url, "" );
2939 }
2940 
2941 #ifndef Q_WS_WIN
2942 // on win32, for invoking browser we're using win32 API
2943 // see kapplication_win.cpp
2944 void KApplication::invokeBrowser( const TQString &url, const TQCString& startup_id )
2945 {
2946  TQString error;
2947 
2948  if (startServiceByDesktopName("kfmclient", url, &error, 0, 0, startup_id, false))
2949  {
2950  if (Tty != kapp->type())
2951  TQMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Browser"),
2952  i18n("Could not launch the browser:\n\n%1").arg(error), i18n("&OK"));
2953  else
2954  kdWarning() << "Could not launch browser:\n" << error << endl;
2955  return;
2956  }
2957 }
2958 #endif
2959 
2960 void KApplication::cut()
2961 {
2962  invokeEditSlot( TQT_SLOT( cut() ) );
2963 }
2964 
2965 void KApplication::copy()
2966 {
2967  invokeEditSlot( TQT_SLOT( copy() ) );
2968 }
2969 
2970 void KApplication::paste()
2971 {
2972  invokeEditSlot( TQT_SLOT( paste() ) );
2973 }
2974 
2975 void KApplication::clear()
2976 {
2977  invokeEditSlot( TQT_SLOT( clear() ) );
2978 }
2979 
2980 void KApplication::selectAll()
2981 {
2982  invokeEditSlot( TQT_SLOT( selectAll() ) );
2983 }
2984 
2985 void KApplication::broadcastKeyCode(unsigned int keyCode)
2986 {
2987  emit coreFakeKeyPress(keyCode);
2988 }
2989 
2990 TQCString
2991 KApplication::launcher()
2992 {
2993  return "klauncher";
2994 }
2995 
2996 static int
2997 startServiceInternal( const TQCString &function,
2998  const TQString& _name, const TQStringList &URLs,
2999  TQString *error, TQCString *dcopService, int *pid, const TQCString& startup_id, bool noWait )
3000 {
3001  struct serviceResult
3002  {
3003  int result;
3004  TQCString dcopName;
3005  TQString error;
3006  pid_t pid;
3007  };
3008 
3009  // Register app as able to send DCOP messages
3010  DCOPClient *dcopClient;
3011  if (kapp)
3012  dcopClient = kapp->dcopClient();
3013  else
3014  dcopClient = new DCOPClient;
3015 
3016  if (!dcopClient->isAttached())
3017  {
3018  if (!dcopClient->attach())
3019  {
3020  if (error)
3021  *error = i18n("Could not register with DCOP.\n");
3022  if (!kapp)
3023  delete dcopClient;
3024 
3025  return -1;
3026  }
3027  }
3028  TQByteArray params;
3029  TQDataStream stream(params, IO_WriteOnly);
3030  stream << _name << URLs;
3031  TQCString replyType;
3032  TQByteArray replyData;
3033  TQCString _launcher = KApplication::launcher();
3034  TQValueList<TQCString> envs;
3035 #ifdef Q_WS_X11
3036  if (qt_xdisplay()) {
3037  TQCString dpystring(XDisplayString(qt_xdisplay()));
3038  envs.append( TQCString("DISPLAY=") + dpystring );
3039  } else if( getenv( "DISPLAY" )) {
3040  TQCString dpystring( getenv( "DISPLAY" ));
3041  envs.append( TQCString("DISPLAY=") + dpystring );
3042  }
3043 #endif
3044  stream << envs;
3045 #if defined Q_WS_X11
3046  // make sure there is id, so that user timestamp exists
3047  stream << ( startup_id.isEmpty() ? KStartupInfo::createNewStartupId() : startup_id );
3048 #endif
3049  if( function.left( 12 ) != "kdeinit_exec" )
3050  stream << noWait;
3051 
3052  if (!dcopClient->call(_launcher, _launcher,
3053  function, params, replyType, replyData))
3054  {
3055  if (error)
3056  *error = i18n("KLauncher could not be reached via DCOP.\n");
3057  if (!kapp)
3058  delete dcopClient;
3059  return -1;
3060  }
3061  if (!kapp)
3062  delete dcopClient;
3063 
3064  if (noWait)
3065  return 0;
3066 
3067  TQDataStream stream2(replyData, IO_ReadOnly);
3068  serviceResult result;
3069  stream2 >> result.result >> result.dcopName >> result.error >> result.pid;
3070  if (dcopService)
3071  *dcopService = result.dcopName;
3072  if (error)
3073  *error = result.error;
3074  if (pid)
3075  *pid = result.pid;
3076  return result.result;
3077 }
3078 
3079 int
3080 KApplication::startServiceByName( const TQString& _name, const TQString &URL,
3081  TQString *error, TQCString *dcopService, int *pid, const TQCString& startup_id, bool noWait )
3082 {
3083  TQStringList URLs;
3084  if (!URL.isEmpty())
3085  URLs.append(URL);
3086  return startServiceInternal(
3087  "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)",
3088  _name, URLs, error, dcopService, pid, startup_id, noWait);
3089 }
3090 
3091 int
3092 KApplication::startServiceByName( const TQString& _name, const TQStringList &URLs,
3093  TQString *error, TQCString *dcopService, int *pid, const TQCString& startup_id, bool noWait )
3094 {
3095  return startServiceInternal(
3096  "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)",
3097  _name, URLs, error, dcopService, pid, startup_id, noWait);
3098 }
3099 
3100 int
3101 KApplication::startServiceByDesktopPath( const TQString& _name, const TQString &URL,
3102  TQString *error, TQCString *dcopService, int *pid, const TQCString& startup_id, bool noWait )
3103 {
3104  TQStringList URLs;
3105  if (!URL.isEmpty())
3106  URLs.append(URL);
3107  return startServiceInternal(
3108  "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)",
3109  _name, URLs, error, dcopService, pid, startup_id, noWait);
3110 }
3111 
3112 int
3113 KApplication::startServiceByDesktopPath( const TQString& _name, const TQStringList &URLs,
3114  TQString *error, TQCString *dcopService, int *pid, const TQCString& startup_id, bool noWait )
3115 {
3116  return startServiceInternal(
3117  "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)",
3118  _name, URLs, error, dcopService, pid, startup_id, noWait);
3119 }
3120 
3121 int
3122 KApplication::startServiceByDesktopName( const TQString& _name, const TQString &URL,
3123  TQString *error, TQCString *dcopService, int *pid, const TQCString& startup_id, bool noWait )
3124 {
3125  TQStringList URLs;
3126  if (!URL.isEmpty())
3127  URLs.append(URL);
3128  return startServiceInternal(
3129  "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)",
3130  _name, URLs, error, dcopService, pid, startup_id, noWait);
3131 }
3132 
3133 int
3134 KApplication::startServiceByDesktopName( const TQString& _name, const TQStringList &URLs,
3135  TQString *error, TQCString *dcopService, int *pid, const TQCString& startup_id, bool noWait )
3136 {
3137  return startServiceInternal(
3138  "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)",
3139  _name, URLs, error, dcopService, pid, startup_id, noWait);
3140 }
3141 
3142 int
3143 KApplication::kdeinitExec( const TQString& name, const TQStringList &args,
3144  TQString *error, int *pid )
3145 {
3146  return kdeinitExec( name, args, error, pid, "" );
3147 }
3148 
3149 int
3150 KApplication::kdeinitExec( const TQString& name, const TQStringList &args,
3151  TQString *error, int *pid, const TQCString& startup_id )
3152 {
3153  return startServiceInternal("kdeinit_exec(TQString,TQStringList,TQValueList<TQCString>,TQCString)",
3154  name, args, error, 0, pid, startup_id, false);
3155 }
3156 
3157 int
3158 KApplication::kdeinitExecWait( const TQString& name, const TQStringList &args,
3159  TQString *error, int *pid )
3160 {
3161  return kdeinitExecWait( name, args, error, pid, "" );
3162 }
3163 
3164 int
3165 KApplication::kdeinitExecWait( const TQString& name, const TQStringList &args,
3166  TQString *error, int *pid, const TQCString& startup_id )
3167 {
3168  return startServiceInternal("kdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>,TQCString)",
3169  name, args, error, 0, pid, startup_id, false);
3170 }
3171 
3172 TQString KApplication::tempSaveName( const TQString& pFilename ) const
3173 {
3174  TQString aFilename;
3175 
3176  if( TQDir::isRelativePath(pFilename) )
3177  {
3178  kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
3179  aFilename = TQFileInfo( TQDir( "." ), pFilename ).absFilePath();
3180  }
3181  else
3182  aFilename = pFilename;
3183 
3184  TQDir aAutosaveDir( TQDir::homeDirPath() + "/autosave/" );
3185  if( !aAutosaveDir.exists() )
3186  {
3187  if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
3188  {
3189  // Last chance: use temp dir
3190  aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
3191  }
3192  }
3193 
3194  aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
3195 
3196  return aFilename;
3197 }
3198 
3199 
3200 TQString KApplication::checkRecoverFile( const TQString& pFilename,
3201  bool& bRecover ) const
3202 {
3203  TQString aFilename;
3204 
3205  if( TQDir::isRelativePath(pFilename) )
3206  {
3207  kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
3208  aFilename = TQFileInfo( TQDir( "." ), pFilename ).absFilePath();
3209  }
3210  else
3211  aFilename = pFilename;
3212 
3213  TQDir aAutosaveDir( TQDir::homeDirPath() + "/autosave/" );
3214  if( !aAutosaveDir.exists() )
3215  {
3216  if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
3217  {
3218  // Last chance: use temp dir
3219  aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
3220  }
3221  }
3222 
3223  aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
3224 
3225  if( TQFile( aFilename ).exists() )
3226  {
3227  bRecover = true;
3228  return aFilename;
3229  }
3230  else
3231  {
3232  bRecover = false;
3233  return pFilename;
3234  }
3235 }
3236 
3237 
3238 bool checkAccess(const TQString& pathname, int mode)
3239 {
3240  int accessOK = access( TQFile::encodeName(pathname), mode );
3241  if ( accessOK == 0 )
3242  return true; // OK, I can really access the file
3243 
3244  // else
3245  // if we want to write the file would be created. Check, if the
3246  // user may write to the directory to create the file.
3247  if ( (mode & W_OK) == 0 )
3248  return false; // Check for write access is not part of mode => bail out
3249 
3250 
3251  if (!access( TQFile::encodeName(pathname), F_OK)) // if it already exists
3252  return false;
3253 
3254  //strip the filename (everything until '/' from the end
3255  TQString dirName(pathname);
3256  int pos = dirName.findRev('/');
3257  if ( pos == -1 )
3258  return false; // No path in argument. This is evil, we won't allow this
3259  else if ( pos == 0 ) // don't turn e.g. /root into an empty string
3260  pos = 1;
3261 
3262  dirName.truncate(pos); // strip everything starting from the last '/'
3263 
3264  accessOK = access( TQFile::encodeName(dirName), W_OK );
3265  // -?- Can I write to the accessed diretory
3266  if ( accessOK == 0 )
3267  return true; // Yes
3268  else
3269  return false; // No
3270 }
3271 
3272 void KApplication::setTopWidget( TQWidget *topWidget )
3273 {
3274  if( !topWidget )
3275  return;
3276 
3277  // set the specified caption
3278  if ( !topWidget->inherits("KMainWindow") ) { // KMainWindow does this already for us
3279  topWidget->setCaption( caption() );
3280  }
3281 
3282  // set the specified icons
3283  topWidget->setIcon( icon() ); //standard X11
3284 #if defined Q_WS_X11
3285 //#ifdef Q_WS_X11 // FIXME(E): Implement for Qt/Embedded
3286  KWin::setIcons(topWidget->winId(), icon(), miniIcon() ); // NET_WM hints for KWin
3287 
3288  // set the app startup notification window property
3289  KStartupInfo::setWindowStartupId( topWidget->winId(), startupId());
3290 #endif
3291 }
3292 
3293 TQCString KApplication::startupId() const
3294 {
3295  return d->startup_id;
3296 }
3297 
3298 void KApplication::setStartupId( const TQCString& startup_id )
3299 {
3300  if( startup_id == d->startup_id )
3301  return;
3302 #if defined Q_WS_X11
3303  KStartupInfo::handleAutoAppStartedSending(); // finish old startup notification if needed
3304 #endif
3305  if( startup_id.isEmpty())
3306  d->startup_id = "0";
3307  else
3308  {
3309  d->startup_id = startup_id;
3310 #if defined Q_WS_X11
3311  KStartupInfoId id;
3312  id.initId( startup_id );
3313  long timestamp = id.timestamp();
3314  if( timestamp != 0 )
3315  updateUserTimestamp( timestamp );
3316 #endif
3317  }
3318 }
3319 
3320 // read the startup notification env variable, save it and unset it in order
3321 // not to propagate it to processes started from this app
3322 void KApplication::read_app_startup_id()
3323 {
3324 #if defined Q_WS_X11
3325  KStartupInfoId id = KStartupInfo::currentStartupIdEnv();
3326  KStartupInfo::resetStartupEnv();
3327  d->startup_id = id.id();
3328 #endif
3329 }
3330 
3331 int KApplication::random()
3332 {
3333  static bool init = false;
3334  if (!init)
3335  {
3336  unsigned int seed;
3337  init = true;
3338  int fd = open("/dev/urandom", O_RDONLY);
3339  if (fd < 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed))
3340  {
3341  // No /dev/urandom... try something else.
3342  srand(getpid());
3343  seed = rand()+time(0);
3344  }
3345  if (fd >= 0) close(fd);
3346  srand(seed);
3347  }
3348  return rand();
3349 }
3350 
3351 TQString KApplication::randomString(int length)
3352 {
3353  if (length <=0 ) return TQString::null;
3354 
3355  TQString str; str.setLength( length );
3356  int i = 0;
3357  while (length--)
3358  {
3359  int r=random() % 62;
3360  r+=48;
3361  if (r>57) r+=7;
3362  if (r>90) r+=6;
3363  str[i++] = char(r);
3364  // so what if I work backwards?
3365  }
3366  return str;
3367 }
3368 
3369 bool KApplication::authorize(const TQString &genericAction)
3370 {
3371  if (!d->actionRestrictions)
3372  return true;
3373 
3374  KConfig *config = KGlobal::config();
3375  KConfigGroupSaver saver( config, "KDE Action Restrictions" );
3376  return config->readBoolEntry(genericAction, true);
3377 }
3378 
3379 bool KApplication::authorizeKAction(const char *action)
3380 {
3381  if (!d->actionRestrictions || !action)
3382  return true;
3383 
3384  static const TQString &action_prefix = KGlobal::staticQString( "action/" );
3385 
3386  return authorize(action_prefix + action);
3387 }
3388 
3389 bool KApplication::authorizeControlModule(const TQString &menuId)
3390 {
3391  if (menuId.isEmpty() || kde_kiosk_exception)
3392  return true;
3393  KConfig *config = KGlobal::config();
3394  KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
3395  return config->readBoolEntry(menuId, true);
3396 }
3397 
3398 TQStringList KApplication::authorizeControlModules(const TQStringList &menuIds)
3399 {
3400  KConfig *config = KGlobal::config();
3401  KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
3402  TQStringList result;
3403  for(TQStringList::ConstIterator it = menuIds.begin();
3404  it != menuIds.end(); ++it)
3405  {
3406  if (config->readBoolEntry(*it, true))
3407  result.append(*it);
3408  }
3409  return result;
3410 }
3411 
3412 void KApplication::initUrlActionRestrictions()
3413 {
3414  d->urlActionRestrictions.setAutoDelete(true);
3415  d->urlActionRestrictions.clear();
3416  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3417  ("open", TQString::null, TQString::null, TQString::null, TQString::null, TQString::null, TQString::null, true));
3418  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3419  ("list", TQString::null, TQString::null, TQString::null, TQString::null, TQString::null, TQString::null, true));
3420 // TEST:
3421 // d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3422 // ("list", TQString::null, TQString::null, TQString::null, TQString::null, TQString::null, TQString::null, false));
3423 // d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3424 // ("list", TQString::null, TQString::null, TQString::null, "file", TQString::null, TQDir::homeDirPath(), true));
3425  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3426  ("link", TQString::null, TQString::null, TQString::null, ":internet", TQString::null, TQString::null, true));
3427  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3428  ("redirect", TQString::null, TQString::null, TQString::null, ":internet", TQString::null, TQString::null, true));
3429 
3430  // We allow redirections to file: but not from internet protocols, redirecting to file:
3431  // is very popular among io-slaves and we don't want to break them
3432  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3433  ("redirect", TQString::null, TQString::null, TQString::null, "file", TQString::null, TQString::null, true));
3434  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3435  ("redirect", ":internet", TQString::null, TQString::null, "file", TQString::null, TQString::null, false));
3436 
3437  // local protocols may redirect everywhere
3438  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3439  ("redirect", ":local", TQString::null, TQString::null, TQString::null, TQString::null, TQString::null, true));
3440 
3441  // Anyone may redirect to about:
3442  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3443  ("redirect", TQString::null, TQString::null, TQString::null, "about", TQString::null, TQString::null, true));
3444 
3445  // Anyone may redirect to itself, cq. within it's own group
3446  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
3447  ("redirect", TQString::null, TQString::null, TQString::null, "=", TQString::null, TQString::null, true));
3448 
3449  KConfig *config = KGlobal::config();
3450  KConfigGroupSaver saver( config, "KDE URL Restrictions" );
3451  int count = config->readNumEntry("rule_count");
3452  TQString keyFormat = TQString("rule_%1");
3453  for(int i = 1; i <= count; i++)
3454  {
3455  TQString key = keyFormat.arg(i);
3456  TQStringList rule = config->readListEntry(key);
3457  if (rule.count() != 8)
3458  continue;
3459  TQString action = rule[0];
3460  TQString refProt = rule[1];
3461  TQString refHost = rule[2];
3462  TQString refPath = rule[3];
3463  TQString urlProt = rule[4];
3464  TQString urlHost = rule[5];
3465  TQString urlPath = rule[6];
3466  TQString strEnabled = rule[7].lower();
3467 
3468  bool bEnabled = (strEnabled == "true");
3469 
3470  if (refPath.startsWith("$HOME"))
3471  refPath.replace(0, 5, TQDir::homeDirPath());
3472  else if (refPath.startsWith("~"))
3473  refPath.replace(0, 1, TQDir::homeDirPath());
3474  if (urlPath.startsWith("$HOME"))
3475  urlPath.replace(0, 5, TQDir::homeDirPath());
3476  else if (urlPath.startsWith("~"))
3477  urlPath.replace(0, 1, TQDir::homeDirPath());
3478 
3479  if (refPath.startsWith("$TMP"))
3480  refPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
3481  if (urlPath.startsWith("$TMP"))
3482  urlPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
3483 
3484  d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
3485  ( action, refProt, refHost, refPath, urlProt, urlHost, urlPath, bEnabled));
3486  }
3487 }
3488 
3489 void KApplication::allowURLAction(const TQString &action, const KURL &_baseURL, const KURL &_destURL)
3490 {
3491  if (authorizeURLAction(action, _baseURL, _destURL))
3492  return;
3493 
3494  d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
3495  ( action, _baseURL.protocol(), _baseURL.host(), _baseURL.path(-1),
3496  _destURL.protocol(), _destURL.host(), _destURL.path(-1), true));
3497 }
3498 
3499 bool KApplication::authorizeURLAction(const TQString &action, const KURL &_baseURL, const KURL &_destURL)
3500 {
3501  if (_destURL.isEmpty())
3502  return true;
3503 
3504  bool result = false;
3505  if (d->urlActionRestrictions.isEmpty())
3506  initUrlActionRestrictions();
3507 
3508  KURL baseURL(_baseURL);
3509  baseURL.setPath(TQDir::cleanDirPath(baseURL.path()));
3510  TQString baseClass = KProtocolInfo::protocolClass(baseURL.protocol());
3511  KURL destURL(_destURL);
3512  destURL.setPath(TQDir::cleanDirPath(destURL.path()));
3513  TQString destClass = KProtocolInfo::protocolClass(destURL.protocol());
3514 
3515  for(KApplicationPrivate::URLActionRule *rule = d->urlActionRestrictions.first();
3516  rule; rule = d->urlActionRestrictions.next())
3517  {
3518  if ((result != rule->permission) && // No need to check if it doesn't make a difference
3519  (action == rule->action) &&
3520  rule->baseMatch(baseURL, baseClass) &&
3521  rule->destMatch(destURL, destClass, baseURL, baseClass))
3522  {
3523  result = rule->permission;
3524  }
3525  }
3526  return result;
3527 }
3528 
3529 
3530 uint KApplication::keyboardModifiers()
3531 {
3532 #ifdef Q_WS_X11
3533  Window root;
3534  Window child;
3535  int root_x, root_y, win_x, win_y;
3536  uint keybstate;
3537  XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
3538  &root_x, &root_y, &win_x, &win_y, &keybstate );
3539  return keybstate & 0x00ff;
3540 #elif defined W_WS_MACX
3541  return GetCurrentEventKeyModifiers() & 0x00ff;
3542 #else
3543  //TODO for win32
3544  return 0;
3545 #endif
3546 }
3547 
3548 uint KApplication::mouseState()
3549 {
3550  uint mousestate;
3551 #ifdef Q_WS_X11
3552  Window root;
3553  Window child;
3554  int root_x, root_y, win_x, win_y;
3555  XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
3556  &root_x, &root_y, &win_x, &win_y, &mousestate );
3557 #elif defined(Q_WS_WIN)
3558  const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
3559  if (GetAsyncKeyState(VK_LBUTTON))
3560  mousestate |= (mousebtn_swapped ? Button3Mask : Button1Mask);
3561  if (GetAsyncKeyState(VK_MBUTTON))
3562  mousestate |= Button2Mask;
3563  if (GetAsyncKeyState(VK_RBUTTON))
3564  mousestate |= (mousebtn_swapped ? Button1Mask : Button3Mask);
3565 #elif defined(Q_WS_MACX)
3566  mousestate = GetCurrentEventButtonState();
3567 #else
3568  //TODO: other platforms
3569 #endif
3570  return mousestate & 0xff00;
3571 }
3572 
3573 TQ_ButtonState KApplication::keyboardMouseState()
3574 {
3575  int ret = 0;
3576 #ifdef Q_WS_X11
3577  Window root;
3578  Window child;
3579  int root_x, root_y, win_x, win_y;
3580  uint state;
3581  XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
3582  &root_x, &root_y, &win_x, &win_y, &state );
3583  // transform the same way like Qt's qt_x11_translateButtonState()
3584  if( state & Button1Mask )
3585  ret |= TQ_LeftButton;
3586  if( state & Button2Mask )
3587  ret |= TQ_MidButton;
3588  if( state & Button3Mask )
3589  ret |= TQ_RightButton;
3590  if( state & ShiftMask )
3591  ret |= TQ_ShiftButton;
3592  if( state & ControlMask )
3593  ret |= TQ_ControlButton;
3594  if( state & KKeyNative::modX( KKey::ALT ))
3595  ret |= TQ_AltButton;
3596  if( state & KKeyNative::modX( KKey::WIN ))
3597  ret |= TQ_MetaButton;
3598 #elif defined(Q_WS_WIN)
3599  const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
3600  if (GetAsyncKeyState(VK_LBUTTON))
3601  ret |= (mousebtn_swapped ? RightButton : LeftButton);
3602  if (GetAsyncKeyState(VK_MBUTTON))
3603  ret |= TQ_MidButton;
3604  if (GetAsyncKeyState(VK_RBUTTON))
3605  ret |= (mousebtn_swapped ? TQ_LeftButton : TQ_RightButton);
3606  if (GetAsyncKeyState(VK_SHIFT))
3607  ret |= TQ_ShiftButton;
3608  if (GetAsyncKeyState(VK_CONTROL))
3609  ret |= TQ_ControlButton;
3610  if (GetAsyncKeyState(VK_MENU))
3611  ret |= TQ_AltButton;
3612  if (GetAsyncKeyState(VK_LWIN) || GetAsyncKeyState(VK_RWIN))
3613  ret |= TQ_MetaButton;
3614 #else
3615  //TODO: other platforms
3616 #endif
3617  return static_cast< ButtonState >( ret );
3618 }
3619 
3620 void KApplication::installSigpipeHandler()
3621 {
3622 #ifdef Q_OS_UNIX
3623  struct sigaction act;
3624  act.sa_handler = SIG_IGN;
3625  sigemptyset( &act.sa_mask );
3626  act.sa_flags = 0;
3627  sigaction( SIGPIPE, &act, 0 );
3628 #endif
3629 }
3630 
3631 void KApplication::sigpipeHandler(int)
3632 {
3633  int saved_errno = errno;
3634  // Using kdDebug from a signal handler is not a good idea.
3635 #ifndef NDEBUG
3636  char msg[1000];
3637  sprintf(msg, "*** SIGPIPE *** (ignored, pid = %ld)\n", (long) getpid());
3638  if (write(2, msg, strlen(msg)) < 0) {
3639  // ERROR
3640  }
3641 #endif
3642 
3643  // Do nothing.
3644  errno = saved_errno;
3645 }
3646 
3647 bool KApplication::guiEnabled()
3648 {
3649  return kapp && kapp->d->guiEnabled;
3650 }
3651 
3652 void KApplication::virtual_hook( int id, void* data )
3653 { KInstance::virtual_hook( id, data ); }
3654 
3655 void KSessionManaged::virtual_hook( int, void* )
3656 { /*BASE::virtual_hook( id, data );*/ }
3657 
3658 #include "kapplication.moc"
DCOPClient
DCOPClient::appId
TQCString appId() const
DCOPClient::attach
bool attach()
DCOPClient::send
bool send(const TQCString &remApp, const TQCString &remObj, const TQCString &remFun, const TQByteArray &data)
DCOPClient::isAttached
bool isAttached() const
DCOPClient::call
bool call(const TQCString &remApp, const TQCString &remObj, const TQCString &remFun, const TQByteArray &data, TQCString &replyType, TQByteArray &replyData, bool useEventLoop, int timeout)
DCOPClient::setMainClient
static void setMainClient(DCOPClient *mainClient)
DCOPClient::setServerAddress
static void setServerAddress(const TQCString &addr)
DCOPClient::registerAs
TQCString registerAs(const TQCString &appId, bool addPID=true)
DCOPRef
DCOPRef::call
DCOPReply call(const TQCString &fun)
DCOPRef::send
bool send(const TQCString &fun)
KAboutData::programName
TQString programName() const
Returns the translated program name.
Definition: kaboutdata.cpp:252
KAppDCOPInterface
This is the main interface to the KApplication.
Definition: kappdcopiface.h:38
KApplication
Controls and provides information to all KDE applications.
Definition: kapplication.h:97
KApplication::isX11CompositionAvailable
bool isX11CompositionAvailable()
Returns whether or not X11 composition is available.
Definition: kapplication.cpp:2093
KApplication::makeStdCaption
TQString makeStdCaption(const TQString &userCaption, bool withAppName=true, bool modified=false) const
Builds a caption that contains the application name along with the userCaption using a standard layou...
Definition: kapplication.cpp:2341
KApplication::startServiceByDesktopPath
static int startServiceByDesktopPath(const TQString &_name, const TQString &URL, TQString *error=0, TQCString *dcopService=0, int *pid=0, const TQCString &startup_id="", bool noWait=false)
Starts a service based on the desktop path of the service.
Definition: kapplication.cpp:3101
KApplication::updateRemoteUserTimestamp
void updateRemoteUserTimestamp(const TQCString &dcopId, unsigned long time=0)
Updates the last user action timestamp in the application registered to DCOP with dcopId to the given...
Definition: kapplication.cpp:2237
KApplication::requestShutDown
bool requestShutDown(ShutdownConfirm confirm=ShutdownConfirmDefault, ShutdownType sdtype=ShutdownTypeDefault, ShutdownMode sdmode=ShutdownModeDefault)
Asks the session manager to shut the session down.
Definition: kapplication.cpp:1241
KApplication::setTopWidget
void setTopWidget(TQWidget *topWidget)
Sets the top widget of the application.
Definition: kapplication.cpp:3272
KApplication::disableSessionManagement
void disableSessionManagement()
Disables session management for this application.
Definition: kapplication.cpp:1213
KApplication::deref
void deref()
Tells KApplication that one operation such as those described in ref() just finished.
Definition: kapplication.cpp:1183
KApplication::detectCompositionManagerAvailable
bool detectCompositionManagerAvailable(bool force_available=false, bool available=true)
Detects the availability of a composition manager such as kompmgr Note that calling this method will ...
Definition: kapplication.cpp:2043
KApplication::installSigpipeHandler
static void installSigpipeHandler()
Installs a handler for the SIGPIPE signal.
Definition: kapplication.cpp:3620
KApplication::settingsChanged
void settingsChanged(int category)
Emitted when the global settings have been changed - see KGlobalSettings KApplication takes care of c...
KApplication::startupId
TQCString startupId() const
Returns the app startup notification identifier for this running application.
Definition: kapplication.cpp:3293
KApplication::ShutdownMode
ShutdownMode
The possible values for the sdmode parameter of requestShutDown().
Definition: kapplication.h:381
KApplication::ShutdownModeDefault
@ ShutdownModeDefault
Select previous mode or the default if it's the first time.
Definition: kapplication.h:385
KApplication::launcher
static TQCString launcher()
Returns the DCOP name of the service launcher.
Definition: kapplication.cpp:2991
KApplication::removeX11EventFilter
void removeX11EventFilter(const TQWidget *filter)
Removes global X11 event filter previously installed by installX11EventFilter().
Definition: kapplication.cpp:462
KApplication::kdisplayStyleChanged
void kdisplayStyleChanged()
Emitted when KApplication has changed its GUI style in response to a KControl request.
KApplication::invokeEditSlot
void invokeEditSlot(const char *slot)
This method is used internally to determine which edit slots are implemented by the widget that has t...
Definition: kapplication.cpp:2246
KApplication::broadcastKeyCode
void broadcastKeyCode(unsigned int keyCode)
Broadcast a received keycode to all listening KDE applications The primary use for this feature is to...
Definition: kapplication.cpp:2985
KApplication::invokeHelp
void invokeHelp(const TQString &anchor, const TQString &appname, const TQCString &startup_id) const
Invokes the KHelpCenter HTML help viewer from docbook sources.
Definition: kapplication.cpp:2598
KApplication::enableSessionManagement
void enableSessionManagement()
Enables again session management for this application, formerly disabled by calling disableSessionMan...
Definition: kapplication.cpp:1217
KApplication::installX11EventFilter
void installX11EventFilter(TQWidget *filter)
Installs widget filter as global X11 event filter.
Definition: kapplication.cpp:447
KApplication::startServiceByDesktopName
static int startServiceByDesktopName(const TQString &_name, const TQString &URL, TQString *error=0, TQCString *dcopService=0, int *pid=0, const TQCString &startup_id="", bool noWait=false)
Starts a service based on the desktop name of the service.
Definition: kapplication.cpp:3122
KApplication::toolbarAppearanceChanged
void toolbarAppearanceChanged(int)
Emitted when the settings for toolbars have been changed.
KApplication::clear
void clear()
If the widget with focus provides a clear() slot, call that slot.
Definition: kapplication.cpp:2975
KApplication::mouseState
static uint mouseState() KDE_DEPRECATED
Definition: kapplication.cpp:3548
KApplication::iconName
TQString iconName() const
Returns the name of the application icon.
Definition: kapplication.cpp:1762
KApplication::authorizeURLAction
bool authorizeURLAction(const TQString &action, const KURL &baseURL, const KURL &destURL)
Returns whether a certain URL related action is authorized.
Definition: kapplication.cpp:3499
KApplication::propagateSessionManager
void propagateSessionManager()
Propagates the network address of the session manager in the SESSION_MANAGER environment variable so ...
Definition: kapplication.cpp:1304
KApplication::createApplicationPalette
static TQPalette createApplicationPalette()
Used to obtain the TQPalette that will be used to set the application palette.
Definition: kapplication.cpp:2360
KApplication::keyboardMouseState
static ButtonState keyboardMouseState()
Returns the state of the currently pressed keyboard modifiers (e.g.
Definition: kapplication.cpp:3573
KApplication::backgroundChanged
void backgroundChanged(int desk)
Emitted when the desktop background has been changed by kcmdisplay.
KApplication::kdeinitExec
static int kdeinitExec(const TQString &name, const TQStringList &args, TQString *error, int *pid, const TQCString &startup_id)
Starts a program via kdeinit.
Definition: kapplication.cpp:3150
KApplication::authorize
bool authorize(const TQString &genericAction)
Returns whether a certain action is authorized.
Definition: kapplication.cpp:3369
KApplication::ref
void ref()
Tells KApplication about one more operation that should be finished before the application exits.
Definition: kapplication.cpp:1177
KApplication::dcopClient
static DCOPClient * dcopClient()
Returns a pointer to a DCOPClient for the application.
Definition: kapplication.cpp:1117
KApplication::keyboardModifiers
static uint keyboardModifiers() KDE_DEPRECATED
Definition: kapplication.cpp:3530
KApplication::kdisplayFontChanged
void kdisplayFontChanged()
Emitted when KApplication has changed its font in response to a KControl request.
KApplication::checkRecoverFile
TQString checkRecoverFile(const TQString &pFilename, bool &bRecover) const
Check whether an auto-save file exists for the document you want to open.
Definition: kapplication.cpp:3200
KApplication::tempSaveName
TQString tempSaveName(const TQString &pFilename) const
Get a file name in order to make a temporary copy of your document.
Definition: kapplication.cpp:3172
KApplication::disableStyles
void disableStyles()
Disables style plugins.
Definition: kapplication.cpp:2290
KApplication::authorizeControlModule
bool authorizeControlModule(const TQString &menuId)
Returns whether access to a certain control module is authorized.
Definition: kapplication.cpp:3389
KApplication::addKipcEventMask
void addKipcEventMask(int id)
Adds a message type to the KIPC event mask.
Definition: kapplication.cpp:2261
KApplication::enableStyles
void enableStyles()
Enables style plugins.
Definition: kapplication.cpp:2281
KApplication::iconChanged
void iconChanged(int group)
Emitted when the global icon settings have been changed.
KApplication::getX11RGBAColormap
Qt::HANDLE getX11RGBAColormap(Display *dpy)
Returns the X11 display colormap.
Definition: kapplication.cpp:2089
KApplication::saveState
void saveState(TQSessionManager &sm)
Reimplemented for internal purposes, mainly the highlevel handling of session management with KSessio...
Definition: kapplication.cpp:1412
KApplication::kdisplayPaletteChanged
void kdisplayPaletteChanged()
Emitted when KApplication has changed its palette due to a KControl request.
KApplication::sessionConfig
KConfig * sessionConfig()
Returns the application session config object.
Definition: kapplication.cpp:1167
KApplication::authorizeControlModules
TQStringList authorizeControlModules(const TQStringList &menuIds)
Returns whether access to a certain control modules is authorized.
Definition: kapplication.cpp:3398
KApplication::updateUserTimestamp
void updateUserTimestamp(unsigned long time=0)
Updates the last user action timestamp to the given time, or to the current time, if 0 is given.
Definition: kapplication.cpp:2204
KApplication::invokeMailer
void invokeMailer(const TQString &address, const TQString &subject, const TQCString &startup_id)
Convenience method; invokes the standard email application.
Definition: kapplication.cpp:2672
KApplication::getX11RGBAVisual
Qt::HANDLE getX11RGBAVisual(Display *dpy)
Returns the X11 display visual.
Definition: kapplication.cpp:2085
KApplication::kdeinitExecWait
static int kdeinitExecWait(const TQString &name, const TQStringList &args, TQString *error, int *pid, const TQCString &startup_id)
Starts a program via kdeinit and wait for it to finish.
Definition: kapplication.cpp:3165
KApplication::KApp
static KApplication * KApp
Current application object.
Definition: kapplication.h:1276
KApplication::saveYourself
void saveYourself()
KApplication::installKDEPropertyMap
void installKDEPropertyMap()
Install a Qt SQL property map with entries for all KDE widgets Call this in any application using KDE...
Definition: kapplication.cpp:2547
KApplication::selectAll
void selectAll()
If the widget with focus provides a selectAll() slot, call that slot.
Definition: kapplication.cpp:2980
KApplication::invokeBrowser
void invokeBrowser(const TQString &url, const TQCString &startup_id)
Invokes the standard browser.
Definition: kapplication.cpp:2944
KApplication::authorizeKAction
bool authorizeKAction(const char *action)
Returns whether a certain KAction is authorized.
Definition: kapplication.cpp:3379
KApplication::randomString
static TQString randomString(int length)
Generates a random string.
Definition: kapplication.cpp:3351
KApplication::userTimestamp
unsigned long userTimestamp() const
Returns the last user action timestamp or 0 if no user activity has taken place yet.
Definition: kapplication.cpp:2228
KApplication::removeKipcEventMask
void removeKipcEventMask(int id)
Removes a message type from the KIPC event mask.
Definition: kapplication.cpp:2271
KApplication::ShutdownConfirm
ShutdownConfirm
The possible values for the confirm parameter of requestShutDown().
Definition: kapplication.h:341
KApplication::ShutdownConfirmNo
@ ShutdownConfirmNo
Don't confirm, shutdown without asking.
Definition: kapplication.h:349
KApplication::ShutdownConfirmYes
@ ShutdownConfirmYes
Always confirm, ask even if the user turned it off.
Definition: kapplication.h:353
KApplication::kipcMessage
void kipcMessage(int id, int data)
Emitted when a KIPC user message has been received.
KApplication::invokeHTMLHelp
void invokeHTMLHelp(const TQString &aFilename, const TQString &aTopic=TQString::null) const KDE_DEPRECATED
Definition: kapplication.cpp:2632
KApplication::commitData
void commitData(TQSessionManager &sm)
Reimplemented for internal purposes, mainly the highlevel handling of session management with KSessio...
Definition: kapplication.cpp:1339
KApplication::copy
void copy()
If the widget with focus provides a copy() slot, call that slot.
Definition: kapplication.cpp:2965
KApplication::disableAutoDcopRegistration
static void disableAutoDcopRegistration()
Disable automatic dcop registration Must be called before creating a KApplication instance to have an...
Definition: kapplication.cpp:1162
KApplication::miniIconName
TQString miniIconName() const
Returns the name of the mini-icon for the application.
Definition: kapplication.cpp:1778
KApplication::cut
void cut()
If the widget with focus provides a cut() slot, call that slot.
Definition: kapplication.cpp:2960
KApplication::startServiceByName
static int startServiceByName(const TQString &_name, const TQString &URL, TQString *error=0, TQCString *dcopService=0, int *pid=0, const TQCString &startup_id="", bool noWait=false)
Starts a service based on the (translated) name of the service.
Definition: kapplication.cpp:3080
KApplication::appearanceChanged
void appearanceChanged()
Emitted when KApplication has changed either its GUI style, its font or its palette in response to a ...
KApplication::addCmdLineOptions
static void addCmdLineOptions()
Add Qt and KDE command line options to KCmdLineArgs.
Definition: kapplication.cpp:1620
KApplication::paste
void paste()
If the widget with focus provides a paste() slot, call that slot.
Definition: kapplication.cpp:2970
KApplication::SettingsCategory
SettingsCategory
Valid values for the settingsChanged signal.
Definition: kapplication.h:1387
KApplication::allowURLAction
void allowURLAction(const TQString &action, const KURL &_baseURL, const KURL &_destURL)
Allow a certain URL action.
Definition: kapplication.cpp:3489
KApplication::KApplication
KApplication(bool allowStyles=true, bool GUIenabled=true, bool SMenabled=true)
This constructor takes aboutData and command line arguments from KCmdLineArgs.
Definition: kapplication.cpp:682
KApplication::random
static int random()
Generates a uniform random number.
Definition: kapplication.cpp:3331
KApplication::ShutdownType
ShutdownType
The possible values for the sdtype parameter of requestShutDown().
Definition: kapplication.h:359
KApplication::ShutdownTypeDefault
@ ShutdownTypeDefault
Select previous action or the default if it's the first time.
Definition: kapplication.h:363
KApplication::caption
TQString caption() const
Returns a text for the window caption.
Definition: kapplication.cpp:2322
KApplication::sessionSaving
bool sessionSaving() const
Returns true if the application is currently saving its session data (most probably before KDE logout...
Definition: kapplication.cpp:1494
KApplication::geometryArgument
TQString geometryArgument() const
Returns the argument to –geometry if any, so the geometry can be set wherever necessary.
Definition: kapplication.cpp:1746
KApplication::isCompositionManagerAvailable
static bool isCompositionManagerAvailable()
Gets the availability of a composition manager such as kompmgr Note that at least one application mus...
Definition: kapplication.cpp:2039
KApplication::shutDown
void shutDown()
Your application is killed.
KClipboardSynchronizer::self
static KClipboardSynchronizer * self()
Returns the KClipboardSynchronizer singleton object.
Definition: kclipboard.cpp:97
KCmdLineArgs
A class for command-line argument handling.
Definition: kcmdlineargs.h:223
KCmdLineArgs::isSet
bool isSet(const char *option) const
Read out a boolean option or check for the presence of string option.
Definition: kcmdlineargs.cpp:1181
KCmdLineArgs::addCmdLineOptions
static void addCmdLineOptions(const KCmdLineOptions *options, const char *name=0, const char *id=0, const char *afterId=0)
Add options to your application.
Definition: kcmdlineargs.cpp:206
KCmdLineArgs::parsedArgs
static KCmdLineArgs * parsedArgs(const char *id=0)
Access parsed arguments.
Definition: kcmdlineargs.cpp:310
KCmdLineArgs::appName
static const char * appName()
Get the appname according to argv[0].
Definition: kcmdlineargs.cpp:199
KCmdLineArgs::getOption
TQCString getOption(const char *option) const
Read out a string option.
Definition: kcmdlineargs.cpp:1119
KCodecs::base64Encode
static TQCString base64Encode(const TQByteArray &in, bool insertLFs=false)
Encodes the given data using the base64 algorithm.
Definition: kmdcodec.cpp:373
KConfigBase
KDE Configuration Management abstract base class.
Definition: kconfigbase.h:71
KConfigBase::readListEntry
int readListEntry(const TQString &pKey, TQStrList &list, char sep=',') const
Reads a list of strings.
Definition: kconfigbase.cpp:490
KConfigBase::sync
virtual void sync()
Flushes all changes that currently reside only in memory back to disk / permanent storage.
Definition: kconfigbase.cpp:1776
KConfigBase::readPathEntry
TQString readPathEntry(const TQString &pKey, const TQString &aDefault=TQString::null) const
Reads a path.
Definition: kconfigbase.cpp:608
KConfigBase::readSizeEntry
TQSize readSizeEntry(const TQString &pKey, const TQSize *pDefault=0L) const
Reads a TQSize entry.
Definition: kconfigbase.cpp:944
KConfigBase::readColorEntry
TQColor readColorEntry(const TQString &pKey, const TQColor *pDefault=0L) const
Reads a TQColor entry.
Definition: kconfigbase.cpp:970
KConfigBase::readEntry
TQString readEntry(const TQString &pKey, const TQString &aDefault=TQString::null) const
Reads the value of an entry specified by pKey in the current group.
Definition: kconfigbase.cpp:222
KConfigBase::setGroup
void setGroup(const TQString &group)
Specifies the group in which keys will be read and written.
Definition: kconfigbase.cpp:80
KConfigBase::hasGroup
bool hasGroup(const TQString &group) const
Returns true if the specified group is known about.
Definition: kconfigbase.cpp:153
KConfigBase::checkConfigFilesWritable
bool checkConfigFilesWritable(bool warnUser)
Check whether the config files are writable.
Definition: kconfigbase.cpp:1942
KConfigBase::readNumEntry
int readNumEntry(const TQString &pKey, int nDefault=0) const
Reads a numerical value.
Definition: kconfigbase.cpp:636
KConfigBase::readBoolEntry
bool readBoolEntry(const TQString &pKey, bool bDefault=false) const
Reads a boolean entry.
Definition: kconfigbase.cpp:771
KConfigGroupSaver
Helper class to facilitate working with KConfig / KSimpleConfig groups.
Definition: kconfigbase.h:2060
KConfigGroup
A KConfigBase derived class for one specific group in a KConfig object.
Definition: kconfigbase.h:2104
KConfig
Access KDE Configuration entries.
Definition: kconfig.h:44
KConfig::reparseConfiguration
virtual void reparseConfiguration()
Clears all internal data structures and then reread configuration information from disk.
Definition: kconfig.cpp:161
KCrash::setCrashHandler
static void setCrashHandler(HandlerType handler=defaultCrashHandler)
Install a function to be called in case a SIGSEGV is caught.
Definition: kcrash.cpp:86
KCrash::setEmergencySaveFunction
static void setEmergencySaveFunction(HandlerType saveFunction=(HandlerType) 0)
Installs a function which should try to save the applications data.
Definition: kcrash.cpp:70
KCrash::defaultCrashHandler
static void defaultCrashHandler(int signal)
The default crash handler.
Definition: kcrash.cpp:119
KCrash::setApplicationName
static void setApplicationName(TQString name)
Sets the application name name which should be passed to Dr.
Definition: kcrash.h:108
KGlobalSettings::contrast
static int contrast()
Returns the contrast for borders.
Definition: kglobalsettings.cpp:363
KGlobalSettings::fixedFont
static TQFont fixedFont()
Returns the default fixed font.
Definition: kglobalsettings.cpp:486
KGlobalSettings::menuFont
static TQFont menuFont()
Returns the default menu font.
Definition: kglobalsettings.cpp:518
KGlobalSettings::generalFont
static TQFont generalFont()
Returns the default general font.
Definition: kglobalsettings.cpp:470
KGlobal::dirs
static KStandardDirs * dirs()
Returns the application standard dirs object.
Definition: kglobal.cpp:54
KGlobal::instance
static KInstance * instance()
Returns the global instance.
Definition: kglobal.cpp:82
KGlobal::config
static KConfig * config()
Returns the general config object.
Definition: kglobal.cpp:61
KGlobal::locale
static KLocale * locale()
Returns the global locale object.
Definition: kglobal.cpp:88
KGlobal::deleteStaticDeleters
static void deleteStaticDeleters()
Calls KStaticDeleterBase::destructObject() on all registered static deleters and unregisters them all...
Definition: kglobal.cpp:185
KGlobal::checkAccess
bool checkAccess(const TQString &pathname, int mode)
Check, if a file may be accessed in a given mode.
Definition: kapplication.cpp:3238
KGlobal::staticQString
static const TQString & staticQString(const char *str)
Creates a static TQString.
Definition: kglobal.cpp:128
KGlobal::iconLoader
static KIconLoader * iconLoader()
Returns an iconloader object.
Definition: kglobal.cpp:75
KIPC::BlockShortcuts
@ BlockShortcuts
Definition: kipc.h:59
KIconLoader::loadIcon
TQPixmap loadIcon(const TQString &name, KIcon::Group group, int size=0, int state=KIcon::DefaultState, TQString *path_store=0L, bool canReturnNull=false) const
Loads an icon.
Definition: kiconloader.cpp:583
KIcon::DefaultState
@ DefaultState
The default state.
Definition: kicontheme.h:130
KIcon::NoGroup
@ NoGroup
No group.
Definition: kicontheme.h:90
KIcon::SizeLarge
@ SizeLarge
large sized icons for the panel
Definition: kicontheme.h:120
KInstance
Access to KDE global objects for use in shared libraries.
Definition: kinstance.h:44
KInstance::newIconLoader
void newIconLoader() const
Re-allocate the global iconloader.
Definition: kinstance.cpp:250
KInstance::aboutData
const KAboutData * aboutData() const
Returns the about data of this instance Warning, can be 0L.
Definition: kinstance.cpp:257
KInstance::mimeSourceFactory
KMimeSourceFactory * mimeSourceFactory() const
Returns the KMimeSourceFactory of the instance.
Definition: kinstance.cpp:269
KInstance::config
KConfig * config() const
Returns the general config object ("appnamerc").
Definition: kinstance.cpp:177
KInstance::instanceName
TQCString instanceName() const
Returns the name of the instance.
Definition: kinstance.cpp:263
KInstance::setConfigName
void setConfigName(const TQString &name)
Set name of default config file.
Definition: kinstance.cpp:233
KKey
A KKey object represents a single key with possible modifiers (Shift, Ctrl, Alt, Win).
Definition: kshortcut.h:41
KLocale::i18n
TQString i18n(const char *text)
i18n is the function that does everything you need to translate a string.
Definition: klocale.cpp:1977
KLocale::I18N_NOOP
#define I18N_NOOP(x)
I18N_NOOP marks a string to be translated without translating it.
Definition: klocale.h:52
KLockFile
The KLockFile class provides NFS safe lockfiles.
Definition: klockfile.h:34
KLockFile::LockOK
@ LockOK
Lock was acquired successfully.
Definition: klockfile.h:52
KLockFile::LockNoBlock
@ LockNoBlock
Return immediately, do not wait for the lock to become available.
Definition: klockfile.h:74
KProcessController::ref
static void ref()
Create an instance if none exists yet.
Definition: kprocctrl.cpp:39
KProcessController::deref
static void deref()
Destroy the instance if one exists and it is not referenced any more.
Definition: kprocctrl.cpp:48
KSessionManaged
Provides highlevel access to session management on a per-object base.
Definition: kapplication.h:1607
KSessionManaged::saveState
virtual bool saveState(TQSessionManager &sm)
See TQApplication::saveState() for documentation.
Definition: kapplication.cpp:1202
KSessionManaged::commitData
virtual bool commitData(TQSessionManager &sm)
See TQApplication::commitData() for documentation.
Definition: kapplication.cpp:1207
KShortcut
The KShortcut class is used to represent a keyboard shortcut to an action.
Definition: kshortcut.h:544
KShortcut::contains
bool contains(const KKey &key) const
Checks whether this shortcut contains a sequence that starts with the given key.
Definition: kshortcut.cpp:532
KStandardDirs::saveLocation
TQString saveLocation(const char *type, const TQString &suffix=TQString::null, bool create=true) const
Finds a location to save files into for the given type in the user's home directory.
Definition: kstandarddirs.cpp:1099
KStandardDirs::addResourceType
bool addResourceType(const char *type, const TQString &relativename)
Adds suffixes for types.
Definition: kstandarddirs.cpp:255
KStandardDirs::findExe
static TQString findExe(const TQString &appname, const TQString &pathstr=TQString::null, bool ignoreExecBit=false)
Finds the executable in the system path.
Definition: kstandarddirs.cpp:932
KStandardDirs::kde_default
static TQString kde_default(const char *type)
This returns a default relative path for the standard KDE resource types.
Definition: kstandarddirs.cpp:1036
KStandardDirs::resourceDirs
TQStringList resourceDirs(const char *type) const
This function is used internally by almost all other function as it serves and fills the directories ...
Definition: kstandarddirs.cpp:795
KURL
Represents and parses a URL.
Definition: kurl.h:128
KURL::path
TQString path() const
Returns the current decoded path.
Definition: kurl.h:532
KURL::query
TQString query() const
Returns the encoded query of the URL.
Definition: kurl.cpp:2063
KURL::encode_string
static TQString encode_string(const TQString &str, int encoding_hint=0)
Encodes a string for use in URLs.
Definition: kurl.cpp:2075
KURL::setPath
void setPath(const TQString &path)
Sets the decoded path of the URL.
Definition: kurl.cpp:1994
KURL::protocol
TQString protocol() const
Returns the protocol for the URL.
Definition: kurl.h:367
KURL::isEmpty
bool isEmpty() const
Tests if the KURL is empty.
Definition: kurl.cpp:632
KURL::setQuery
void setQuery(const TQString &_txt, int encoding_hint=0)
Sets the encoded query of the URL.
Definition: kurl.cpp:2016
KURL::url
TQString url(int _trailing=0, int encoding_hint=0) const
Returns the URL as string, with all escape sequences intact, encoded in a given charset.
Definition: kurl.cpp:1468
KURL::host
TQString host() const
Returns the decoded hostname included in the URL.
Definition: kurl.h:477
KURL::decode_string
static TQString decode_string(const TQString &str, int encoding_hint=0)
Decodes a string as used in URLs.
Definition: kurl.cpp:2070
KURL::setProtocol
void setProtocol(const TQString &_txt)
Sets the protocol for the URL.
Definition: kurl.cpp:1941
KWin::setIcons
static void setIcons(WId win, const TQPixmap &icon, const TQPixmap &miniIcon)
Sets an icon and a miniIcon on window win.
Definition: kwin.cpp:515
NET::timestampCompare
static int timestampCompare(unsigned long time1, unsigned long time2)
Compares two X timestamps, taking into account wrapping and 64bit architectures.
endl
kndbgstream & endl(kndbgstream &s)
Does nothing.
Definition: kdebug.h:583
klocale.h
KMacroExpander::expandMacros
TQString expandMacros(const TQString &ostr, const TQMap< TQChar, TQString > &map, TQChar c)
Perform safe macro expansion (substitution) on a string.
Definition: kmacroexpander.cpp:520
KNotifyClient::event
int event(const TQString &message, const TQString &text=TQString::null) KDE_DEPRECATED
Definition: knotifyclient.cpp:112
KShell::splitArgs
TQStringList splitArgs(const TQString &cmd, int flags=0, int *err=0)
Splits cmd according to POSIX shell word splitting and quoting rules.
Definition: kshell.cpp:65
KStdAccel::key
int key(StdAccel id)
Definition: kstdaccel.cpp:383
KStdAccel::selectAll
const KShortcut & selectAll()
Reload.
Definition: kstdaccel.cpp:313
KStdAction::home
KAction * home(const TQObject *recvr, const char *slot, KActionCollection *parent, const char *name=0)
KStdAction::action
KAction * action(StdAction act_enum, const TQObject *recvr, const char *slot, KActionCollection *parent, const char *name=0L)
KStdAction::name
const char * name(StdAction id)
KCmdLineOptions
Structure that holds command line options.
Definition: kcmdlineargs.h:41

kdecore

Skip menu "kdecore"
  • Main Page
  • Modules
  • Namespace List
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Namespace Members
  • Class Members
  • Related Pages

kdecore

Skip menu "kdecore"
  • arts
  • dcop
  • dnssd
  • interfaces
  •     interface
  •     library
  •   kspeech
  •   ktexteditor
  • kabc
  • kate
  • kcmshell
  • kdecore
  • kded
  • kdefx
  • kdeprint
  • kdesu
  • kdeui
  • kdoctools
  • khtml
  • kimgio
  • kinit
  • kio
  •   bookmarks
  •   httpfilter
  •   kfile
  •   kio
  •   kioexec
  •   kpasswdserver
  •   kssl
  • kioslave
  •   http
  • kjs
  • kmdi
  •   kmdi
  • knewstuff
  • kparts
  • krandr
  • kresources
  • kspell2
  • kunittest
  • kutils
  • kwallet
  • libkmid
  • libkscreensaver
Generated for kdecore by doxygen 1.9.1
This website is maintained by Timothy Pearson.
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V. |