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

tdecore

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

tdecore

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

tdecore

Skip menu "tdecore"
  • arts
  • dcop
  • dnssd
  • interfaces
  •   kspeech
  •     interface
  •     library
  •   tdetexteditor
  • kate
  • kded
  • kdoctools
  • kimgio
  • kjs
  • knewstuff
  • libtdemid
  • libtdescreensaver
  • tdeabc
  • tdecmshell
  • tdecore
  • tdefx
  • tdehtml
  • tdeinit
  • tdeio
  •   bookmarks
  •   httpfilter
  •   kpasswdserver
  •   kssl
  •   tdefile
  •   tdeio
  •   tdeioexec
  • tdeioslave
  •   http
  • tdemdi
  •   tdemdi
  • tdeparts
  • tdeprint
  • tderandr
  • tderesources
  • tdespell2
  • tdesu
  • tdeui
  • tdeunittest
  • tdeutils
  • tdewallet
Generated for tdecore by doxygen 1.8.3.1
This website is maintained by Timothy Pearson.