00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
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>
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
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
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
00152 KDE_EXPORT bool kde_have_kipc = true;
00153 bool kde_kiosk_exception = false;
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
00170
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
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
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
00436
00437
00438
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
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
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
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
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())
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
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
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
00571
00572
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
00587
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 {
00739 #ifdef Q_WS_X11
00740 XErrorEvent* err = static_cast< XErrorEvent* >( err_ );
00741 if(kapp)
00742 {
00743
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 if (getuid() == 0) {
00778 setenv("ICEAUTHORITY", "/root/.ICEauthority", 0);
00779 setenv("KDEROOTHOME", "/root/.kde", 0);
00780 setenv("HOME", "/root", 1);
00781 }
00782
00783 d->guiEnabled = GUIenabled;
00784 if ((getuid() != geteuid()) ||
00785 (getgid() != getegid()))
00786 {
00787 fprintf(stderr, "The KDE libraries are not designed to run with suid privileges.\n");
00788 ::exit(127);
00789 }
00790
00791 KProcessController::ref();
00792
00793 (void) KClipboardSynchronizer::self();
00794
00795 QApplication::setDesktopSettingsAware( false );
00796
00797 KApp = this;
00798
00799
00800 #ifdef Q_WS_X11 //FIXME(E)
00801
00802 if ( GUIenabled ) {
00803 const int max = 20;
00804 Atom* atoms[max];
00805 char* names[max];
00806 Atom atoms_return[max];
00807 int n = 0;
00808
00809 atoms[n] = &kipcCommAtom;
00810 names[n++] = (char *) "KIPC_COMM_ATOM";
00811
00812 atoms[n] = &atom_DesktopWindow;
00813 names[n++] = (char *) "KDE_DESKTOP_WINDOW";
00814
00815 atoms[n] = &atom_NetSupported;
00816 names[n++] = (char *) "_NET_SUPPORTED";
00817
00818 atoms[n] = &kde_xdnd_drop;
00819 names[n++] = (char *) "XdndDrop";
00820
00821 XInternAtoms( qt_xdisplay(), names, n, false, atoms_return );
00822
00823 for (int i = 0; i < n; i++ )
00824 *atoms[i] = atoms_return[i];
00825 }
00826 #endif
00827
00828 dcopAutoRegistration();
00829 dcopClientPostInit();
00830
00831 smw = 0;
00832
00833
00834 #if defined Q_WS_X11
00835 kipcEventMask = (1 << KIPC::StyleChanged) | (1 << KIPC::PaletteChanged) |
00836 (1 << KIPC::FontChanged) | (1 << KIPC::BackgroundChanged) |
00837 (1 << KIPC::ToolbarStyleChanged) | (1 << KIPC::SettingsChanged) |
00838 (1 << KIPC::ClipboardConfigChanged) | (1 << KIPC::BlockShortcuts);
00839 #endif
00840
00841
00842 (void) KGlobal::locale();
00843
00844 KConfig* config = KGlobal::config();
00845 d->actionRestrictions = config->hasGroup("KDE Action Restrictions" ) && !kde_kiosk_exception;
00846
00847
00848
00849
00850 QCString readOnly = getenv("KDE_HOME_READONLY");
00851 if (readOnly.isEmpty() && (qstrcmp(name(), "kdialog") != 0))
00852 {
00853 KConfigGroupSaver saver(config, "KDE Action Restrictions");
00854 if (config->readBoolEntry("warn_unwritable_config",true))
00855 config->checkConfigFilesWritable(true);
00856 }
00857
00858 if (GUIenabled)
00859 {
00860 #ifdef Q_WS_X11
00861
00862 fcntl(ConnectionNumber(qt_xdisplay()), F_SETFD, FD_CLOEXEC);
00863
00864 d->oldXErrorHandler = XSetErrorHandler( kde_x_errhandler );
00865 d->oldXIOErrorHandler = XSetIOErrorHandler( kde_xio_errhandler );
00866 #endif
00867
00868 connect( this, SIGNAL( aboutToQuit() ), this, SIGNAL( shutDown() ) );
00869
00870 #ifdef Q_WS_X11 //FIXME(E)
00871 display = desktop()->x11Display();
00872 #endif
00873
00874 {
00875 QStringList plugins = KGlobal::dirs()->resourceDirs( "qtplugins" );
00876 QStringList::Iterator it = plugins.begin();
00877 while (it != plugins.end()) {
00878 addLibraryPath( *it );
00879 ++it;
00880 }
00881
00882 }
00883 kdisplaySetStyle();
00884 kdisplaySetFont();
00885
00886 propagateSettings(SETTINGS_QT);
00887
00888
00889
00890
00891
00892
00893
00894
00895
00896 QMimeSourceFactory* oldDefaultFactory = QMimeSourceFactory::takeDefaultFactory();
00897 QMimeSourceFactory::setDefaultFactory( mimeSourceFactory() );
00898 if ( oldDefaultFactory ) {
00899 QMimeSourceFactory::addFactory( oldDefaultFactory );
00900 }
00901
00902 d->checkAccelerators = new KCheckAccelerators( this );
00903 }
00904
00905 #ifdef Q_WS_MACX
00906 if (GUIenabled) {
00907 QPixmap pixmap = KGlobal::iconLoader()->loadIcon( KCmdLineArgs::appName(),
00908 KIcon::NoGroup, KIcon::SizeLarge, KIcon::DefaultState, 0L, false );
00909 if (!pixmap.isNull()) {
00910 QImage i = pixmap.convertToImage().convertDepth(32).smoothScale(40, 40);
00911 for(int y = 0; y < i.height(); y++) {
00912 uchar *l = i.scanLine(y);
00913 for(int x = 0; x < i.width(); x+=4)
00914 *(l+x) = 255;
00915 }
00916 CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
00917 CGDataProviderRef dp = CGDataProviderCreateWithData(NULL,
00918 i.bits(), i.numBytes(), NULL);
00919 CGImageRef ir = CGImageCreate(i.width(), i.height(), 8, 32, i.bytesPerLine(),
00920 cs, kCGImageAlphaNoneSkipFirst, dp,
00921 0, 0, kCGRenderingIntentDefault);
00922
00923 SetApplicationDockTileImage(ir);
00924 CGImageRelease(ir);
00925 CGColorSpaceRelease(cs);
00926 CGDataProviderRelease(dp);
00927 }
00928 }
00929 #endif
00930
00931
00932
00933
00934 bool rtl = reverseLayout();
00935 installTranslator(new KDETranslator(this));
00936 setReverseLayout( rtl );
00937 if (i18n( "_: Dear Translator! Translate this string to the string 'LTR' in "
00938 "left-to-right languages (as english) or to 'RTL' in right-to-left "
00939 "languages (such as Hebrew and Arabic) to get proper widget layout." ) == "RTL")
00940 setReverseLayout( !rtl );
00941
00942
00943 KGlobal::dirs()->addResourceType("appdata", KStandardDirs::kde_default("data")
00944 + QString::fromLatin1(name()) + '/');
00945 pSessionConfig = 0L;
00946 bSessionManagement = true;
00947
00948 #ifdef Q_WS_X11
00949
00950 if (GUIenabled && kde_have_kipc )
00951 {
00952 smw = new QWidget(0,0);
00953 long data = 1;
00954 XChangeProperty(qt_xdisplay(), smw->winId(),
00955 atom_DesktopWindow, atom_DesktopWindow,
00956 32, PropModeReplace, (unsigned char *)&data, 1);
00957 }
00958 d->oldIceIOErrorHandler = IceSetIOErrorHandler( kde_ice_ioerrorhandler );
00959 #elif defined(Q_WS_WIN)
00960 KApplication_init_windows(GUIenabled);
00961 #else
00962
00963 #endif
00964 }
00965
00966 static int my_system (const char *command) {
00967 int pid, status;
00968
00969 pid = fork();
00970 if (pid == -1)
00971 return -1;
00972 if (pid == 0) {
00973 const char* shell = "/bin/sh";
00974 execl(shell, shell, "-c", command, (void *)0);
00975 ::_exit(127);
00976 }
00977 do {
00978 if (waitpid(pid, &status, 0) == -1) {
00979 if (errno != EINTR)
00980 return -1;
00981 } else
00982 return status;
00983 } while(1);
00984 }
00985
00986
00987 DCOPClient *KApplication::dcopClient()
00988 {
00989 if (s_DCOPClient)
00990 return s_DCOPClient;
00991
00992 s_DCOPClient = new DCOPClient();
00993 KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
00994 if (args && args->isSet("dcopserver"))
00995 {
00996 s_DCOPClient->setServerAddress( args->getOption("dcopserver"));
00997 }
00998 if( kapp ) {
00999 connect(s_DCOPClient, SIGNAL(attachFailed(const QString &)),
01000 kapp, SLOT(dcopFailure(const QString &)));
01001 connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
01002 kapp, SLOT(dcopBlockUserInput(bool)) );
01003 }
01004 else
01005 s_dcopClientNeedsPostInit = true;
01006
01007 DCOPClient::setMainClient( s_DCOPClient );
01008 return s_DCOPClient;
01009 }
01010
01011 void KApplication::dcopClientPostInit()
01012 {
01013 if( s_dcopClientNeedsPostInit )
01014 {
01015 s_dcopClientNeedsPostInit = false;
01016 connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
01017 SLOT(dcopBlockUserInput(bool)) );
01018 s_DCOPClient->bindToApp();
01019 }
01020 }
01021
01022 void KApplication::dcopAutoRegistration()
01023 {
01024 if (autoDcopRegistration)
01025 {
01026 ( void ) dcopClient();
01027 if( dcopClient()->appId().isEmpty())
01028 dcopClient()->registerAs(name());
01029 }
01030 }
01031
01032 void KApplication::disableAutoDcopRegistration()
01033 {
01034 autoDcopRegistration = false;
01035 }
01036
01037 KConfig* KApplication::sessionConfig()
01038 {
01039 if (pSessionConfig)
01040 return pSessionConfig;
01041
01042
01043 pSessionConfig = new KConfig( sessionConfigName(), false, false);
01044 return pSessionConfig;
01045 }
01046
01047 void KApplication::ref()
01048 {
01049 d->refCount++;
01050
01051 }
01052
01053 void KApplication::deref()
01054 {
01055 d->refCount--;
01056
01057 if ( d->refCount <= 0 )
01058 quit();
01059 }
01060
01061 KSessionManaged::KSessionManaged()
01062 {
01063 sessionClients()->remove( this );
01064 sessionClients()->append( this );
01065 }
01066
01067 KSessionManaged::~KSessionManaged()
01068 {
01069 sessionClients()->remove( this );
01070 }
01071
01072 bool KSessionManaged::saveState(QSessionManager&)
01073 {
01074 return true;
01075 }
01076
01077 bool KSessionManaged::commitData(QSessionManager&)
01078 {
01079 return true;
01080 }
01081
01082
01083 void KApplication::disableSessionManagement() {
01084 bSessionManagement = false;
01085 }
01086
01087 void KApplication::enableSessionManagement() {
01088 bSessionManagement = true;
01089 #ifdef Q_WS_X11
01090
01091
01092
01093
01094
01095
01096
01097
01098
01099 if( mySmcConnection ) {
01100 SmcRequestSaveYourself( mySmcConnection, SmSaveLocal, False,
01101 SmInteractStyleAny,
01102 False, False );
01103
01104
01105 IceFlush(SmcGetIceConnection(mySmcConnection));
01106 }
01107 #endif
01108 }
01109
01110
01111 bool KApplication::requestShutDown(
01112 ShutdownConfirm confirm, ShutdownType sdtype, ShutdownMode sdmode )
01113 {
01114 #ifdef Q_WS_X11
01115 QApplication::syncX();
01116
01117 if ( confirm == ShutdownConfirmYes ||
01118 sdtype != ShutdownTypeDefault ||
01119 sdmode != ShutdownModeDefault )
01120 {
01121 QByteArray data;
01122 QDataStream arg(data, IO_WriteOnly);
01123 arg << (int)confirm << (int)sdtype << (int)sdmode;
01124 return dcopClient()->send( "ksmserver", "ksmserver",
01125 "logout(int,int,int)", data );
01126 }
01127
01128 if ( mySmcConnection ) {
01129
01130 SmcRequestSaveYourself( mySmcConnection, SmSaveBoth, True,
01131 SmInteractStyleAny,
01132 confirm == ShutdownConfirmNo, True );
01133
01134
01135 IceFlush(SmcGetIceConnection(mySmcConnection));
01136 return true;
01137 }
01138
01139
01140
01141 propagateSessionManager();
01142 QCString smEnv = ::getenv("SESSION_MANAGER");
01143 if (smEnv.isEmpty())
01144 return false;
01145
01146 if (! tmpSmcConnection) {
01147 char cerror[256];
01148 char* myId = 0;
01149 char* prevId = 0;
01150 SmcCallbacks cb;
01151 tmpSmcConnection = SmcOpenConnection( 0, 0, 1, 0,
01152 0, &cb,
01153 prevId,
01154 &myId,
01155 255,
01156 cerror );
01157 ::free( myId );
01158 if (!tmpSmcConnection )
01159 return false;
01160 }
01161
01162 SmcRequestSaveYourself( tmpSmcConnection, SmSaveBoth, True,
01163 SmInteractStyleAny, False, True );
01164
01165
01166 IceFlush(SmcGetIceConnection(tmpSmcConnection));
01167 return true;
01168 #else
01169
01170 return false;
01171 #endif
01172 }
01173
01174 void KApplication::propagateSessionManager()
01175 {
01176 #ifdef Q_WS_X11
01177 QCString fName = QFile::encodeName(locateLocal("socket", "KSMserver"));
01178 QCString display = ::getenv(DISPLAY);
01179
01180 display.replace(QRegExp("\\.[0-9]+$"), "");
01181 int i;
01182 while( (i = display.find(':')) >= 0)
01183 display[i] = '_';
01184
01185 fName += "_"+display;
01186 QCString smEnv = ::getenv("SESSION_MANAGER");
01187 bool check = smEnv.isEmpty();
01188 if ( !check && smModificationTime ) {
01189 QFileInfo info( fName );
01190 QTime current = info.lastModified().time();
01191 check = current > *smModificationTime;
01192 }
01193 if ( check ) {
01194 delete smModificationTime;
01195 QFile f( fName );
01196 if ( !f.open( IO_ReadOnly ) )
01197 return;
01198 QFileInfo info ( f );
01199 smModificationTime = new QTime( info.lastModified().time() );
01200 QTextStream t(&f);
01201 t.setEncoding( QTextStream::Latin1 );
01202 QString s = t.readLine();
01203 f.close();
01204 ::setenv( "SESSION_MANAGER", s.latin1(), true );
01205 }
01206 #endif
01207 }
01208
01209 void KApplication::commitData( QSessionManager& sm )
01210 {
01211 d->session_save = true;
01212 bool canceled = false;
01213 for (KSessionManaged* it = sessionClients()->first();
01214 it && !canceled;
01215 it = sessionClients()->next() ) {
01216 canceled = !it->commitData( sm );
01217 }
01218 if ( canceled )
01219 sm.cancel();
01220
01221 if ( sm.allowsInteraction() ) {
01222 QWidgetList done;
01223 QWidgetList *list = QApplication::topLevelWidgets();
01224 bool canceled = false;
01225 QWidget* w = list->first();
01226 while ( !canceled && w ) {
01227 if ( !w->testWState( WState_ForceHide ) && !w->inherits("KMainWindow") ) {
01228 QCloseEvent e;
01229 sendEvent( w, &e );
01230 canceled = !e.isAccepted();
01231 if ( !canceled )
01232 done.append( w );
01233 delete list;
01234 list = QApplication::topLevelWidgets();
01235 w = list->first();
01236 } else {
01237 w = list->next();
01238 }
01239 while ( w && done.containsRef( w ) )
01240 w = list->next();
01241 }
01242 delete list;
01243 }
01244
01245
01246 if ( !bSessionManagement )
01247 sm.setRestartHint( QSessionManager::RestartNever );
01248 else
01249 sm.setRestartHint( QSessionManager::RestartIfRunning );
01250 d->session_save = false;
01251 }
01252
01253 void KApplication::saveState( QSessionManager& sm )
01254 {
01255 d->session_save = true;
01256 #ifdef Q_WS_X11
01257 static bool firstTime = true;
01258 mySmcConnection = (SmcConn) sm.handle();
01259
01260 if ( !bSessionManagement ) {
01261 sm.setRestartHint( QSessionManager::RestartNever );
01262 d->session_save = false;
01263 return;
01264 }
01265 else
01266 sm.setRestartHint( QSessionManager::RestartIfRunning );
01267
01268 if ( firstTime ) {
01269 firstTime = false;
01270 d->session_save = false;
01271 return;
01272 }
01273
01274
01275
01276
01277
01278
01279
01280 if ( pSessionConfig ) {
01281 delete pSessionConfig;
01282 pSessionConfig = 0;
01283 }
01284
01285
01286 QStringList restartCommand = sm.restartCommand();
01287
01288 QCString multiHead = getenv("KDE_MULTIHEAD");
01289 if (multiHead.lower() == "true") {
01290
01291
01292
01293
01294
01295
01296 QCString displayname = getenv(DISPLAY);
01297 if (! displayname.isNull()) {
01298
01299
01300 restartCommand.append("-display");
01301 restartCommand.append(displayname);
01302 }
01303 sm.setRestartCommand( restartCommand );
01304 }
01305
01306
01307
01308 emit saveYourself();
01309 bool canceled = false;
01310 for (KSessionManaged* it = sessionClients()->first();
01311 it && !canceled;
01312 it = sessionClients()->next() ) {
01313 canceled = !it->saveState( sm );
01314 }
01315
01316
01317 if ( pSessionConfig ) {
01318 pSessionConfig->sync();
01319 QStringList discard;
01320 discard << "rm" << locateLocal("config", sessionConfigName());
01321 sm.setDiscardCommand( discard );
01322 } else {
01323 sm.setDiscardCommand( "" );
01324 }
01325
01326 if ( canceled )
01327 sm.cancel();
01328 #else
01329
01330 #endif
01331 d->session_save = false;
01332 }
01333
01334 bool KApplication::sessionSaving() const
01335 {
01336 return d->session_save;
01337 }
01338
01339 void KApplication::startKdeinit()
01340 {
01341 #ifndef Q_WS_WIN //TODO
01342
01343 QString srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"));
01344 if (srv.isEmpty())
01345 srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"), KGlobal::dirs()->kfsstnd_defaultbindir());
01346 if (srv.isEmpty())
01347 return;
01348 if (kapp && (Tty != kapp->type()))
01349 setOverrideCursor( Qt::waitCursor );
01350 my_system(QFile::encodeName(srv)+" --suicide");
01351 if (kapp && (Tty != kapp->type()))
01352 restoreOverrideCursor();
01353 #endif
01354 }
01355
01356 void KApplication::dcopFailure(const QString &msg)
01357 {
01358 static int failureCount = 0;
01359 failureCount++;
01360 if (failureCount == 1)
01361 {
01362 startKdeinit();
01363 return;
01364 }
01365 if (failureCount == 2)
01366 {
01367 #ifdef Q_WS_WIN
01368 KGlobal::config()->setGroup("General");
01369 if (KGlobal::config()->readBoolEntry("ignoreDCOPFailures", false))
01370 return;
01371 #endif
01372 QString msgStr(i18n("There was an error setting up inter-process "
01373 "communications for KDE. The message returned "
01374 "by the system was:\n\n"));
01375 msgStr += msg;
01376 msgStr += i18n("\n\nPlease check that the \"dcopserver\" program is running!");
01377
01378 if (Tty != kapp->type())
01379 {
01380 QMessageBox::critical
01381 (
01382 kapp->mainWidget(),
01383 i18n("DCOP communications error (%1)").arg(kapp->caption()),
01384 msgStr,
01385 i18n("&OK")
01386 );
01387 }
01388 else
01389 {
01390 fprintf(stderr, "%s\n", msgStr.local8Bit().data());
01391 }
01392
01393 return;
01394 }
01395 }
01396
01397 static const KCmdLineOptions qt_options[] =
01398 {
01399
01400 #ifdef Q_WS_X11
01401 { "display <displayname>", I18N_NOOP("Use the X-server display 'displayname'"), 0},
01402 #else
01403 { "display <displayname>", I18N_NOOP("Use the QWS display 'displayname'"), 0},
01404 #endif
01405 { "session <sessionId>", I18N_NOOP("Restore the application for the given 'sessionId'"), 0},
01406 { "cmap", I18N_NOOP("Causes the application to install a private color\nmap on an 8-bit display"), 0},
01407 { "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},
01408 { "nograb", I18N_NOOP("tells Qt to never grab the mouse or the keyboard"), 0},
01409 { "dograb", I18N_NOOP("running under a debugger can cause an implicit\n-nograb, use -dograb to override"), 0},
01410 { "sync", I18N_NOOP("switches to synchronous mode for debugging"), 0},
01411 { "fn", 0, 0},
01412 { "font <fontname>", I18N_NOOP("defines the application font"), 0},
01413 { "bg", 0, 0},
01414 { "background <color>", I18N_NOOP("sets the default background color and an\napplication palette (light and dark shades are\ncalculated)"), 0},
01415 { "fg", 0, 0},
01416 { "foreground <color>", I18N_NOOP("sets the default foreground color"), 0},
01417 { "btn", 0, 0},
01418 { "button <color>", I18N_NOOP("sets the default button color"), 0},
01419 { "name <name>", I18N_NOOP("sets the application name"), 0},
01420 { "title <title>", I18N_NOOP("sets the application title (caption)"), 0},
01421 #ifdef Q_WS_X11
01422 { "visual TrueColor", I18N_NOOP("forces the application to use a TrueColor visual on\nan 8-bit display"), 0},
01423 { "inputstyle <inputstyle>", I18N_NOOP("sets XIM (X Input Method) input style. Possible\nvalues are onthespot, overthespot, offthespot and\nroot"), 0 },
01424 { "im <XIM server>", I18N_NOOP("set XIM server"),0},
01425 { "noxim", I18N_NOOP("disable XIM"), 0 },
01426 #endif
01427 #ifdef Q_WS_QWS
01428 { "qws", I18N_NOOP("forces the application to run as QWS Server"), 0},
01429 #endif
01430 { "reverse", I18N_NOOP("mirrors the whole layout of widgets"), 0},
01431 KCmdLineLastOption
01432 };
01433
01434 static const KCmdLineOptions kde_options[] =
01435 {
01436 { "caption <caption>", I18N_NOOP("Use 'caption' as name in the titlebar"), 0},
01437 { "icon <icon>", I18N_NOOP("Use 'icon' as the application icon"), 0},
01438 { "miniicon <icon>", I18N_NOOP("Use 'icon' as the icon in the titlebar"), 0},
01439 { "config <filename>", I18N_NOOP("Use alternative configuration file"), 0},
01440 { "dcopserver <server>", I18N_NOOP("Use the DCOP Server specified by 'server'"), 0},
01441 { "nocrashhandler", I18N_NOOP("Disable crash handler, to get core dumps"), 0},
01442 { "waitforwm", I18N_NOOP("Waits for a WM_NET compatible windowmanager"), 0},
01443 { "style <style>", I18N_NOOP("sets the application GUI style"), 0},
01444 { "geometry <geometry>", I18N_NOOP("sets the client geometry of the main widget - see man X for the argument format"), 0},
01445 { "smkey <sessionKey>", 0, 0},
01446
01447
01448 KCmdLineLastOption
01449 };
01450
01451 void
01452 KApplication::addCmdLineOptions()
01453 {
01454 KCmdLineArgs::addCmdLineOptions(qt_options, "Qt", "qt");
01455 KCmdLineArgs::addCmdLineOptions(kde_options, "KDE", "kde");
01456 }
01457
01458 void KApplication::parseCommandLine( )
01459 {
01460 KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
01461
01462 if ( !args ) return;
01463
01464 if (args->isSet("config"))
01465 {
01466 QString config = QString::fromLocal8Bit(args->getOption("config"));
01467 setConfigName(config);
01468 }
01469
01470 if (args->isSet("style"))
01471 {
01472
01473 QStringList styles = QStyleFactory::keys();
01474 QString reqStyle(args->getOption("style").lower());
01475
01476 for (QStringList::ConstIterator it = styles.begin(); it != styles.end(); ++it)
01477 if ((*it).lower() == reqStyle)
01478 {
01479 d->overrideStyle = *it;
01480 break;
01481 }
01482
01483 if (d->overrideStyle.isEmpty())
01484 fprintf(stderr, "%s", i18n("The style %1 was not found\n").arg(reqStyle).local8Bit().data());
01485 }
01486
01487 if (args->isSet("caption"))
01488 {
01489 aCaption = QString::fromLocal8Bit(args->getOption("caption"));
01490 }
01491
01492 if (args->isSet("miniicon"))
01493 {
01494 const char *tmp = args->getOption("miniicon");
01495 if (!aIconPixmap.pm.miniIcon) {
01496 aIconPixmap.pm.miniIcon = new QPixmap;
01497 }
01498 *aIconPixmap.pm.miniIcon = SmallIcon(tmp);
01499 aMiniIconName = tmp;
01500 }
01501
01502 if (args->isSet("icon"))
01503 {
01504 const char *tmp = args->getOption("icon");
01505 if (!aIconPixmap.pm.icon) {
01506 aIconPixmap.pm.icon = new QPixmap;
01507 }
01508 *aIconPixmap.pm.icon = DesktopIcon( tmp );
01509 aIconName = tmp;
01510 if (!aIconPixmap.pm.miniIcon) {
01511 aIconPixmap.pm.miniIcon = new QPixmap;
01512 }
01513 if (aIconPixmap.pm.miniIcon->isNull())
01514 {
01515 *aIconPixmap.pm.miniIcon = SmallIcon( tmp );
01516 aMiniIconName = tmp;
01517 }
01518 }
01519
01520 bool nocrashhandler = (getenv("KDE_DEBUG") != NULL);
01521 if (!nocrashhandler && args->isSet("crashhandler"))
01522 {
01523
01524 KCrash::setCrashHandler(KCrash::defaultCrashHandler);
01525 KCrash::setEmergencySaveFunction(NULL);
01526
01527 KCrash::setApplicationName(QString(args->appName()));
01528 }
01529
01530 #ifdef Q_WS_X11
01531 if ( args->isSet( "waitforwm" ) ) {
01532 Atom type;
01533 (void) desktop();
01534 int format;
01535 unsigned long length, after;
01536 unsigned char *data;
01537 while ( XGetWindowProperty( qt_xdisplay(), qt_xrootwin(), atom_NetSupported,
01538 0, 1, false, AnyPropertyType, &type, &format,
01539 &length, &after, &data ) != Success || !length ) {
01540 if ( data )
01541 XFree( data );
01542 XEvent event;
01543 XWindowEvent( qt_xdisplay(), qt_xrootwin(), PropertyChangeMask, &event );
01544 }
01545 if ( data )
01546 XFree( data );
01547 }
01548 #else
01549
01550 #endif
01551
01552 if (args->isSet("geometry"))
01553 {
01554 d->geometry_arg = args->getOption("geometry");
01555 }
01556
01557 if (args->isSet("smkey"))
01558 {
01559 d->sessionKey = args->getOption("smkey");
01560 }
01561
01562 }
01563
01564 QString KApplication::geometryArgument() const
01565 {
01566 return d->geometry_arg;
01567 }
01568
01569 QPixmap KApplication::icon() const
01570 {
01571 if( !aIconPixmap.pm.icon) {
01572 aIconPixmap.pm.icon = new QPixmap;
01573 }
01574 if( aIconPixmap.pm.icon->isNull()) {
01575 *aIconPixmap.pm.icon = DesktopIcon( instanceName() );
01576 }
01577 return *aIconPixmap.pm.icon;
01578 }
01579
01580 QString KApplication::iconName() const
01581 {
01582 return aIconName.isNull() ? (QString)instanceName() : aIconName;
01583 }
01584
01585 QPixmap KApplication::miniIcon() const
01586 {
01587 if (!aIconPixmap.pm.miniIcon) {
01588 aIconPixmap.pm.miniIcon = new QPixmap;
01589 }
01590 if (aIconPixmap.pm.miniIcon->isNull()) {
01591 *aIconPixmap.pm.miniIcon = SmallIcon( instanceName() );
01592 }
01593 return *aIconPixmap.pm.miniIcon;
01594 }
01595
01596 QString KApplication::miniIconName() const
01597 {
01598 return aMiniIconName.isNull() ? (QString)instanceName() : aMiniIconName;
01599 }
01600
01601 extern void kDebugCleanup();
01602
01603 KApplication::~KApplication()
01604 {
01605 delete aIconPixmap.pm.miniIcon;
01606 aIconPixmap.pm.miniIcon = 0L;
01607 delete aIconPixmap.pm.icon;
01608 aIconPixmap.pm.icon = 0L;
01609 delete d->m_KAppDCOPInterface;
01610
01611
01612
01613
01614 KGlobal::deleteStaticDeleters();
01615 KLibLoader::cleanUp();
01616
01617 delete smw;
01618
01619
01620 delete s_DCOPClient;
01621 s_DCOPClient = 0L;
01622
01623 KProcessController::deref();
01624
01625 #ifdef Q_WS_X11
01626 if ( d->oldXErrorHandler != NULL )
01627 XSetErrorHandler( d->oldXErrorHandler );
01628 if ( d->oldXIOErrorHandler != NULL )
01629 XSetIOErrorHandler( d->oldXIOErrorHandler );
01630 if ( d->oldIceIOErrorHandler != NULL )
01631 IceSetIOErrorHandler( d->oldIceIOErrorHandler );
01632 #endif
01633
01634 delete d;
01635 KApp = 0;
01636
01637 #ifdef Q_WS_X11
01638 mySmcConnection = 0;
01639 delete smModificationTime;
01640 smModificationTime = 0;
01641
01642
01643 if (tmpSmcConnection) {
01644 SmcCloseConnection( tmpSmcConnection, 0, 0 );
01645 tmpSmcConnection = 0;
01646 }
01647 #else
01648
01649 #endif
01650 }
01651
01652
01653 #ifdef Q_WS_X11
01654 class KAppX11HackWidget: public QWidget
01655 {
01656 public:
01657 bool publicx11Event( XEvent * e) { return x11Event( e ); }
01658 };
01659 #endif
01660
01661
01662
01663 static bool kapp_block_user_input = false;
01664
01665 void KApplication::dcopBlockUserInput( bool b )
01666 {
01667 kapp_block_user_input = b;
01668 }
01669
01670 #ifdef Q_WS_X11
01671 bool KApplication::x11EventFilter( XEvent *_event )
01672 {
01673 switch ( _event->type ) {
01674 case ClientMessage:
01675 {
01676 #if KDE_IS_VERSION( 3, 90, 90 )
01677 #warning This should be already in Qt, check.
01678 #endif
01679
01680
01681
01682
01683
01684 if( _event->xclient.message_type == kde_xdnd_drop )
01685 {
01686 if( _event->xclient.data.l[ 1 ] == 1 << 24
01687 && _event->xclient.data.l[ 2 ] == 0
01688 && _event->xclient.data.l[ 4 ] == 0
01689 && _event->xclient.data.l[ 3 ] != 0 )
01690 {
01691 if( qt_x_user_time == 0
01692 || NET::timestampCompare( _event->xclient.data.l[ 3 ], qt_x_user_time ) > 0 )
01693 {
01694 qt_x_user_time = _event->xclient.data.l[ 3 ];
01695 }
01696 }
01697 else
01698 {
01699 if( qt_x_user_time == 0
01700 || NET::timestampCompare( _event->xclient.data.l[ 2 ], qt_x_user_time ) > 0 )
01701 {
01702 qt_x_user_time = _event->xclient.data.l[ 2 ];
01703 }
01704 }
01705 }
01706 }
01707 default: break;
01708 }
01709
01710 if ( kapp_block_user_input ) {
01711 switch ( _event->type ) {
01712 case ButtonPress:
01713 case ButtonRelease:
01714 case XKeyPress:
01715 case XKeyRelease:
01716 case MotionNotify:
01717 case EnterNotify:
01718 case LeaveNotify:
01719 return true;
01720 default:
01721 break;
01722 }
01723 }
01724
01725 if (x11Filter) {
01726 for (QWidget *w=x11Filter->first(); w; w=x11Filter->next()) {
01727 if (((KAppX11HackWidget*) w)->publicx11Event(_event))
01728 return true;
01729 }
01730 }
01731
01732 if ((_event->type == ClientMessage) &&
01733 (_event->xclient.message_type == kipcCommAtom))
01734 {
01735 XClientMessageEvent *cme = (XClientMessageEvent *) _event;
01736
01737 int id = cme->data.l[0];
01738 int arg = cme->data.l[1];
01739 if ((id < 32) && (kipcEventMask & (1 << id)))
01740 {
01741 switch (id)
01742 {
01743 case KIPC::StyleChanged:
01744 KGlobal::config()->reparseConfiguration();
01745 kdisplaySetStyle();
01746 break;
01747
01748 case KIPC::ToolbarStyleChanged:
01749 KGlobal::config()->reparseConfiguration();
01750 if (useStyles)
01751 emit toolbarAppearanceChanged(arg);
01752 break;
01753
01754 case KIPC::PaletteChanged:
01755 KGlobal::config()->reparseConfiguration();
01756 kdisplaySetPalette();
01757 break;
01758
01759 case KIPC::FontChanged:
01760 KGlobal::config()->reparseConfiguration();
01761 KGlobalSettings::rereadFontSettings();
01762 kdisplaySetFont();
01763 break;
01764
01765 case KIPC::BackgroundChanged:
01766 emit backgroundChanged(arg);
01767 break;
01768
01769 case KIPC::SettingsChanged:
01770 KGlobal::config()->reparseConfiguration();
01771 if (arg == SETTINGS_PATHS)
01772 KGlobalSettings::rereadPathSettings();
01773 else if (arg == SETTINGS_MOUSE)
01774 KGlobalSettings::rereadMouseSettings();
01775 propagateSettings((SettingsCategory)arg);
01776 break;
01777
01778 case KIPC::IconChanged:
01779 QPixmapCache::clear();
01780 KGlobal::config()->reparseConfiguration();
01781 KGlobal::instance()->newIconLoader();
01782 emit updateIconLoaders();
01783 emit iconChanged(arg);
01784 break;
01785
01786 case KIPC::ClipboardConfigChanged:
01787 KClipboardSynchronizer::newConfiguration(arg);
01788 break;
01789
01790 case KIPC::BlockShortcuts:
01791 KGlobalAccel::blockShortcuts(arg);
01792 emit kipcMessage(id, arg);
01793 break;
01794 }
01795 }
01796 else if (id >= 32)
01797 {
01798 emit kipcMessage(id, arg);
01799 }
01800 return true;
01801 }
01802 return false;
01803 }
01804 #endif // Q_WS_X11
01805
01806 void KApplication::updateUserTimestamp( unsigned long time )
01807 {
01808 #if defined Q_WS_X11
01809 if( time == 0 )
01810 {
01811 Window w = XCreateSimpleWindow( qt_xdisplay(), qt_xrootwin(), 0, 0, 1, 1, 0, 0, 0 );
01812 XSelectInput( qt_xdisplay(), w, PropertyChangeMask );
01813 unsigned char data[ 1 ];
01814 XChangeProperty( qt_xdisplay(), w, XA_ATOM, XA_ATOM, 8, PropModeAppend, data, 1 );
01815 XEvent ev;
01816 XWindowEvent( qt_xdisplay(), w, PropertyChangeMask, &ev );
01817 time = ev.xproperty.time;
01818 XDestroyWindow( qt_xdisplay(), w );
01819 }
01820 if( qt_x_user_time == 0
01821 || NET::timestampCompare( time, qt_x_user_time ) > 0 )
01822 qt_x_user_time = time;
01823 #endif
01824 }
01825
01826 unsigned long KApplication::userTimestamp() const
01827 {
01828 #if defined Q_WS_X11
01829 return qt_x_user_time;
01830 #else
01831 return 0;
01832 #endif
01833 }
01834
01835 void KApplication::updateRemoteUserTimestamp( const QCString& dcopId, unsigned long time )
01836 {
01837 #if defined Q_WS_X11
01838 if( time == 0 )
01839 time = qt_x_user_time;
01840 DCOPRef( dcopId, "MainApplication-Interface" ).call( "updateUserTimestamp", time );
01841 #endif
01842 }
01843
01844 void KApplication::invokeEditSlot( const char *slot )
01845 {
01846 QObject *object = focusWidget();
01847 if( !object )
01848 return;
01849
01850 QMetaObject *meta = object->metaObject();
01851
01852 int idx = meta->findSlot( slot + 1, true );
01853 if( idx < 0 )
01854 return;
01855
01856 object->qt_invoke( idx, 0 );
01857 }
01858
01859 void KApplication::addKipcEventMask(int id)
01860 {
01861 if (id >= 32)
01862 {
01863 kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01864 return;
01865 }
01866 kipcEventMask |= (1 << id);
01867 }
01868
01869 void KApplication::removeKipcEventMask(int id)
01870 {
01871 if (id >= 32)
01872 {
01873 kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01874 return;
01875 }
01876 kipcEventMask &= ~(1 << id);
01877 }
01878
01879 void KApplication::enableStyles()
01880 {
01881 if (!useStyles)
01882 {
01883 useStyles = true;
01884 applyGUIStyle();
01885 }
01886 }
01887
01888 void KApplication::disableStyles()
01889 {
01890 useStyles = false;
01891 }
01892
01893 void KApplication::applyGUIStyle()
01894 {
01895 if ( !useStyles ) return;
01896
01897 KConfigGroup pConfig (KGlobal::config(), "General");
01898 QString defaultStyle = KStyle::defaultStyle();
01899 QString styleStr = pConfig.readEntry("widgetStyle", defaultStyle);
01900
01901 if (d->overrideStyle.isEmpty()) {
01902
01903
01904
01905 QStyle* sp = QStyleFactory::create( styleStr );
01906
01907
01908 if ( !sp && styleStr != defaultStyle)
01909 sp = QStyleFactory::create( defaultStyle );
01910 if ( !sp )
01911 sp = QStyleFactory::create( *(QStyleFactory::keys().begin()) );
01912 setStyle(sp);
01913 }
01914 else
01915 setStyle(d->overrideStyle);
01916
01917 kdisplaySetPalette();
01918 }
01919
01920 QString KApplication::caption() const
01921 {
01922
01923 if( !aCaption.isNull() )
01924 return aCaption;
01925 else
01926
01927 if ( KGlobal::instance()->aboutData() )
01928 return KGlobal::instance()->aboutData()->programName();
01929 else
01930
01931 return name();
01932 }
01933
01934
01935
01936
01937
01938
01939 QString KApplication::makeStdCaption( const QString &userCaption,
01940 bool withAppName, bool modified ) const
01941 {
01942 QString s = userCaption.isEmpty() ? caption() : userCaption;
01943
01944
01945 if (modified)
01946 s += QString::fromUtf8(" [") + i18n("modified") + QString::fromUtf8("]");
01947
01948 if ( !userCaption.isEmpty() ) {
01949
01950
01951 if ( withAppName && !caption().isNull() && !userCaption.endsWith(caption()) )
01952 s += QString::fromUtf8(" - ") + caption();
01953 }
01954
01955 return s;
01956 }
01957
01958 QPalette KApplication::createApplicationPalette()
01959 {
01960 KConfig *config = KGlobal::config();
01961 KConfigGroupSaver saver( config, "General" );
01962 return createApplicationPalette( config, KGlobalSettings::contrast() );
01963 }
01964
01965 QPalette KApplication::createApplicationPalette( KConfig *config, int contrast_ )
01966 {
01967 QColor kde34Background( 239, 239, 239 );
01968 QColor kde34Blue( 103,141,178 );
01969
01970 QColor kde34Button;
01971 if ( QPixmap::defaultDepth() > 8 )
01972 kde34Button.setRgb( 221, 223, 228 );
01973 else
01974 kde34Button.setRgb( 220, 220, 220 );
01975
01976 QColor kde34Link( 0, 0, 238 );
01977 QColor kde34VisitedLink( 82, 24, 139 );
01978
01979 QColor background = config->readColorEntry( "background", &kde34Background );
01980 QColor foreground = config->readColorEntry( "foreground", &black );
01981 QColor button = config->readColorEntry( "buttonBackground", &kde34Button );
01982 QColor buttonText = config->readColorEntry( "buttonForeground", &black );
01983 QColor highlight = config->readColorEntry( "selectBackground", &kde34Blue );
01984 QColor highlightedText = config->readColorEntry( "selectForeground", &white );
01985 QColor base = config->readColorEntry( "windowBackground", &white );
01986 QColor baseText = config->readColorEntry( "windowForeground", &black );
01987 QColor link = config->readColorEntry( "linkColor", &kde34Link );
01988 QColor visitedLink = config->readColorEntry( "visitedLinkColor", &kde34VisitedLink );
01989
01990 int highlightVal, lowlightVal;
01991 highlightVal = 100 + (2*contrast_+4)*16/10;
01992 lowlightVal = 100 + (2*contrast_+4)*10;
01993
01994 QColor disfg = foreground;
01995
01996 int h, s, v;
01997 disfg.hsv( &h, &s, &v );
01998 if (v > 128)
01999
02000 disfg = disfg.dark(lowlightVal);
02001 else if (disfg != black)
02002
02003 disfg = disfg.light(highlightVal);
02004 else
02005
02006 disfg = Qt::darkGray;
02007
02008
02009 QColorGroup disabledgrp(disfg, background,
02010 background.light(highlightVal),
02011 background.dark(lowlightVal),
02012 background.dark(120),
02013 background.dark(120), base);
02014
02015 QColorGroup colgrp(foreground, background, background.light(highlightVal),
02016 background.dark(lowlightVal),
02017 background.dark(120),
02018 baseText, base);
02019
02020 int inlowlightVal = lowlightVal-25;
02021 if(inlowlightVal < 120)
02022 inlowlightVal = 120;
02023
02024 colgrp.setColor(QColorGroup::Highlight, highlight);
02025 colgrp.setColor(QColorGroup::HighlightedText, highlightedText);
02026 colgrp.setColor(QColorGroup::Button, button);
02027 colgrp.setColor(QColorGroup::ButtonText, buttonText);
02028 colgrp.setColor(QColorGroup::Midlight, background.light(110));
02029 colgrp.setColor(QColorGroup::Link, link);
02030 colgrp.setColor(QColorGroup::LinkVisited, visitedLink);
02031
02032 disabledgrp.setColor(QColorGroup::Button, button);
02033
02034 QColor disbtntext = buttonText;
02035 disbtntext.hsv( &h, &s, &v );
02036 if (v > 128)
02037
02038 disbtntext = disbtntext.dark(lowlightVal);
02039 else if (disbtntext != black)
02040
02041 disbtntext = disbtntext.light(highlightVal);
02042 else
02043
02044 disbtntext = Qt::darkGray;
02045
02046 disabledgrp.setColor(QColorGroup::ButtonText, disbtntext);
02047 disabledgrp.setColor(QColorGroup::Midlight, background.light(110));
02048 disabledgrp.setColor(QColorGroup::Highlight, highlight.dark(120));
02049 disabledgrp.setColor(QColorGroup::Link, link);
02050 disabledgrp.setColor(QColorGroup::LinkVisited, visitedLink);
02051
02052 return QPalette(colgrp, disabledgrp, colgrp);
02053 }
02054
02055
02056 void KApplication::kdisplaySetPalette()
02057 {
02058 #ifdef Q_WS_MACX
02059
02060 {
02061 KConfig *config = KGlobal::config();
02062 KConfigGroupSaver saver( config, "General" );
02063 bool do_not_set_palette = FALSE;
02064 if(config->readBoolEntry("nopaletteChange", &do_not_set_palette))
02065 return;
02066 }
02067 #endif
02068 QApplication::setPalette( createApplicationPalette(), true);
02069 emit kdisplayPaletteChanged();
02070 emit appearanceChanged();
02071 }
02072
02073
02074 void KApplication::kdisplaySetFont()
02075 {
02076 QApplication::setFont(KGlobalSettings::generalFont(), true);
02077 QApplication::setFont(KGlobalSettings::menuFont(), true, "QMenuBar");
02078 QApplication::setFont(KGlobalSettings::menuFont(), true, "QPopupMenu");
02079 QApplication::setFont(KGlobalSettings::menuFont(), true, "KPopupTitle");
02080
02081
02082 QStyleSheet* sheet = QStyleSheet::defaultSheet();
02083 sheet->item ("pre")->setFontFamily (KGlobalSettings::fixedFont().family());
02084 sheet->item ("code")->setFontFamily (KGlobalSettings::fixedFont().family());
02085 sheet->item ("tt")->setFontFamily (KGlobalSettings::fixedFont().family());
02086
02087 emit kdisplayFontChanged();
02088 emit appearanceChanged();
02089 }
02090
02091
02092 void KApplication::kdisplaySetStyle()
02093 {
02094 if (useStyles)
02095 {
02096 applyGUIStyle();
02097 emit kdisplayStyleChanged();
02098 emit appearanceChanged();
02099 }
02100 }
02101
02102
02103 void KApplication::propagateSettings(SettingsCategory arg)
02104 {
02105 KConfigBase* config = KGlobal::config();
02106 KConfigGroupSaver saver( config, "KDE" );
02107
02108 int num = config->readNumEntry("CursorBlinkRate", QApplication::cursorFlashTime());
02109 if ((num != 0) && (num < 200))
02110 num = 200;
02111 if (num > 2000)
02112 num = 2000;
02113 QApplication::setCursorFlashTime(num);
02114 num = config->readNumEntry("DoubleClickInterval", QApplication::doubleClickInterval());
02115 QApplication::setDoubleClickInterval(num);
02116 num = config->readNumEntry("StartDragTime", QApplication::startDragTime());
02117 QApplication::setStartDragTime(num);
02118 num = config->readNumEntry("StartDragDist", QApplication::startDragDistance());
02119 QApplication::setStartDragDistance(num);
02120 num = config->readNumEntry("WheelScrollLines", QApplication::wheelScrollLines());
02121 QApplication::setWheelScrollLines(num);
02122
02123 bool b = config->readBoolEntry("EffectAnimateMenu", false);
02124 QApplication::setEffectEnabled( Qt::UI_AnimateMenu, b);
02125 b = config->readBoolEntry("EffectFadeMenu", false);
02126 QApplication::setEffectEnabled( Qt::UI_FadeMenu, b);
02127 b = config->readBoolEntry("EffectAnimateCombo", false);
02128 QApplication::setEffectEnabled( Qt::UI_AnimateCombo, b);
02129 b = config->readBoolEntry("EffectAnimateTooltip", false);
02130 QApplication::setEffectEnabled( Qt::UI_AnimateTooltip, b);
02131 b = config->readBoolEntry("EffectFadeTooltip", false);
02132 QApplication::setEffectEnabled( Qt::UI_FadeTooltip, b);
02133 b = !config->readBoolEntry("EffectNoTooltip", false);
02134 QToolTip::setGloballyEnabled( b );
02135
02136 emit settingsChanged(arg);
02137 }
02138
02139 void KApplication::installKDEPropertyMap()
02140 {
02141 #ifndef QT_NO_SQL
02142 static bool installed = false;
02143 if (installed) return;
02144 installed = true;
02151
02152 QSqlPropertyMap *kdeMap = new QSqlPropertyMap;
02153 kdeMap->insert( "KColorButton", "color" );
02154 kdeMap->insert( "KComboBox", "currentItem" );
02155 kdeMap->insert( "KDatePicker", "date" );
02156 kdeMap->insert( "KDateWidget", "date" );
02157 kdeMap->insert( "KDateTimeWidget", "dateTime" );
02158 kdeMap->insert( "KEditListBox", "items" );
02159 kdeMap->insert( "KFontCombo", "family" );
02160 kdeMap->insert( "KFontRequester", "font" );
02161 kdeMap->insert( "KFontChooser", "font" );
02162 kdeMap->insert( "KHistoryCombo", "currentItem" );
02163 kdeMap->insert( "KListBox", "currentItem" );
02164 kdeMap->insert( "KLineEdit", "text" );
02165 kdeMap->insert( "KRestrictedLine", "text" );
02166 kdeMap->insert( "KSqueezedTextLabel", "text" );
02167 kdeMap->insert( "KTextBrowser", "source" );
02168 kdeMap->insert( "KTextEdit", "text" );
02169 kdeMap->insert( "KURLRequester", "url" );
02170 kdeMap->insert( "KPasswordEdit", "password" );
02171 kdeMap->insert( "KIntNumInput", "value" );
02172 kdeMap->insert( "KIntSpinBox", "value" );
02173 kdeMap->insert( "KDoubleNumInput", "value" );
02174
02175 kdeMap->insert( "QGroupBox", "checked" );
02176 kdeMap->insert( "QTabWidget", "currentPage" );
02177 QSqlPropertyMap::installDefaultMap( kdeMap );
02178 #endif
02179 }
02180
02181 void KApplication::invokeHelp( const QString& anchor,
02182 const QString& _appname) const
02183 {
02184 return invokeHelp( anchor, _appname, "" );
02185 }
02186
02187 #ifndef Q_WS_WIN
02188
02189
02190 void KApplication::invokeHelp( const QString& anchor,
02191 const QString& _appname,
02192 const QCString& startup_id ) const
02193 {
02194 QString url;
02195 QString appname;
02196 if (_appname.isEmpty())
02197 appname = name();
02198 else
02199 appname = _appname;
02200
02201 if (!anchor.isEmpty())
02202 url = QString("help:/%1?anchor=%2").arg(appname).arg(anchor);
02203 else
02204 url = QString("help:/%1/index.html").arg(appname);
02205
02206 QString error;
02207 if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02208 {
02209 if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, startup_id, false))
02210 {
02211 if (Tty != kapp->type())
02212 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02213 i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02214 else
02215 kdWarning() << "Could not launch help:\n" << error << endl;
02216 return;
02217 }
02218 }
02219 else
02220 DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url, startup_id );
02221 }
02222 #endif
02223
02224 void KApplication::invokeHTMLHelp( const QString& _filename, const QString& topic ) const
02225 {
02226 kdWarning() << "invoking HTML help is deprecated! use docbook and invokeHelp!\n";
02227
02228 QString filename;
02229
02230 if( _filename.isEmpty() )
02231 filename = QString(name()) + "/index.html";
02232 else
02233 filename = _filename;
02234
02235 QString url;
02236 if (!topic.isEmpty())
02237 url = QString("help:/%1#%2").arg(filename).arg(topic);
02238 else
02239 url = QString("help:/%1").arg(filename);
02240
02241 QString error;
02242 if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02243 {
02244 if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, "", false))
02245 {
02246 if (Tty != kapp->type())
02247 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02248 i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02249 else
02250 kdWarning() << "Could not launch help:\n" << error << endl;
02251 return;
02252 }
02253 }
02254 else
02255 DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url );
02256 }
02257
02258
02259 void KApplication::invokeMailer(const QString &address, const QString &subject)
02260 {
02261 return invokeMailer(address,subject,"");
02262 }
02263
02264 void KApplication::invokeMailer(const QString &address, const QString &subject, const QCString& startup_id)
02265 {
02266 invokeMailer(address, QString::null, QString::null, subject, QString::null, QString::null,
02267 QStringList(), startup_id );
02268 }
02269
02270 void KApplication::invokeMailer(const KURL &mailtoURL)
02271 {
02272 return invokeMailer( mailtoURL, "" );
02273 }
02274
02275 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id )
02276 {
02277 return invokeMailer( mailtoURL, startup_id, false);
02278 }
02279
02280 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id, bool allowAttachments )
02281 {
02282 QString address = KURL::decode_string(mailtoURL.path()), subject, cc, bcc, body;
02283 QStringList queries = QStringList::split('&', mailtoURL.query().mid(1));
02284 QStringList attachURLs;
02285 for (QStringList::Iterator it = queries.begin(); it != queries.end(); ++it)
02286 {
02287 QString q = (*it).lower();
02288 if (q.startsWith("subject="))
02289 subject = KURL::decode_string((*it).mid(8));
02290 else
02291 if (q.startsWith("cc="))
02292 cc = cc.isEmpty()? KURL::decode_string((*it).mid(3)): cc + ',' + KURL::decode_string((*it).mid(3));
02293 else
02294 if (q.startsWith("bcc="))
02295 bcc = bcc.isEmpty()? KURL::decode_string((*it).mid(4)): bcc + ',' + KURL::decode_string((*it).mid(4));
02296 else
02297 if (q.startsWith("body="))
02298 body = KURL::decode_string((*it).mid(5));
02299 else
02300 if (allowAttachments && q.startsWith("attach="))
02301 attachURLs.push_back(KURL::decode_string((*it).mid(7)));
02302 else
02303 if (allowAttachments && q.startsWith("attachment="))
02304 attachURLs.push_back(KURL::decode_string((*it).mid(11)));
02305 else
02306 if (q.startsWith("to="))
02307 address = address.isEmpty()? KURL::decode_string((*it).mid(3)): address + ',' + KURL::decode_string((*it).mid(3));
02308 }
02309
02310 invokeMailer( address, cc, bcc, subject, body, QString::null, attachURLs, startup_id );
02311 }
02312
02313 void KApplication::invokeMailer(const QString &to, const QString &cc, const QString &bcc,
02314 const QString &subject, const QString &body,
02315 const QString & messageFile, const QStringList &attachURLs)
02316 {
02317 return invokeMailer(to,cc,bcc,subject,body,messageFile,attachURLs,"");
02318 }
02319
02320 #ifndef Q_WS_WIN
02321
02322
02323
02324 static QStringList splitEmailAddressList( const QString & aStr )
02325 {
02326
02327
02328
02329
02330
02331
02332
02333
02334
02335 QStringList list;
02336
02337 if (aStr.isEmpty())
02338 return list;
02339
02340 QString addr;
02341 uint addrstart = 0;
02342 int commentlevel = 0;
02343 bool insidequote = false;
02344
02345 for (uint index=0; index<aStr.length(); index++) {
02346
02347
02348 switch (aStr[index].latin1()) {
02349 case '"' :
02350 if (commentlevel == 0)
02351 insidequote = !insidequote;
02352 break;
02353 case '(' :
02354 if (!insidequote)
02355 commentlevel++;
02356 break;
02357 case ')' :
02358 if (!insidequote) {
02359 if (commentlevel > 0)
02360 commentlevel--;
02361 else {
02362
02363
02364 return list;
02365 }
02366 }
02367 break;
02368 case '\\' :
02369 index++;
02370 break;
02371 case ',' :
02372 if (!insidequote && (commentlevel == 0)) {
02373 addr = aStr.mid(addrstart, index-addrstart);
02374 if (!addr.isEmpty())
02375 list += addr.simplifyWhiteSpace();
02376 addrstart = index+1;
02377 }
02378 break;
02379 }
02380 }
02381
02382 if (!insidequote && (commentlevel == 0)) {
02383 addr = aStr.mid(addrstart, aStr.length()-addrstart);
02384 if (!addr.isEmpty())
02385 list += addr.simplifyWhiteSpace();
02386 }
02387
02388
02389
02390
02391
02392 return list;
02393 }
02394
02395 void KApplication::invokeMailer(const QString &_to, const QString &_cc, const QString &_bcc,
02396 const QString &subject, const QString &body,
02397 const QString & , const QStringList &attachURLs,
02398 const QCString& startup_id )
02399 {
02400 KConfig config("emaildefaults");
02401
02402 config.setGroup("Defaults");
02403 QString group = config.readEntry("Profile","Default");
02404
02405 config.setGroup( QString("PROFILE_%1").arg(group) );
02406 QString command = config.readPathEntry("EmailClient");
02407
02408 QString to, cc, bcc;
02409 if (command.isEmpty() || command == QString::fromLatin1("kmail")
02410 || command.endsWith("/kmail"))
02411 {
02412 command = QString::fromLatin1("kmail --composer -s %s -c %c -b %b --body %B --attach %A -- %t");
02413 if ( !_to.isEmpty() )
02414 {
02415
02416
02417 to = QString( "=?utf8?b?%1?=" )
02418 .arg( KCodecs::base64Encode( _to.utf8(), false ) );
02419 }
02420 if ( !_cc.isEmpty() )
02421 cc = QString( "=?utf8?b?%1?=" )
02422 .arg( KCodecs::base64Encode( _cc.utf8(), false ) );
02423 if ( !_bcc.isEmpty() )
02424 bcc = QString( "=?utf8?b?%1?=" )
02425 .arg( KCodecs::base64Encode( _bcc.utf8(), false ) );
02426 } else {
02427 to = _to;
02428 cc = _cc;
02429 bcc = _bcc;
02430 if( !command.contains( '%' ))
02431 command += " %u";
02432 }
02433
02434 if (config.readBoolEntry("TerminalClient", false))
02435 {
02436 KConfigGroup confGroup( KGlobal::config(), "General" );
02437 QString preferredTerminal = confGroup.readPathEntry("TerminalApplication", "konsole");
02438 command = preferredTerminal + " -e " + command;
02439 }
02440
02441 QStringList cmdTokens = KShell::splitArgs(command);
02442 QString cmd = cmdTokens[0];
02443 cmdTokens.remove(cmdTokens.begin());
02444
02445 KURL url;
02446 QStringList qry;
02447 if (!to.isEmpty())
02448 {
02449 QStringList tos = splitEmailAddressList( to );
02450 url.setPath( tos.first() );
02451 tos.remove( tos.begin() );
02452 for (QStringList::ConstIterator it = tos.begin(); it != tos.end(); ++it)
02453 qry.append( "to=" + KURL::encode_string( *it ) );
02454 }
02455 const QStringList ccs = splitEmailAddressList( cc );
02456 for (QStringList::ConstIterator it = ccs.begin(); it != ccs.end(); ++it)
02457 qry.append( "cc=" + KURL::encode_string( *it ) );
02458 const QStringList bccs = splitEmailAddressList( bcc );
02459 for (QStringList::ConstIterator it = bccs.begin(); it != bccs.end(); ++it)
02460 qry.append( "bcc=" + KURL::encode_string( *it ) );
02461 for (QStringList::ConstIterator it = attachURLs.begin(); it != attachURLs.end(); ++it)
02462 qry.append( "attach=" + KURL::encode_string( *it ) );
02463 if (!subject.isEmpty())
02464 qry.append( "subject=" + KURL::encode_string( subject ) );
02465 if (!body.isEmpty())
02466 qry.append( "body=" + KURL::encode_string( body ) );
02467 url.setQuery( qry.join( "&" ) );
02468 if ( ! (to.isEmpty() && qry.isEmpty()) )
02469 url.setProtocol("mailto");
02470
02471 QMap<QChar, QString> keyMap;
02472 keyMap.insert('t', to);
02473 keyMap.insert('s', subject);
02474 keyMap.insert('c', cc);
02475 keyMap.insert('b', bcc);
02476 keyMap.insert('B', body);
02477 keyMap.insert('u', url.url());
02478
02479 QString attachlist = attachURLs.join(",");
02480 attachlist.prepend('\'');
02481 attachlist.append('\'');
02482 keyMap.insert('A', attachlist);
02483
02484 for (QStringList::Iterator it = cmdTokens.begin(); it != cmdTokens.end(); )
02485 {
02486 if (*it == "%A")
02487 {
02488 if (it == cmdTokens.begin())
02489 continue;
02490 QStringList::ConstIterator urlit = attachURLs.begin();
02491 QStringList::ConstIterator urlend = attachURLs.end();
02492 if ( urlit != urlend )
02493 {
02494 QStringList::Iterator previt = it;
02495 --previt;
02496 *it = *urlit;
02497 ++it;
02498 while ( ++urlit != urlend )
02499 {
02500 cmdTokens.insert( it, *previt );
02501 cmdTokens.insert( it, *urlit );
02502 }
02503 } else {
02504 --it;
02505 it = cmdTokens.remove( cmdTokens.remove( it ) );
02506 }
02507 } else {
02508 *it = KMacroExpander::expandMacros(*it, keyMap);
02509 ++it;
02510 }
02511 }
02512
02513 QString error;
02514
02515
02516 if (kdeinitExec(cmd, cmdTokens, &error, NULL, startup_id ))
02517 if (Tty != kapp->type())
02518 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Mail Client"),
02519 i18n("Could not launch the mail client:\n\n%1").arg(error), i18n("&OK"));
02520 else
02521 kdWarning() << "Could not launch mail client:\n" << error << endl;
02522 }
02523 #endif
02524
02525 void KApplication::invokeBrowser( const QString &url )
02526 {
02527 return invokeBrowser( url, "" );
02528 }
02529
02530 #ifndef Q_WS_WIN
02531
02532
02533 void KApplication::invokeBrowser( const QString &url, const QCString& startup_id )
02534 {
02535 QString error;
02536
02537 if (startServiceByDesktopName("kfmclient", url, &error, 0, 0, startup_id, false))
02538 {
02539 if (Tty != kapp->type())
02540 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Browser"),
02541 i18n("Could not launch the browser:\n\n%1").arg(error), i18n("&OK"));
02542 else
02543 kdWarning() << "Could not launch browser:\n" << error << endl;
02544 return;
02545 }
02546 }
02547 #endif
02548
02549 void KApplication::cut()
02550 {
02551 invokeEditSlot( SLOT( cut() ) );
02552 }
02553
02554 void KApplication::copy()
02555 {
02556 invokeEditSlot( SLOT( copy() ) );
02557 }
02558
02559 void KApplication::paste()
02560 {
02561 invokeEditSlot( SLOT( paste() ) );
02562 }
02563
02564 void KApplication::clear()
02565 {
02566 invokeEditSlot( SLOT( clear() ) );
02567 }
02568
02569 void KApplication::selectAll()
02570 {
02571 invokeEditSlot( SLOT( selectAll() ) );
02572 }
02573
02574 QCString
02575 KApplication::launcher()
02576 {
02577 return "klauncher";
02578 }
02579
02580 static int
02581 startServiceInternal( const QCString &function,
02582 const QString& _name, const QStringList &URLs,
02583 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02584 {
02585 struct serviceResult
02586 {
02587 int result;
02588 QCString dcopName;
02589 QString error;
02590 pid_t pid;
02591 };
02592
02593
02594 DCOPClient *dcopClient;
02595 if (kapp)
02596 dcopClient = kapp->dcopClient();
02597 else
02598 dcopClient = new DCOPClient;
02599
02600 if (!dcopClient->isAttached())
02601 {
02602 if (!dcopClient->attach())
02603 {
02604 if (error)
02605 *error = i18n("Could not register with DCOP.\n");
02606 return -1;
02607 }
02608 }
02609 QByteArray params;
02610 QDataStream stream(params, IO_WriteOnly);
02611 stream << _name << URLs;
02612 QCString replyType;
02613 QByteArray replyData;
02614 QCString _launcher = KApplication::launcher();
02615 QValueList<QCString> envs;
02616 #ifdef Q_WS_X11
02617 if (qt_xdisplay()) {
02618 QCString dpystring(XDisplayString(qt_xdisplay()));
02619 envs.append( QCString("DISPLAY=") + dpystring );
02620 } else if( getenv( "DISPLAY" )) {
02621 QCString dpystring( getenv( "DISPLAY" ));
02622 envs.append( QCString("DISPLAY=") + dpystring );
02623 }
02624 #endif
02625 stream << envs;
02626 #if defined Q_WS_X11
02627
02628 stream << ( startup_id.isEmpty() ? KStartupInfo::createNewStartupId() : startup_id );
02629 #endif
02630 if( function.left( 12 ) != "kdeinit_exec" )
02631 stream << noWait;
02632
02633 if (!dcopClient->call(_launcher, _launcher,
02634 function, params, replyType, replyData))
02635 {
02636 if (error)
02637 *error = i18n("KLauncher could not be reached via DCOP.\n");
02638 if (!kapp)
02639 delete dcopClient;
02640 return -1;
02641 }
02642 if (!kapp)
02643 delete dcopClient;
02644
02645 if (noWait)
02646 return 0;
02647
02648 QDataStream stream2(replyData, IO_ReadOnly);
02649 serviceResult result;
02650 stream2 >> result.result >> result.dcopName >> result.error >> result.pid;
02651 if (dcopService)
02652 *dcopService = result.dcopName;
02653 if (error)
02654 *error = result.error;
02655 if (pid)
02656 *pid = result.pid;
02657 return result.result;
02658 }
02659
02660 int
02661 KApplication::startServiceByName( const QString& _name, const QString &URL,
02662 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02663 {
02664 QStringList URLs;
02665 if (!URL.isEmpty())
02666 URLs.append(URL);
02667 return startServiceInternal(
02668 "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02669 _name, URLs, error, dcopService, pid, startup_id, noWait);
02670 }
02671
02672 int
02673 KApplication::startServiceByName( const QString& _name, const QStringList &URLs,
02674 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02675 {
02676 return startServiceInternal(
02677 "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02678 _name, URLs, error, dcopService, pid, startup_id, noWait);
02679 }
02680
02681 int
02682 KApplication::startServiceByDesktopPath( const QString& _name, const QString &URL,
02683 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02684 {
02685 QStringList URLs;
02686 if (!URL.isEmpty())
02687 URLs.append(URL);
02688 return startServiceInternal(
02689 "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02690 _name, URLs, error, dcopService, pid, startup_id, noWait);
02691 }
02692
02693 int
02694 KApplication::startServiceByDesktopPath( const QString& _name, const QStringList &URLs,
02695 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02696 {
02697 return startServiceInternal(
02698 "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02699 _name, URLs, error, dcopService, pid, startup_id, noWait);
02700 }
02701
02702 int
02703 KApplication::startServiceByDesktopName( const QString& _name, const QString &URL,
02704 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02705 {
02706 QStringList URLs;
02707 if (!URL.isEmpty())
02708 URLs.append(URL);
02709 return startServiceInternal(
02710 "start_service_by_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02711 _name, URLs, error, dcopService, pid, startup_id, noWait);
02712 }
02713
02714 int
02715 KApplication::startServiceByDesktopName( const QString& _name, const QStringList &URLs,
02716 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02717 {
02718 return startServiceInternal(
02719 "start_service_by_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02720 _name, URLs, error, dcopService, pid, startup_id, noWait);
02721 }
02722
02723 int
02724 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02725 QString *error, int *pid )
02726 {
02727 return kdeinitExec( name, args, error, pid, "" );
02728 }
02729
02730 int
02731 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02732 QString *error, int *pid, const QCString& startup_id )
02733 {
02734 return startServiceInternal("kdeinit_exec(QString,QStringList,QValueList<QCString>,QCString)",
02735 name, args, error, 0, pid, startup_id, false);
02736 }
02737
02738 int
02739 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02740 QString *error, int *pid )
02741 {
02742 return kdeinitExecWait( name, args, error, pid, "" );
02743 }
02744
02745 int
02746 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02747 QString *error, int *pid, const QCString& startup_id )
02748 {
02749 return startServiceInternal("kdeinit_exec_wait(QString,QStringList,QValueList<QCString>,QCString)",
02750 name, args, error, 0, pid, startup_id, false);
02751 }
02752
02753 QString KApplication::tempSaveName( const QString& pFilename ) const
02754 {
02755 QString aFilename;
02756
02757 if( QDir::isRelativePath(pFilename) )
02758 {
02759 kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02760 aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02761 }
02762 else
02763 aFilename = pFilename;
02764
02765 QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02766 if( !aAutosaveDir.exists() )
02767 {
02768 if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02769 {
02770
02771 aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02772 }
02773 }
02774
02775 aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02776
02777 return aFilename;
02778 }
02779
02780
02781 QString KApplication::checkRecoverFile( const QString& pFilename,
02782 bool& bRecover ) const
02783 {
02784 QString aFilename;
02785
02786 if( QDir::isRelativePath(pFilename) )
02787 {
02788 kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02789 aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02790 }
02791 else
02792 aFilename = pFilename;
02793
02794 QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02795 if( !aAutosaveDir.exists() )
02796 {
02797 if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02798 {
02799
02800 aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02801 }
02802 }
02803
02804 aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02805
02806 if( QFile( aFilename ).exists() )
02807 {
02808 bRecover = true;
02809 return aFilename;
02810 }
02811 else
02812 {
02813 bRecover = false;
02814 return pFilename;
02815 }
02816 }
02817
02818
02819 bool checkAccess(const QString& pathname, int mode)
02820 {
02821 int accessOK = access( QFile::encodeName(pathname), mode );
02822 if ( accessOK == 0 )
02823 return true;
02824
02825
02826
02827
02828 if ( (mode & W_OK) == 0 )
02829 return false;
02830
02831
02832 if (!access( QFile::encodeName(pathname), F_OK))
02833 return false;
02834
02835
02836 QString dirName(pathname);
02837 int pos = dirName.findRev('/');
02838 if ( pos == -1 )
02839 return false;
02840 else if ( pos == 0 )
02841 pos = 1;
02842
02843 dirName.truncate(pos);
02844
02845 accessOK = access( QFile::encodeName(dirName), W_OK );
02846
02847 if ( accessOK == 0 )
02848 return true;
02849 else
02850 return false;
02851 }
02852
02853 void KApplication::setTopWidget( QWidget *topWidget )
02854 {
02855 if( !topWidget )
02856 return;
02857
02858
02859 if ( !topWidget->inherits("KMainWindow") ) {
02860 topWidget->setCaption( caption() );
02861 }
02862
02863
02864 topWidget->setIcon( icon() );
02865 #if defined Q_WS_X11
02866
02867 KWin::setIcons(topWidget->winId(), icon(), miniIcon() );
02868
02869
02870 KStartupInfo::setWindowStartupId( topWidget->winId(), startupId());
02871 #endif
02872 }
02873
02874 QCString KApplication::startupId() const
02875 {
02876 return d->startup_id;
02877 }
02878
02879 void KApplication::setStartupId( const QCString& startup_id )
02880 {
02881 if( startup_id == d->startup_id )
02882 return;
02883 #if defined Q_WS_X11
02884 KStartupInfo::handleAutoAppStartedSending();
02885 #endif
02886 if( startup_id.isEmpty())
02887 d->startup_id = "0";
02888 else
02889 {
02890 d->startup_id = startup_id;
02891 #if defined Q_WS_X11
02892 KStartupInfoId id;
02893 id.initId( startup_id );
02894 long timestamp = id.timestamp();
02895 if( timestamp != 0 )
02896 updateUserTimestamp( timestamp );
02897 #endif
02898 }
02899 }
02900
02901
02902
02903 void KApplication::read_app_startup_id()
02904 {
02905 #if defined Q_WS_X11
02906 KStartupInfoId id = KStartupInfo::currentStartupIdEnv();
02907 KStartupInfo::resetStartupEnv();
02908 d->startup_id = id.id();
02909 #endif
02910 }
02911
02912 int KApplication::random()
02913 {
02914 static bool init = false;
02915 if (!init)
02916 {
02917 unsigned int seed;
02918 init = true;
02919 int fd = open("/dev/urandom", O_RDONLY);
02920 if (fd < 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed))
02921 {
02922
02923 srand(getpid());
02924 seed = rand()+time(0);
02925 }
02926 if (fd >= 0) close(fd);
02927 srand(seed);
02928 }
02929 return rand();
02930 }
02931
02932 QString KApplication::randomString(int length)
02933 {
02934 if (length <=0 ) return QString::null;
02935
02936 QString str; str.setLength( length );
02937 int i = 0;
02938 while (length--)
02939 {
02940 int r=random() % 62;
02941 r+=48;
02942 if (r>57) r+=7;
02943 if (r>90) r+=6;
02944 str[i++] = char(r);
02945
02946 }
02947 return str;
02948 }
02949
02950 bool KApplication::authorize(const QString &genericAction)
02951 {
02952 if (!d->actionRestrictions)
02953 return true;
02954
02955 KConfig *config = KGlobal::config();
02956 KConfigGroupSaver saver( config, "KDE Action Restrictions" );
02957 return config->readBoolEntry(genericAction, true);
02958 }
02959
02960 bool KApplication::authorizeKAction(const char *action)
02961 {
02962 if (!d->actionRestrictions || !action)
02963 return true;
02964
02965 static const QString &action_prefix = KGlobal::staticQString( "action/" );
02966
02967 return authorize(action_prefix + action);
02968 }
02969
02970 bool KApplication::authorizeControlModule(const QString &menuId)
02971 {
02972 if (menuId.isEmpty() || kde_kiosk_exception)
02973 return true;
02974 KConfig *config = KGlobal::config();
02975 KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02976 return config->readBoolEntry(menuId, true);
02977 }
02978
02979 QStringList KApplication::authorizeControlModules(const QStringList &menuIds)
02980 {
02981 KConfig *config = KGlobal::config();
02982 KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02983 QStringList result;
02984 for(QStringList::ConstIterator it = menuIds.begin();
02985 it != menuIds.end(); ++it)
02986 {
02987 if (config->readBoolEntry(*it, true))
02988 result.append(*it);
02989 }
02990 return result;
02991 }
02992
02993 void KApplication::initUrlActionRestrictions()
02994 {
02995 d->urlActionRestrictions.setAutoDelete(true);
02996 d->urlActionRestrictions.clear();
02997 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02998 ("open", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
02999 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03000 ("list", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
03001
03002
03003
03004
03005
03006 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03007 ("link", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
03008 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03009 ("redirect", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
03010
03011
03012
03013 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03014 ("redirect", QString::null, QString::null, QString::null, "file", QString::null, QString::null, true));
03015 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03016 ("redirect", ":internet", QString::null, QString::null, "file", QString::null, QString::null, false));
03017
03018
03019 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03020 ("redirect", ":local", QString::null, QString::null, QString::null, QString::null, QString::null, true));
03021
03022
03023 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03024 ("redirect", QString::null, QString::null, QString::null, "about", QString::null, QString::null, true));
03025
03026
03027 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03028 ("redirect", QString::null, QString::null, QString::null, "=", QString::null, QString::null, true));
03029
03030 KConfig *config = KGlobal::config();
03031 KConfigGroupSaver saver( config, "KDE URL Restrictions" );
03032 int count = config->readNumEntry("rule_count");
03033 QString keyFormat = QString("rule_%1");
03034 for(int i = 1; i <= count; i++)
03035 {
03036 QString key = keyFormat.arg(i);
03037 QStringList rule = config->readListEntry(key);
03038 if (rule.count() != 8)
03039 continue;
03040 QString action = rule[0];
03041 QString refProt = rule[1];
03042 QString refHost = rule[2];
03043 QString refPath = rule[3];
03044 QString urlProt = rule[4];
03045 QString urlHost = rule[5];
03046 QString urlPath = rule[6];
03047 QString strEnabled = rule[7].lower();
03048
03049 bool bEnabled = (strEnabled == "true");
03050
03051 if (refPath.startsWith("$HOME"))
03052 refPath.replace(0, 5, QDir::homeDirPath());
03053 else if (refPath.startsWith("~"))
03054 refPath.replace(0, 1, QDir::homeDirPath());
03055 if (urlPath.startsWith("$HOME"))
03056 urlPath.replace(0, 5, QDir::homeDirPath());
03057 else if (urlPath.startsWith("~"))
03058 urlPath.replace(0, 1, QDir::homeDirPath());
03059
03060 if (refPath.startsWith("$TMP"))
03061 refPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
03062 if (urlPath.startsWith("$TMP"))
03063 urlPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
03064
03065 d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
03066 ( action, refProt, refHost, refPath, urlProt, urlHost, urlPath, bEnabled));
03067 }
03068 }
03069
03070 void KApplication::allowURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
03071 {
03072 if (authorizeURLAction(action, _baseURL, _destURL))
03073 return;
03074
03075 d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
03076 ( action, _baseURL.protocol(), _baseURL.host(), _baseURL.path(-1),
03077 _destURL.protocol(), _destURL.host(), _destURL.path(-1), true));
03078 }
03079
03080 bool KApplication::authorizeURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
03081 {
03082 if (_destURL.isEmpty())
03083 return true;
03084
03085 bool result = false;
03086 if (d->urlActionRestrictions.isEmpty())
03087 initUrlActionRestrictions();
03088
03089 KURL baseURL(_baseURL);
03090 baseURL.setPath(QDir::cleanDirPath(baseURL.path()));
03091 QString baseClass = KProtocolInfo::protocolClass(baseURL.protocol());
03092 KURL destURL(_destURL);
03093 destURL.setPath(QDir::cleanDirPath(destURL.path()));
03094 QString destClass = KProtocolInfo::protocolClass(destURL.protocol());
03095
03096 for(KApplicationPrivate::URLActionRule *rule = d->urlActionRestrictions.first();
03097 rule; rule = d->urlActionRestrictions.next())
03098 {
03099 if ((result != rule->permission) &&
03100 (action == rule->action) &&
03101 rule->baseMatch(baseURL, baseClass) &&
03102 rule->destMatch(destURL, destClass, baseURL, baseClass))
03103 {
03104 result = rule->permission;
03105 }
03106 }
03107 return result;
03108 }
03109
03110
03111 uint KApplication::keyboardModifiers()
03112 {
03113 #ifdef Q_WS_X11
03114 Window root;
03115 Window child;
03116 int root_x, root_y, win_x, win_y;
03117 uint keybstate;
03118 XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03119 &root_x, &root_y, &win_x, &win_y, &keybstate );
03120 return keybstate & 0x00ff;
03121 #elif defined W_WS_MACX
03122 return GetCurrentEventKeyModifiers() & 0x00ff;
03123 #else
03124
03125 return 0;
03126 #endif
03127 }
03128
03129 uint KApplication::mouseState()
03130 {
03131 uint mousestate;
03132 #ifdef Q_WS_X11
03133 Window root;
03134 Window child;
03135 int root_x, root_y, win_x, win_y;
03136 XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03137 &root_x, &root_y, &win_x, &win_y, &mousestate );
03138 #elif defined(Q_WS_WIN)
03139 const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
03140 if (GetAsyncKeyState(VK_LBUTTON))
03141 mousestate |= (mousebtn_swapped ? Button3Mask : Button1Mask);
03142 if (GetAsyncKeyState(VK_MBUTTON))
03143 mousestate |= Button2Mask;
03144 if (GetAsyncKeyState(VK_RBUTTON))
03145 mousestate |= (mousebtn_swapped ? Button1Mask : Button3Mask);
03146 #elif defined(Q_WS_MACX)
03147 mousestate = GetCurrentEventButtonState();
03148 #else
03149
03150 #endif
03151 return mousestate & 0xff00;
03152 }
03153
03154 Qt::ButtonState KApplication::keyboardMouseState()
03155 {
03156 int ret = 0;
03157 #ifdef Q_WS_X11
03158 Window root;
03159 Window child;
03160 int root_x, root_y, win_x, win_y;
03161 uint state;
03162 XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03163 &root_x, &root_y, &win_x, &win_y, &state );
03164
03165 if( state & Button1Mask )
03166 ret |= LeftButton;
03167 if( state & Button2Mask )
03168 ret |= MidButton;
03169 if( state & Button3Mask )
03170 ret |= RightButton;
03171 if( state & ShiftMask )
03172 ret |= ShiftButton;
03173 if( state & ControlMask )
03174 ret |= ControlButton;
03175 if( state & KKeyNative::modX( KKey::ALT ))
03176 ret |= AltButton;
03177 if( state & KKeyNative::modX( KKey::WIN ))
03178 ret |= MetaButton;
03179 #elif defined(Q_WS_WIN)
03180 const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
03181 if (GetAsyncKeyState(VK_LBUTTON))
03182 ret |= (mousebtn_swapped ? RightButton : LeftButton);
03183 if (GetAsyncKeyState(VK_MBUTTON))
03184 ret |= MidButton;
03185 if (GetAsyncKeyState(VK_RBUTTON))
03186 ret |= (mousebtn_swapped ? LeftButton : RightButton);
03187 if (GetAsyncKeyState(VK_SHIFT))
03188 ret |= ShiftButton;
03189 if (GetAsyncKeyState(VK_CONTROL))
03190 ret |= ControlButton;
03191 if (GetAsyncKeyState(VK_MENU))
03192 ret |= AltButton;
03193 if (GetAsyncKeyState(VK_LWIN) || GetAsyncKeyState(VK_RWIN))
03194 ret |= MetaButton;
03195 #else
03196
03197 #endif
03198 return static_cast< ButtonState >( ret );
03199 }
03200
03201 void KApplication::installSigpipeHandler()
03202 {
03203 #ifdef Q_OS_UNIX
03204 struct sigaction act;
03205 act.sa_handler = SIG_IGN;
03206 sigemptyset( &act.sa_mask );
03207 act.sa_flags = 0;
03208 sigaction( SIGPIPE, &act, 0 );
03209 #endif
03210 }
03211
03212 void KApplication::sigpipeHandler(int)
03213 {
03214 int saved_errno = errno;
03215
03216 #ifndef NDEBUG
03217 char msg[1000];
03218 sprintf(msg, "*** SIGPIPE *** (ignored, pid = %ld)\n", (long) getpid());
03219 write(2, msg, strlen(msg));
03220 #endif
03221
03222
03223 errno = saved_errno;
03224 }
03225
03226 bool KApplication::guiEnabled()
03227 {
03228 return kapp && kapp->d->guiEnabled;
03229 }
03230
03231 void KApplication::virtual_hook( int id, void* data )
03232 { KInstance::virtual_hook( id, data ); }
03233
03234 void KSessionManaged::virtual_hook( int, void* )
03235 { }
03236
03237 #include "kapplication.moc"