kapplication.cpp

00001 /* This file is part of the KDE libraries
00002     Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
00003     Copyright (C) 1998, 1999, 2000 KDE Team
00004 
00005     This library is free software; you can redistribute it and/or
00006     modify it under the terms of the GNU Library General Public
00007     License as published by the Free Software Foundation; either
00008     version 2 of the License, or (at your option) any later version.
00009 
00010     This library is distributed in the hope that it will be useful,
00011     but WITHOUT ANY WARRANTY; without even the implied warranty of
00012     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013     Library General Public License for more details.
00014 
00015     You should have received a copy of the GNU Library General Public License
00016     along with this library; see the file COPYING.LIB.  If not, write to
00017     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00018     Boston, MA 02110-1301, USA.
00019         */
00020 
00021 #include "config.h"
00022 
00023 #undef QT_NO_TRANSLATION
00024 #include <qtranslator.h>
00025 #define QT_NO_TRANSLATION
00026 #include <qdir.h>
00027 #include <qptrcollection.h>
00028 #include <qwidgetlist.h>
00029 #include <qstrlist.h>
00030 #include <qfile.h>
00031 #include <qmessagebox.h>
00032 #include <qtextstream.h>
00033 #include <qregexp.h>
00034 #include <qlineedit.h>
00035 #include <qtextedit.h>
00036 #include <qsessionmanager.h>
00037 #include <qptrlist.h>
00038 #include <qtimer.h>
00039 #include <qstylesheet.h>
00040 #include <qpixmapcache.h>
00041 #include <qtooltip.h>
00042 #include <qstylefactory.h>
00043 #include <qmetaobject.h>
00044 #include <qimage.h>
00045 #ifndef QT_NO_SQL
00046 #include <qsqlpropertymap.h>
00047 #endif
00048 
00049 #undef QT_NO_TRANSLATION
00050 #include "kapplication.h"
00051 #define QT_NO_TRANSLATION
00052 #include <kglobal.h>
00053 #include <kstandarddirs.h>
00054 #include <kdebug.h>
00055 #include <klocale.h>
00056 #include <kstyle.h>
00057 #include <kiconloader.h>
00058 #include <kclipboard.h>
00059 #include <kconfig.h>
00060 #include <ksimpleconfig.h>
00061 #include <kcmdlineargs.h>
00062 #include <kaboutdata.h>
00063 #include <kglobalsettings.h>
00064 #include <kcrash.h>
00065 #include <kdatastream.h>
00066 #include <klibloader.h>
00067 #include <kmimesourcefactory.h>
00068 #include <kstdaccel.h>
00069 #include <kaccel.h>
00070 #include "kcheckaccelerators.h"
00071 #include <qptrdict.h>
00072 #include <kmacroexpander.h>
00073 #include <kshell.h>
00074 #include <kprotocolinfo.h>
00075 #include <kkeynative.h>
00076 #include <kmdcodec.h>
00077 #include <kglobalaccel.h>
00078 
00079 #if defined Q_WS_X11
00080 #include <kstartupinfo.h>
00081 #endif
00082 
00083 #include <dcopclient.h>
00084 #include <dcopref.h>
00085 
00086 #include <sys/types.h>
00087 #ifdef HAVE_SYS_STAT_H
00088 #include <sys/stat.h>
00089 #endif
00090 #include <sys/wait.h>
00091 
00092 #ifndef Q_WS_WIN
00093 #include "kwin.h"
00094 #endif
00095 
00096 #include <fcntl.h>
00097 #include <stdlib.h> // getenv(), srand(), rand()
00098 #include <signal.h>
00099 #include <unistd.h>
00100 #include <time.h>
00101 #include <sys/time.h>
00102 #include <errno.h>
00103 #include <string.h>
00104 #include <netdb.h>
00105 #if defined Q_WS_X11
00106 //#ifndef Q_WS_QWS //FIXME(E): NetWM should talk to QWS...
00107 #include <netwm.h>
00108 #endif
00109 
00110 #include "kprocctrl.h"
00111 
00112 #ifdef HAVE_PATHS_H
00113 #include <paths.h>
00114 #endif
00115 
00116 #ifdef Q_WS_X11
00117 #include <X11/Xlib.h>
00118 #include <X11/Xutil.h>
00119 #include <X11/Xatom.h>
00120 #include <X11/SM/SMlib.h>
00121 #include <fixx11h.h>
00122 #endif
00123 
00124 #ifndef Q_WS_WIN
00125 #include <KDE-ICE/ICElib.h>
00126 #else
00127 typedef void* IceIOErrorHandler;
00128 #include <windows.h>
00129 //KDE4: remove
00130 #define Button1Mask (1<<8)
00131 #define Button2Mask (1<<9)
00132 #define Button3Mask (1<<10)
00133 #endif
00134 
00135 #ifdef Q_WS_X11
00136 #define DISPLAY "DISPLAY"
00137 #elif defined(Q_WS_QWS)
00138 #define DISPLAY "QWS_DISPLAY"
00139 #endif
00140 
00141 #if defined Q_WS_X11
00142 #include <kipc.h>
00143 #endif
00144 
00145 #ifdef Q_WS_MACX
00146 #include <Carbon/Carbon.h>
00147 #include <qimage.h>
00148 #endif
00149 
00150 #include "kappdcopiface.h"
00151 
00152 // exported for kdm kfrontend
00153 KDE_EXPORT bool kde_have_kipc = true; // magic hook to disable kipc in kdm
00154 bool kde_kiosk_exception = false; // flag to disable kiosk restrictions
00155 bool kde_kiosk_admin = false;
00156 
00157 KApplication* KApplication::KApp = 0L;
00158 bool KApplication::loadedByKdeinit = false;
00159 DCOPClient *KApplication::s_DCOPClient = 0L;
00160 bool KApplication::s_dcopClientNeedsPostInit = false;
00161 
00162 #ifdef Q_WS_X11
00163 static Atom atom_DesktopWindow;
00164 static Atom atom_NetSupported;
00165 extern Time qt_x_time;
00166 extern Time qt_x_user_time;
00167 static Atom kde_xdnd_drop;
00168 #endif
00169 
00170 // duplicated from patched Qt, so that there won't be unresolved symbols if Qt gets
00171 // replaced by unpatched one
00172 KDECORE_EXPORT bool qt_qclipboard_bailout_hack = false;
00173 
00174 template class QPtrList<KSessionManaged>;
00175 
00176 #ifdef Q_WS_X11
00177 extern "C" {
00178 static int kde_xio_errhandler( Display * dpy )
00179 {
00180   return kapp->xioErrhandler( dpy );
00181 }
00182 
00183 static int kde_x_errhandler( Display *dpy, XErrorEvent *err )
00184 {
00185   return kapp->xErrhandler( dpy, err );
00186 }
00187 
00188 }
00189 
00190 extern "C" {
00191 static void kde_ice_ioerrorhandler( IceConn conn )
00192 {
00193     if(kapp)
00194         kapp->iceIOErrorHandler( conn );
00195     // else ignore the error for now
00196 }
00197 }
00198 #endif
00199 
00200 #ifdef Q_WS_WIN
00201 void KApplication_init_windows(bool GUIenabled);
00202 
00203 class QAssistantClient;
00204 #endif
00205 
00206 /*
00207   Private data to make keeping binary compatibility easier
00208  */
00209 class KApplicationPrivate
00210 {
00211 public:
00212   KApplicationPrivate()
00213     :   actionRestrictions( false ),
00214     refCount( 1 ),
00215     oldIceIOErrorHandler( 0 ),
00216     checkAccelerators( 0 ),
00217     overrideStyle( QString::null ),
00218     startup_id( "0" ),
00219     app_started_timer( NULL ),
00220     m_KAppDCOPInterface( 0L ),
00221     session_save( false )
00222 #ifdef Q_WS_X11
00223     ,oldXErrorHandler( NULL )
00224     ,oldXIOErrorHandler( NULL )
00225 #elif defined Q_WS_WIN
00226     ,qassistantclient( 0 )
00227 #endif
00228   {
00229   }
00230 
00231   ~KApplicationPrivate()
00232   {
00233 #ifdef Q_WS_WIN
00234      delete qassistantclient;
00235 #endif
00236   }
00237 
00238 
00239   bool actionRestrictions : 1;
00240   bool guiEnabled : 1;
00247   int refCount;
00248   IceIOErrorHandler oldIceIOErrorHandler;
00249   KCheckAccelerators* checkAccelerators;
00250   QString overrideStyle;
00251   QString geometry_arg;
00252   QCString startup_id;
00253   QTimer* app_started_timer;
00254   KAppDCOPInterface *m_KAppDCOPInterface;
00255   bool session_save;
00256 #ifdef Q_WS_X11
00257   int (*oldXErrorHandler)(Display*,XErrorEvent*);
00258   int (*oldXIOErrorHandler)(Display*);
00259 #elif defined Q_WS_WIN
00260   QAssistantClient* qassistantclient;
00261 #endif
00262 
00263   class URLActionRule
00264   {
00265   public:
00266 #define checkExactMatch(s, b) \
00267         if (s.isEmpty()) b = true; \
00268         else if (s[s.length()-1] == '!') \
00269         { b = false; s.truncate(s.length()-1); } \
00270         else b = true;
00271 #define checkStartWildCard(s, b) \
00272         if (s.isEmpty()) b = true; \
00273         else if (s[0] == '*') \
00274         { b = true; s = s.mid(1); } \
00275         else b = false;
00276 #define checkEqual(s, b) \
00277         b = (s == "=");
00278 
00279      URLActionRule(const QString &act,
00280                    const QString &bProt, const QString &bHost, const QString &bPath,
00281                    const QString &dProt, const QString &dHost, const QString &dPath,
00282                    bool perm)
00283                    : action(act),
00284                      baseProt(bProt), baseHost(bHost), basePath(bPath),
00285                      destProt(dProt), destHost(dHost), destPath(dPath),
00286                      permission(perm)
00287                    {
00288                       checkExactMatch(baseProt, baseProtWildCard);
00289                       checkStartWildCard(baseHost, baseHostWildCard);
00290                       checkExactMatch(basePath, basePathWildCard);
00291                       checkExactMatch(destProt, destProtWildCard);
00292                       checkStartWildCard(destHost, destHostWildCard);
00293                       checkExactMatch(destPath, destPathWildCard);
00294                       checkEqual(destProt, destProtEqual);
00295                       checkEqual(destHost, destHostEqual);
00296                    }
00297 
00298      bool baseMatch(const KURL &url, const QString &protClass)
00299      {
00300         if (baseProtWildCard)
00301         {
00302            if ( !baseProt.isEmpty() && !url.protocol().startsWith(baseProt) &&
00303                 (protClass.isEmpty() || (protClass != baseProt)) )
00304               return false;
00305         }
00306         else
00307         {
00308            if ( (url.protocol() != baseProt) &&
00309                 (protClass.isEmpty() || (protClass != baseProt)) )
00310               return false;
00311         }
00312         if (baseHostWildCard)
00313         {
00314            if (!baseHost.isEmpty() && !url.host().endsWith(baseHost))
00315               return false;
00316         }
00317         else
00318         {
00319            if (url.host() != baseHost)
00320               return false;
00321         }
00322         if (basePathWildCard)
00323         {
00324            if (!basePath.isEmpty() && !url.path().startsWith(basePath))
00325               return false;
00326         }
00327         else
00328         {
00329            if (url.path() != basePath)
00330               return false;
00331         }
00332         return true;
00333      }
00334 
00335      bool destMatch(const KURL &url, const QString &protClass, const KURL &base, const QString &baseClass)
00336      {
00337         if (destProtEqual)
00338         {
00339            if ( (url.protocol() != base.protocol()) &&
00340                 (protClass.isEmpty() || baseClass.isEmpty() || protClass != baseClass) )
00341               return false;
00342         }
00343         else if (destProtWildCard)
00344         {
00345            if ( !destProt.isEmpty() && !url.protocol().startsWith(destProt) &&
00346                 (protClass.isEmpty() || (protClass != destProt)) )
00347               return false;
00348         }
00349         else
00350         {
00351            if ( (url.protocol() != destProt) &&
00352                 (protClass.isEmpty() || (protClass != destProt)) )
00353               return false;
00354         }
00355         if (destHostWildCard)
00356         {
00357            if (!destHost.isEmpty() && !url.host().endsWith(destHost))
00358               return false;
00359         }
00360         else if (destHostEqual)
00361         {
00362            if (url.host() != base.host())
00363               return false;
00364         }
00365         else
00366         {
00367            if (url.host() != destHost)
00368               return false;
00369         }
00370         if (destPathWildCard)
00371         {
00372            if (!destPath.isEmpty() && !url.path().startsWith(destPath))
00373               return false;
00374         }
00375         else
00376         {
00377            if (url.path() != destPath)
00378               return false;
00379         }
00380         return true;
00381      }
00382 
00383      QString action;
00384      QString baseProt;
00385      QString baseHost;
00386      QString basePath;
00387      QString destProt;
00388      QString destHost;
00389      QString destPath;
00390      bool baseProtWildCard : 1;
00391      bool baseHostWildCard : 1;
00392      bool basePathWildCard : 1;
00393      bool destProtWildCard : 1;
00394      bool destHostWildCard : 1;
00395      bool destPathWildCard : 1;
00396      bool destProtEqual    : 1;
00397      bool destHostEqual    : 1;
00398      bool permission;
00399   };
00400   QPtrList<URLActionRule> urlActionRestrictions;
00401 
00402     QString sessionKey;
00403     QString pSessionConfigFile;
00404 };
00405 
00406 
00407 static QPtrList<QWidget>*x11Filter = 0;
00408 static bool autoDcopRegistration = true;
00409 
00410 void KApplication::installX11EventFilter( QWidget* filter )
00411 {
00412     if ( !filter )
00413         return;
00414     if (!x11Filter)
00415         x11Filter = new QPtrList<QWidget>;
00416     connect ( filter, SIGNAL( destroyed() ), this, SLOT( x11FilterDestroyed() ) );
00417     x11Filter->append( filter );
00418 }
00419 
00420 void KApplication::x11FilterDestroyed()
00421 {
00422     removeX11EventFilter( static_cast< const QWidget* >( sender()));
00423 }
00424 
00425 void KApplication::removeX11EventFilter( const QWidget* filter )
00426 {
00427     if ( !x11Filter || !filter )
00428         return;
00429     x11Filter->removeRef( filter );
00430     if ( x11Filter->isEmpty() ) {
00431         delete x11Filter;
00432         x11Filter = 0;
00433     }
00434 }
00435 
00436 // FIXME: remove this when we've get a better method of
00437 // customizing accelerator handling -- hopefully in Qt.
00438 // For now, this is set whenever an accelerator is overridden
00439 // in KAccelEventHandler so that the AccelOverride isn't sent twice. -- ellis, 19/10/02
00440 extern bool kde_g_bKillAccelOverride;
00441 
00442 bool KApplication::notify(QObject *receiver, QEvent *event)
00443 {
00444     QEvent::Type t = event->type();
00445     if (kde_g_bKillAccelOverride)
00446     {
00447        kde_g_bKillAccelOverride = false;
00448        // Indicate that the accelerator has been overridden.
00449        if (t == QEvent::AccelOverride)
00450        {
00451           static_cast<QKeyEvent *>(event)->accept();
00452           return true;
00453        }
00454        else
00455           kdWarning(125) << "kde_g_bKillAccelOverride set, but received an event other than AccelOverride." << endl;
00456     }
00457 
00458     if ((t == QEvent::AccelOverride) || (t == QEvent::KeyPress))
00459     {
00460        static const KShortcut& _selectAll = KStdAccel::selectAll();
00461        QLineEdit *edit = ::qt_cast<QLineEdit *>(receiver);
00462        if (edit)
00463        {
00464           // We have a keypress for a lineedit...
00465           QKeyEvent *kevent = static_cast<QKeyEvent *>(event);
00466           KKey key(kevent);
00467           if (_selectAll.contains(key))
00468           {
00469              if (t == QEvent::KeyPress)
00470              {
00471                 edit->selectAll();
00472                 return true;
00473              }
00474              else
00475              {
00476                 kevent->accept();
00477              }
00478           }
00479           // Ctrl-U deletes from start of line.
00480           if (key == KKey(Qt::CTRL + Qt::Key_U))
00481           {
00482              if (t == QEvent::KeyPress)
00483              {
00484                 if (!edit->isReadOnly())
00485                 {
00486                    QString t(edit->text());
00487                    t = t.mid(edit->cursorPosition());
00488                    edit->validateAndSet(t, 0, 0, 0);
00489                 }
00490                 return true;
00491              }
00492              else
00493              {
00494                 kevent->accept();
00495              }
00496 
00497           }
00498        }
00499        QTextEdit *medit = ::qt_cast<QTextEdit *>(receiver);
00500        if (medit)
00501        {
00502           // We have a keypress for a multilineedit...
00503           QKeyEvent *kevent = static_cast<QKeyEvent *>(event);
00504           if (_selectAll.contains(KKey(kevent)))
00505           {
00506              if (t == QEvent::KeyPress)
00507              {
00508                 medit->selectAll();
00509                 return true;
00510              }
00511              else
00512              {
00513                 kevent->accept();
00514              }
00515           }
00516        }
00517     }
00518     if( t == QEvent::Show && receiver->isWidgetType())
00519     {
00520         QWidget* w = static_cast< QWidget* >( receiver );
00521 #if defined Q_WS_X11
00522         if( w->isTopLevel() && !startupId().isEmpty() && !static_cast<QShowEvent*>(event)->spontaneous()) // TODO better done using window group leader?
00523             KStartupInfo::setWindowStartupId( w->winId(), startupId());
00524 #endif
00525         if( w->isTopLevel() && !w->testWFlags( WX11BypassWM ) && !w->isPopup() && !event->spontaneous())
00526         {
00527             if( d->app_started_timer == NULL )
00528             {
00529                 d->app_started_timer = new QTimer( this, "app_started_timer" );
00530                 connect( d->app_started_timer, SIGNAL( timeout()), SLOT( checkAppStartedSlot()));
00531             }
00532             if( !d->app_started_timer->isActive())
00533                 d->app_started_timer->start( 0, true );
00534         }
00535         if( w->isTopLevel() && ( w->icon() == NULL || w->icon()->isNull()))
00536         {
00537             // icon() cannot be null pixmap, it'll be the "unknown" icon - so check if there is this application icon
00538             static QPixmap* ic = NULL;
00539             if( ic == NULL )
00540                 ic = new QPixmap( KGlobal::iconLoader()->loadIcon( iconName(),
00541                     KIcon::NoGroup, 0, KIcon::DefaultState, NULL, true ));
00542             if( !ic->isNull())
00543             {
00544                 w->setIcon( *ic );
00545 #if defined Q_WS_X11
00546                 KWin::setIcons( w->winId(), *ic, miniIcon());
00547 #endif
00548             }
00549         }
00550     }
00551     return QApplication::notify(receiver, event);
00552 }
00553 
00554 void KApplication::checkAppStartedSlot()
00555 {
00556 #if defined Q_WS_X11
00557     KStartupInfo::handleAutoAppStartedSending();
00558 #endif
00559 }
00560 
00561 // the help class for session management communication
00562 static QPtrList<KSessionManaged>* sessionClients()
00563 {
00564     static QPtrList<KSessionManaged>* session_clients = 0L;
00565     if ( !session_clients )
00566         session_clients = new QPtrList<KSessionManaged>;
00567     return session_clients;
00568 }
00569 
00570 /*
00571   Auxiliary function to calculate a a session config name used for the
00572   instance specific config object.
00573   Syntax:  "session/<appname>_<sessionId>"
00574  */
00575 QString KApplication::sessionConfigName() const
00576 {
00577     QString sessKey = sessionKey();
00578     if ( sessKey.isEmpty() && !d->sessionKey.isEmpty() )
00579         sessKey = d->sessionKey;
00580     return QString("session/%1_%2_%3").arg(name()).arg(sessionId()).arg(sessKey);
00581 }
00582 
00583 #ifdef Q_WS_X11
00584 static SmcConn mySmcConnection = 0;
00585 static SmcConn tmpSmcConnection = 0;
00586 #else
00587 // FIXME(E): Implement for Qt Embedded
00588 // Possibly "steal" XFree86's libSM?
00589 #endif
00590 static QTime* smModificationTime = 0;
00591 
00592 KApplication::KApplication( int& argc, char** argv, const QCString& rAppName,
00593                             bool allowStyles, bool GUIenabled ) :
00594   QApplication( argc, argv, GUIenabled ), KInstance(rAppName),
00595 #ifdef Q_WS_X11
00596   display(0L),
00597 #endif
00598   d (new KApplicationPrivate())
00599 {
00600     aIconPixmap.pm.icon = 0L;
00601     aIconPixmap.pm.miniIcon = 0L;
00602     read_app_startup_id();
00603     if (!GUIenabled)
00604        allowStyles = false;
00605     useStyles = allowStyles;
00606     Q_ASSERT (!rAppName.isEmpty());
00607     setName(rAppName);
00608 
00609     installSigpipeHandler();
00610     KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
00611     parseCommandLine( );
00612     init(GUIenabled);
00613     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00614 }
00615 
00616 KApplication::KApplication( bool allowStyles, bool GUIenabled ) :
00617   QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00618                 GUIenabled ),
00619   KInstance( KCmdLineArgs::about),
00620 #ifdef Q_WS_X11
00621   display(0L),
00622 #endif
00623   d (new KApplicationPrivate)
00624 {
00625     aIconPixmap.pm.icon = 0L;
00626     aIconPixmap.pm.miniIcon = 0L;
00627     read_app_startup_id();
00628     if (!GUIenabled)
00629        allowStyles = false;
00630     useStyles = allowStyles;
00631     setName( instanceName() );
00632 
00633     installSigpipeHandler();
00634     parseCommandLine( );
00635     init(GUIenabled);
00636     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00637 }
00638 
00639 #ifdef Q_WS_X11
00640 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
00641                     bool allowStyles ) :
00642   QApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00643                 visual, colormap ),
00644   KInstance( KCmdLineArgs::about), display(0L), d (new KApplicationPrivate)
00645 {
00646     aIconPixmap.pm.icon = 0L;
00647     aIconPixmap.pm.miniIcon = 0L;
00648     read_app_startup_id();
00649     useStyles = allowStyles;
00650     setName( instanceName() );
00651     installSigpipeHandler();
00652     parseCommandLine( );
00653     init( true );
00654     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00655 }
00656 
00657 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
00658                     bool allowStyles, KInstance * _instance ) :
00659   QApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00660                 visual, colormap ),
00661   KInstance( _instance ), display(0L), d (new KApplicationPrivate)
00662 {
00663     aIconPixmap.pm.icon = 0L;
00664     aIconPixmap.pm.miniIcon = 0L;
00665     read_app_startup_id();
00666     useStyles = allowStyles;
00667     setName( instanceName() );
00668     installSigpipeHandler();
00669     parseCommandLine( );
00670     init( true );
00671     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00672 }
00673 #endif
00674 
00675 KApplication::KApplication( bool allowStyles, bool GUIenabled, KInstance* _instance ) :
00676   QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00677                 GUIenabled ),
00678   KInstance( _instance ),
00679 #ifdef Q_WS_X11
00680   display(0L),
00681 #endif
00682   d (new KApplicationPrivate)
00683 {
00684     aIconPixmap.pm.icon = 0L;
00685     aIconPixmap.pm.miniIcon = 0L;
00686     read_app_startup_id();
00687     if (!GUIenabled)
00688        allowStyles = false;
00689     useStyles = allowStyles;
00690     setName( instanceName() );
00691 
00692     installSigpipeHandler();
00693     parseCommandLine( );
00694     init(GUIenabled);
00695     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00696 }
00697 
00698 #ifdef Q_WS_X11
00699 KApplication::KApplication(Display *display, int& argc, char** argv, const QCString& rAppName,
00700                            bool allowStyles, bool GUIenabled ) :
00701   QApplication( display ), KInstance(rAppName),
00702   display(0L),
00703   d (new KApplicationPrivate())
00704 {
00705     aIconPixmap.pm.icon = 0L;
00706     aIconPixmap.pm.miniIcon = 0L;
00707     read_app_startup_id();
00708     if (!GUIenabled)
00709        allowStyles = false;
00710     useStyles = allowStyles;
00711 
00712     Q_ASSERT (!rAppName.isEmpty());
00713     setName(rAppName);
00714 
00715     installSigpipeHandler();
00716     KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
00717     parseCommandLine( );
00718     init(GUIenabled);
00719     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00720 }
00721 #endif
00722 
00723 int KApplication::xioErrhandler( Display* dpy )
00724 {
00725     if(kapp)
00726     {
00727         emit shutDown();
00728 #ifdef Q_WS_X11
00729         d->oldXIOErrorHandler( dpy );
00730 #else
00731         Q_UNUSED(dpy);
00732 #endif
00733     }
00734     exit( 1 );
00735     return 0;
00736 }
00737 
00738 int KApplication::xErrhandler( Display* dpy, void* err_ )
00739 { // no idea how to make forward decl. for XErrorEvent
00740 #ifdef Q_WS_X11
00741     XErrorEvent* err = static_cast< XErrorEvent* >( err_ );
00742     if(kapp)
00743     {
00744         // add KDE specific stuff here
00745         d->oldXErrorHandler( dpy, err );
00746     }
00747 #endif
00748     return 0;
00749 }
00750 
00751 void KApplication::iceIOErrorHandler( _IceConn *conn )
00752 {
00753     emit shutDown();
00754 
00755 #ifdef Q_WS_X11
00756     if ( d->oldIceIOErrorHandler != NULL )
00757       (*d->oldIceIOErrorHandler)( conn );
00758 #endif
00759     exit( 1 );
00760 }
00761 
00762 class KDETranslator : public QTranslator
00763 {
00764 public:
00765   KDETranslator(QObject *parent) : QTranslator(parent, "kdetranslator") {}
00766   virtual QTranslatorMessage findMessage(const char* context,
00767                      const char *sourceText,
00768                      const char* message) const
00769   {
00770     QTranslatorMessage res;
00771     res.setTranslation(KGlobal::locale()->translateQt(context, sourceText, message));
00772     return res;
00773   }
00774 };
00775 
00776 void KApplication::init(bool GUIenabled)
00777 {
00778   d->guiEnabled = GUIenabled;
00779   if ((getuid() != geteuid()) ||
00780       (getgid() != getegid()))
00781   {
00782      fprintf(stderr, "The KDE libraries are not designed to run with suid privileges.\n");
00783      ::exit(127);
00784   }
00785 
00786   KProcessController::ref();
00787 
00788   (void) KClipboardSynchronizer::self();
00789 
00790   QApplication::setDesktopSettingsAware( false );
00791 
00792   KApp = this;
00793 
00794 
00795 #ifdef Q_WS_X11 //FIXME(E)
00796   // create all required atoms in _one_ roundtrip to the X server
00797   if ( GUIenabled ) {
00798       const int max = 20;
00799       Atom* atoms[max];
00800       char* names[max];
00801       Atom atoms_return[max];
00802       int n = 0;
00803 
00804       atoms[n] = &kipcCommAtom;
00805       names[n++] = (char *) "KIPC_COMM_ATOM";
00806 
00807       atoms[n] = &atom_DesktopWindow;
00808       names[n++] = (char *) "KDE_DESKTOP_WINDOW";
00809 
00810       atoms[n] = &atom_NetSupported;
00811       names[n++] = (char *) "_NET_SUPPORTED";
00812 
00813       atoms[n] = &kde_xdnd_drop;
00814       names[n++] = (char *) "XdndDrop";
00815 
00816       XInternAtoms( qt_xdisplay(), names, n, false, atoms_return );
00817 
00818       for (int i = 0; i < n; i++ )
00819       *atoms[i] = atoms_return[i];
00820   }
00821 #endif
00822 
00823   dcopAutoRegistration();
00824   dcopClientPostInit();
00825 
00826   smw = 0;
00827 
00828   // Initial KIPC event mask.
00829 #if defined Q_WS_X11
00830   kipcEventMask = (1 << KIPC::StyleChanged) | (1 << KIPC::PaletteChanged) |
00831                   (1 << KIPC::FontChanged) | (1 << KIPC::BackgroundChanged) |
00832                   (1 << KIPC::ToolbarStyleChanged) | (1 << KIPC::SettingsChanged) |
00833                   (1 << KIPC::ClipboardConfigChanged) | (1 << KIPC::BlockShortcuts);
00834 #endif
00835 
00836   // Trigger creation of locale.
00837   (void) KGlobal::locale();
00838 
00839   KConfig* config = KGlobal::config();
00840   d->actionRestrictions = config->hasGroup("KDE Action Restrictions" ) && !kde_kiosk_exception;
00841   // For brain-dead configurations where the user's local config file is not writable.
00842   // * We use kdialog to warn the user, so we better not generate warnings from
00843   //   kdialog itself.
00844   // * Don't warn if we run with a read-only $HOME
00845   QCString readOnly = getenv("KDE_HOME_READONLY");
00846   if (readOnly.isEmpty() && (qstrcmp(name(), "kdialog") != 0))
00847   {
00848     KConfigGroupSaver saver(config, "KDE Action Restrictions");
00849     if (config->readBoolEntry("warn_unwritable_config",true))
00850        config->checkConfigFilesWritable(true);
00851   }
00852 
00853   if (GUIenabled)
00854   {
00855 #ifdef Q_WS_X11
00856     // this is important since we fork() to launch the help (Matthias)
00857     fcntl(ConnectionNumber(qt_xdisplay()), F_SETFD, FD_CLOEXEC);
00858     // set up the fancy (=robust and error ignoring ) KDE xio error handlers (Matthias)
00859     d->oldXErrorHandler = XSetErrorHandler( kde_x_errhandler );
00860     d->oldXIOErrorHandler = XSetIOErrorHandler( kde_xio_errhandler );
00861 #endif
00862 
00863     connect( this, SIGNAL( aboutToQuit() ), this, SIGNAL( shutDown() ) );
00864 
00865 #ifdef Q_WS_X11 //FIXME(E)
00866     display = desktop()->x11Display();
00867 #endif
00868 
00869     {
00870         QStringList plugins = KGlobal::dirs()->resourceDirs( "qtplugins" );
00871         QStringList::Iterator it = plugins.begin();
00872         while (it != plugins.end()) {
00873             addLibraryPath( *it );
00874             ++it;
00875         }
00876 
00877     }
00878     kdisplaySetStyle();
00879     kdisplaySetFont();
00880 //    kdisplaySetPalette(); done by kdisplaySetStyle
00881     propagateSettings(SETTINGS_QT);
00882 
00883     // Set default mime-source factory
00884     // XXX: This is a hack. Make our factory the default factory, but add the
00885     // previous default factory to the list of factories. Why? When the default
00886     // factory can't resolve something, it iterates in the list of factories.
00887     // But it QWhatsThis only uses the default factory. So if there was already
00888     // a default factory (which happens when using an image library using uic),
00889     // we prefer KDE's factory and so we put that old default factory in the
00890     // list and use KDE as the default. This may speed up things as well.
00891     QMimeSourceFactory* oldDefaultFactory = QMimeSourceFactory::takeDefaultFactory();
00892     QMimeSourceFactory::setDefaultFactory( mimeSourceFactory() );
00893     if ( oldDefaultFactory ) {
00894         QMimeSourceFactory::addFactory( oldDefaultFactory );
00895     }
00896 
00897     d->checkAccelerators = new KCheckAccelerators( this );
00898   }
00899 
00900 #ifdef Q_WS_MACX
00901   if (GUIenabled) {
00902       QPixmap pixmap = KGlobal::iconLoader()->loadIcon( KCmdLineArgs::appName(),
00903               KIcon::NoGroup, KIcon::SizeLarge, KIcon::DefaultState, 0L, false );
00904       if (!pixmap.isNull()) {
00905           QImage i = pixmap.convertToImage().convertDepth(32).smoothScale(40, 40);
00906           for(int y = 0; y < i.height(); y++) {
00907               uchar *l = i.scanLine(y);
00908               for(int x = 0; x < i.width(); x+=4)
00909                   *(l+x) = 255;
00910           }
00911           CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
00912           CGDataProviderRef dp = CGDataProviderCreateWithData(NULL,
00913                   i.bits(), i.numBytes(), NULL);
00914           CGImageRef ir = CGImageCreate(i.width(), i.height(), 8, 32, i.bytesPerLine(),
00915                   cs, kCGImageAlphaNoneSkipFirst, dp,
00916                   0, 0, kCGRenderingIntentDefault);
00917           //cleanup
00918           SetApplicationDockTileImage(ir);
00919           CGImageRelease(ir);
00920           CGColorSpaceRelease(cs);
00921           CGDataProviderRelease(dp);
00922       }
00923   }
00924 #endif
00925 
00926 
00927   // save and restore the RTL setting, as installTranslator calls qt_detectRTLLanguage,
00928   // which makes it impossible to use the -reverse cmdline switch with KDE apps
00929   bool rtl = reverseLayout();
00930   installTranslator(new KDETranslator(this));
00931   setReverseLayout( rtl );
00932   if (i18n( "_: Dear Translator! Translate this string to the string 'LTR' in "
00933      "left-to-right languages (as english) or to 'RTL' in right-to-left "
00934      "languages (such as Hebrew and Arabic) to get proper widget layout." ) == "RTL")
00935     setReverseLayout( !rtl );
00936 
00937   // install appdata resource type
00938   KGlobal::dirs()->addResourceType("appdata", KStandardDirs::kde_default("data")
00939                                    + QString::fromLatin1(name()) + '/');
00940   pSessionConfig = 0L;
00941   bSessionManagement = true;
00942 
00943 #ifdef Q_WS_X11
00944   // register a communication window for desktop changes (Matthias)
00945   if (GUIenabled && kde_have_kipc )
00946   {
00947     smw = new QWidget(0,0);
00948     long data = 1;
00949     XChangeProperty(qt_xdisplay(), smw->winId(),
00950             atom_DesktopWindow, atom_DesktopWindow,
00951             32, PropModeReplace, (unsigned char *)&data, 1);
00952   }
00953   d->oldIceIOErrorHandler = IceSetIOErrorHandler( kde_ice_ioerrorhandler );
00954 #elif defined(Q_WS_WIN)
00955   KApplication_init_windows(GUIenabled);
00956 #else
00957   // FIXME(E): Implement for Qt Embedded
00958 #endif
00959 }
00960 
00961 static int my_system (const char *command) {
00962    int pid, status;
00963 
00964    pid = fork();
00965    if (pid == -1)
00966       return -1;
00967    if (pid == 0) {
00968       const char* shell = "/bin/sh";
00969       execl(shell, shell, "-c", command, (void *)0);
00970       ::_exit(127);
00971    }
00972    do {
00973       if (waitpid(pid, &status, 0) == -1) {
00974          if (errno != EINTR)
00975             return -1;
00976        } else
00977             return status;
00978    } while(1);
00979 }
00980 
00981 
00982 DCOPClient *KApplication::dcopClient()
00983 {
00984   if (s_DCOPClient)
00985     return s_DCOPClient;
00986 
00987   s_DCOPClient = new DCOPClient();
00988   KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
00989   if (args && args->isSet("dcopserver"))
00990   {
00991     s_DCOPClient->setServerAddress( args->getOption("dcopserver"));
00992   }
00993   if( kapp ) {
00994     connect(s_DCOPClient, SIGNAL(attachFailed(const QString &)),
00995             kapp, SLOT(dcopFailure(const QString &)));
00996     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
00997             kapp, SLOT(dcopBlockUserInput(bool)) );
00998   }
00999   else
01000     s_dcopClientNeedsPostInit = true;
01001 
01002   DCOPClient::setMainClient( s_DCOPClient );
01003   return s_DCOPClient;
01004 }
01005 
01006 void KApplication::dcopClientPostInit()
01007 {
01008   if( s_dcopClientNeedsPostInit )
01009     {
01010     s_dcopClientNeedsPostInit = false;
01011     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
01012             SLOT(dcopBlockUserInput(bool)) );
01013     s_DCOPClient->bindToApp(); // Make sure we get events from the DCOPClient.
01014     }
01015 }
01016 
01017 void KApplication::dcopAutoRegistration()
01018 {
01019   if (autoDcopRegistration)
01020      {
01021      ( void ) dcopClient();
01022      if( dcopClient()->appId().isEmpty())
01023          dcopClient()->registerAs(name());
01024      }
01025 }
01026 
01027 void KApplication::disableAutoDcopRegistration()
01028 {
01029   autoDcopRegistration = false;
01030 }
01031 
01032 KConfig* KApplication::sessionConfig()
01033 {
01034     if (pSessionConfig)
01035         return pSessionConfig;
01036 
01037     // create an instance specific config object
01038     pSessionConfig = new KConfig( sessionConfigName(), false, false);
01039     return pSessionConfig;
01040 }
01041 
01042 void KApplication::ref()
01043 {
01044     d->refCount++;
01045     //kdDebug() << "KApplication::ref() : refCount = " << d->refCount << endl;
01046 }
01047 
01048 void KApplication::deref()
01049 {
01050     d->refCount--;
01051     //kdDebug() << "KApplication::deref() : refCount = " << d->refCount << endl;
01052     if ( d->refCount <= 0 )
01053         quit();
01054 }
01055 
01056 KSessionManaged::KSessionManaged()
01057 {
01058     sessionClients()->remove( this );
01059     sessionClients()->append( this );
01060 }
01061 
01062 KSessionManaged::~KSessionManaged()
01063 {
01064     sessionClients()->remove( this );
01065 }
01066 
01067 bool KSessionManaged::saveState(QSessionManager&)
01068 {
01069     return true;
01070 }
01071 
01072 bool KSessionManaged::commitData(QSessionManager&)
01073 {
01074     return true;
01075 }
01076 
01077 
01078 void KApplication::disableSessionManagement() {
01079   bSessionManagement = false;
01080 }
01081 
01082 void KApplication::enableSessionManagement() {
01083   bSessionManagement = true;
01084 #ifdef Q_WS_X11
01085   // Session management support in Qt/KDE is awfully broken.
01086   // If konqueror disables session management right after its startup,
01087   // and enables it later (preloading stuff), it won't be properly
01088   // saved on session shutdown.
01089   // I'm not actually sure why it doesn't work, but saveState()
01090   // doesn't seem to be called on session shutdown, possibly
01091   // because disabling session management after konqueror startup
01092   // disabled it somehow. Forcing saveState() here for this application
01093   // seems to fix it.
01094   if( mySmcConnection ) {
01095         SmcRequestSaveYourself( mySmcConnection, SmSaveLocal, False,
01096                 SmInteractStyleAny,
01097                 False, False );
01098 
01099     // flush the request
01100     IceFlush(SmcGetIceConnection(mySmcConnection));
01101   }
01102 #endif
01103 }
01104 
01105 
01106 bool KApplication::requestShutDown(
01107     ShutdownConfirm confirm, ShutdownType sdtype, ShutdownMode sdmode )
01108 {
01109 #ifdef Q_WS_X11
01110     QApplication::syncX();
01111     /*  use ksmserver's dcop interface if necessary  */
01112     if ( confirm == ShutdownConfirmYes ||
01113          sdtype != ShutdownTypeDefault ||
01114          sdmode != ShutdownModeDefault )
01115     {
01116         QByteArray data;
01117         QDataStream arg(data, IO_WriteOnly);
01118         arg << (int)confirm << (int)sdtype << (int)sdmode;
01119     return dcopClient()->send( "ksmserver", "ksmserver",
01120                                    "logout(int,int,int)", data );
01121     }
01122 
01123     if ( mySmcConnection ) {
01124         // we already have a connection to the session manager, use it.
01125         SmcRequestSaveYourself( mySmcConnection, SmSaveBoth, True,
01126                 SmInteractStyleAny,
01127                 confirm == ShutdownConfirmNo, True );
01128 
01129     // flush the request
01130     IceFlush(SmcGetIceConnection(mySmcConnection));
01131         return true;
01132     }
01133 
01134     // open a temporary connection, if possible
01135 
01136     propagateSessionManager();
01137     QCString smEnv = ::getenv("SESSION_MANAGER");
01138     if (smEnv.isEmpty())
01139         return false;
01140 
01141     if (! tmpSmcConnection) {
01142     char cerror[256];
01143     char* myId = 0;
01144     char* prevId = 0;
01145     SmcCallbacks cb;
01146     tmpSmcConnection = SmcOpenConnection( 0, 0, 1, 0,
01147                           0, &cb,
01148                           prevId,
01149                           &myId,
01150                           255,
01151                           cerror );
01152     ::free( myId ); // it was allocated by C
01153     if (!tmpSmcConnection )
01154         return false;
01155     }
01156 
01157     SmcRequestSaveYourself( tmpSmcConnection, SmSaveBoth, True,
01158                 SmInteractStyleAny, False, True );
01159 
01160     // flush the request
01161     IceFlush(SmcGetIceConnection(tmpSmcConnection));
01162     return true;
01163 #else
01164     // FIXME(E): Implement for Qt Embedded
01165     return false;
01166 #endif
01167 }
01168 
01169 void KApplication::propagateSessionManager()
01170 {
01171 #ifdef Q_WS_X11
01172     QCString fName = QFile::encodeName(locateLocal("socket", "KSMserver"));
01173     QCString display = ::getenv(DISPLAY);
01174     // strip the screen number from the display
01175     display.replace(QRegExp("\\.[0-9]+$"), "");
01176     int i;
01177     while( (i = display.find(':')) >= 0)
01178        display[i] = '_';
01179 
01180     fName += "_"+display;
01181     QCString smEnv = ::getenv("SESSION_MANAGER");
01182     bool check = smEnv.isEmpty();
01183     if ( !check && smModificationTime ) {
01184          QFileInfo info( fName );
01185          QTime current = info.lastModified().time();
01186          check = current > *smModificationTime;
01187     }
01188     if ( check ) {
01189         delete smModificationTime;
01190         QFile f( fName );
01191         if ( !f.open( IO_ReadOnly ) )
01192             return;
01193         QFileInfo info ( f );
01194         smModificationTime = new QTime( info.lastModified().time() );
01195         QTextStream t(&f);
01196         t.setEncoding( QTextStream::Latin1 );
01197         QString s = t.readLine();
01198         f.close();
01199         ::setenv( "SESSION_MANAGER", s.latin1(), true  );
01200     }
01201 #endif
01202 }
01203 
01204 void KApplication::commitData( QSessionManager& sm )
01205 {
01206     d->session_save = true;
01207     bool canceled = false;
01208     for (KSessionManaged* it = sessionClients()->first();
01209          it && !canceled;
01210          it = sessionClients()->next() ) {
01211         canceled = !it->commitData( sm );
01212     }
01213     if ( canceled )
01214         sm.cancel();
01215 
01216     if ( sm.allowsInteraction() ) {
01217         QWidgetList done;
01218         QWidgetList *list = QApplication::topLevelWidgets();
01219         bool canceled = false;
01220         QWidget* w = list->first();
01221         while ( !canceled && w ) {
01222             if ( !w->testWState( WState_ForceHide ) && !w->inherits("KMainWindow") ) {
01223                 QCloseEvent e;
01224                 sendEvent( w, &e );
01225                 canceled = !e.isAccepted();
01226                 if ( !canceled )
01227                     done.append( w );
01228                 delete list; // one never knows...
01229                 list = QApplication::topLevelWidgets();
01230                 w = list->first();
01231             } else {
01232                 w = list->next();
01233             }
01234             while ( w && done.containsRef( w ) )
01235                 w = list->next();
01236         }
01237         delete list;
01238     }
01239 
01240 
01241     if ( !bSessionManagement )
01242         sm.setRestartHint( QSessionManager::RestartNever );
01243     else
01244     sm.setRestartHint( QSessionManager::RestartIfRunning );
01245     d->session_save = false;
01246 }
01247 
01248 void KApplication::saveState( QSessionManager& sm )
01249 {
01250     d->session_save = true;
01251 #ifdef Q_WS_X11
01252     static bool firstTime = true;
01253     mySmcConnection = (SmcConn) sm.handle();
01254 
01255     if ( !bSessionManagement ) {
01256         sm.setRestartHint( QSessionManager::RestartNever );
01257     d->session_save = false;
01258         return;
01259     }
01260     else
01261     sm.setRestartHint( QSessionManager::RestartIfRunning );
01262 
01263     if ( firstTime ) {
01264         firstTime = false;
01265     d->session_save = false;
01266         return; // no need to save the state.
01267     }
01268 
01269     // remove former session config if still existing, we want a new
01270     // and fresh one. Note that we do not delete the config file here,
01271     // this is done by the session manager when it executes the
01272     // discard commands. In fact it would be harmful to remove the
01273     // file here, as the session might be stored under a different
01274     // name, meaning the user still might need it eventually.
01275     if ( pSessionConfig ) {
01276         delete pSessionConfig;
01277         pSessionConfig = 0;
01278     }
01279 
01280     // tell the session manager about our new lifecycle
01281     QStringList restartCommand = sm.restartCommand();
01282 
01283     QCString multiHead = getenv("KDE_MULTIHEAD");
01284     if (multiHead.lower() == "true") {
01285         // if multihead is enabled, we save our -display argument so that
01286         // we are restored onto the correct head... one problem with this
01287         // is that the display is hard coded, which means we cannot restore
01288         // to a different display (ie. if we are in a university lab and try,
01289         // try to restore a multihead session, our apps could be started on
01290         // someone else's display instead of our own)
01291         QCString displayname = getenv(DISPLAY);
01292         if (! displayname.isNull()) {
01293             // only store the command if we actually have a DISPLAY
01294             // environment variable
01295             restartCommand.append("-display");
01296             restartCommand.append(displayname);
01297         }
01298         sm.setRestartCommand( restartCommand );
01299     }
01300 
01301 
01302     // finally: do session management
01303     emit saveYourself(); // for compatibility
01304     bool canceled = false;
01305     for (KSessionManaged* it = sessionClients()->first();
01306          it && !canceled;
01307          it = sessionClients()->next() ) {
01308         canceled = !it->saveState( sm );
01309     }
01310 
01311     // if we created a new session config object, register a proper discard command
01312     if ( pSessionConfig ) {
01313         pSessionConfig->sync();
01314         QStringList discard;
01315         discard  << "rm" << locateLocal("config", sessionConfigName());
01316         sm.setDiscardCommand( discard );
01317     } else {
01318     sm.setDiscardCommand( "" );
01319     }
01320 
01321     if ( canceled )
01322         sm.cancel();
01323 #else
01324     // FIXME(E): Implement for Qt Embedded
01325 #endif
01326     d->session_save = false;
01327 }
01328 
01329 bool KApplication::sessionSaving() const
01330 {
01331     return d->session_save;
01332 }
01333 
01334 void KApplication::startKdeinit()
01335 {
01336 #ifndef Q_WS_WIN //TODO
01337   KInstance inst( "startkdeinitlock" );
01338   KLockFile lock( locateLocal( "tmp", "startkdeinitlock", &inst ));
01339   if( lock.lock( KLockFile::LockNoBlock ) != KLockFile::LockOK ) {
01340      lock.lock();
01341      DCOPClient cl;
01342      if( cl.attach())
01343          return; // whoever held the lock has already started dcopserver
01344   }
01345   // Try to launch kdeinit.
01346   QString srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"));
01347   if (srv.isEmpty())
01348      srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"), KGlobal::dirs()->kfsstnd_defaultbindir());
01349   if (srv.isEmpty())
01350      return;
01351   if (kapp && (Tty != kapp->type()))
01352     setOverrideCursor( Qt::waitCursor );
01353   my_system(QFile::encodeName(srv)+" --suicide");
01354   if (kapp && (Tty != kapp->type()))
01355     restoreOverrideCursor();
01356 #endif
01357 }
01358 
01359 void KApplication::dcopFailure(const QString &msg)
01360 {
01361   static int failureCount = 0;
01362   failureCount++;
01363   if (failureCount == 1)
01364   {
01365      startKdeinit();
01366      return;
01367   }
01368   if (failureCount == 2)
01369   {
01370 #ifdef Q_WS_WIN
01371      KGlobal::config()->setGroup("General");
01372      if (KGlobal::config()->readBoolEntry("ignoreDCOPFailures", false))
01373          return;
01374 #endif
01375      QString msgStr(i18n("There was an error setting up inter-process "
01376                       "communications for KDE. The message returned "
01377                       "by the system was:\n\n"));
01378      msgStr += msg;
01379      msgStr += i18n("\n\nPlease check that the \"dcopserver\" program is running!");
01380 
01381      if (Tty != kapp->type())
01382      {
01383        QMessageBox::critical
01384          (
01385            kapp->mainWidget(),
01386            i18n("DCOP communications error (%1)").arg(kapp->caption()),
01387            msgStr,
01388            i18n("&OK")
01389          );
01390      }
01391      else
01392      {
01393        fprintf(stderr, "%s\n", msgStr.local8Bit().data());
01394      }
01395 
01396      return;
01397   }
01398 }
01399 
01400 static const KCmdLineOptions qt_options[] =
01401 {
01402   //FIXME: Check if other options are specific to Qt/X11
01403 #ifdef Q_WS_X11
01404    { "display <displayname>", I18N_NOOP("Use the X-server display 'displayname'"), 0},
01405 #else
01406    { "display <displayname>", I18N_NOOP("Use the QWS display 'displayname'"), 0},
01407 #endif
01408    { "session <sessionId>", I18N_NOOP("Restore the application for the given 'sessionId'"), 0},
01409    { "cmap", I18N_NOOP("Causes the application to install a private color\nmap on an 8-bit display"), 0},
01410    { "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 QApplication::ManyColor color\nspecification"), 0},
01411    { "nograb", I18N_NOOP("tells Qt to never grab the mouse or the keyboard"), 0},
01412    { "dograb", I18N_NOOP("running under a debugger can cause an implicit\n-nograb, use -dograb to override"), 0},
01413    { "sync", I18N_NOOP("switches to synchronous mode for debugging"), 0},
01414    { "fn", 0, 0},
01415    { "font <fontname>", I18N_NOOP("defines the application font"), 0},
01416    { "bg", 0, 0},
01417    { "background <color>", I18N_NOOP("sets the default background color and an\napplication palette (light and dark shades are\ncalculated)"), 0},
01418    { "fg", 0, 0},
01419    { "foreground <color>", I18N_NOOP("sets the default foreground color"), 0},
01420    { "btn", 0, 0},
01421    { "button <color>", I18N_NOOP("sets the default button color"), 0},
01422    { "name <name>", I18N_NOOP("sets the application name"), 0},
01423    { "title <title>", I18N_NOOP("sets the application title (caption)"), 0},
01424 #ifdef Q_WS_X11
01425    { "visual TrueColor", I18N_NOOP("forces the application to use a TrueColor visual on\nan 8-bit display"), 0},
01426    { "inputstyle <inputstyle>", I18N_NOOP("sets XIM (X Input Method) input style. Possible\nvalues are onthespot, overthespot, offthespot and\nroot"), 0 },
01427    { "im <XIM server>", I18N_NOOP("set XIM server"),0},
01428    { "noxim", I18N_NOOP("disable XIM"), 0 },
01429 #endif
01430 #ifdef Q_WS_QWS
01431    { "qws", I18N_NOOP("forces the application to run as QWS Server"), 0},
01432 #endif
01433    { "reverse", I18N_NOOP("mirrors the whole layout of widgets"), 0},
01434    KCmdLineLastOption
01435 };
01436 
01437 static const KCmdLineOptions kde_options[] =
01438 {
01439    { "caption <caption>",       I18N_NOOP("Use 'caption' as name in the titlebar"), 0},
01440    { "icon <icon>",             I18N_NOOP("Use 'icon' as the application icon"), 0},
01441    { "miniicon <icon>",         I18N_NOOP("Use 'icon' as the icon in the titlebar"), 0},
01442    { "config <filename>",       I18N_NOOP("Use alternative configuration file"), 0},
01443    { "dcopserver <server>",     I18N_NOOP("Use the DCOP Server specified by 'server'"), 0},
01444    { "nocrashhandler",          I18N_NOOP("Disable crash handler, to get core dumps"), 0},
01445    { "waitforwm",          I18N_NOOP("Waits for a WM_NET compatible windowmanager"), 0},
01446    { "style <style>", I18N_NOOP("sets the application GUI style"), 0},
01447    { "geometry <geometry>", I18N_NOOP("sets the client geometry of the main widget - see man X for the argument format"), 0},
01448    { "smkey <sessionKey>", 0, 0}, // this option is obsolete and exists only to allow smooth upgrades from sessions
01449                                   // saved under Qt 3.0.x -- Qt 3.1.x includes the session key now automatically in
01450                   // the session id (Simon)
01451    KCmdLineLastOption
01452 };
01453 
01454 void
01455 KApplication::addCmdLineOptions()
01456 {
01457    KCmdLineArgs::addCmdLineOptions(qt_options, "Qt", "qt");
01458    KCmdLineArgs::addCmdLineOptions(kde_options, "KDE", "kde");
01459 }
01460 
01461 void KApplication::parseCommandLine( )
01462 {
01463     KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
01464 
01465     if ( !args ) return;
01466 
01467     if (args->isSet("config"))
01468     {
01469         QString config = QString::fromLocal8Bit(args->getOption("config"));
01470         setConfigName(config);
01471     }
01472 
01473     if (args->isSet("style"))
01474     {
01475 
01476        QStringList styles = QStyleFactory::keys();
01477        QString reqStyle(args->getOption("style").lower());
01478 
01479        for (QStringList::ConstIterator it = styles.begin(); it != styles.end(); ++it)
01480            if ((*it).lower() == reqStyle)
01481            {
01482                d->overrideStyle = *it;
01483                break;
01484            }
01485 
01486        if (d->overrideStyle.isEmpty())
01487           fprintf(stderr, "%s", i18n("The style %1 was not found\n").arg(reqStyle).local8Bit().data());
01488     }
01489 
01490     if (args->isSet("caption"))
01491     {
01492        aCaption = QString::fromLocal8Bit(args->getOption("caption"));
01493     }
01494 
01495     if (args->isSet("miniicon"))
01496     {
01497        const char *tmp = args->getOption("miniicon");
01498        if (!aIconPixmap.pm.miniIcon) {
01499          aIconPixmap.pm.miniIcon = new QPixmap;
01500        }
01501        *aIconPixmap.pm.miniIcon = SmallIcon(tmp);
01502        aMiniIconName = tmp;
01503     }
01504 
01505     if (args->isSet("icon"))
01506     {
01507        const char *tmp = args->getOption("icon");
01508        if (!aIconPixmap.pm.icon) {
01509           aIconPixmap.pm.icon = new QPixmap;
01510        }
01511        *aIconPixmap.pm.icon = DesktopIcon( tmp );
01512        aIconName = tmp;
01513        if (!aIconPixmap.pm.miniIcon) {
01514          aIconPixmap.pm.miniIcon = new QPixmap;
01515        }
01516        if (aIconPixmap.pm.miniIcon->isNull())
01517        {
01518           *aIconPixmap.pm.miniIcon = SmallIcon( tmp );
01519           aMiniIconName = tmp;
01520        }
01521     }
01522 
01523     bool nocrashhandler = (getenv("KDE_DEBUG") != NULL);
01524     if (!nocrashhandler && args->isSet("crashhandler"))
01525     {
01526         // set default crash handler / set emergency save function to nothing
01527         KCrash::setCrashHandler(KCrash::defaultCrashHandler);
01528         KCrash::setEmergencySaveFunction(NULL);
01529 
01530         KCrash::setApplicationName(QString(args->appName()));
01531     }
01532 
01533 #ifdef Q_WS_X11
01534     if ( args->isSet( "waitforwm" ) ) {
01535         Atom type;
01536         (void) desktop(); // trigger desktop creation, we need PropertyNotify events for the root window
01537         int format;
01538         unsigned long length, after;
01539         unsigned char *data;
01540         while ( XGetWindowProperty( qt_xdisplay(), qt_xrootwin(), atom_NetSupported,
01541                     0, 1, false, AnyPropertyType, &type, &format,
01542                                     &length, &after, &data ) != Success || !length ) {
01543             if ( data )
01544                 XFree( data );
01545             XEvent event;
01546             XWindowEvent( qt_xdisplay(), qt_xrootwin(), PropertyChangeMask, &event );
01547         }
01548         if ( data )
01549             XFree( data );
01550     }
01551 #else
01552     // FIXME(E): Implement for Qt Embedded
01553 #endif
01554 
01555     if (args->isSet("geometry"))
01556     {
01557         d->geometry_arg = args->getOption("geometry");
01558     }
01559 
01560     if (args->isSet("smkey"))
01561     {
01562         d->sessionKey = args->getOption("smkey");
01563     }
01564 
01565 }
01566 
01567 QString KApplication::geometryArgument() const
01568 {
01569     return d->geometry_arg;
01570 }
01571 
01572 QPixmap KApplication::icon() const
01573 {
01574   if( !aIconPixmap.pm.icon) {
01575       aIconPixmap.pm.icon = new QPixmap;
01576   }
01577   if( aIconPixmap.pm.icon->isNull()) {
01578       *aIconPixmap.pm.icon = DesktopIcon( instanceName() );
01579   }
01580   return *aIconPixmap.pm.icon;
01581 }
01582 
01583 QString KApplication::iconName() const
01584 {
01585   return aIconName.isNull() ? (QString)instanceName() : aIconName;
01586 }
01587 
01588 QPixmap KApplication::miniIcon() const
01589 {
01590   if (!aIconPixmap.pm.miniIcon) {
01591       aIconPixmap.pm.miniIcon = new QPixmap;
01592   }
01593   if (aIconPixmap.pm.miniIcon->isNull()) {
01594       *aIconPixmap.pm.miniIcon = SmallIcon( instanceName() );
01595   }
01596   return *aIconPixmap.pm.miniIcon;
01597 }
01598 
01599 QString KApplication::miniIconName() const
01600 {
01601   return aMiniIconName.isNull() ? (QString)instanceName() : aMiniIconName;
01602 }
01603 
01604 extern void kDebugCleanup();
01605 
01606 KApplication::~KApplication()
01607 {
01608   delete aIconPixmap.pm.miniIcon;
01609   aIconPixmap.pm.miniIcon = 0L;
01610   delete aIconPixmap.pm.icon;
01611   aIconPixmap.pm.icon = 0L;
01612   delete d->m_KAppDCOPInterface;
01613 
01614   // First call the static deleters and then call KLibLoader::cleanup()
01615   // The static deleters may delete libraries for which they need KLibLoader.
01616   // KLibLoader will take care of the remaining ones.
01617   KGlobal::deleteStaticDeleters();
01618   KLibLoader::cleanUp();
01619 
01620   delete smw;
01621 
01622   // close down IPC
01623   delete s_DCOPClient;
01624   s_DCOPClient = 0L;
01625 
01626   KProcessController::deref();
01627 
01628 #ifdef Q_WS_X11
01629   if ( d->oldXErrorHandler != NULL )
01630       XSetErrorHandler( d->oldXErrorHandler );
01631   if ( d->oldXIOErrorHandler != NULL )
01632       XSetIOErrorHandler( d->oldXIOErrorHandler );
01633   if ( d->oldIceIOErrorHandler != NULL )
01634       IceSetIOErrorHandler( d->oldIceIOErrorHandler );
01635 #endif
01636 
01637   delete d;
01638   KApp = 0;
01639 
01640 #ifdef Q_WS_X11
01641   mySmcConnection = 0;
01642   delete smModificationTime;
01643   smModificationTime = 0;
01644 
01645   // close the temporary smc connection
01646   if (tmpSmcConnection) {
01647       SmcCloseConnection( tmpSmcConnection, 0, 0 );
01648       tmpSmcConnection = 0;
01649   }
01650 #else
01651   // FIXME(E): Implement for Qt Embedded
01652 #endif
01653 }
01654 
01655 
01656 #ifdef Q_WS_X11
01657 class KAppX11HackWidget: public QWidget
01658 {
01659 public:
01660     bool publicx11Event( XEvent * e) { return x11Event( e ); }
01661 };
01662 #endif
01663 
01664 
01665 
01666 static bool kapp_block_user_input = false;
01667 
01668 void KApplication::dcopBlockUserInput( bool b )
01669 {
01670     kapp_block_user_input = b;
01671 }
01672 
01673 #ifdef Q_WS_X11
01674 bool KApplication::x11EventFilter( XEvent *_event )
01675 {
01676     switch ( _event->type ) {
01677         case ClientMessage:
01678         {
01679 #if KDE_IS_VERSION( 3, 90, 90 )
01680 #warning This should be already in Qt, check.
01681 #endif
01682         // Workaround for focus stealing prevention not working when dragging e.g. text from KWrite
01683         // to KDesktop -> the dialog asking for filename doesn't get activated. This is because
01684         // Qt-3.2.x doesn't have concept of qt_x_user_time at all, and Qt-3.3.0b1 passes the timestamp
01685         // in the XdndDrop message in incorrect field (and doesn't update qt_x_user_time either).
01686         // Patch already sent, future Qt version should have this fixed.
01687             if( _event->xclient.message_type == kde_xdnd_drop )
01688                 { // if the message is XdndDrop
01689                 if( _event->xclient.data.l[ 1 ] == 1 << 24     // and it's broken the way it's in Qt-3.2.x
01690                     && _event->xclient.data.l[ 2 ] == 0
01691                     && _event->xclient.data.l[ 4 ] == 0
01692                     && _event->xclient.data.l[ 3 ] != 0 )
01693                     {
01694                     if( qt_x_user_time == 0
01695                         || NET::timestampCompare( _event->xclient.data.l[ 3 ], qt_x_user_time ) > 0 )
01696                         { // and the timestamp looks reasonable
01697                         qt_x_user_time = _event->xclient.data.l[ 3 ]; // update our qt_x_user_time from it
01698                         }
01699                     }
01700                 else // normal DND, only needed until Qt updates qt_x_user_time from XdndDrop
01701                     {
01702                     if( qt_x_user_time == 0
01703                         || NET::timestampCompare( _event->xclient.data.l[ 2 ], qt_x_user_time ) > 0 )
01704                         { // the timestamp looks reasonable
01705                         qt_x_user_time = _event->xclient.data.l[ 2 ]; // update our qt_x_user_time from it
01706                         }
01707                     }
01708                 }
01709         }
01710     default: break;
01711     }
01712 
01713     if ( kapp_block_user_input ) {
01714         switch ( _event->type  ) {
01715         case ButtonPress:
01716         case ButtonRelease:
01717         case XKeyPress:
01718         case XKeyRelease:
01719         case MotionNotify:
01720         case EnterNotify:
01721         case LeaveNotify:
01722             return true;
01723         default:
01724             break;
01725         }
01726     }
01727 
01728     if (x11Filter) {
01729         for (QWidget *w=x11Filter->first(); w; w=x11Filter->next()) {
01730             if (((KAppX11HackWidget*) w)->publicx11Event(_event))
01731                 return true;
01732         }
01733     }
01734 
01735     if ((_event->type == ClientMessage) &&
01736             (_event->xclient.message_type == kipcCommAtom))
01737     {
01738         XClientMessageEvent *cme = (XClientMessageEvent *) _event;
01739 
01740         int id = cme->data.l[0];
01741         int arg = cme->data.l[1];
01742         if ((id < 32) && (kipcEventMask & (1 << id)))
01743         {
01744             switch (id)
01745             {
01746             case KIPC::StyleChanged:
01747                 KGlobal::config()->reparseConfiguration();
01748                 kdisplaySetStyle();
01749                 break;
01750 
01751             case KIPC::ToolbarStyleChanged:
01752                 KGlobal::config()->reparseConfiguration();
01753                 if (useStyles)
01754                     emit toolbarAppearanceChanged(arg);
01755                 break;
01756 
01757             case KIPC::PaletteChanged:
01758                 KGlobal::config()->reparseConfiguration();
01759                 kdisplaySetPalette();
01760                 break;
01761 
01762             case KIPC::FontChanged:
01763                 KGlobal::config()->reparseConfiguration();
01764                 KGlobalSettings::rereadFontSettings();
01765                 kdisplaySetFont();
01766                 break;
01767 
01768             case KIPC::BackgroundChanged:
01769                 emit backgroundChanged(arg);
01770                 break;
01771 
01772             case KIPC::SettingsChanged:
01773                 KGlobal::config()->reparseConfiguration();
01774                 if (arg == SETTINGS_PATHS)
01775                     KGlobalSettings::rereadPathSettings();
01776                 else if (arg == SETTINGS_MOUSE)
01777                     KGlobalSettings::rereadMouseSettings();
01778                 propagateSettings((SettingsCategory)arg);
01779                 break;
01780 
01781             case KIPC::IconChanged:
01782                 QPixmapCache::clear();
01783                 KGlobal::config()->reparseConfiguration();
01784                 KGlobal::instance()->newIconLoader();
01785                 emit updateIconLoaders();
01786                 emit iconChanged(arg);
01787                 break;
01788 
01789             case KIPC::ClipboardConfigChanged:
01790                 KClipboardSynchronizer::newConfiguration(arg);
01791                 break;
01792                 
01793             case KIPC::BlockShortcuts:
01794                 KGlobalAccel::blockShortcuts(arg);
01795                 emit kipcMessage(id, arg); // some apps may do additional things
01796                 break;
01797             }
01798         }
01799         else if (id >= 32)
01800         {
01801             emit kipcMessage(id, arg);
01802         }
01803         return true;
01804     }
01805     return false;
01806 }
01807 #endif // Q_WS_X11
01808 
01809 void KApplication::updateUserTimestamp( unsigned long time )
01810 {
01811 #if defined Q_WS_X11
01812     if( time == 0 )
01813     { // get current X timestamp
01814         Window w = XCreateSimpleWindow( qt_xdisplay(), qt_xrootwin(), 0, 0, 1, 1, 0, 0, 0 );
01815         XSelectInput( qt_xdisplay(), w, PropertyChangeMask );
01816         unsigned char data[ 1 ];
01817         XChangeProperty( qt_xdisplay(), w, XA_ATOM, XA_ATOM, 8, PropModeAppend, data, 1 );
01818         XEvent ev;
01819         XWindowEvent( qt_xdisplay(), w, PropertyChangeMask, &ev );
01820         time = ev.xproperty.time;
01821         XDestroyWindow( qt_xdisplay(), w );
01822     }
01823     if( qt_x_user_time == 0
01824         || NET::timestampCompare( time, qt_x_user_time ) > 0 ) // check time > qt_x_user_time
01825         qt_x_user_time = time;
01826 #endif
01827 }
01828 
01829 unsigned long KApplication::userTimestamp() const
01830 {
01831 #if defined Q_WS_X11
01832     return qt_x_user_time;
01833 #else
01834     return 0;
01835 #endif
01836 }
01837 
01838 void KApplication::updateRemoteUserTimestamp( const QCString& dcopId, unsigned long time )
01839 {
01840 #if defined Q_WS_X11
01841     if( time == 0 )
01842         time = qt_x_user_time;
01843     DCOPRef( dcopId, "MainApplication-Interface" ).call( "updateUserTimestamp", time );
01844 #endif
01845 }
01846 
01847 void KApplication::invokeEditSlot( const char *slot )
01848 {
01849   QObject *object = focusWidget();
01850   if( !object )
01851     return;
01852 
01853   QMetaObject *meta = object->metaObject();
01854 
01855   int idx = meta->findSlot( slot + 1, true );
01856   if( idx < 0 )
01857     return;
01858 
01859   object->qt_invoke( idx, 0 );
01860 }
01861 
01862 void KApplication::addKipcEventMask(int id)
01863 {
01864     if (id >= 32)
01865     {
01866         kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01867         return;
01868     }
01869     kipcEventMask |= (1 << id);
01870 }
01871 
01872 void KApplication::removeKipcEventMask(int id)
01873 {
01874     if (id >= 32)
01875     {
01876         kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01877         return;
01878     }
01879     kipcEventMask &= ~(1 << id);
01880 }
01881 
01882 void KApplication::enableStyles()
01883 {
01884     if (!useStyles)
01885     {
01886         useStyles = true;
01887         applyGUIStyle();
01888     }
01889 }
01890 
01891 void KApplication::disableStyles()
01892 {
01893     useStyles = false;
01894 }
01895 
01896 void KApplication::applyGUIStyle()
01897 {
01898     if ( !useStyles ) return;
01899 
01900     KConfigGroup pConfig (KGlobal::config(), "General");
01901     QString defaultStyle = KStyle::defaultStyle();
01902     QString styleStr = pConfig.readEntry("widgetStyle", defaultStyle);
01903 
01904     if (d->overrideStyle.isEmpty()) {
01905       // ### add check whether we already use the correct style to return then
01906       // (workaround for Qt misbehavior to avoid double style initialization)
01907 
01908       QStyle* sp = QStyleFactory::create( styleStr );
01909 
01910       // If there is no default style available, try falling back any available style
01911       if ( !sp && styleStr != defaultStyle)
01912           sp = QStyleFactory::create( defaultStyle );
01913       if ( !sp )
01914           sp = QStyleFactory::create( *(QStyleFactory::keys().begin()) );
01915       setStyle(sp);
01916     }
01917     else
01918         setStyle(d->overrideStyle);
01919     // Reread palette from config file.
01920     kdisplaySetPalette();
01921 }
01922 
01923 QString KApplication::caption() const
01924 {
01925   // Caption set from command line ?
01926   if( !aCaption.isNull() )
01927         return aCaption;
01928   else
01929       // We have some about data ?
01930       if ( KGlobal::instance()->aboutData() )
01931         return KGlobal::instance()->aboutData()->programName();
01932       else
01933         // Last resort : application name
01934         return name();
01935 }
01936 
01937 
01938 //
01939 // 1999-09-20: Espen Sand
01940 // An attempt to simplify consistent captions.
01941 //
01942 QString KApplication::makeStdCaption( const QString &userCaption,
01943                                       bool withAppName, bool modified ) const
01944 {
01945   QString s = userCaption.isEmpty() ? caption() : userCaption;
01946 
01947   // If the document is modified, add '[modified]'.
01948   if (modified)
01949       s += QString::fromUtf8(" [") + i18n("modified") + QString::fromUtf8("]");
01950 
01951   if ( !userCaption.isEmpty() ) {
01952       // Add the application name if:
01953       // User asked for it, it's not a duplication  and the app name (caption()) is not empty
01954       if ( withAppName && !caption().isNull() && !userCaption.endsWith(caption())  )
01955       s += QString::fromUtf8(" - ") + caption();
01956   }
01957 
01958   return s;
01959 }
01960 
01961 QPalette KApplication::createApplicationPalette()
01962 {
01963     KConfig *config = KGlobal::config();
01964     KConfigGroupSaver saver( config, "General" );
01965     return createApplicationPalette( config, KGlobalSettings::contrast() );
01966 }
01967 
01968 QPalette KApplication::createApplicationPalette( KConfig *config, int contrast_ )
01969 {
01970     QColor kde34Background( 239, 239, 239 );
01971     QColor kde34Blue( 103,141,178 );
01972 
01973     QColor kde34Button;
01974     if ( QPixmap::defaultDepth() > 8 )
01975       kde34Button.setRgb( 221, 223, 228 );
01976     else
01977       kde34Button.setRgb( 220, 220, 220 );
01978 
01979     QColor kde34Link( 0, 0, 238 );
01980     QColor kde34VisitedLink( 82, 24, 139 );
01981 
01982     QColor background = config->readColorEntry( "background", &kde34Background );
01983     QColor foreground = config->readColorEntry( "foreground", &black );
01984     QColor button = config->readColorEntry( "buttonBackground", &kde34Button );
01985     QColor buttonText = config->readColorEntry( "buttonForeground", &black );
01986     QColor highlight = config->readColorEntry( "selectBackground", &kde34Blue );
01987     QColor highlightedText = config->readColorEntry( "selectForeground", &white );
01988     QColor base = config->readColorEntry( "windowBackground", &white );
01989     QColor baseText = config->readColorEntry( "windowForeground", &black );
01990     QColor link = config->readColorEntry( "linkColor", &kde34Link );
01991     QColor visitedLink = config->readColorEntry( "visitedLinkColor", &kde34VisitedLink );
01992 
01993     int highlightVal, lowlightVal;
01994     highlightVal = 100 + (2*contrast_+4)*16/10;
01995     lowlightVal = 100 + (2*contrast_+4)*10;
01996 
01997     QColor disfg = foreground;
01998 
01999     int h, s, v;
02000     disfg.hsv( &h, &s, &v );
02001     if (v > 128)
02002     // dark bg, light fg - need a darker disabled fg
02003     disfg = disfg.dark(lowlightVal);
02004     else if (disfg != black)
02005     // light bg, dark fg - need a lighter disabled fg - but only if !black
02006     disfg = disfg.light(highlightVal);
02007     else
02008     // black fg - use darkgray disabled fg
02009     disfg = Qt::darkGray;
02010 
02011 
02012     QColorGroup disabledgrp(disfg, background,
02013                             background.light(highlightVal),
02014                             background.dark(lowlightVal),
02015                             background.dark(120),
02016                             background.dark(120), base);
02017 
02018     QColorGroup colgrp(foreground, background, background.light(highlightVal),
02019                        background.dark(lowlightVal),
02020                        background.dark(120),
02021                        baseText, base);
02022 
02023     int inlowlightVal = lowlightVal-25;
02024     if(inlowlightVal < 120)
02025         inlowlightVal = 120;
02026 
02027     colgrp.setColor(QColorGroup::Highlight, highlight);
02028     colgrp.setColor(QColorGroup::HighlightedText, highlightedText);
02029     colgrp.setColor(QColorGroup::Button, button);
02030     colgrp.setColor(QColorGroup::ButtonText, buttonText);
02031     colgrp.setColor(QColorGroup::Midlight, background.light(110));
02032     colgrp.setColor(QColorGroup::Link, link);
02033     colgrp.setColor(QColorGroup::LinkVisited, visitedLink);
02034 
02035     disabledgrp.setColor(QColorGroup::Button, button);
02036 
02037     QColor disbtntext = buttonText;
02038     disbtntext.hsv( &h, &s, &v );
02039     if (v > 128)
02040     // dark button, light buttonText - need a darker disabled buttonText
02041     disbtntext = disbtntext.dark(lowlightVal);
02042     else if (disbtntext != black)
02043     // light buttonText, dark button - need a lighter disabled buttonText - but only if !black
02044     disbtntext = disbtntext.light(highlightVal);
02045     else
02046     // black button - use darkgray disabled buttonText
02047     disbtntext = Qt::darkGray;
02048 
02049     disabledgrp.setColor(QColorGroup::ButtonText, disbtntext);
02050     disabledgrp.setColor(QColorGroup::Midlight, background.light(110));
02051     disabledgrp.setColor(QColorGroup::Highlight, highlight.dark(120));
02052     disabledgrp.setColor(QColorGroup::Link, link);
02053     disabledgrp.setColor(QColorGroup::LinkVisited, visitedLink);
02054 
02055     return QPalette(colgrp, disabledgrp, colgrp);
02056 }
02057 
02058 
02059 void KApplication::kdisplaySetPalette()
02060 {
02061 #ifdef Q_WS_MACX
02062     //Can I have this on other platforms, please!? --Sam
02063     {
02064         KConfig *config = KGlobal::config();
02065         KConfigGroupSaver saver( config, "General" );
02066         bool do_not_set_palette = FALSE;
02067         if(config->readBoolEntry("nopaletteChange", &do_not_set_palette))
02068             return;
02069     }
02070 #endif
02071     QApplication::setPalette( createApplicationPalette(), true);
02072     emit kdisplayPaletteChanged();
02073     emit appearanceChanged();
02074 }
02075 
02076 
02077 void KApplication::kdisplaySetFont()
02078 {
02079     QApplication::setFont(KGlobalSettings::generalFont(), true);
02080     QApplication::setFont(KGlobalSettings::menuFont(), true, "QMenuBar");
02081     QApplication::setFont(KGlobalSettings::menuFont(), true, "QPopupMenu");
02082     QApplication::setFont(KGlobalSettings::menuFont(), true, "KPopupTitle");
02083 
02084     // "patch" standard QStyleSheet to follow our fonts
02085     QStyleSheet* sheet = QStyleSheet::defaultSheet();
02086     sheet->item ("pre")->setFontFamily (KGlobalSettings::fixedFont().family());
02087     sheet->item ("code")->setFontFamily (KGlobalSettings::fixedFont().family());
02088     sheet->item ("tt")->setFontFamily (KGlobalSettings::fixedFont().family());
02089 
02090     emit kdisplayFontChanged();
02091     emit appearanceChanged();
02092 }
02093 
02094 
02095 void KApplication::kdisplaySetStyle()
02096 {
02097     if (useStyles)
02098     {
02099         applyGUIStyle();
02100         emit kdisplayStyleChanged();
02101         emit appearanceChanged();
02102     }
02103 }
02104 
02105 
02106 void KApplication::propagateSettings(SettingsCategory arg)
02107 {
02108     KConfigBase* config = KGlobal::config();
02109     KConfigGroupSaver saver( config, "KDE" );
02110 
02111 #ifdef QT_HAVE_MAX_IMAGE_SIZE
02112     QSize maxImageSize(4096, 4096);
02113     maxImageSize = config->readSizeEntry("MaxImageSize", &maxImageSize);
02114     QImage::setMaxImageSize(maxImageSize);
02115 #endif
02116 
02117     int num = config->readNumEntry("CursorBlinkRate", QApplication::cursorFlashTime());
02118     if ((num != 0) && (num < 200))
02119         num = 200;
02120     if (num > 2000)
02121         num = 2000;
02122     QApplication::setCursorFlashTime(num);
02123     num = config->readNumEntry("DoubleClickInterval", QApplication::doubleClickInterval());
02124     QApplication::setDoubleClickInterval(num);
02125     num = config->readNumEntry("StartDragTime", QApplication::startDragTime());
02126     QApplication::setStartDragTime(num);
02127     num = config->readNumEntry("StartDragDist", QApplication::startDragDistance());
02128     QApplication::setStartDragDistance(num);
02129     num = config->readNumEntry("WheelScrollLines", QApplication::wheelScrollLines());
02130     QApplication::setWheelScrollLines(num);
02131 
02132     bool b = config->readBoolEntry("EffectAnimateMenu", false);
02133     QApplication::setEffectEnabled( Qt::UI_AnimateMenu, b);
02134     b = config->readBoolEntry("EffectFadeMenu", false);
02135     QApplication::setEffectEnabled( Qt::UI_FadeMenu, b);
02136     b = config->readBoolEntry("EffectAnimateCombo", false);
02137     QApplication::setEffectEnabled( Qt::UI_AnimateCombo, b);
02138     b = config->readBoolEntry("EffectAnimateTooltip", false);
02139     QApplication::setEffectEnabled( Qt::UI_AnimateTooltip, b);
02140     b = config->readBoolEntry("EffectFadeTooltip", false);
02141     QApplication::setEffectEnabled( Qt::UI_FadeTooltip, b);
02142     b = !config->readBoolEntry("EffectNoTooltip", false);
02143     QToolTip::setGloballyEnabled( b );
02144 
02145     emit settingsChanged(arg);
02146 }
02147 
02148 void KApplication::installKDEPropertyMap()
02149 {
02150 #ifndef QT_NO_SQL
02151     static bool installed = false;
02152     if (installed) return;
02153     installed = true;
02160     // QSqlPropertyMap takes ownership of the new default map.
02161     QSqlPropertyMap *kdeMap = new QSqlPropertyMap;
02162     kdeMap->insert( "KColorButton", "color" );
02163     kdeMap->insert( "KComboBox", "currentItem" );
02164     kdeMap->insert( "KDatePicker", "date" );
02165     kdeMap->insert( "KDateWidget", "date" );
02166     kdeMap->insert( "KDateTimeWidget", "dateTime" );
02167     kdeMap->insert( "KEditListBox", "items" );
02168     kdeMap->insert( "KFontCombo", "family" );
02169     kdeMap->insert( "KFontRequester", "font" );
02170     kdeMap->insert( "KFontChooser", "font" );
02171     kdeMap->insert( "KHistoryCombo", "currentItem" );
02172     kdeMap->insert( "KListBox", "currentItem" );
02173     kdeMap->insert( "KLineEdit", "text" );
02174     kdeMap->insert( "KRestrictedLine", "text" );
02175     kdeMap->insert( "KSqueezedTextLabel", "text" );
02176     kdeMap->insert( "KTextBrowser", "source" );
02177     kdeMap->insert( "KTextEdit", "text" );
02178     kdeMap->insert( "KURLRequester", "url" );
02179     kdeMap->insert( "KPasswordEdit", "password" );
02180     kdeMap->insert( "KIntNumInput", "value" );
02181     kdeMap->insert( "KIntSpinBox", "value" );
02182     kdeMap->insert( "KDoubleNumInput", "value" );
02183     // Temp til fixed in QT then enable ifdef with the correct version num
02184     kdeMap->insert( "QGroupBox", "checked" );
02185     kdeMap->insert( "QTabWidget", "currentPage" );
02186     QSqlPropertyMap::installDefaultMap( kdeMap );
02187 #endif
02188 }
02189 
02190 void KApplication::invokeHelp( const QString& anchor,
02191                                const QString& _appname) const
02192 {
02193     return invokeHelp( anchor, _appname, "" );
02194 }
02195 
02196 #ifndef Q_WS_WIN
02197 // for win32 we're using simple help tools like Qt Assistant,
02198 // see kapplication_win.cpp
02199 void KApplication::invokeHelp( const QString& anchor,
02200                                const QString& _appname,
02201                                const QCString& startup_id ) const
02202 {
02203    QString url;
02204    QString appname;
02205    if (_appname.isEmpty())
02206      appname = name();
02207    else
02208      appname = _appname;
02209 
02210    if (!anchor.isEmpty())
02211      url = QString("help:/%1?anchor=%2").arg(appname).arg(anchor);
02212    else
02213      url = QString("help:/%1/index.html").arg(appname);
02214 
02215    QString error;
02216    if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02217    {
02218        if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, startup_id, false))
02219        {
02220            if (Tty != kapp->type())
02221                QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02222                i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02223            else
02224                kdWarning() << "Could not launch help:\n" << error << endl;
02225        return;
02226        }
02227    }
02228    else
02229        DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url, startup_id );
02230 }
02231 #endif
02232 
02233 void KApplication::invokeHTMLHelp( const QString& _filename, const QString& topic ) const
02234 {
02235    kdWarning() << "invoking HTML help is deprecated! use docbook and invokeHelp!\n";
02236 
02237    QString filename;
02238 
02239    if( _filename.isEmpty() )
02240      filename = QString(name()) + "/index.html";
02241    else
02242      filename = _filename;
02243 
02244    QString url;
02245    if (!topic.isEmpty())
02246      url = QString("help:/%1#%2").arg(filename).arg(topic);
02247    else
02248      url = QString("help:/%1").arg(filename);
02249 
02250    QString error;
02251    if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02252    {
02253        if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, "", false))
02254        {
02255            if (Tty != kapp->type())
02256                QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02257                i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02258            else
02259                kdWarning() << "Could not launch help:\n" << error << endl;
02260            return;
02261        }
02262    }
02263    else
02264        DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url );
02265 }
02266 
02267 
02268 void KApplication::invokeMailer(const QString &address, const QString &subject)
02269 {
02270     return invokeMailer(address,subject,"");
02271 }
02272 
02273 void KApplication::invokeMailer(const QString &address, const QString &subject, const QCString& startup_id)
02274 {
02275    invokeMailer(address, QString::null, QString::null, subject, QString::null, QString::null,
02276        QStringList(), startup_id );
02277 }
02278 
02279 void KApplication::invokeMailer(const KURL &mailtoURL)
02280 {
02281     return invokeMailer( mailtoURL, "" );
02282 }
02283 
02284 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id )
02285 {
02286     return invokeMailer( mailtoURL, startup_id, false);
02287 }
02288 
02289 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id, bool allowAttachments )
02290 {
02291    QString address = KURL::decode_string(mailtoURL.path()), subject, cc, bcc, body;
02292    QStringList queries = QStringList::split('&', mailtoURL.query().mid(1));
02293    QStringList attachURLs;
02294    for (QStringList::Iterator it = queries.begin(); it != queries.end(); ++it)
02295    {
02296      QString q = (*it).lower();
02297      if (q.startsWith("subject="))
02298        subject = KURL::decode_string((*it).mid(8));
02299      else
02300      if (q.startsWith("cc="))
02301        cc = cc.isEmpty()? KURL::decode_string((*it).mid(3)): cc + ',' + KURL::decode_string((*it).mid(3));
02302      else
02303      if (q.startsWith("bcc="))
02304        bcc = bcc.isEmpty()? KURL::decode_string((*it).mid(4)): bcc + ',' + KURL::decode_string((*it).mid(4));
02305      else
02306      if (q.startsWith("body="))
02307        body = KURL::decode_string((*it).mid(5));
02308      else
02309      if (allowAttachments && q.startsWith("attach="))
02310        attachURLs.push_back(KURL::decode_string((*it).mid(7)));
02311      else
02312      if (allowAttachments && q.startsWith("attachment="))
02313        attachURLs.push_back(KURL::decode_string((*it).mid(11)));
02314      else
02315      if (q.startsWith("to="))
02316        address = address.isEmpty()? KURL::decode_string((*it).mid(3)): address + ',' + KURL::decode_string((*it).mid(3));
02317    }
02318 
02319    invokeMailer( address, cc, bcc, subject, body, QString::null, attachURLs, startup_id );
02320 }
02321 
02322 void KApplication::invokeMailer(const QString &to, const QString &cc, const QString &bcc,
02323                                 const QString &subject, const QString &body,
02324                                 const QString & messageFile, const QStringList &attachURLs)
02325 {
02326     return invokeMailer(to,cc,bcc,subject,body,messageFile,attachURLs,"");
02327 }
02328 
02329 #ifndef Q_WS_WIN
02330 // on win32, for invoking browser we're using win32 API
02331 // see kapplication_win.cpp
02332 
02333 static QStringList splitEmailAddressList( const QString & aStr )
02334 {
02335   // This is a copy of KPIM::splitEmailAddrList().
02336   // Features:
02337   // - always ignores quoted characters
02338   // - ignores everything (including parentheses and commas)
02339   //   inside quoted strings
02340   // - supports nested comments
02341   // - ignores everything (including double quotes and commas)
02342   //   inside comments
02343 
02344   QStringList list;
02345 
02346   if (aStr.isEmpty())
02347     return list;
02348 
02349   QString addr;
02350   uint addrstart = 0;
02351   int commentlevel = 0;
02352   bool insidequote = false;
02353 
02354   for (uint index=0; index<aStr.length(); index++) {
02355     // the following conversion to latin1 is o.k. because
02356     // we can safely ignore all non-latin1 characters
02357     switch (aStr[index].latin1()) {
02358     case '"' : // start or end of quoted string
02359       if (commentlevel == 0)
02360         insidequote = !insidequote;
02361       break;
02362     case '(' : // start of comment
02363       if (!insidequote)
02364         commentlevel++;
02365       break;
02366     case ')' : // end of comment
02367       if (!insidequote) {
02368         if (commentlevel > 0)
02369           commentlevel--;
02370         else {
02371           //kdDebug() << "Error in address splitting: Unmatched ')'"
02372           //          << endl;
02373           return list;
02374         }
02375       }
02376       break;
02377     case '\\' : // quoted character
02378       index++; // ignore the quoted character
02379       break;
02380     case ',' :
02381       if (!insidequote && (commentlevel == 0)) {
02382         addr = aStr.mid(addrstart, index-addrstart);
02383         if (!addr.isEmpty())
02384           list += addr.simplifyWhiteSpace();
02385         addrstart = index+1;
02386       }
02387       break;
02388     }
02389   }
02390   // append the last address to the list
02391   if (!insidequote && (commentlevel == 0)) {
02392     addr = aStr.mid(addrstart, aStr.length()-addrstart);
02393     if (!addr.isEmpty())
02394       list += addr.simplifyWhiteSpace();
02395   }
02396   //else
02397   //  kdDebug() << "Error in address splitting: "
02398   //            << "Unexpected end of address list"
02399   //            << endl;
02400 
02401   return list;
02402 }
02403 
02404 void KApplication::invokeMailer(const QString &_to, const QString &_cc, const QString &_bcc,
02405                                 const QString &subject, const QString &body,
02406                                 const QString & /*messageFile TODO*/, const QStringList &attachURLs,
02407                                 const QCString& startup_id )
02408 {
02409    KConfig config("emaildefaults");
02410 
02411    config.setGroup("Defaults");
02412    QString group = config.readEntry("Profile","Default");
02413 
02414    config.setGroup( QString("PROFILE_%1").arg(group) );
02415    QString command = config.readPathEntry("EmailClient");
02416 
02417    QString to, cc, bcc;
02418    if (command.isEmpty() || command == QString::fromLatin1("kmail")
02419        || command.endsWith("/kmail"))
02420    {
02421      command = QString::fromLatin1("kmail --composer -s %s -c %c -b %b --body %B --attach %A -- %t");
02422      if ( !_to.isEmpty() )
02423      {
02424        // put the whole address lists into RFC2047 encoded blobs; technically
02425        // this isn't correct, but KMail understands it nonetheless
02426        to = QString( "=?utf8?b?%1?=" )
02427             .arg( KCodecs::base64Encode( _to.utf8(), false ) );
02428      }
02429      if ( !_cc.isEmpty() )
02430        cc = QString( "=?utf8?b?%1?=" )
02431             .arg( KCodecs::base64Encode( _cc.utf8(), false ) );
02432      if ( !_bcc.isEmpty() )
02433        bcc = QString( "=?utf8?b?%1?=" )
02434              .arg( KCodecs::base64Encode( _bcc.utf8(), false ) );
02435    } else {
02436      to = _to;
02437      cc = _cc;
02438      bcc = _bcc;
02439      if( !command.contains( '%' ))
02440          command += " %u";
02441    }
02442 
02443    if (config.readBoolEntry("TerminalClient", false))
02444    {
02445      KConfigGroup confGroup( KGlobal::config(), "General" );
02446      QString preferredTerminal = confGroup.readPathEntry("TerminalApplication", "konsole");
02447      command = preferredTerminal + " -e " + command;
02448    }
02449 
02450    QStringList cmdTokens = KShell::splitArgs(command);
02451    QString cmd = cmdTokens[0];
02452    cmdTokens.remove(cmdTokens.begin());
02453 
02454    KURL url;
02455    QStringList qry;
02456    if (!to.isEmpty())
02457    {
02458      QStringList tos = splitEmailAddressList( to );
02459      url.setPath( tos.first() );
02460      tos.remove( tos.begin() );
02461      for (QStringList::ConstIterator it = tos.begin(); it != tos.end(); ++it)
02462        qry.append( "to=" + KURL::encode_string( *it ) );
02463    }
02464    const QStringList ccs = splitEmailAddressList( cc );
02465    for (QStringList::ConstIterator it = ccs.begin(); it != ccs.end(); ++it)
02466       qry.append( "cc=" + KURL::encode_string( *it ) );
02467    const QStringList bccs = splitEmailAddressList( bcc );
02468    for (QStringList::ConstIterator it = bccs.begin(); it != bccs.end(); ++it)
02469       qry.append( "bcc=" + KURL::encode_string( *it ) );
02470    for (QStringList::ConstIterator it = attachURLs.begin(); it != attachURLs.end(); ++it)
02471       qry.append( "attach=" + KURL::encode_string( *it ) );
02472    if (!subject.isEmpty())
02473       qry.append( "subject=" + KURL::encode_string( subject ) );
02474    if (!body.isEmpty())
02475       qry.append( "body=" + KURL::encode_string( body ) );
02476    url.setQuery( qry.join( "&" ) );
02477    if ( ! (to.isEmpty() && qry.isEmpty()) )
02478       url.setProtocol("mailto");
02479 
02480    QMap<QChar, QString> keyMap;
02481    keyMap.insert('t', to);
02482    keyMap.insert('s', subject);
02483    keyMap.insert('c', cc);
02484    keyMap.insert('b', bcc);
02485    keyMap.insert('B', body);
02486    keyMap.insert('u', url.url());
02487 
02488    QString attachlist = attachURLs.join(",");
02489    attachlist.prepend('\'');
02490    attachlist.append('\'');
02491    keyMap.insert('A', attachlist);
02492 
02493    for (QStringList::Iterator it = cmdTokens.begin(); it != cmdTokens.end(); )
02494    {
02495      if (*it == "%A")
02496      {
02497          if (it == cmdTokens.begin()) // better safe than sorry ...
02498              continue;
02499          QStringList::ConstIterator urlit = attachURLs.begin();
02500          QStringList::ConstIterator urlend = attachURLs.end();
02501          if ( urlit != urlend )
02502          {
02503              QStringList::Iterator previt = it;
02504              --previt;
02505              *it = *urlit;
02506              ++it;
02507              while ( ++urlit != urlend )
02508              {
02509                  cmdTokens.insert( it, *previt );
02510                  cmdTokens.insert( it, *urlit );
02511              }
02512          } else {
02513              --it;
02514              it = cmdTokens.remove( cmdTokens.remove( it ) );
02515          }
02516      } else {
02517          *it = KMacroExpander::expandMacros(*it, keyMap);
02518          ++it;
02519      }
02520    }
02521 
02522    QString error;
02523    // TODO this should check if cmd has a .desktop file, and use data from it, together
02524    // with sending more ASN data
02525    if (kdeinitExec(cmd, cmdTokens, &error, NULL, startup_id ))
02526      if (Tty != kapp->type())
02527        QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Mail Client"),
02528              i18n("Could not launch the mail client:\n\n%1").arg(error), i18n("&OK"));
02529      else
02530        kdWarning() << "Could not launch mail client:\n" << error << endl;
02531 }
02532 #endif
02533 
02534 void KApplication::invokeBrowser( const QString &url )
02535 {
02536     return invokeBrowser( url, "" );
02537 }
02538 
02539 #ifndef Q_WS_WIN
02540 // on win32, for invoking browser we're using win32 API
02541 // see kapplication_win.cpp
02542 void KApplication::invokeBrowser( const QString &url, const QCString& startup_id )
02543 {
02544    QString error;
02545 
02546    if (startServiceByDesktopName("kfmclient", url, &error, 0, 0, startup_id, false))
02547    {
02548       if (Tty != kapp->type())
02549           QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Browser"),
02550                i18n("Could not launch the browser:\n\n%1").arg(error), i18n("&OK"));
02551       else
02552           kdWarning() << "Could not launch browser:\n" << error << endl;
02553       return;
02554    }
02555 }
02556 #endif
02557 
02558 void KApplication::cut()
02559 {
02560   invokeEditSlot( SLOT( cut() ) );
02561 }
02562 
02563 void KApplication::copy()
02564 {
02565   invokeEditSlot( SLOT( copy() ) );
02566 }
02567 
02568 void KApplication::paste()
02569 {
02570   invokeEditSlot( SLOT( paste() ) );
02571 }
02572 
02573 void KApplication::clear()
02574 {
02575   invokeEditSlot( SLOT( clear() ) );
02576 }
02577 
02578 void KApplication::selectAll()
02579 {
02580   invokeEditSlot( SLOT( selectAll() ) );
02581 }
02582 
02583 QCString
02584 KApplication::launcher()
02585 {
02586    return "klauncher";
02587 }
02588 
02589 static int
02590 startServiceInternal( const QCString &function,
02591               const QString& _name, const QStringList &URLs,
02592               QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02593 {
02594    struct serviceResult
02595    {
02596       int result;
02597       QCString dcopName;
02598       QString error;
02599       pid_t pid;
02600    };
02601 
02602    // Register app as able to send DCOP messages
02603    DCOPClient *dcopClient;
02604    if (kapp)
02605       dcopClient = kapp->dcopClient();
02606    else
02607       dcopClient = new DCOPClient;
02608 
02609    if (!dcopClient->isAttached())
02610    {
02611       if (!dcopClient->attach())
02612       {
02613          if (error)
02614             *error = i18n("Could not register with DCOP.\n");
02615          if (!kapp)
02616             delete dcopClient;
02617 
02618          return -1;
02619       }
02620    }
02621    QByteArray params;
02622    QDataStream stream(params, IO_WriteOnly);
02623    stream << _name << URLs;
02624    QCString replyType;
02625    QByteArray replyData;
02626    QCString _launcher = KApplication::launcher();
02627    QValueList<QCString> envs;
02628 #ifdef Q_WS_X11
02629    if (qt_xdisplay()) {
02630        QCString dpystring(XDisplayString(qt_xdisplay()));
02631        envs.append( QCString("DISPLAY=") + dpystring );
02632    } else if( getenv( "DISPLAY" )) {
02633        QCString dpystring( getenv( "DISPLAY" ));
02634        envs.append( QCString("DISPLAY=") + dpystring );
02635    }
02636 #endif
02637    stream << envs;
02638 #if defined Q_WS_X11
02639    // make sure there is id, so that user timestamp exists
02640    stream << ( startup_id.isEmpty() ? KStartupInfo::createNewStartupId() : startup_id );
02641 #endif
02642    if( function.left( 12 ) != "kdeinit_exec" )
02643        stream << noWait;
02644 
02645    if (!dcopClient->call(_launcher, _launcher,
02646         function, params, replyType, replyData))
02647    {
02648         if (error)
02649            *error = i18n("KLauncher could not be reached via DCOP.\n");
02650         if (!kapp)
02651            delete dcopClient;
02652         return -1;
02653    }
02654    if (!kapp)
02655       delete dcopClient;
02656 
02657    if (noWait)
02658       return 0;
02659 
02660    QDataStream stream2(replyData, IO_ReadOnly);
02661    serviceResult result;
02662    stream2 >> result.result >> result.dcopName >> result.error >> result.pid;
02663    if (dcopService)
02664       *dcopService = result.dcopName;
02665    if (error)
02666       *error = result.error;
02667    if (pid)
02668       *pid = result.pid;
02669    return result.result;
02670 }
02671 
02672 int
02673 KApplication::startServiceByName( const QString& _name, const QString &URL,
02674                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02675 {
02676    QStringList URLs;
02677    if (!URL.isEmpty())
02678       URLs.append(URL);
02679    return startServiceInternal(
02680                       "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02681                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02682 }
02683 
02684 int
02685 KApplication::startServiceByName( const QString& _name, const QStringList &URLs,
02686                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02687 {
02688    return startServiceInternal(
02689                       "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02690                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02691 }
02692 
02693 int
02694 KApplication::startServiceByDesktopPath( const QString& _name, const QString &URL,
02695                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02696 {
02697    QStringList URLs;
02698    if (!URL.isEmpty())
02699       URLs.append(URL);
02700    return startServiceInternal(
02701                       "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02702                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02703 }
02704 
02705 int
02706 KApplication::startServiceByDesktopPath( const QString& _name, const QStringList &URLs,
02707                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02708 {
02709    return startServiceInternal(
02710                       "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02711                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02712 }
02713 
02714 int
02715 KApplication::startServiceByDesktopName( const QString& _name, const QString &URL,
02716                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02717 {
02718    QStringList URLs;
02719    if (!URL.isEmpty())
02720       URLs.append(URL);
02721    return startServiceInternal(
02722                       "start_service_by_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02723                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02724 }
02725 
02726 int
02727 KApplication::startServiceByDesktopName( const QString& _name, const QStringList &URLs,
02728                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02729 {
02730    return startServiceInternal(
02731                       "start_service_by_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02732                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02733 }
02734 
02735 int
02736 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02737                            QString *error, int *pid )
02738 {
02739     return kdeinitExec( name, args, error, pid, "" );
02740 }
02741 
02742 int
02743 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02744                            QString *error, int *pid, const QCString& startup_id )
02745 {
02746    return startServiceInternal("kdeinit_exec(QString,QStringList,QValueList<QCString>,QCString)",
02747         name, args, error, 0, pid, startup_id, false);
02748 }
02749 
02750 int
02751 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02752                            QString *error, int *pid )
02753 {
02754     return kdeinitExecWait( name, args, error, pid, "" );
02755 }
02756 
02757 int
02758 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02759                            QString *error, int *pid, const QCString& startup_id )
02760 {
02761    return startServiceInternal("kdeinit_exec_wait(QString,QStringList,QValueList<QCString>,QCString)",
02762         name, args, error, 0, pid, startup_id, false);
02763 }
02764 
02765 QString KApplication::tempSaveName( const QString& pFilename ) const
02766 {
02767   QString aFilename;
02768 
02769   if( QDir::isRelativePath(pFilename) )
02770     {
02771       kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02772       aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02773     }
02774   else
02775     aFilename = pFilename;
02776 
02777   QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02778   if( !aAutosaveDir.exists() )
02779     {
02780       if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02781         {
02782           // Last chance: use temp dir
02783           aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02784         }
02785     }
02786 
02787   aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02788 
02789   return aFilename;
02790 }
02791 
02792 
02793 QString KApplication::checkRecoverFile( const QString& pFilename,
02794         bool& bRecover ) const
02795 {
02796   QString aFilename;
02797 
02798   if( QDir::isRelativePath(pFilename) )
02799     {
02800       kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02801       aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02802     }
02803   else
02804     aFilename = pFilename;
02805 
02806   QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02807   if( !aAutosaveDir.exists() )
02808     {
02809       if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02810         {
02811           // Last chance: use temp dir
02812           aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02813         }
02814     }
02815 
02816   aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02817 
02818   if( QFile( aFilename ).exists() )
02819     {
02820       bRecover = true;
02821       return aFilename;
02822     }
02823   else
02824     {
02825       bRecover = false;
02826       return pFilename;
02827     }
02828 }
02829 
02830 
02831 bool checkAccess(const QString& pathname, int mode)
02832 {
02833   int accessOK = access( QFile::encodeName(pathname), mode );
02834   if ( accessOK == 0 )
02835     return true;  // OK, I can really access the file
02836 
02837   // else
02838   // if we want to write the file would be created. Check, if the
02839   // user may write to the directory to create the file.
02840   if ( (mode & W_OK) == 0 )
02841     return false;   // Check for write access is not part of mode => bail out
02842 
02843 
02844   if (!access( QFile::encodeName(pathname), F_OK)) // if it already exists
02845       return false;
02846 
02847   //strip the filename (everything until '/' from the end
02848   QString dirName(pathname);
02849   int pos = dirName.findRev('/');
02850   if ( pos == -1 )
02851     return false;   // No path in argument. This is evil, we won't allow this
02852   else if ( pos == 0 ) // don't turn e.g. /root into an empty string
02853       pos = 1;
02854 
02855   dirName.truncate(pos); // strip everything starting from the last '/'
02856 
02857   accessOK = access( QFile::encodeName(dirName), W_OK );
02858   // -?- Can I write to the accessed diretory
02859   if ( accessOK == 0 )
02860     return true;  // Yes
02861   else
02862     return false; // No
02863 }
02864 
02865 void KApplication::setTopWidget( QWidget *topWidget )
02866 {
02867   if( !topWidget )
02868       return;
02869 
02870     // set the specified caption
02871     if ( !topWidget->inherits("KMainWindow") ) { // KMainWindow does this already for us
02872         topWidget->setCaption( caption() );
02873     }
02874 
02875     // set the specified icons
02876     topWidget->setIcon( icon() ); //standard X11
02877 #if defined Q_WS_X11
02878 //#ifdef Q_WS_X11 // FIXME(E): Implement for Qt/Embedded
02879     KWin::setIcons(topWidget->winId(), icon(), miniIcon() ); // NET_WM hints for KWin
02880 
02881     // set the app startup notification window property
02882     KStartupInfo::setWindowStartupId( topWidget->winId(), startupId());
02883 #endif
02884 }
02885 
02886 QCString KApplication::startupId() const
02887 {
02888     return d->startup_id;
02889 }
02890 
02891 void KApplication::setStartupId( const QCString& startup_id )
02892 {
02893     if( startup_id == d->startup_id )
02894         return;
02895 #if defined Q_WS_X11
02896     KStartupInfo::handleAutoAppStartedSending(); // finish old startup notification if needed
02897 #endif
02898     if( startup_id.isEmpty())
02899         d->startup_id = "0";
02900     else
02901         {
02902         d->startup_id = startup_id;
02903 #if defined Q_WS_X11
02904         KStartupInfoId id;
02905         id.initId( startup_id );
02906         long timestamp = id.timestamp();
02907         if( timestamp != 0 )
02908             updateUserTimestamp( timestamp );
02909 #endif
02910         }
02911 }
02912 
02913 // read the startup notification env variable, save it and unset it in order
02914 // not to propagate it to processes started from this app
02915 void KApplication::read_app_startup_id()
02916 {
02917 #if defined Q_WS_X11
02918     KStartupInfoId id = KStartupInfo::currentStartupIdEnv();
02919     KStartupInfo::resetStartupEnv();
02920     d->startup_id = id.id();
02921 #endif
02922 }
02923 
02924 int KApplication::random()
02925 {
02926    static bool init = false;
02927    if (!init)
02928    {
02929       unsigned int seed;
02930       init = true;
02931       int fd = open("/dev/urandom", O_RDONLY);
02932       if (fd < 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed))
02933       {
02934             // No /dev/urandom... try something else.
02935             srand(getpid());
02936             seed = rand()+time(0);
02937       }
02938       if (fd >= 0) close(fd);
02939       srand(seed);
02940    }
02941    return rand();
02942 }
02943 
02944 QString KApplication::randomString(int length)
02945 {
02946    if (length <=0 ) return QString::null;
02947 
02948    QString str; str.setLength( length );
02949    int i = 0;
02950    while (length--)
02951    {
02952       int r=random() % 62;
02953       r+=48;
02954       if (r>57) r+=7;
02955       if (r>90) r+=6;
02956       str[i++] =  char(r);
02957       // so what if I work backwards?
02958    }
02959    return str;
02960 }
02961 
02962 bool KApplication::authorize(const QString &genericAction)
02963 {
02964    if (!d->actionRestrictions)
02965       return true;
02966 
02967    KConfig *config = KGlobal::config();
02968    KConfigGroupSaver saver( config, "KDE Action Restrictions" );
02969    return config->readBoolEntry(genericAction, true);
02970 }
02971 
02972 bool KApplication::authorizeKAction(const char *action)
02973 {
02974    if (!d->actionRestrictions || !action)
02975       return true;
02976 
02977    static const QString &action_prefix = KGlobal::staticQString( "action/" );
02978 
02979    return authorize(action_prefix + action);
02980 }
02981 
02982 bool KApplication::authorizeControlModule(const QString &menuId)
02983 {
02984    if (menuId.isEmpty() || kde_kiosk_exception)
02985       return true;
02986    KConfig *config = KGlobal::config();
02987    KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02988    return config->readBoolEntry(menuId, true);
02989 }
02990 
02991 QStringList KApplication::authorizeControlModules(const QStringList &menuIds)
02992 {
02993    KConfig *config = KGlobal::config();
02994    KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02995    QStringList result;
02996    for(QStringList::ConstIterator it = menuIds.begin();
02997        it != menuIds.end(); ++it)
02998    {
02999       if (config->readBoolEntry(*it, true))
03000          result.append(*it);
03001    }
03002    return result;
03003 }
03004 
03005 void KApplication::initUrlActionRestrictions()
03006 {
03007   d->urlActionRestrictions.setAutoDelete(true);
03008   d->urlActionRestrictions.clear();
03009   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03010   ("open", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
03011   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03012   ("list", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
03013 // TEST:
03014 //  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03015 //  ("list", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, false));
03016 //  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03017 //  ("list", QString::null, QString::null, QString::null, "file", QString::null, QDir::homeDirPath(), true));
03018   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03019   ("link", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
03020   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03021   ("redirect", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
03022 
03023   // We allow redirections to file: but not from internet protocols, redirecting to file:
03024   // is very popular among io-slaves and we don't want to break them
03025   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03026   ("redirect", QString::null, QString::null, QString::null, "file", QString::null, QString::null, true));
03027   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03028   ("redirect", ":internet", QString::null, QString::null, "file", QString::null, QString::null, false));
03029 
03030   // local protocols may redirect everywhere
03031   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03032   ("redirect", ":local", QString::null, QString::null, QString::null, QString::null, QString::null, true));
03033 
03034   // Anyone may redirect to about:
03035   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03036   ("redirect", QString::null, QString::null, QString::null, "about", QString::null, QString::null, true));
03037 
03038   // Anyone may redirect to itself, cq. within it's own group
03039   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03040   ("redirect", QString::null, QString::null, QString::null, "=", QString::null, QString::null, true));
03041 
03042   KConfig *config = KGlobal::config();
03043   KConfigGroupSaver saver( config, "KDE URL Restrictions" );
03044   int count = config->readNumEntry("rule_count");
03045   QString keyFormat = QString("rule_%1");
03046   for(int i = 1; i <= count; i++)
03047   {
03048     QString key = keyFormat.arg(i);
03049     QStringList rule = config->readListEntry(key);
03050     if (rule.count() != 8)
03051       continue;
03052     QString action = rule[0];
03053     QString refProt = rule[1];
03054     QString refHost = rule[2];
03055     QString refPath = rule[3];
03056     QString urlProt = rule[4];
03057     QString urlHost = rule[5];
03058     QString urlPath = rule[6];
03059     QString strEnabled = rule[7].lower();
03060 
03061     bool bEnabled = (strEnabled == "true");
03062 
03063     if (refPath.startsWith("$HOME"))
03064        refPath.replace(0, 5, QDir::homeDirPath());
03065     else if (refPath.startsWith("~"))
03066        refPath.replace(0, 1, QDir::homeDirPath());
03067     if (urlPath.startsWith("$HOME"))
03068        urlPath.replace(0, 5, QDir::homeDirPath());
03069     else if (urlPath.startsWith("~"))
03070        urlPath.replace(0, 1, QDir::homeDirPath());
03071 
03072     if (refPath.startsWith("$TMP"))
03073        refPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
03074     if (urlPath.startsWith("$TMP"))
03075        urlPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
03076 
03077     d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
03078         ( action, refProt, refHost, refPath, urlProt, urlHost, urlPath, bEnabled));
03079   }
03080 }
03081 
03082 void KApplication::allowURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
03083 {
03084   if (authorizeURLAction(action, _baseURL, _destURL))
03085      return;
03086 
03087   d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
03088         ( action, _baseURL.protocol(), _baseURL.host(), _baseURL.path(-1),
03089                   _destURL.protocol(), _destURL.host(), _destURL.path(-1), true));
03090 }
03091 
03092 bool KApplication::authorizeURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
03093 {
03094   if (_destURL.isEmpty())
03095      return true;
03096 
03097   bool result = false;
03098   if (d->urlActionRestrictions.isEmpty())
03099      initUrlActionRestrictions();
03100 
03101   KURL baseURL(_baseURL);
03102   baseURL.setPath(QDir::cleanDirPath(baseURL.path()));
03103   QString baseClass = KProtocolInfo::protocolClass(baseURL.protocol());
03104   KURL destURL(_destURL);
03105   destURL.setPath(QDir::cleanDirPath(destURL.path()));
03106   QString destClass = KProtocolInfo::protocolClass(destURL.protocol());
03107 
03108   for(KApplicationPrivate::URLActionRule *rule = d->urlActionRestrictions.first();
03109       rule; rule = d->urlActionRestrictions.next())
03110   {
03111      if ((result != rule->permission) && // No need to check if it doesn't make a difference
03112          (action == rule->action) &&
03113          rule->baseMatch(baseURL, baseClass) &&
03114          rule->destMatch(destURL, destClass, baseURL, baseClass))
03115      {
03116         result = rule->permission;
03117      }
03118   }
03119   return result;
03120 }
03121 
03122 
03123 uint KApplication::keyboardModifiers()
03124 {
03125 #ifdef Q_WS_X11
03126     Window root;
03127     Window child;
03128     int root_x, root_y, win_x, win_y;
03129     uint keybstate;
03130     XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03131                    &root_x, &root_y, &win_x, &win_y, &keybstate );
03132     return keybstate & 0x00ff;
03133 #elif defined W_WS_MACX
03134     return GetCurrentEventKeyModifiers() & 0x00ff;
03135 #else
03136     //TODO for win32
03137     return 0;
03138 #endif
03139 }
03140 
03141 uint KApplication::mouseState()
03142 {
03143     uint mousestate;
03144 #ifdef Q_WS_X11
03145     Window root;
03146     Window child;
03147     int root_x, root_y, win_x, win_y;
03148     XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03149                    &root_x, &root_y, &win_x, &win_y, &mousestate );
03150 #elif defined(Q_WS_WIN)
03151     const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
03152     if (GetAsyncKeyState(VK_LBUTTON))
03153         mousestate |= (mousebtn_swapped ? Button3Mask : Button1Mask);
03154     if (GetAsyncKeyState(VK_MBUTTON))
03155         mousestate |= Button2Mask;
03156     if (GetAsyncKeyState(VK_RBUTTON))
03157         mousestate |= (mousebtn_swapped ? Button1Mask : Button3Mask);
03158 #elif defined(Q_WS_MACX)
03159     mousestate = GetCurrentEventButtonState();
03160 #else
03161     //TODO: other platforms
03162 #endif
03163     return mousestate & 0xff00;
03164 }
03165 
03166 Qt::ButtonState KApplication::keyboardMouseState()
03167 {
03168     int ret = 0;
03169 #ifdef Q_WS_X11
03170     Window root;
03171     Window child;
03172     int root_x, root_y, win_x, win_y;
03173     uint state;
03174     XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03175                    &root_x, &root_y, &win_x, &win_y, &state );
03176     // transform the same way like Qt's qt_x11_translateButtonState()
03177     if( state & Button1Mask )
03178         ret |= LeftButton;
03179     if( state & Button2Mask )
03180         ret |= MidButton;
03181     if( state & Button3Mask )
03182         ret |= RightButton;
03183     if( state & ShiftMask )
03184         ret |= ShiftButton;
03185     if( state & ControlMask )
03186         ret |= ControlButton;
03187     if( state & KKeyNative::modX( KKey::ALT ))
03188         ret |= AltButton;
03189     if( state & KKeyNative::modX( KKey::WIN ))
03190         ret |= MetaButton;
03191 #elif defined(Q_WS_WIN)
03192     const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
03193     if (GetAsyncKeyState(VK_LBUTTON))
03194         ret |= (mousebtn_swapped ? RightButton : LeftButton);
03195     if (GetAsyncKeyState(VK_MBUTTON))
03196         ret |= MidButton;
03197     if (GetAsyncKeyState(VK_RBUTTON))
03198         ret |= (mousebtn_swapped ? LeftButton : RightButton);
03199     if (GetAsyncKeyState(VK_SHIFT))
03200         ret |= ShiftButton;
03201     if (GetAsyncKeyState(VK_CONTROL))
03202         ret |= ControlButton;
03203     if (GetAsyncKeyState(VK_MENU))
03204         ret |= AltButton;
03205     if (GetAsyncKeyState(VK_LWIN) || GetAsyncKeyState(VK_RWIN))
03206         ret |= MetaButton;
03207 #else
03208     //TODO: other platforms
03209 #endif
03210     return static_cast< ButtonState >( ret );
03211 }
03212 
03213 void KApplication::installSigpipeHandler()
03214 {
03215 #ifdef Q_OS_UNIX
03216     struct sigaction act;
03217     act.sa_handler = SIG_IGN;
03218     sigemptyset( &act.sa_mask );
03219     act.sa_flags = 0;
03220     sigaction( SIGPIPE, &act, 0 );
03221 #endif
03222 }
03223 
03224 void KApplication::sigpipeHandler(int)
03225 {
03226     int saved_errno = errno;
03227     // Using kdDebug from a signal handler is not a good idea.
03228 #ifndef NDEBUG
03229     char msg[1000];
03230     sprintf(msg, "*** SIGPIPE *** (ignored, pid = %ld)\n", (long) getpid());
03231     write(2, msg, strlen(msg));
03232 #endif
03233 
03234     // Do nothing.
03235     errno = saved_errno;
03236 }
03237 
03238 bool KApplication::guiEnabled()
03239 {
03240     return kapp && kapp->d->guiEnabled;
03241 }
03242 
03243 void KApplication::virtual_hook( int id, void* data )
03244 { KInstance::virtual_hook( id, data ); }
03245 
03246 void KSessionManaged::virtual_hook( int, void* )
03247 { /*BASE::virtual_hook( id, data );*/ }
03248 
03249 #include "kapplication.moc"
KDE Home | KDE Accessibility Home | Description of Access Keys