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