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, "app_started_timer" );
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    pid = fork();
00964    if (pid == -1)
00965       return -1;
00966    if (pid == 0) {
00967       const char* shell = "/bin/sh";
00968       execl(shell, shell, "-c", command, (void *)0);
00969       ::_exit(127);
00970    }
00971    do {
00972       if (waitpid(pid, &status, 0) == -1) {
00973          if (errno != EINTR)
00974             return -1;
00975        } else
00976             return status;
00977    } while(1);
00978 }
00979 
00980 
00981 DCOPClient *KApplication::dcopClient()
00982 {
00983   if (s_DCOPClient)
00984     return s_DCOPClient;
00985 
00986   s_DCOPClient = new DCOPClient();
00987   KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
00988   if (args && args->isSet("dcopserver"))
00989   {
00990     s_DCOPClient->setServerAddress( args->getOption("dcopserver"));
00991   }
00992   if( kapp ) {
00993     connect(s_DCOPClient, SIGNAL(attachFailed(const QString &)),
00994             kapp, SLOT(dcopFailure(const QString &)));
00995     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
00996             kapp, SLOT(dcopBlockUserInput(bool)) );
00997   }
00998   else
00999     s_dcopClientNeedsPostInit = true;
01000 
01001   DCOPClient::setMainClient( s_DCOPClient );
01002   return s_DCOPClient;
01003 }
01004 
01005 void KApplication::dcopClientPostInit()
01006 {
01007   if( s_dcopClientNeedsPostInit )
01008     {
01009     s_dcopClientNeedsPostInit = false;
01010     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
01011             SLOT(dcopBlockUserInput(bool)) );
01012     s_DCOPClient->bindToApp(); // Make sure we get events from the DCOPClient.
01013     }
01014 }
01015 
01016 void KApplication::dcopAutoRegistration()
01017 {
01018   if (autoDcopRegistration)
01019      {
01020      ( void ) dcopClient();
01021      if( dcopClient()->appId().isEmpty())
01022          dcopClient()->registerAs(name());
01023      }
01024 }
01025 
01026 void KApplication::disableAutoDcopRegistration()
01027 {
01028   autoDcopRegistration = false;
01029 }
01030 
01031 KConfig* KApplication::sessionConfig()
01032 {
01033     if (pSessionConfig)
01034         return pSessionConfig;
01035 
01036     // create an instance specific config object
01037     pSessionConfig = new KConfig( sessionConfigName(), false, false);
01038     return pSessionConfig;
01039 }
01040 
01041 void KApplication::ref()
01042 {
01043     d->refCount++;
01044     //kdDebug() << "KApplication::ref() : refCount = " << d->refCount << endl;
01045 }
01046 
01047 void KApplication::deref()
01048 {
01049     d->refCount--;
01050     //kdDebug() << "KApplication::deref() : refCount = " << d->refCount << endl;
01051     if ( d->refCount <= 0 )
01052         quit();
01053 }
01054 
01055 KSessionManaged::KSessionManaged()
01056 {
01057     sessionClients()->remove( this );
01058     sessionClients()->append( this );
01059 }
01060 
01061 KSessionManaged::~KSessionManaged()
01062 {
01063     sessionClients()->remove( this );
01064 }
01065 
01066 bool KSessionManaged::saveState(QSessionManager&)
01067 {
01068     return true;
01069 }
01070 
01071 bool KSessionManaged::commitData(QSessionManager&)
01072 {
01073     return true;
01074 }
01075 
01076 
01077 void KApplication::disableSessionManagement() {
01078   bSessionManagement = false;
01079 }
01080 
01081 void KApplication::enableSessionManagement() {
01082   bSessionManagement = true;
01083 #ifdef Q_WS_X11
01084   // Session management support in Qt/KDE is awfully broken.
01085   // If konqueror disables session management right after its startup,
01086   // and enables it later (preloading stuff), it won't be properly
01087   // saved on session shutdown.
01088   // I'm not actually sure why it doesn't work, but saveState()
01089   // doesn't seem to be called on session shutdown, possibly
01090   // because disabling session management after konqueror startup
01091   // disabled it somehow. Forcing saveState() here for this application
01092   // seems to fix it.
01093   if( mySmcConnection ) {
01094         SmcRequestSaveYourself( mySmcConnection, SmSaveLocal, False,
01095                 SmInteractStyleAny,
01096                 False, False );
01097 
01098     // flush the request
01099     IceFlush(SmcGetIceConnection(mySmcConnection));
01100   }
01101 #endif
01102 }
01103 
01104 
01105 bool KApplication::requestShutDown(
01106     ShutdownConfirm confirm, ShutdownType sdtype, ShutdownMode sdmode )
01107 {
01108 #ifdef Q_WS_X11
01109     QApplication::syncX();
01110     /*  use ksmserver's dcop interface if necessary  */
01111     if ( confirm == ShutdownConfirmYes ||
01112          sdtype != ShutdownTypeDefault ||
01113          sdmode != ShutdownModeDefault )
01114     {
01115         QByteArray data;
01116         QDataStream arg(data, IO_WriteOnly);
01117         arg << (int)confirm << (int)sdtype << (int)sdmode;
01118     return dcopClient()->send( "ksmserver", "ksmserver",
01119                                    "logout(int,int,int)", data );
01120     }
01121 
01122     if ( mySmcConnection ) {
01123         // we already have a connection to the session manager, use it.
01124         SmcRequestSaveYourself( mySmcConnection, SmSaveBoth, True,
01125                 SmInteractStyleAny,
01126                 confirm == ShutdownConfirmNo, True );
01127 
01128     // flush the request
01129     IceFlush(SmcGetIceConnection(mySmcConnection));
01130         return true;
01131     }
01132 
01133     // open a temporary connection, if possible
01134 
01135     propagateSessionManager();
01136     QCString smEnv = ::getenv("SESSION_MANAGER");
01137     if (smEnv.isEmpty())
01138         return false;
01139 
01140     if (! tmpSmcConnection) {
01141     char cerror[256];
01142     char* myId = 0;
01143     char* prevId = 0;
01144     SmcCallbacks cb;
01145     tmpSmcConnection = SmcOpenConnection( 0, 0, 1, 0,
01146                           0, &cb,
01147                           prevId,
01148                           &myId,
01149                           255,
01150                           cerror );
01151     ::free( myId ); // it was allocated by C
01152     if (!tmpSmcConnection )
01153         return false;
01154     }
01155 
01156     SmcRequestSaveYourself( tmpSmcConnection, SmSaveBoth, True,
01157                 SmInteractStyleAny, False, True );
01158 
01159     // flush the request
01160     IceFlush(SmcGetIceConnection(tmpSmcConnection));
01161     return true;
01162 #else
01163     // FIXME(E): Implement for Qt Embedded
01164     return false;
01165 #endif
01166 }
01167 
01168 void KApplication::propagateSessionManager()
01169 {
01170 #ifdef Q_WS_X11
01171     QCString fName = QFile::encodeName(locateLocal("socket", "KSMserver"));
01172     QCString display = ::getenv(DISPLAY);
01173     // strip the screen number from the display
01174     display.replace(QRegExp("\\.[0-9]+$"), "");
01175     int i;
01176     while( (i = display.find(':')) >= 0)
01177        display[i] = '_';
01178 
01179     fName += "_"+display;
01180     QCString smEnv = ::getenv("SESSION_MANAGER");
01181     bool check = smEnv.isEmpty();
01182     if ( !check && smModificationTime ) {
01183          QFileInfo info( fName );
01184          QTime current = info.lastModified().time();
01185          check = current > *smModificationTime;
01186     }
01187     if ( check ) {
01188         delete smModificationTime;
01189         QFile f( fName );
01190         if ( !f.open( IO_ReadOnly ) )
01191             return;
01192         QFileInfo info ( f );
01193         smModificationTime = new QTime( info.lastModified().time() );
01194         QTextStream t(&f);
01195         t.setEncoding( QTextStream::Latin1 );
01196         QString s = t.readLine();
01197         f.close();
01198         ::setenv( "SESSION_MANAGER", s.latin1(), true  );
01199     }
01200 #endif
01201 }
01202 
01203