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