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