-rw-r--r-- | kabc/formatfactory.cpp | 5 | ||||
-rw-r--r-- | kmicromail/libmailwrapper/settings.cpp | 1 | ||||
-rw-r--r-- | korganizer/koagendaitem.cpp | 2 | ||||
-rw-r--r-- | korganizer/korganizer.pro | 2 | ||||
-rw-r--r-- | libkcal/calendar.cpp | 1 | ||||
-rw-r--r-- | libkcal/event.cpp | 6 | ||||
-rw-r--r-- | libkcal/todo.cpp | 4 | ||||
-rw-r--r-- | libkdepim/ksyncmanager.cpp | 7 | ||||
-rw-r--r-- | libkdepim/phoneaccess.cpp | 2 | ||||
-rw-r--r-- | microkde/kapplication.cpp | 3 | ||||
-rw-r--r-- | microkde/kdecore/klibloader.cpp | 14 | ||||
-rw-r--r-- | microkde/kdeui/ktoolbar.cpp | 2 | ||||
-rw-r--r-- | microkde/kdeui/ktoolbar.h | 2 |
13 files changed, 21 insertions, 30 deletions
diff --git a/kabc/formatfactory.cpp b/kabc/formatfactory.cpp index f2f03c6..3ae1c27 100644 --- a/kabc/formatfactory.cpp +++ b/kabc/formatfactory.cpp @@ -1,180 +1,181 @@ /* This file is part of libkabc. Copyright (c) 2002 Tobias Koenig <tokoe@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kdebug.h> #include <klocale.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include <kstaticdeleter.h> #include <qfile.h> #include <qstringlist.h> #include "vcardformatplugin.h" #include "formatfactory.h" using namespace KABC; FormatFactory *FormatFactory::mSelf = 0; static KStaticDeleter<FormatFactory> factoryDeleter; FormatFactory *FormatFactory::self() { if ( !mSelf ) { //US factoryDeleter.setObject( mSelf, new FormatFactory ); mSelf = factoryDeleter.setObject( new FormatFactory ); } return mSelf; } FormatFactory::FormatFactory() { mFormatList.setAutoDelete( true ); // dummy entry for default format FormatInfo *info = new FormatInfo; info->library = "<NoLibrary>"; info->nameLabel = i18n( "vCard" ); info->descriptionLabel = i18n( "vCard Format" ); mFormatList.insert( "vcard", info ); -/*US lets enter all resources directly instead of using teh desktopfiles. +#if 0 +US lets enter all resources directly instead of using teh desktopfiles. QStringList list = KGlobal::dirs()->findAllResources( "data" ,"kabc/formats/*.desktop", true, true ); for ( QStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) { //US KSimpleConfig config( *it, true ); KConfig config( *it ); if ( !config.hasGroup( "Misc" ) || !config.hasGroup( "Plugin" ) ) continue; info = new FormatInfo; config.setGroup( "Plugin" ); QString type = config.readEntry( "Type" ); info->library = config.readEntry( "X-KDE-Library" ); config.setGroup( "Misc" ); info->nameLabel = config.readEntry( "Name" ); info->descriptionLabel = config.readEntry( "Comment", i18n( "No description available." ) ); mFormatList.insert( type, info ); } -*/ +#endif //US we already have vcard as default format. info = new FormatInfo; info->library = i18n("microkabcformat_binary"); info->nameLabel = i18n( "Binary" ); info->descriptionLabel = i18n( "No description available." ); mFormatList.insert( "binary", info ); } FormatFactory::~FormatFactory() { mFormatList.clear(); } QStringList FormatFactory::formats() { QStringList retval; // make sure 'vcard' is the first entry retval << "vcard"; QDictIterator<FormatInfo> it( mFormatList ); for ( ; it.current(); ++it ) if ( it.currentKey() != "vcard" ) retval << it.currentKey(); return retval; } FormatInfo *FormatFactory::info( const QString &type ) { if ( type.isEmpty() ) return 0; else return mFormatList[ type ]; } FormatPlugin *FormatFactory::format( const QString& type ) { FormatPlugin *format = 0; if ( type.isEmpty() ) return 0; if ( type == "vcard" ) { format = new VCardFormatPlugin; format->setType( type ); format->setNameLabel( i18n( "vCard" ) ); format->setDescriptionLabel( i18n( "vCard Format" ) ); return format; } FormatInfo *fi = mFormatList[ type ]; if (!fi) return 0; QString libName = fi->library; #ifndef DESKTOP_VERSION KLibrary *library = openLibrary( libName ); if ( !library ) return 0; void *format_func = library->symbol( "format"); if ( format_func ) { format = ((FormatPlugin* (*)())format_func)(); format->setType( type ); format->setNameLabel( fi->nameLabel ); format->setDescriptionLabel( fi->descriptionLabel ); } else { kdDebug( 5700 ) << "'" << libName << "' is not a format plugin." << endl; return 0; } #endif return format; } #ifndef DESKTOP_VERSION KLibrary *FormatFactory::openLibrary( const QString& libName ) { KLibrary *library = 0; QString path = KLibLoader::findLibrary( QFile::encodeName( libName ) ); if ( path.isEmpty() ) { kdDebug( 5700 ) << "No format plugin library was found!" << endl; return 0; } library = KLibLoader::self()->library( QFile::encodeName( path ) ); if ( !library ) { kdDebug( 5700 ) << "Could not load library '" << libName << "'" << endl; return 0; } return library; } #endif diff --git a/kmicromail/libmailwrapper/settings.cpp b/kmicromail/libmailwrapper/settings.cpp index 8f909f9..9436d43 100644 --- a/kmicromail/libmailwrapper/settings.cpp +++ b/kmicromail/libmailwrapper/settings.cpp @@ -1,545 +1,544 @@ #include <stdlib.h> #include <qdir.h> #include <qtextcodec.h> #include <qtextstream.h> #include <qfile.h> //#include <opie2/odebug.h> #include <kconfig.h> #include <kstandarddirs.h> #include "settings.h" //#include "defines.h" #define IMAP_PORT "143" #define IMAP_SSL_PORT "993" #define SMTP_PORT "25" #define SMTP_SSL_PORT "465" #define POP3_PORT "110" #define POP3_SSL_PORT "995" #define NNTP_PORT "119" #define NNTP_SSL_PORT "563" Settings::Settings() : QObject() { accounts.setAutoDelete( true ); ; updateAccounts(); //qDebug("++++++++++++++++++new settings "); } void Settings::checkDirectory() { return; locateLocal("data", "kopiemail" ); /* if ( !QDir( (QString) getenv( "HOME" ) + "/Applications/opiemail/" ).exists() ) { system( "mkdir -p $HOME/Applications/opiemail" ); qDebug("$HOME/Applications/opiemail created "); } */ } QList<Account> Settings::getAccounts() { return accounts; } void Settings::addAccount( Account *account ) { accounts.append( account ); } void Settings::delAccount( Account *account ) { account->remove(); accounts.remove( account ); } void Settings::updateAccounts() { accounts.clear(); QDir dir( locateLocal("data", "kopiemail" ) ); QStringList::Iterator it; QStringList imap = dir.entryList( "imap-*" ); for ( it = imap.begin(); it != imap.end(); it++ ) { IMAPaccount *account = new IMAPaccount( (*it).replace(0, 5, "") ); accounts.append( account ); } QStringList pop3 = dir.entryList( "pop3-*" ); for ( it = pop3.begin(); it != pop3.end(); it++ ) { POP3account *account = new POP3account( (*it).replace(0, 5, "") ); accounts.append( account ); } QStringList smtp = dir.entryList( "smtp-*" ); for ( it = smtp.begin(); it != smtp.end(); it++ ) { SMTPaccount *account = new SMTPaccount( (*it).replace(0, 5, "") ); accounts.append( account ); } QStringList nntp = dir.entryList( "nntp-*" ); for ( it = nntp.begin(); it != nntp.end(); it++ ) { NNTPaccount *account = new NNTPaccount( (*it).replace(0, 5, "") ); accounts.append( account ); } readAccounts(); } void Settings::saveAccounts() { checkDirectory(); Account *it; for ( it = accounts.first(); it; it = accounts.next() ) { it->save(); } } void Settings::readAccounts() { checkDirectory(); Account *it; for ( it = accounts.first(); it; it = accounts.next() ) { it->read(); } } Account::Account() { accountName = "changeMe"; type = MAILLIB::A_UNDEFINED; ssl = false; connectionType = 1; offline = false; maxMailSize = 0; - lastFetch; leaveOnServer = false; } void Account::remove() { QFile file( getFileName() ); file.remove(); } void Account::setPasswordList(const QStringList &str) { password = ""; int i; for ( i = 0; i < str.count() ; ++i ) { QChar c ( (str[i].toUInt()-131)/(str.count()- (i%3))); password.append( c ); } //qDebug("password %s ", password.latin1()); } QStringList Account::getPasswordList() { int i; int len = password.length(); QStringList str; for ( i = 0; i < len ; ++i ) { int val = password.at(i).unicode()*(len-(i%3))+131; str.append( QString::number( val ) ); // qDebug("append %s ", str[i].latin1()); } return str; } IMAPaccount::IMAPaccount() : Account() { file = IMAPaccount::getUniqueFileName(); accountName = "New IMAP Account"; ssl = false; connectionType = 1; type = MAILLIB::A_IMAP; port = IMAP_PORT; } IMAPaccount::IMAPaccount( QString filename ) : Account() { file = filename; accountName = "New IMAP Account"; ssl = false; connectionType = 1; type = MAILLIB::A_IMAP; port = IMAP_PORT; } QString IMAPaccount::getUniqueFileName() { int num = 0; QString unique; QDir dir( locateLocal("data", "kopiemail" ) ); QStringList imap = dir.entryList( "imap-*" ); do { unique.setNum( num++ ); } while ( imap.contains( "imap-" + unique ) > 0 ); return unique; } void IMAPaccount::read() { KConfig *conf = new KConfig( getFileName() ); conf->setGroup( "IMAP Account" ); accountName = conf->readEntry( "Account","" ); if (accountName.isNull()) accountName = ""; server = conf->readEntry( "Server","" ); if (server.isNull()) server=""; port = conf->readEntry( "Port","" ); if (port.isNull()) port="143"; connectionType = conf->readNumEntry( "ConnectionType" ); ssl = conf->readBoolEntry( "SSL",false ); user = conf->readEntry( "User","" ); if (user.isNull()) user = ""; //password = conf->readEntryCrypt( "Password","" ); setPasswordList( conf->readListEntry( "FolderHistory")); if (password.isNull()) password = ""; prefix = conf->readEntry("MailPrefix",""); if (prefix.isNull()) prefix = ""; offline = conf->readBoolEntry("Offline",false); localFolder = conf->readEntry( "LocalFolder" ); maxMailSize = conf->readNumEntry( "MaxSize",0 ); int lf = conf->readNumEntry( "LastFetch",0 ); QDateTime dt ( QDate ( 2004, 1, 1 ), QTime( 0,0,0) ); leaveOnServer = conf->readBoolEntry("LeaveOnServer",false); if ( lf < 0 ) lf = 0; lastFetch = dt.addSecs( lf ); delete conf; } void IMAPaccount::save() { Settings::checkDirectory(); KConfig *conf = new KConfig( getFileName() ); conf->setGroup( "IMAP Account" ); conf->writeEntry( "Account", accountName ); conf->writeEntry( "Server", server ); conf->writeEntry( "Port", port ); conf->writeEntry( "SSL", ssl ); conf->writeEntry( "ConnectionType", connectionType ); conf->writeEntry( "User", user ); //conf->writeEntryCrypt( "Password", password ); conf->writeEntry( "FolderHistory",getPasswordList() ); conf->writeEntry( "MailPrefix",prefix); conf->writeEntry( "Offline",offline); conf->writeEntry( "LocalFolder", localFolder ); conf->writeEntry( "MaxSize", maxMailSize ); QDateTime dt ( QDate ( 2004, 1, 1 ), QTime( 0,0,0) ); int lf = dt.secsTo ( lastFetch ); conf->writeEntry( "LastFetch", lf ); conf->writeEntry( "LeaveOnServer", leaveOnServer); conf->sync(); delete conf; } QString IMAPaccount::getFileName() { return locateLocal("data", "kopiemail" ) +"/imap-" + file; } POP3account::POP3account() : Account() { file = POP3account::getUniqueFileName(); accountName = "New POP3 Account"; ssl = false; connectionType = 1; type = MAILLIB::A_POP3; port = POP3_PORT; } POP3account::POP3account( QString filename ) : Account() { file = filename; accountName = "New POP3 Account"; ssl = false; connectionType = 1; type = MAILLIB::A_POP3; port = POP3_PORT; } QString POP3account::getUniqueFileName() { int num = 0; QString unique; QDir dir( locateLocal("data", "kopiemail" ) ); QStringList imap = dir.entryList( "pop3-*" ); do { unique.setNum( num++ ); } while ( imap.contains( "pop3-" + unique ) > 0 ); return unique; } void POP3account::read() { KConfig *conf = new KConfig( getFileName()); conf->setGroup( "POP3 Account" ); accountName = conf->readEntry( "Account" ); server = conf->readEntry( "Server" ); port = conf->readEntry( "Port" ); ssl = conf->readBoolEntry( "SSL" ); connectionType = conf->readNumEntry( "ConnectionType" ); user = conf->readEntry( "User" ); //password = conf->readEntryCrypt( "Password" ); setPasswordList( conf->readListEntry( "FolderHistory")); offline = conf->readBoolEntry("Offline",false); localFolder = conf->readEntry( "LocalFolder" ); maxMailSize = conf->readNumEntry( "MaxSize",0 ); int lf = conf->readNumEntry( "LastFetch",0 ); QDateTime dt ( QDate ( 2004, 1, 1 ), QTime( 0,0,0) ); leaveOnServer = conf->readBoolEntry("LeaveOnServer",false); lastFetch = dt.addSecs( lf ); delete conf; } void POP3account::save() { Settings::checkDirectory(); KConfig *conf = new KConfig( getFileName() ); conf->setGroup( "POP3 Account" ); conf->writeEntry( "Account", accountName ); conf->writeEntry( "Server", server ); conf->writeEntry( "Port", port ); conf->writeEntry( "SSL", ssl ); conf->writeEntry( "ConnectionType", connectionType ); conf->writeEntry( "User", user ); //conf->writeEntryCrypt( "Password", password ); conf->writeEntry( "FolderHistory",getPasswordList() ); conf->writeEntry( "Offline",offline); conf->writeEntry( "LocalFolder", localFolder ); conf->writeEntry( "MaxSize", maxMailSize ); QDateTime dt ( QDate ( 2004, 1, 1 ), QTime( 0,0,0) ); int lf = dt.secsTo ( lastFetch ); conf->writeEntry( "LastFetch", lf ); conf->writeEntry( "LeaveOnServer", leaveOnServer); conf->sync(); delete conf; } QString POP3account::getFileName() { return locateLocal("data", "kopiemail" ) +"/pop3-" + file; } SMTPaccount::SMTPaccount() : Account() { file = SMTPaccount::getUniqueFileName(); accountName = "New SMTP Account"; ssl = false; connectionType = 1; login = false; useCC = false; useBCC = false; useReply = false; type = MAILLIB::A_SMTP; port = SMTP_PORT; } SMTPaccount::SMTPaccount( QString filename ) : Account() { file = filename; accountName = "New SMTP Account"; ssl = false; connectionType = 1; login = false; type = MAILLIB::A_SMTP; port = SMTP_PORT; } QString SMTPaccount::getSignature() { QFileInfo fi ( signature ); if ( ! fi.exists() ) return QString(); QFile file( signature ); if (!file.open( IO_ReadOnly ) ) { return QString(); } QTextStream ts( &file ); ts.setCodec( QTextCodec::codecForName("utf8") ); QString text = ts.read(); file.close(); return text; } void SMTPaccount::setSignature( QString b ) { QFileInfo fi ( signature ); if ( ! fi.exists() ) { QString filedir( locateLocal("data", "kopiemail" ) ); signature = filedir+ "/" + getAccountName() +".sig"; qDebug("new sig %s ", signature.latin1()); save(); } QFile fileIn( signature ); if (!fileIn.open( IO_WriteOnly ) ) { qDebug("OM: Cannot write signature file %s ", signature.latin1() ); return ; } QTextStream tsIn( &fileIn ); tsIn.setCodec( QTextCodec::codecForName("utf8") ); tsIn << b ; fileIn.close(); } QString SMTPaccount::getUniqueFileName() { int num = 0; QString unique; QDir dir( locateLocal("data", "kopiemail" ) ); QStringList imap = dir.entryList( "smtp-*" ); do { unique.setNum( num++ ); } while ( imap.contains( "smtp-" + unique ) > 0 ); return unique; } void SMTPaccount::read() { KConfig *conf = new KConfig( getFileName() ); conf->setGroup( "SMTP Account" ); accountName = conf->readEntry( "Account" ); server = conf->readEntry( "Server" ); port = conf->readEntry( "Port" ); ssl = conf->readBoolEntry( "SSL" ); connectionType = conf->readNumEntry( "ConnectionType" ); login = conf->readBoolEntry( "Login" ); user = conf->readEntry( "User" ); signature = conf->readEntry( "SigFile" ); setPasswordList( conf->readListEntry( "FolderHistory")); delete conf; } void SMTPaccount::save() { Settings::checkDirectory(); KConfig *conf = new KConfig( getFileName() ); conf->setGroup( "SMTP Account" ); conf->writeEntry( "Account", accountName ); conf->writeEntry( "Server", server ); conf->writeEntry( "Port", port ); conf->writeEntry( "SSL", ssl ); conf->writeEntry( "ConnectionType", connectionType ); conf->writeEntry( "Login", login ); conf->writeEntry( "User", user ); conf->writeEntry( "SigFile", signature ); //conf->writeEntryCrypt( "Password", password ); conf->writeEntry( "FolderHistory",getPasswordList() ); conf->sync(); delete conf; } QString SMTPaccount::getFileName() { return locateLocal("data", "kopiemail" ) +"/smtp-" + file; } NNTPaccount::NNTPaccount() : Account() { file = NNTPaccount::getUniqueFileName(); accountName = "New NNTP Account"; ssl = false; login = false; type = MAILLIB::A_NNTP; port = NNTP_PORT; } NNTPaccount::NNTPaccount( QString filename ) : Account() { file = filename; accountName = "New NNTP Account"; ssl = false; login = false; type = MAILLIB::A_NNTP; port = NNTP_PORT; } QString NNTPaccount::getUniqueFileName() { int num = 0; QString unique; QDir dir( locateLocal("data", "kopiemail" ) ); QStringList imap = dir.entryList( "nntp-*" ); do { unique.setNum( num++ ); } while ( imap.contains( "nntp-" + unique ) > 0 ); return unique; } void NNTPaccount::read() { KConfig *conf = new KConfig( getFileName() ); conf->setGroup( "NNTP Account" ); accountName = conf->readEntry( "Account" ); server = conf->readEntry( "Server" ); port = conf->readEntry( "Port" ); ssl = conf->readBoolEntry( "SSL" ); login = conf->readBoolEntry( "Login" ); user = conf->readEntry( "User" ); //password = conf->readEntryCrypt( "Password" ); setPasswordList( conf->readListEntry( "FolderHistory")); subscribedGroups = conf->readListEntry( "Subscribed"); delete conf; } void NNTPaccount::save() { Settings::checkDirectory(); KConfig *conf = new KConfig( getFileName() ); conf->setGroup( "NNTP Account" ); conf->writeEntry( "Account", accountName ); conf->writeEntry( "Server", server ); conf->writeEntry( "Port", port ); conf->writeEntry( "SSL", ssl ); conf->writeEntry( "Login", login ); conf->writeEntry( "User", user ); //conf->writeEntryCrypt( "Password", password ); conf->writeEntry( "FolderHistory",getPasswordList() ); conf->writeEntry( "Subscribed" , subscribedGroups ); conf->sync(); delete conf; } QString NNTPaccount::getFileName() { return locateLocal("data", "kopiemail" ) +"/nntp-" + file; } diff --git a/korganizer/koagendaitem.cpp b/korganizer/koagendaitem.cpp index df7d612..6a312b3 100644 --- a/korganizer/koagendaitem.cpp +++ b/korganizer/koagendaitem.cpp @@ -1,759 +1,759 @@ /* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qlabel.h> #include <qlayout.h> #include <qhbox.h> #include <qvbox.h> #include <qtooltip.h> #include <qwhatsthis.h> #include <qdragobject.h> #include <qdrawutil.h> #include <qpainter.h> #include <kiconloader.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #ifndef DESKTOP_VERSION #include <qpe/qpeapplication.h> #define AGENDA_ICON_SIZE 5 #else #define AGENDA_ICON_SIZE 7 #endif #include <libkcal/icaldrag.h> #include <libkcal/vcaldrag.h> #include <libkcal/kincidenceformatter.h> extern int globalFlagBlockAgenda; extern int globalFlagBlockAgendaItemPaint; extern int globalFlagBlockAgendaItemUpdate; #include "koprefs.h" #include "koagendaitem.h" //#include "koagendaitem.moc" //-------------------------------------------------------------------------- QToolTipGroup *KOAgendaItem::mToolTipGroup = 0; //-------------------------------------------------------------------------- class KOAgendaItemWhatsThis :public QWhatsThis { public: KOAgendaItemWhatsThis( KOAgendaItem* view ) : QWhatsThis( view ),_view (view) { }; protected: virtual QString text( const QPoint& ) { return _view->getWhatsThisText() ; } private: KOAgendaItem * _view; }; KOAgendaItem::KOAgendaItem(Incidence *incidence, QDate qd, QWidget *parent,bool allday, const char *name,WFlags) : QWidget(parent, name), mIncidence(incidence), mDate(qd) { #ifndef DESKTOP_VERSION QPEApplication::setStylusOperation( this, QPEApplication::RightOnHold ); #endif new KOAgendaItemWhatsThis(this); int wflags = getWFlags() |WRepaintNoErase;// WResizeNoErase setWFlags ( wflags); mAllDay = allday; init ( incidence, qd ); setMouseTracking(true); //setAcceptDrops(true); xPaintCoord = -1; yPaintCoord = -1; } QString KOAgendaItem::getWhatsThisText() { if ( mIncidence ) return KIncidenceFormatter::instance()->getFormattedText( mIncidence ); return "KOAgendaItem::getWhatsThisText()::internal error"; } void KOAgendaItem::init ( Incidence *incidence, QDate qd ) { mIncidence = incidence; mDate = qd; mFirstMultiItem = 0; mNextMultiItem = 0; mLastMultiItem = 0; computeText(); if ( (incidence->type() == "Todo") && ( !((static_cast<Todo*>(incidence))->isCompleted()) && ((static_cast<Todo*>(incidence))->dtDue().date() <= QDate::currentDate()) ) ) { if ( (static_cast<Todo*>(incidence))->dtDue() < QDateTime::currentDateTime().date()) mBackgroundColor = KOPrefs::instance()->mTodoOverdueColor ; else mBackgroundColor = KOPrefs::instance()->mTodoDueTodayColor; } else { QStringList categories = mIncidence->categories(); QString cat = categories.first(); if (cat.isEmpty()) { if ( (incidence->type() == "Todo") &&((static_cast<Todo*>(incidence))->isCompleted()) ) mBackgroundColor =KOPrefs::instance()->mTodoDoneColor; else mBackgroundColor =KOPrefs::instance()->mEventColor; } else { mBackgroundColor = *KOPrefs::instance()->categoryColor(cat); if ( (incidence->type() == "Todo") &&((static_cast<Todo*>(incidence))->isCompleted()) ) { if ( mBackgroundColor == KOPrefs::instance()->mEventColor ) mBackgroundColor =KOPrefs::instance()->mTodoDoneColor; } } } mColorGroup = QColorGroup( mBackgroundColor.light(), mBackgroundColor.dark(),mBackgroundColor.light(), mBackgroundColor.dark(),mBackgroundColor, black, mBackgroundColor) ; setBackgroundColor( mBackgroundColor ); setCellXY(0,0,1); setCellXWidth(0); setSubCell(0); setSubCells(1); setMultiItem(0,0,0); startMove(); mSelected = true; select(false); QFontMetrics fontinf(KOPrefs::instance()->mAgendaViewFont); mFontPixelSize = fontinf.height();; hide(); xPaintCoord = -1; yPaintCoord = -1; } KOAgendaItem::~KOAgendaItem() { // qDebug("deleteKOAgendaItem::~KOAgendaItem( "); } void KOAgendaItem::recreateIncidence() { #if 0 Incidence* newInc = mIncidence->clone(); newInc->recreate(); if ( mIncidence->doesRecur() ) { mIncidence->addExDate( mDate ); newInc->recurrence()->unsetRecurs(); int len = mIncidence->dtStart().secsTo( ((Event*)mIncidence)->dtEnd()); QTime tim = mIncidence->dtStart().time(); newInc->setDtStart( QDateTime(mDate, tim) ); ((Event*)newInc)->setDtEnd( newInc->dtStart().addSecs( len ) ); } #endif mIncidence = mIncidence->recreateCloneException( mDate ); } bool KOAgendaItem::updateIcons(QPainter * p, bool horLayout) { int size = AGENDA_ICON_SIZE; int yOff = 0; int xOff = 0; int x = pos().x() +3; int y; if ( mAllDay ) y = pos().y()+3; else y = mCellYTop * ( height() / cellHeight() ) +3; if (mIncidence->cancelled()) { int xpos = xOff*( 1 +AGENDA_ICON_SIZE )+x; int ypos = yOff*( 1 +AGENDA_ICON_SIZE)+y; p->drawLine( xpos, ypos, xpos+AGENDA_ICON_SIZE-1, ypos+AGENDA_ICON_SIZE-1 ); p->drawLine( xpos, ypos+AGENDA_ICON_SIZE-1, xpos+AGENDA_ICON_SIZE-1, ypos ); if ( horLayout ) ++xOff; else ++yOff; } if (mIncidence->isAlarmEnabled()) { p->fillRect ( xOff*( 1 +AGENDA_ICON_SIZE )+x, yOff*( 1 +AGENDA_ICON_SIZE)+y, AGENDA_ICON_SIZE, AGENDA_ICON_SIZE, red ); if ( horLayout ) ++xOff; else ++yOff; } if (mIncidence->recurrence()->doesRecur()) { p->fillRect ( xOff*( 1 +AGENDA_ICON_SIZE )+x, yOff*( 1 +AGENDA_ICON_SIZE)+y, AGENDA_ICON_SIZE, AGENDA_ICON_SIZE, blue ); if ( horLayout ) ++xOff; else ++yOff; } if (mIncidence->description().length() > 0) { p->fillRect ( xOff*( 1 +AGENDA_ICON_SIZE )+x, yOff*( 1 +AGENDA_ICON_SIZE)+y, AGENDA_ICON_SIZE, AGENDA_ICON_SIZE, darkGreen ); if ( horLayout ) ++xOff; else ++yOff; } if (mIncidence->isReadOnly()) { p->fillRect ( xOff*( 1 +AGENDA_ICON_SIZE )+x, yOff*( 1 +AGENDA_ICON_SIZE)+y, AGENDA_ICON_SIZE, AGENDA_ICON_SIZE, white ); if ( horLayout ) ++xOff; else ++yOff; } if (mIncidence->attendeeCount()>0) { if (mIncidence->organizer() == KOPrefs::instance()->email()) { p->fillRect ( xOff*( 1 +AGENDA_ICON_SIZE )+x, yOff*( 1 +AGENDA_ICON_SIZE)+y, AGENDA_ICON_SIZE, AGENDA_ICON_SIZE, black ); if ( horLayout ) ++xOff; else ++yOff; } else { Attendee *me = mIncidence->attendeeByMails(KOPrefs::instance()->mAdditionalMails,KOPrefs::instance()->email()); if (me!=0) { } else { p->fillRect ( xOff*( 1 +AGENDA_ICON_SIZE )+x, yOff*( 1 +AGENDA_ICON_SIZE)+y, AGENDA_ICON_SIZE, AGENDA_ICON_SIZE, yellow ); if ( horLayout ) ++xOff; else ++yOff; } p->fillRect ( xOff*( 1 +AGENDA_ICON_SIZE )+x, yOff*( 1 +AGENDA_ICON_SIZE)+y, AGENDA_ICON_SIZE, AGENDA_ICON_SIZE, darkYellow ); if ( horLayout ) ++xOff; else ++yOff; } } return ( yOff || xOff ); } void KOAgendaItem::select(bool selected) { //qDebug("select %d %d",firstMultiItem(), nextMultiItem() ); if (mSelected == selected) return; mSelected = selected; if ( ! isVisible() ) return; if ( firstMultiItem() ) firstMultiItem()->select( selected ); if ( !firstMultiItem() && nextMultiItem() ) { KOAgendaItem * placeItem = nextMultiItem(); while ( placeItem ) { placeItem->select( selected ); placeItem = placeItem->nextMultiItem(); } } globalFlagBlockAgendaItemUpdate = 0; paintMe( selected ); globalFlagBlockAgendaItemUpdate = 1; repaint( false ); } /* The eventFilter has to filter the mouse events of the agenda item childs. The events are fed into the event handling method of KOAgendaItem. This allows the KOAgenda to handle the KOAgendaItems by using an eventFilter. */ bool KOAgendaItem::eventFilter ( QObject *object, QEvent *e ) { if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonDblClick || e->type() == QEvent::MouseButtonRelease || e->type() == QEvent::MouseMove) { QMouseEvent *me = (QMouseEvent *)e; QPoint itemPos = this->mapFromGlobal(((QWidget *)object)-> mapToGlobal(me->pos())); QMouseEvent returnEvent (e->type(),itemPos,me->button(),me->state()); return event(&returnEvent); } else { return false; } } void KOAgendaItem::repaintMe( ) { paintMe ( mSelected ); } void KOAgendaItem::paintMe( bool selected, QPainter* paint ) { if ( globalFlagBlockAgendaItemUpdate && ! selected) return; QPainter pa; if ( mSelected ) { pa.begin( paintPixSel() ); } else { if ( mAllDay ) pa.begin( paintPixAllday() ); else pa.begin( paintPix() ); } int x, yy, w, h; - float nfh; + float nfh = 7.0; x = pos().x(); w = width(); h = height (); if ( mAllDay ) yy = y(); else yy = mCellYTop * ( height() / cellHeight() ); xPaintCoord= x; yPaintCoord = yy; wPaintCoord = width(); hPaintCoord = height(); //qDebug("paintMe %s %d %d %d %d",incidence()->summary().latin1(), x, yy, width(), height()); if ( paint == 0 ) paint = &pa; bool horLayout = ( w < h ); int maxhei = mFontPixelSize+4; if ( horLayout ) maxhei += AGENDA_ICON_SIZE -4; bool small = ( h < maxhei ); if ( ! small ) paint->setFont(KOPrefs::instance()->mAgendaViewFont); else { QFont f = KOPrefs::instance()->mAgendaViewFont; f.setBold( false ); int fh = f.pointSize(); nfh = (((float)height())/(float)(mFontPixelSize+4))*fh; if ( nfh < 6 ) nfh = 6; f.setPointSize( nfh ); paint->setFont(f); } paint->fillRect ( x, yy, w, h, mBackgroundColor ); static const QPixmap completedPxmp = SmallIcon("greenhook16"); static const QPixmap overduePxmp = SmallIcon("redcross16"); if ( mIncidence->type() == "Todo" ) { Todo* tempTodo = static_cast<Todo*>(mIncidence); int xx = pos().x()+(width()-completedPxmp.width()-3 ); int yyy = yy+3; if ( tempTodo->isCompleted() ) paint->drawPixmap ( xx, yyy, completedPxmp ); else { paint->drawPixmap ( xx, yyy, overduePxmp ); } } bool addIcon = false; if ( ! small || w > 3 * h || h > 3* w ) addIcon = updateIcons( paint, horLayout ); qDrawShadePanel (paint, x, yy, w, h, mColorGroup, selected , 2, 0); //qDebug("draw rect %d %d %d %d ",x, yy, w, h ); if ( ! small ) { x += 3; yy += 3;w -= 6; h-= 5; } else { x += 2; yy += 1;w -= 4; h-= 4; if ( nfh < 6.01 ) { yy -= 2; h += 4; } else if ( nfh < h -2 ) ++yy; } int align; #ifndef DESKTOP_VERSION align = ( AlignLeft|WordBreak|AlignTop); #else align = ( AlignLeft|BreakAnywhere|WordBreak|AlignTop); #endif if ( addIcon ) { if ( ! horLayout ) { x += AGENDA_ICON_SIZE+3; w -= (AGENDA_ICON_SIZE+3); } else { yy+= AGENDA_ICON_SIZE+2; h -=(AGENDA_ICON_SIZE+3); } } int colsum = mBackgroundColor.red() + mBackgroundColor.green() + mBackgroundColor.blue(); if ( colsum < 250 ) paint->setPen ( white); if ( x < 0 ) { w = w+x-3; x = 3; if ( w > parentWidget()->width() ){ w = parentWidget()->width() - 6; #ifndef DESKTOP_VERSION align = ( AlignCenter|WordBreak); #else align = ( AlignCenter|BreakAnywhere|WordBreak); #endif } } QRect dr; paint->drawText ( x, yy, w, h, align, mDisplayedText, -1, &dr ); if ( mIncidence->cancelled() ){ if ( ! small ) { QFontMetrics fm ( paint->font() ); paint->drawLine(dr.left(), yy+fm.height()/2, dr.right()-2, yy+fm.height()/2); } } pa.end(); } void KOAgendaItem::resizePixmap( int w , int h ) { paintPix()->resize( w, h ); paintPixSel()->resize( w, h ); } QPixmap * KOAgendaItem::paintPix() { static QPixmap* mPaintPix = 0; if ( ! mPaintPix ) mPaintPix = new QPixmap(1,1); return mPaintPix ; } QPixmap * KOAgendaItem::paintPixAllday() { static QPixmap* mPaintPixA = 0; if ( ! mPaintPixA ) mPaintPixA = new QPixmap(1,1); return mPaintPixA ; } QPixmap * KOAgendaItem::paintPixSel() { static QPixmap* mPaintPixSel = 0; if ( ! mPaintPixSel ) mPaintPixSel = new QPixmap(1,1); return mPaintPixSel ; } void KOAgendaItem::paintEvent ( QPaintEvent *e ) { if ( globalFlagBlockAgendaItemPaint ) return; if ( globalFlagBlockAgenda > 0 && globalFlagBlockAgenda < 5 ) return; int yy; if ( mAllDay ) yy = y(); else yy = mCellYTop * ( height() / cellHeight() ); int xx = x(); if ( xPaintCoord != xx || yPaintCoord != yy || wPaintCoord != width() || hPaintCoord != height()) { xPaintCoord= xx; yPaintCoord = yy; wPaintCoord = width(); hPaintCoord = height(); globalFlagBlockAgendaItemUpdate = 0; paintMe( mSelected ); //qDebug("calling paintMe "); globalFlagBlockAgendaItemUpdate = 1; } int rx, ry, rw, rh; rx = e->rect().x(); ry = e->rect().y(); rw = e->rect().width(); rh = e->rect().height(); //qDebug(" paintevent %s %d %d %d %d", mIncidence->summary().latin1(), x(), yy, width(), height()); QPixmap* paintFrom ; if ( mSelected ) { paintFrom = paintPixSel(); } else { if ( mAllDay ) paintFrom = paintPixAllday(); else paintFrom = paintPix(); } bitBlt (this, rx, ry, paintFrom, x()+rx ,yPaintCoord+ry, rw, rh ,CopyROP); } void KOAgendaItem::computeText() { mDisplayedText = mIncidence->summary(); if ( (mIncidence->type() == "Todo") ) { if ( static_cast<Todo*>(mIncidence)->hasDueDate() ) { if ( static_cast<Todo*>(mIncidence)->dtDue().date() < QDate::currentDate() ) mDisplayedText += i18n(" (") +KGlobal::locale()->formatDate((static_cast<Todo*>(mIncidence))->dtDue().date(), true)+")"; else if ( !(mIncidence->doesFloat())) mDisplayedText += i18n(" (") +KGlobal::locale()->formatTime((static_cast<Todo*>(mIncidence))->dtDue().time())+")"; } } else { if ( !(mIncidence->doesFloat()) && KOPrefs::instance()->mShowTimeInAgenda) mDisplayedText += ": " +KGlobal::locale()->formatTime((static_cast<Event*>(mIncidence))->dtStart().time()) + "-" + KGlobal::locale()->formatTime((static_cast<Event*>(mIncidence))->dtEnd().time()) ; if ( mAllDay ) { if ( mIncidence->dtStart().date().addDays(3) < mIncidence->dtEnd().date() ) { mDisplayedText += ": " +KGlobal::locale()->formatDate((static_cast<Event*>(mIncidence))->dtStart().date(), true) + " - " + KGlobal::locale()->formatDate((static_cast<Event*>(mIncidence))->dtEnd().date(), true) ; } } } if ( !mIncidence->location().isEmpty() ) { if ( mAllDay ) mDisplayedText += " ("; else mDisplayedText += "\n("; mDisplayedText += mIncidence->location() +")"; } QString tipText = mIncidence->summary(); if ( !mIncidence->doesFloat() ) { if ( mIncidence->type() == "Event" ) { if ( (static_cast<Event*>(mIncidence))->isMultiDay() ) { tipText += "\n"+i18n("From: ")+mIncidence->dtStartStr(); tipText += "\n"+i18n("To: ")+(static_cast<Event*>(mIncidence))->dtEndStr(); } else { tipText += "\n"+i18n("Time: ")+mIncidence->dtStartTimeStr(); tipText += " - "+(static_cast<Event*>(mIncidence))->dtEndTimeStr(); } } else if ( mIncidence->type() == "Todo" ) { if (mIncidence->hasStartDate()) tipText += "\n"+i18n("Start: ")+ (static_cast<Todo*>(mIncidence))->dtStartStr(); if (((Todo*)mIncidence)->hasDueDate()) tipText += "\n"+i18n("Due: ")+ (static_cast<Todo*>(mIncidence))->dtDueStr(); } } else if ( mIncidence->type() == "Todo" ) { if (mIncidence->hasStartDate()) tipText += "\n"+i18n("Start: ")+ (static_cast<Todo*>(mIncidence))->dtStartDateStr(); if (((Todo*)mIncidence)->hasDueDate()) tipText += "\n"+i18n("Due: ")+ (static_cast<Todo*>(mIncidence))->dtDueDateStr(); } if (!mIncidence->location().isEmpty()) { tipText += "\n"+i18n("Location: ")+mIncidence->location(); } QToolTip::add(this,tipText,toolTipGroup(),""); } void KOAgendaItem::updateItem() { computeText(); //qDebug("KOAgendaItem:: updateItem() %s %d %d ",incidence()->summary().latin1(), x(), y()); paintMe( mSelected ); repaint( false); } void KOAgendaItem::resizeEvent ( QResizeEvent *ev ) { //qDebug("KOAgendaItem::resizeEvent %s ", mIncidence->summary().latin1()); paintMe( mSelected ); repaint( false ); } /* Return height of item in units of agenda cells */ int KOAgendaItem::cellHeight() { int ret = mCellYBottom - mCellYTop + 1; if ( ret <= 0 ) { ret = 1; mCellYBottom = 0; mCellYTop = 0; } return ret; } /* Return height of item in units of agenda cells */ int KOAgendaItem::cellWidth() { return mCellXWidth - mCellX + 1; } void KOAgendaItem::setItemDate(QDate qd) { mDate = qd; } void KOAgendaItem::setCellXY(int X, int YTop, int YBottom) { mCellX = X; mCellYTop = YTop; mCellYBottom = YBottom; } void KOAgendaItem::setCellXWidth(int xwidth) { mCellXWidth = xwidth; } void KOAgendaItem::setCellX(int XLeft, int XRight) { mCellX = XLeft; mCellXWidth = XRight; } void KOAgendaItem::setCellY(int YTop, int YBottom) { mCellYTop = YTop; mCellYBottom = YBottom; } void KOAgendaItem::setSubCell(int subCell) { mSubCell = subCell; } void KOAgendaItem::setSubCells(int subCells) { mSubCells = subCells; } void KOAgendaItem::setMultiItem(KOAgendaItem *first,KOAgendaItem *next, KOAgendaItem *last) { mFirstMultiItem = first; mNextMultiItem = next; mLastMultiItem = last; } void KOAgendaItem::startMove() { mStartCellX = mCellX; mStartCellXWidth = mCellXWidth; mStartCellYTop = mCellYTop; mStartCellYBottom = mCellYBottom; } void KOAgendaItem::resetMove() { mCellX = mStartCellX; mCellXWidth = mStartCellXWidth; mCellYTop = mStartCellYTop; mCellYBottom = mStartCellYBottom; } void KOAgendaItem::moveRelative(int dx, int dy) { int newX = cellX() + dx; int newXWidth = cellXWidth() + dx; int newYTop = cellYTop() + dy; int newYBottom = cellYBottom() + dy; setCellXY(newX,newYTop,newYBottom); setCellXWidth(newXWidth); } void KOAgendaItem::expandTop(int dy) { int newYTop = cellYTop() + dy; int newYBottom = cellYBottom(); if (newYTop > newYBottom) newYTop = newYBottom; setCellY(newYTop, newYBottom); } void KOAgendaItem::expandBottom(int dy) { int newYTop = cellYTop(); int newYBottom = cellYBottom() + dy; if (newYBottom < newYTop) newYBottom = newYTop; setCellY(newYTop, newYBottom); } void KOAgendaItem::expandLeft(int dx) { int newX = cellX() + dx; int newXWidth = cellXWidth(); if (newX > newXWidth) newX = newXWidth; setCellX(newX,newXWidth); } void KOAgendaItem::expandRight(int dx) { int newX = cellX(); int newXWidth = cellXWidth() + dx; if (newXWidth < newX) newXWidth = newX; setCellX(newX,newXWidth); } QToolTipGroup *KOAgendaItem::toolTipGroup() { if (!mToolTipGroup) mToolTipGroup = new QToolTipGroup(0); return mToolTipGroup; } void KOAgendaItem::dragEnterEvent( QDragEnterEvent *e ) { #ifndef KORG_NODND if ( ICalDrag::canDecode( e ) || VCalDrag::canDecode( e ) || !QTextDrag::canDecode( e ) ) { e->ignore(); return; } e->accept(); #endif } void KOAgendaItem::dropEvent( QDropEvent *e ) { #ifndef KORG_NODND QString text; if(QTextDrag::decode(e,text)) { kdDebug() << "Dropped : " << text << endl; QStringList emails = QStringList::split(",",text); for(QStringList::ConstIterator it = emails.begin();it!=emails.end();++it) { kdDebug() << " Email: " << (*it) << endl; int pos = (*it).find("<"); QString name = (*it).left(pos); QString email = (*it).mid(pos); if (!email.isEmpty()) { mIncidence->addAttendee(new Attendee(name,email)); } } } #endif } QPtrList<KOAgendaItem> KOAgendaItem::conflictItems() { return mConflictItems; } void KOAgendaItem::setConflictItems(QPtrList<KOAgendaItem> ci) { mConflictItems = ci; KOAgendaItem *item; for ( item=mConflictItems.first(); item != 0; item=mConflictItems.next() ) { item->addConflictItem(this); } } void KOAgendaItem::addConflictItem(KOAgendaItem *ci) { if (mConflictItems.find(ci)<0) mConflictItems.append(ci); } diff --git a/korganizer/korganizer.pro b/korganizer/korganizer.pro index 3c7a1fb..5e82721 100644 --- a/korganizer/korganizer.pro +++ b/korganizer/korganizer.pro @@ -1,191 +1,191 @@ TEMPLATE = app -CONFIG += qt warn_off +CONFIG += qt warn_on TARGET = kopi OBJECTS_DIR = _obj/ MOC_DIR = _moc DESTDIR= ../bin include( ../variables.pri ) INCLUDEPATH += ../microkde ../ interfaces ../microkde/kdecore ../microkde/kdeui ../microkde/kio/kfile ../microkde/kio/kio ../libkdepim #../qtcompat DEFINES += KORG_NOPLUGINS KORG_NOARCHIVE KORG_NOMAIL DEFINES += KORG_NODCOP KORG_NOKALARMD KORG_NORESOURCEVIEW KORG_NOSPLITTER #KORG_NOPRINTER KORG_NOKABC KORG_NODND DEFINES += KORG_NOLVALTERNATION DEFINES += DESKTOP_VERSION unix : { LIBS += ../bin/libmicrokdepim.so LIBS += ../bin/libmicrokcal.so LIBS += ../bin/libmicrokde.so LIBS += ../bin/libmicrokabc.so #LIBS += -lbluetooth #LIBS += -lsdp #LIBS += -lldap OBJECTS_DIR = obj/unix MOC_DIR = moc/unix } win32: { RC_FILE = winicons.rc DEFINES += _WIN32_ LIBS += ../bin/microkdepim.lib LIBS += ../bin/microkcal.lib LIBS += ../bin/microkde.lib LIBS += ../bin/microkabc.lib LIBS += ../libical/lib/ical.lib LIBS += ../libical/lib/icalss.lib #LIBS += atls.lib QMAKE_LINK += /NODEFAULTLIB:LIBC #QMAKE_LINK += /NODEFAULTLIB:MSVCRT #QMAKE_LINK += /NODEFAULTLIB:uafxcw.lib OBJECTS_DIR = obj/win MOC_DIR = moc/win #olimport section #blabla: { LIBS += mfc71u.lib DEFINES += _OL_IMPORT_ HEADERS += ../outport/msoutl9.h \ koimportoldialog.h SOURCES += ../outport/msoutl9.cpp \ koimportoldialog.cpp #} #olimport section end } INTERFACES = kofilterview_base.ui #filteredit_base.ui # kdateedit.h \ HEADERS += \ filteredit_base.h \ alarmclient.h \ calendarview.h \ customlistviewitem.h \ datenavigator.h \ docprefs.h \ filtereditdialog.h \ incomingdialog.h \ incomingdialog_base.h \ interfaces/korganizer/baseview.h \ interfaces/korganizer/calendarviewbase.h \ journalentry.h \ kdatenavigator.h \ koagenda.h \ koagendaitem.h \ koagendaview.h \ kocounterdialog.h \ kodaymatrix.h \ kodialogmanager.h \ koeditordetails.h \ koeditorgeneral.h \ koeditorgeneralevent.h \ koeditorgeneraltodo.h \ koeditorrecurrence.h \ koeventeditor.h \ koeventpopupmenu.h \ koeventview.h \ koeventviewer.h \ koeventviewerdialog.h \ kofilterview.h \ koglobals.h \ koincidenceeditor.h \ kojournalview.h \ kolistview.h \ kolocationbox.h \ komonthview.h \ koprefs.h \ koprefsdialog.h \ kotimespanview.h \ kotodoeditor.h \ kotodoview.h \ kotodoviewitem.h \ koviewmanager.h \ kowhatsnextview.h \ ktimeedit.h \ lineview.h \ mainwindow.h \ navigatorbar.h \ outgoingdialog.h \ outgoingdialog_base.h \ publishdialog.h \ publishdialog_base.h \ savetemplatedialog.h \ searchdialog.h \ simplealarmclient.h \ statusdialog.h \ timeline.h \ timespanview.h \ version.h \ ../kalarmd/alarmdialog.h \ SOURCES += \ filteredit_base.cpp \ calendarview.cpp \ datenavigator.cpp \ docprefs.cpp \ filtereditdialog.cpp \ incomingdialog.cpp \ incomingdialog_base.cpp \ journalentry.cpp \ kdatenavigator.cpp \ koagenda.cpp \ koagendaitem.cpp \ koagendaview.cpp \ kocounterdialog.cpp \ kodaymatrix.cpp \ kodialogmanager.cpp \ koeditordetails.cpp \ koeditorgeneral.cpp \ koeditorgeneralevent.cpp \ koeditorgeneraltodo.cpp \ koeditorrecurrence.cpp \ koeventeditor.cpp \ koeventpopupmenu.cpp \ koeventview.cpp \ koeventviewer.cpp \ koeventviewerdialog.cpp \ kofilterview.cpp \ koglobals.cpp \ koincidenceeditor.cpp \ kojournalview.cpp \ kolistview.cpp \ kolocationbox.cpp \ komonthview.cpp \ koprefs.cpp \ koprefsdialog.cpp \ kotimespanview.cpp \ kotodoeditor.cpp \ kotodoview.cpp \ kotodoviewitem.cpp \ koviewmanager.cpp \ kowhatsnextview.cpp \ ktimeedit.cpp \ lineview.cpp \ main.cpp \ mainwindow.cpp \ navigatorbar.cpp \ outgoingdialog.cpp \ outgoingdialog_base.cpp \ publishdialog.cpp \ publishdialog_base.cpp \ savetemplatedialog.cpp \ searchdialog.cpp \ simplealarmclient.cpp \ statusdialog.cpp \ timeline.cpp \ timespanview.cpp \ ../kalarmd/alarmdialog.cpp HEADERS += calprintbase.h calprinter.h calprintplugins.h cellitem.h INTERFACES += calprintdayconfig_base.ui \ calprintmonthconfig_base.ui \ calprinttodoconfig_base.ui \ calprintweekconfig_base.ui SOURCES += calprintbase.cpp calprinter.cpp calprintplugins.cpp cellitem.cpp diff --git a/libkcal/calendar.cpp b/libkcal/calendar.cpp index 88351eb..dcfee5d 100644 --- a/libkcal/calendar.cpp +++ b/libkcal/calendar.cpp @@ -1,466 +1,467 @@ /* This file is part of libkcal. Copyright (c) 1998 Preston Brown Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdlib.h> #include <time.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include "exceptions.h" #include "calfilter.h" #include "calendar.h" #include "syncdefines.h" using namespace KCal; Calendar::Calendar() { init(); setTimeZoneId( i18n (" 00:00 Europe/London(UTC)") ); } Calendar::Calendar( const QString &timeZoneId ) { init(); setTimeZoneId(timeZoneId); } void Calendar::init() { mObserver = 0; mNewObserver = false; mUndoIncidence = 0; mModified = false; // Setup default filter, which does nothing mDefaultFilter = new CalFilter; mFilter = mDefaultFilter; mFilter->setEnabled(false); // initialize random numbers. This is a hack, and not // even that good of one at that. // srandom(time(0)); // user information... setOwner(i18n("Unknown Name")); setEmail(i18n("unknown@nowhere")); #if 0 tmpStr = KOPrefs::instance()->mTimeZone; // kdDebug(5800) << "Calendar::Calendar(): TimeZone: " << tmpStr << endl; int dstSetting = KOPrefs::instance()->mDaylightSavings; extern long int timezone; struct tm *now; time_t curtime; curtime = time(0); now = localtime(&curtime); int hourOff = - ((timezone / 60) / 60); if (now->tm_isdst) hourOff += 1; QString tzStr; tzStr.sprintf("%.2d%.2d", hourOff, abs((timezone / 60) % 60)); // if no time zone was in the config file, write what we just discovered. if (tmpStr.isEmpty()) { // KOPrefs::instance()->mTimeZone = tzStr; } else { tzStr = tmpStr; } // if daylight savings has changed since last load time, we need // to rewrite these settings to the config file. if ((now->tm_isdst && !dstSetting) || (!now->tm_isdst && dstSetting)) { KOPrefs::instance()->mTimeZone = tzStr; KOPrefs::instance()->mDaylightSavings = now->tm_isdst; } setTimeZone(tzStr); #endif // KOPrefs::instance()->writeConfig(); } Calendar::~Calendar() { delete mDefaultFilter; if ( mUndoIncidence ) delete mUndoIncidence; } const QString &Calendar::getOwner() const { return mOwner; } bool Calendar::undoDeleteIncidence() { if (!mUndoIncidence) return false; addIncidence(mUndoIncidence); mUndoIncidence = 0; + return true; } void Calendar::setOwner(const QString &os) { int i; mOwner = os; i = mOwner.find(','); if (i != -1) mOwner = mOwner.left(i); setModified( true ); } void Calendar::setTimeZone(const QString & tz) { bool neg = FALSE; int hours, minutes; QString tmpStr(tz); if (tmpStr.left(1) == "-") neg = TRUE; if (tmpStr.left(1) == "-" || tmpStr.left(1) == "+") tmpStr.remove(0, 1); hours = tmpStr.left(2).toInt(); if (tmpStr.length() > 2) minutes = tmpStr.right(2).toInt(); else minutes = 0; mTimeZone = (60*hours+minutes); if (neg) mTimeZone = -mTimeZone; mLocalTime = false; setModified( true ); } QString Calendar::getTimeZoneStr() const { if (mLocalTime) return ""; QString tmpStr; int hours = abs(mTimeZone / 60); int minutes = abs(mTimeZone % 60); bool neg = mTimeZone < 0; tmpStr.sprintf("%c%.2d%.2d", (neg ? '-' : '+'), hours, minutes); return tmpStr; } void Calendar::setTimeZone(int tz) { mTimeZone = tz; mLocalTime = false; setModified( true ); } int Calendar::getTimeZone() const { return mTimeZone; } void Calendar::setTimeZoneId(const QString &id) { mTimeZoneId = id; mLocalTime = false; mTimeZone = KGlobal::locale()->timezoneOffset(mTimeZoneId); if ( mTimeZone > 1000) setLocalTime(); //qDebug("Calendar::setTimeZoneOffset %s %d ",mTimeZoneId.latin1(), mTimeZone); setModified( true ); } QString Calendar::timeZoneId() const { return mTimeZoneId; } void Calendar::setLocalTime() { //qDebug("Calendar::setLocalTime() "); mLocalTime = true; mTimeZone = 0; mTimeZoneId = ""; setModified( true ); } bool Calendar::isLocalTime() const { return mLocalTime; } const QString &Calendar::getEmail() { return mOwnerEmail; } void Calendar::setEmail(const QString &e) { mOwnerEmail = e; setModified( true ); } void Calendar::setFilter(CalFilter *filter) { mFilter = filter; } CalFilter *Calendar::filter() { return mFilter; } QPtrList<Incidence> Calendar::incidences() { QPtrList<Incidence> incidences; Incidence *i; QPtrList<Event> e = events(); for( i = e.first(); i; i = e.next() ) incidences.append( i ); QPtrList<Todo> t = todos(); for( i = t.first(); i; i = t.next() ) incidences.append( i ); QPtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) incidences.append( i ); return incidences; } void Calendar::resetPilotStat(int id ) { QPtrList<Incidence> incidences; Incidence *i; QPtrList<Event> e = rawEvents(); for( i = e.first(); i; i = e.next() ) i->setPilotId( id ); QPtrList<Todo> t = rawTodos(); for( i = t.first(); i; i = t.next() ) i->setPilotId( id ); QPtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) i->setPilotId( id ); } void Calendar::resetTempSyncStat() { QPtrList<Incidence> incidences; Incidence *i; QPtrList<Event> e = rawEvents(); for( i = e.first(); i; i = e.next() ) i->setTempSyncStat( SYNC_TEMPSTATE_INITIAL ); QPtrList<Todo> t = rawTodos(); for( i = t.first(); i; i = t.next() ) i->setTempSyncStat( SYNC_TEMPSTATE_INITIAL ); QPtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) i->setTempSyncStat( SYNC_TEMPSTATE_INITIAL ); } QPtrList<Incidence> Calendar::rawIncidences() { QPtrList<Incidence> incidences; Incidence *i; QPtrList<Event> e = rawEvents(); for( i = e.first(); i; i = e.next() ) incidences.append( i ); QPtrList<Todo> t = rawTodos(); for( i = t.first(); i; i = t.next() ) incidences.append( i ); QPtrList<Journal> j = journals(); for( i = j.first(); i; i = j.next() ) incidences.append( i ); return incidences; } QPtrList<Event> Calendar::events( const QDate &date, bool sorted ) { QPtrList<Event> el = rawEventsForDate(date,sorted); mFilter->apply(&el); return el; } QPtrList<Event> Calendar::events( const QDateTime &qdt ) { QPtrList<Event> el = rawEventsForDate(qdt); mFilter->apply(&el); return el; } QPtrList<Event> Calendar::events( const QDate &start, const QDate &end, bool inclusive) { QPtrList<Event> el = rawEvents(start,end,inclusive); mFilter->apply(&el); return el; } QPtrList<Event> Calendar::events() { QPtrList<Event> el = rawEvents(); mFilter->apply(&el); return el; } bool Calendar::addIncidence(Incidence *i) { Incidence::AddVisitor<Calendar> v(this); return i->accept(v); } void Calendar::deleteIncidence(Incidence *in) { if ( in->type() == "Event" ) deleteEvent( (Event*) in ); else if ( in->type() =="Todo" ) deleteTodo( (Todo*) in); else if ( in->type() =="Journal" ) deleteJournal( (Journal*) in ); } Incidence* Calendar::incidence( const QString& uid ) { Incidence* i; if( (i = todo( uid )) != 0 ) return i; if( (i = event( uid )) != 0 ) return i; if( (i = journal( uid )) != 0 ) return i; return 0; } QPtrList<Todo> Calendar::todos() { QPtrList<Todo> tl = rawTodos(); mFilter->apply( &tl ); return tl; } // When this is called, the todo have already been added to the calendar. // This method is only about linking related todos void Calendar::setupRelations( Incidence *incidence ) { QString uid = incidence->uid(); //qDebug("Calendar::setupRelations "); // First, go over the list of orphans and see if this is their parent while( Incidence* i = mOrphans[ uid ] ) { mOrphans.remove( uid ); i->setRelatedTo( incidence ); incidence->addRelation( i ); mOrphanUids.remove( i->uid() ); } // Now see about this incidences parent if( !incidence->relatedTo() && !incidence->relatedToUid().isEmpty() ) { // This incidence has a uid it is related to, but is not registered to it yet // Try to find it Incidence* parent = this->incidence( incidence->relatedToUid() ); if( parent ) { // Found it incidence->setRelatedTo( parent ); parent->addRelation( incidence ); } else { // Not found, put this in the mOrphans list mOrphans.insert( incidence->relatedToUid(), incidence ); mOrphanUids.insert( incidence->uid(), incidence ); } } } // If a task with subtasks is deleted, move it's subtasks to the orphans list void Calendar::removeRelations( Incidence *incidence ) { // qDebug("Calendar::removeRelations "); QString uid = incidence->uid(); QPtrList<Incidence> relations = incidence->relations(); for( Incidence* i = relations.first(); i; i = relations.next() ) if( !mOrphanUids.find( i->uid() ) ) { mOrphans.insert( uid, i ); mOrphanUids.insert( i->uid(), i ); i->setRelatedTo( 0 ); i->setRelatedToUid( uid ); } // If this incidence is related to something else, tell that about it if( incidence->relatedTo() ) incidence->relatedTo()->removeRelation( incidence ); // Remove this one from the orphans list if( mOrphanUids.remove( uid ) ) // This incidence is located in the orphans list - it should be removed if( !( incidence->relatedTo() != 0 && mOrphans.remove( incidence->relatedTo()->uid() ) ) ) { // Removing wasn't that easy for( QDictIterator<Incidence> it( mOrphans ); it.current(); ++it ) { if( it.current()->uid() == uid ) { mOrphans.remove( it.currentKey() ); break; } } } } void Calendar::registerObserver( Observer *observer ) { mObserver = observer; mNewObserver = true; } void Calendar::setModified( bool modified ) { if ( mObserver ) mObserver->calendarModified( modified, this ); if ( modified != mModified || mNewObserver ) { mNewObserver = false; // if ( mObserver ) mObserver->calendarModified( modified, this ); mModified = modified; } } void Calendar::setLoadedProductId( const QString &id ) { mLoadedProductId = id; } QString Calendar::loadedProductId() { return mLoadedProductId; } //#include "calendar.moc" diff --git a/libkcal/event.cpp b/libkcal/event.cpp index 7256f05..de8dceb 100644 --- a/libkcal/event.cpp +++ b/libkcal/event.cpp @@ -1,223 +1,221 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kglobal.h> #include <klocale.h> #include <kdebug.h> #include "event.h" using namespace KCal; Event::Event() : mHasEndDate( false ), mTransparency( Opaque ) { } Event::Event(const Event &e) : Incidence(e) { mDtEnd = e.mDtEnd; mHasEndDate = e.mHasEndDate; mTransparency = e.mTransparency; } Event::~Event() { } Incidence *Event::clone() { return new Event(*this); } bool KCal::operator==( const Event& e1, const Event& e2 ) { return operator==( (const Incidence&)e1, (const Incidence&)e2 ) && e1.dtEnd() == e2.dtEnd() && e1.hasEndDate() == e2.hasEndDate() && e1.transparency() == e2.transparency(); } bool Event::contains ( Event* from ) { if ( !from->summary().isEmpty() ) if ( !summary().startsWith( from->summary() )) return false; if ( from->dtStart().isValid() ) if (dtStart() != from->dtStart() ) return false; if ( from->dtEnd().isValid() ) if ( dtEnd() != from->dtEnd() ) return false; if ( !from->location().isEmpty() ) if ( !location().startsWith( from->location() ) ) return false; if ( !from->description().isEmpty() ) if ( !description().startsWith( from->description() )) return false; if ( from->alarms().count() ) { Alarm *a = from->alarms().first(); if ( a->enabled() ){ if ( !alarms().count() ) return false; Alarm *b = alarms().first(); if( ! b->enabled() ) return false; if ( ! (a->offset() == b->offset() )) return false; } } QStringList cat = categories(); QStringList catFrom = from->categories(); QString nCat; - int iii; + unsigned int iii; for ( iii = 0; iii < catFrom.count();++iii ) { nCat = catFrom[iii]; if ( !nCat.isEmpty() ) if ( !cat.contains( nCat )) { return false; } } if ( from->doesRecur() ) if ( from->doesRecur() != doesRecur() && ! (from->doesRecur()== Recurrence::rYearlyMonth && doesRecur()== Recurrence::rYearlyDay) ) return false; return true; } void Event::setDtEnd(const QDateTime &dtEnd) { if (mReadOnly) return; mDtEnd = getEvenTime( dtEnd ); setHasEndDate(true); setHasDuration(false); updated(); } QDateTime Event::dtEnd() const { if (hasEndDate()) return mDtEnd; if (hasDuration()) return dtStart().addSecs(duration()); - kdDebug(5800) << "Warning! Event '" << summary() - << "' does have neither end date nor duration." << endl; return dtStart(); } QString Event::dtEndTimeStr() const { return KGlobal::locale()->formatTime(mDtEnd.time()); } QString Event::dtEndDateStr(bool shortfmt) const { return KGlobal::locale()->formatDate(mDtEnd.date(),shortfmt); } QString Event::dtEndStr(bool shortfmt) const { return KGlobal::locale()->formatDateTime(mDtEnd, shortfmt); } void Event::setHasEndDate(bool b) { mHasEndDate = b; } bool Event::hasEndDate() const { return mHasEndDate; } bool Event::isMultiDay() const { bool multi = !(dtStart().date() == dtEnd().date()); return multi; } void Event::setTransparency(Event::Transparency transparency) { if (mReadOnly) return; mTransparency = transparency; updated(); } Event::Transparency Event::transparency() const { return mTransparency; } void Event::setDuration(int seconds) { setHasEndDate(false); Incidence::setDuration(seconds); } QDateTime Event::getNextAlarmDateTime( bool * ok, int * offset ) const { bool yes; QDateTime incidenceStart = getNextOccurence( QDateTime::currentDateTime(), &yes ); if ( ! yes || cancelled() ) { *ok = false; return QDateTime (); } bool enabled = false; Alarm* alarm; - int off; + int off = 0; QDateTime alarmStart = QDateTime::currentDateTime().addDays( 3650 );; // if ( QDateTime::currentDateTime() > incidenceStart ){ // *ok = false; // return incidenceStart; // } for (QPtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { if (alarm->enabled()) { if ( alarm->hasTime () ) { if ( alarm->time() < alarmStart ) { alarmStart = alarm->time(); enabled = true; off = alarmStart.secsTo( incidenceStart ); } } else { int secs = alarm->startOffset().asSeconds(); if ( incidenceStart.addSecs( secs ) < alarmStart ) { alarmStart = incidenceStart.addSecs( secs ); enabled = true; off = -secs; } } } } if ( enabled ) { if ( alarmStart > QDateTime::currentDateTime() ) { *ok = true; * offset = off; return alarmStart; } } *ok = false; return QDateTime (); } diff --git a/libkcal/todo.cpp b/libkcal/todo.cpp index d81a68f..9c04a7e 100644 --- a/libkcal/todo.cpp +++ b/libkcal/todo.cpp @@ -1,414 +1,414 @@ /* This file is part of libkcal. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <kglobal.h> #include <klocale.h> #include <kdebug.h> #include "todo.h" using namespace KCal; Todo::Todo(): Incidence() { // mStatus = TENTATIVE; mHasDueDate = false; setHasStartDate( false ); mCompleted = getEvenTime(QDateTime::currentDateTime()); mHasCompletedDate = false; mPercentComplete = 0; } Todo::Todo(const Todo &t) : Incidence(t) { mDtDue = t.mDtDue; mHasDueDate = t.mHasDueDate; mCompleted = t.mCompleted; mHasCompletedDate = t.mHasCompletedDate; mPercentComplete = t.mPercentComplete; } Todo::~Todo() { } Incidence *Todo::clone() { return new Todo(*this); } bool Todo::contains ( Todo* from ) { if ( !from->summary().isEmpty() ) if ( !summary().startsWith( from->summary() )) return false; if ( from->hasStartDate() ) { if ( !hasStartDate() ) return false; if ( from->dtStart() != dtStart()) return false; } if ( from->hasDueDate() ){ if ( !hasDueDate() ) return false; if ( from->dtDue() != dtDue()) return false; } if ( !from->location().isEmpty() ) if ( !location().startsWith( from->location() ) ) return false; if ( !from->description().isEmpty() ) if ( !description().startsWith( from->description() )) return false; if ( from->alarms().count() ) { Alarm *a = from->alarms().first(); if ( a->enabled() ){ if ( !alarms().count() ) return false; Alarm *b = alarms().first(); if( ! b->enabled() ) return false; if ( ! (a->offset() == b->offset() )) return false; } } QStringList cat = categories(); QStringList catFrom = from->categories(); QString nCat; - int iii; + unsigned int iii; for ( iii = 0; iii < catFrom.count();++iii ) { nCat = catFrom[iii]; if ( !nCat.isEmpty() ) if ( !cat.contains( nCat )) { return false; } } if ( from->isCompleted() ) { if ( !isCompleted() ) return false; } if( priority() != from->priority() ) return false; return true; } bool KCal::operator==( const Todo& t1, const Todo& t2 ) { bool ret = operator==( (const Incidence&)t1, (const Incidence&)t2 ); if ( ! ret ) return false; if ( t1.hasDueDate() == t2.hasDueDate() ) { if ( t1.hasDueDate() ) { if ( t1.doesFloat() == t2.doesFloat() ) { if ( t1.doesFloat() ) { if ( t1.dtDue().date() != t2.dtDue().date() ) return false; } else if ( t1.dtDue() != t2.dtDue() ) return false; } else return false;// float != } } else return false; if ( t1.percentComplete() != t2.percentComplete() ) return false; if ( t1.isCompleted() ) { if ( t1.hasCompletedDate() == t2.hasCompletedDate() ) { if ( t1.hasCompletedDate() ) { if ( t1.completed() != t2.completed() ) return false; } } else return false; } return true; } void Todo::setDtDue(const QDateTime &dtDue) { //int diffsecs = mDtDue.secsTo(dtDue); /*if (mReadOnly) return; const QPtrList<Alarm>& alarms = alarms(); for (Alarm* alarm = alarms.first(); alarm; alarm = alarms.next()) { if (alarm->enabled()) { alarm->setTime(alarm->time().addSecs(diffsecs)); } }*/ mDtDue = getEvenTime(dtDue); //kdDebug(5800) << "setDtDue says date is " << mDtDue.toString() << endl; /*const QPtrList<Alarm>& alarms = alarms(); for (Alarm* alarm = alarms.first(); alarm; alarm = alarms.next()) alarm->setAlarmStart(mDtDue);*/ updated(); } QDateTime Todo::dtDue() const { return mDtDue; } QString Todo::dtDueTimeStr() const { return KGlobal::locale()->formatTime(mDtDue.time()); } QString Todo::dtDueDateStr(bool shortfmt) const { return KGlobal::locale()->formatDate(mDtDue.date(),shortfmt); } QString Todo::dtDueStr(bool shortfmt) const { return KGlobal::locale()->formatDateTime(mDtDue, shortfmt); } // retval 0 : no found // 1 : due for date found // 2 : overdue for date found int Todo::hasDueSubTodoForDate( const QDate & date, bool checkSubtodos ) { int retval = 0; if ( isCompleted() ) return 0; if ( hasDueDate() ) { if ( dtDue().date() < date ) return 2; // we do not return, because we may find an overdue sub todo if ( dtDue().date() == date ) retval = 1; } if ( checkSubtodos ) { Incidence *aTodo; for (aTodo = mRelations.first(); aTodo; aTodo = mRelations.next()) { int ret = ((Todo*)aTodo)->hasDueSubTodoForDate( date ,checkSubtodos ); if ( ret == 2 ) return 2; if ( ret == 1) retval = 1; } } return retval; } int Todo::hasDueSubTodo( bool checkSubtodos ) //= true { return hasDueSubTodoForDate(QDate::currentDate(), checkSubtodos ); } bool Todo::hasDueDate() const { return mHasDueDate; } void Todo::setHasDueDate(bool f) { if (mReadOnly) return; mHasDueDate = f; updated(); } #if 0 void Todo::setStatus(const QString &statStr) { if (mReadOnly) return; QString ss(statStr.upper()); if (ss == "X-ACTION") mStatus = NEEDS_ACTION; else if (ss == "NEEDS ACTION") mStatus = NEEDS_ACTION; else if (ss == "ACCEPTED") mStatus = ACCEPTED; else if (ss == "SENT") mStatus = SENT; else if (ss == "TENTATIVE") mStatus = TENTATIVE; else if (ss == "CONFIRMED") mStatus = CONFIRMED; else if (ss == "DECLINED") mStatus = DECLINED; else if (ss == "COMPLETED") mStatus = COMPLETED; else if (ss == "DELEGATED") mStatus = DELEGATED; updated(); } void Todo::setStatus(int status) { if (mReadOnly) return; mStatus = status; updated(); } int Todo::status() const { return mStatus; } QString Todo::statusStr() const { switch(mStatus) { case NEEDS_ACTION: return QString("NEEDS ACTION"); break; case ACCEPTED: return QString("ACCEPTED"); break; case SENT: return QString("SENT"); break; case TENTATIVE: return QString("TENTATIVE"); break; case CONFIRMED: return QString("CONFIRMED"); break; case DECLINED: return QString("DECLINED"); break; case COMPLETED: return QString("COMPLETED"); break; case DELEGATED: return QString("DELEGATED"); break; } return QString(""); } #endif bool Todo::isCompleted() const { if (mPercentComplete == 100) return true; else return false; } void Todo::setCompleted(bool completed) { if (completed) mPercentComplete = 100; else { mPercentComplete = 0; mHasCompletedDate = false; } updated(); } QDateTime Todo::completed() const { return mCompleted; } QString Todo::completedStr( bool shortF ) const { return KGlobal::locale()->formatDateTime(mCompleted, shortF); } void Todo::setCompleted(const QDateTime &completed) { //qDebug("Todo::setCompleted "); if ( mHasCompletedDate ) { // qDebug("has completed data - return "); return; } mHasCompletedDate = true; mPercentComplete = 100; mCompleted = getEvenTime(completed); updated(); } bool Todo::hasCompletedDate() const { return mHasCompletedDate; } int Todo::percentComplete() const { return mPercentComplete; } void Todo::setPercentComplete(int v) { mPercentComplete = v; if ( v != 100 ) mHasCompletedDate = false; updated(); } QDateTime Todo::getNextAlarmDateTime( bool * ok, int * offset ) const { if ( isCompleted() || ! hasDueDate() || cancelled() ) { *ok = false; return QDateTime (); } QDateTime incidenceStart; incidenceStart = dtDue(); bool enabled = false; Alarm* alarm; - int off; + int off = 0; QDateTime alarmStart = QDateTime::currentDateTime().addDays( 3650 );; // if ( QDateTime::currentDateTime() > incidenceStart ){ // *ok = false; // return incidenceStart; // } for (QPtrListIterator<Alarm> it(mAlarms); (alarm = it.current()) != 0; ++it) { if (alarm->enabled()) { if ( alarm->hasTime () ) { if ( alarm->time() < alarmStart ) { alarmStart = alarm->time(); enabled = true; off = alarmStart.secsTo( incidenceStart ); } } else { int secs = alarm->startOffset().asSeconds(); if ( incidenceStart.addSecs( secs ) < alarmStart ) { alarmStart = incidenceStart.addSecs( secs ); enabled = true; off = -secs; } } } } if ( enabled ) { if ( alarmStart > QDateTime::currentDateTime() ) { *ok = true; * offset = off; return alarmStart; } } *ok = false; return QDateTime (); } diff --git a/libkdepim/ksyncmanager.cpp b/libkdepim/ksyncmanager.cpp index 3adbf61..df5a0d9 100644 --- a/libkdepim/ksyncmanager.cpp +++ b/libkdepim/ksyncmanager.cpp @@ -1,1485 +1,1484 @@ /* This file is part of KDE-Pim/Pi. Copyright (c) 2004 Ulf Schenk This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // $Id$ #include "ksyncmanager.h" #include <stdlib.h> #ifndef _WIN32_ #include <unistd.h> #endif #include "ksyncprofile.h" #include "ksyncprefsdialog.h" #include "kpimprefs.h" #include <kmessagebox.h> #include <qdir.h> #include <qprogressbar.h> #include <qpopupmenu.h> #include <qpushbutton.h> #include <qradiobutton.h> #include <qbuttongroup.h> #include <qtimer.h> #include <qmessagebox.h> #include <qapplication.h> #include <qlineedit.h> #include <qdialog.h> #include <qlayout.h> #include <qtextcodec.h> #include <qlabel.h> #include <qcheckbox.h> #include <klocale.h> #include <kglobal.h> #include <kconfig.h> #include <kfiledialog.h> QDateTime KSyncManager::mRequestedSyncEvent; KSyncManager::KSyncManager(QWidget* parent, KSyncInterface* implementation, TargetApp ta, KPimPrefs* prefs, QPopupMenu* syncmenu) - : QObject(), mParent(parent), mImplementation(implementation), mTargetApp(ta), mPrefs(prefs ),mSyncMenu(syncmenu) + : QObject(), mPrefs(prefs ), mParent(parent),mImplementation(implementation), mTargetApp(ta), mSyncMenu(syncmenu) { mServerSocket = 0; bar = new QProgressBar ( 1, 0 ); bar->setCaption (""); mWriteBackInPast = 2; int w = 300; if ( QApplication::desktop()->width() < 320 ) w = 220; int h = bar->sizeHint().height() ; int dw = QApplication::desktop()->width(); int dh = QApplication::desktop()->height(); bar->setGeometry( (dw-w)/2, (dh - h )/2 ,w,h ); if ( mPrefs->mPassiveSyncAutoStart ) enableQuick( false ); } KSyncManager::~KSyncManager() { delete bar; } void KSyncManager::fillSyncMenu() { if ( mSyncMenu->count() ) mSyncMenu->clear(); mSyncMenu->insertItem( i18n("Configure..."), 0 ); mSyncMenu->insertSeparator(); QPopupMenu *clearMenu = new QPopupMenu ( mSyncMenu ); mSyncMenu->insertItem( i18n("Remove sync info"),clearMenu, 5000 ); clearMenu->insertItem( i18n("For all profiles"), 1 ); clearMenu->insertSeparator(); connect ( clearMenu, SIGNAL( activated ( int ) ), this, SLOT (slotClearMenu( int ) ) ); mSyncMenu->insertSeparator(); if ( mServerSocket == 0 ) { mSyncMenu->insertItem( i18n("Enable Pi-Sync"), 2 ); } else { mSyncMenu->insertItem( i18n("Disable Pi-Sync"), 3 ); } mSyncMenu->insertSeparator(); mSyncMenu->insertItem( i18n("Multiple sync"), 1 ); mSyncMenu->insertSeparator(); KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); config.setGroup("General"); QStringList prof = config.readListEntry("SyncProfileNames"); mLocalMachineName = config.readEntry("LocalMachineName","undefined"); if ( prof.count() < 2 ) { prof.clear(); QString externalName; #ifdef DESKTOP_VERSION #ifdef _WIN32_ externalName = "OutLook(not_implemented)"; #else externalName = "KDE_Desktop"; #endif #else externalName = "Sharp_DTM"; #endif prof << externalName; prof << i18n("Local_file"); prof << i18n("Last_file"); KSyncProfile* temp = new KSyncProfile (); temp->setName( prof[0] ); temp->writeConfig(&config); temp->setName( prof[1] ); temp->writeConfig(&config); temp->setName( prof[2] ); temp->writeConfig(&config); config.setGroup("General"); config.writeEntry("SyncProfileNames",prof); config.writeEntry("ExternSyncProfiles",externalName); config.sync(); delete temp; } mExternSyncProfiles = config.readListEntry("ExternSyncProfiles"); mSyncProfileNames = prof; unsigned int i; for ( i = 0; i < prof.count(); ++i ) { mSyncMenu->insertItem( prof[i], 1000+i ); clearMenu->insertItem( prof[i], 1000+i ); if ( i == 2 ) mSyncMenu->insertSeparator(); } QDir app_dir; //US do not display SharpDTM if app is pwmpi, or no sharpfiles available if ( mTargetApp == PWMPI) { mSyncMenu->removeItem( 1000 ); clearMenu->removeItem( 1000 ); } #ifndef DESKTOP_VERSION else if (!app_dir.exists(QDir::homeDirPath()+"/Applications/dtm" ) ) { mSyncMenu->removeItem( 1000 ); clearMenu->removeItem( 1000 ); } #endif mSyncMenu->removeItem( 1002 ); clearMenu->removeItem( 1002 ); } void KSyncManager::slotClearMenu( int action ) { QString syncDevice; if ( action > 999 ) { syncDevice = mSyncProfileNames[action - 1000] ; } int result = 0; QString sd; if ( syncDevice.isEmpty() ) sd = i18n("Do you want to\nclear all sync info\nof all profiles?"); else sd = i18n("Do you want to\nclear the sync\ninfo of profile\n%1?\n"). arg( syncDevice ); result = QMessageBox::warning( mParent, i18n("Warning!"),sd,i18n("OK"), i18n("Cancel"), 0, 0, 1 ); if ( result ) return; mImplementation->removeSyncInfo( syncDevice ); } void KSyncManager::slotSyncMenu( int action ) { qDebug("KSM::syncaction %d ", action); if ( action == 5000 ) return; mSyncWithDesktop = false; if ( action == 0 ) { // seems to be a Qt2 event handling bug // syncmenu.clear causes a segfault at first time // when we call it after the main event loop, it is ok // same behaviour when calling OM/Pi via QCOP for the first time QTimer::singleShot ( 1, this, SLOT ( confSync() ) ); //confSync(); return; } if ( action == 1 ) { multiSync( true ); return; } if ( action == 2 ) { enableQuick(); QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); return; } if ( action == 3 ) { delete mServerSocket; mServerSocket = 0; QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); return; } if (blockSave()) return; setBlockSave(true); bool silent = false; if ( action == 999 ) { //special mode for silent syncing action = 1000; silent = true; } mCurrentSyncProfile = action - 1000 ; mCurrentSyncDevice = mSyncProfileNames[mCurrentSyncProfile] ; mCurrentSyncName = mLocalMachineName ; KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); KSyncProfile* temp = new KSyncProfile (); temp->setName(mSyncProfileNames[mCurrentSyncProfile]); temp->readConfig(&config); if (silent) { mAskForPreferences = false; mShowSyncSummary = false; mWriteBackFile = true; mSyncAlgoPrefs = 2;// take newest } else { mAskForPreferences = temp->getAskForPreferences(); mShowSyncSummary = temp->getShowSummaryAfterSync(); mWriteBackFile = temp->getWriteBackFile(); mSyncAlgoPrefs = temp->getSyncPrefs(); } mWriteBackExistingOnly = temp->getWriteBackExisting(); mIsKapiFile = temp->getIsKapiFile(); mWriteBackInFuture = 0; if ( temp->getWriteBackFuture() ) { mWriteBackInFuture = temp->getWriteBackFutureWeeks( ); mWriteBackInPast = temp->getWriteBackPastWeeks( ); } mFilterInCal = temp->getFilterInCal(); mFilterOutCal = temp->getFilterOutCal(); mFilterInAB = temp->getFilterInAB(); mFilterOutAB = temp->getFilterOutAB(); if ( action == 1000 ) { mIsKapiFile = false; #ifdef DESKTOP_VERSION syncKDE(); #else syncSharp(); #endif } else if ( action == 1001 ) { syncLocalFile(); } else if ( action == 1002 ) { mWriteBackFile = false; mAskForPreferences = false; mShowSyncSummary = false; mSyncAlgoPrefs = 3; quickSyncLocalFile(); } else if ( action >= 1003 ) { if ( temp->getIsLocalFileSync() ) { switch(mTargetApp) { case (KAPI): if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) ) mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB(); break; case (KOPI): if ( syncWithFile( temp->getRemoteFileName( ), false ) ) mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName(); break; case (PWMPI): if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) ) mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM(); break; default: qDebug("KSM::slotSyncMenu: invalid apptype selected"); break; } } else { if ( temp->getIsPhoneSync() ) { mPhoneDevice = temp->getPhoneDevice( ) ; mPhoneConnection = temp->getPhoneConnection( ); mPhoneModel = temp->getPhoneModel( ); syncPhone(); } else if ( temp->getIsPiSync() ) { if ( mTargetApp == KAPI ) { mPassWordPiSync = temp->getRemotePwAB(); mActiveSyncPort = temp->getRemotePortAB(); mActiveSyncIP = temp->getRemoteIPAB(); } else if ( mTargetApp == KOPI ) { mPassWordPiSync = temp->getRemotePw(); mActiveSyncPort = temp->getRemotePort(); mActiveSyncIP = temp->getRemoteIP(); } else { mPassWordPiSync = temp->getRemotePwPWM(); mActiveSyncPort = temp->getRemotePortPWM(); mActiveSyncIP = temp->getRemoteIPPWM(); } syncPi(); while ( !mPisyncFinished ) { //qDebug("waiting "); qApp->processEvents(); } } else syncRemote( temp ); } } delete temp; setBlockSave(false); } void KSyncManager::enableQuick( bool ask ) { bool autoStart; bool changed = false; if ( ask ) { QDialog dia ( 0, "input-dialog", true ); QLineEdit lab ( &dia ); QVBoxLayout lay( &dia ); lab.setText( mPrefs->mPassiveSyncPort ); lay.setMargin(7); lay.setSpacing(7); int po = 9197+mTargetApp; QLabel label ( i18n("Port number (Default: %1)").arg(po), &dia ); lay.addWidget( &label); lay.addWidget( &lab); QLineEdit lepw ( &dia ); lepw.setText( mPrefs->mPassiveSyncPw ); QLabel label2 ( i18n("Password to enable\naccess from remote:"), &dia ); lay.addWidget( &label2); lay.addWidget( &lepw); QCheckBox autostart(i18n("Automatically start\nat application startup"), &dia ); lay.addWidget( &autostart); autostart.setChecked( mPrefs->mPassiveSyncAutoStart ); #ifdef DESKTOP_VERSION #ifdef _WIN32_ QCheckBox syncdesktop( i18n("Automatically sync with Outlook\nwhen receiving sync request"),&dia ); syncdesktop.hide();// not implemented! #else QCheckBox syncdesktop( i18n("Automatically sync with KDE-Desktop\nwhen receiving sync request"),&dia ); #endif lay.addWidget( &syncdesktop); #else mPrefs->mPassiveSyncWithDesktop = false; QCheckBox syncdesktop( i18n("Automatically sync\nwith KDE-Desktop"),&dia ); syncdesktop.hide(); #endif syncdesktop.setChecked( mPrefs->mPassiveSyncWithDesktop ); dia.setFixedSize( 230,120 ); dia.setCaption( i18n("Enter port for Pi-Sync") ); QPushButton pb ( "OK", &dia); lay.addWidget( &pb ); connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) ); dia.show(); if ( ! dia.exec() ) return; dia.hide(); qApp->processEvents(); if ( mPrefs->mPassiveSyncPw != lepw.text() ) { changed = true; mPrefs->mPassiveSyncPw = lepw.text(); } if ( mPrefs->mPassiveSyncPort != lab.text() ) { mPrefs->mPassiveSyncPort = lab.text(); changed = true; } autoStart = autostart.isChecked(); if (mPrefs->mPassiveSyncWithDesktop != syncdesktop.isChecked() ) { changed = true; mPrefs->mPassiveSyncWithDesktop = syncdesktop.isChecked(); } } else autoStart = mPrefs->mPassiveSyncAutoStart; if ( autoStart != mPrefs->mPassiveSyncAutoStart ) changed = true; bool ok; mPrefs->mPassiveSyncAutoStart = false; Q_UINT16 port = mPrefs->mPassiveSyncPort.toUInt(&ok); if ( ! ok ) { KMessageBox::information( 0, i18n("No valid port")); return; } //qDebug("port %d ", port); mServerSocket = new KServerSocket ( mPrefs->mPassiveSyncPw, port ,1 ); mServerSocket->setFileName( defaultFileName() );//bbb //qDebug("connected "); if ( !mServerSocket->ok() ) { KMessageBox::information( 0, i18n("Failed to bind or\nlisten to the port!")); delete mServerSocket; mServerSocket = 0; return; } mPrefs->mPassiveSyncAutoStart = autoStart; if ( changed ) { mPrefs->writeConfig(); } connect( mServerSocket, SIGNAL ( request_file() ),this, SIGNAL ( request_file() ) ); connect( mServerSocket, SIGNAL ( file_received( bool ) ), this, SIGNAL ( getFile( bool ) ) ); } void KSyncManager::syncLocalFile() { QString fn =mPrefs->mLastSyncedLocalFile; QString ext; switch(mTargetApp) { case (KAPI): ext = "(*.vcf)"; break; case (KOPI): ext = "(*.ics/*.vcs)"; break; case (PWMPI): ext = "(*.pwm)"; break; default: qDebug("KSM::syncLocalFile: invalid apptype selected"); break; } fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename"+ext), mParent ); if ( fn == "" ) return; if ( syncWithFile( fn, false ) ) { qDebug("KSM::syncLocalFile() successful "); } } bool KSyncManager::syncWithFile( QString fn , bool quick ) { bool ret = false; QFileInfo info; info.setFile( fn ); QString mess; - bool loadbup = true; if ( !info. exists() ) { mess = i18n( "Sync file \n...%1\ndoes not exist!\nNothing synced!\n").arg(fn.right( 30) ); - int result = QMessageBox::warning( mParent, i18n("Warning!"), + QMessageBox::warning( mParent, i18n("Warning!"), mess ); return ret; } int result = 0; if ( !quick ) { mess = i18n("Sync with file \n...%1\nfrom:\n%2\n").arg(fn.right( 25)).arg(KGlobal::locale()->formatDateTime(info.lastModified (), true, false )); result = QMessageBox::warning( mParent, i18n("Warning!"), mess, i18n("Sync"), i18n("Cancel"), 0, 0, 1 ); if ( result ) return false; } if ( mAskForPreferences ) if ( !edit_sync_options()) { mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") ); return false; } if ( result == 0 ) { //qDebug("Now sycing ... "); if ( ret = mImplementation->sync( this, fn, mSyncAlgoPrefs ) ) mParent->topLevelWidget()->setCaption( i18n("Synchronization successful") ); else mParent->topLevelWidget()->setCaption( i18n("Sync cancelled or failed.") ); if ( ! quick ) mPrefs->mLastSyncedLocalFile = fn; } return ret; } void KSyncManager::quickSyncLocalFile() { if ( syncWithFile( mPrefs->mLastSyncedLocalFile, true ) ) { qDebug("KSM::quick syncLocalFile() successful "); } } void KSyncManager::multiSync( bool askforPrefs ) { if (blockSave()) return; setBlockSave(true); QString question = i18n("Do you really want\nto multiple sync\nwith all checked profiles?\nSyncing takes some\ntime - all profiles\nare synced twice!"); if ( QMessageBox::information( mParent, i18n("KDE-Pim Sync"), question, i18n("Yes"), i18n("No"), 0, 0 ) != 0 ) { setBlockSave(false); mParent->topLevelWidget()->setCaption(i18n("Aborted! Nothing synced!")); return; } mCurrentSyncDevice = i18n("Multiple profiles") ; mSyncAlgoPrefs = mPrefs->mRingSyncAlgoPrefs; if ( askforPrefs ) { if ( !edit_sync_options()) { mParent->topLevelWidget()->setCaption( i18n("Syncing aborted.") ); return; } mPrefs->mRingSyncAlgoPrefs = mSyncAlgoPrefs; } mParent->topLevelWidget()->setCaption(i18n("Multiple sync started.") ); qApp->processEvents(); int num = ringSync() ; if ( num > 1 ) ringSync(); setBlockSave(false); if ( num ) emit save(); if ( num ) mParent->topLevelWidget()->setCaption(i18n("%1 profiles synced. Multiple sync complete!").arg(num) ); else mParent->topLevelWidget()->setCaption(i18n("Nothing synced! No profiles defined for multisync!")); return; } int KSyncManager::ringSync() { int syncedProfiles = 0; unsigned int i; QTime timer; KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); QStringList syncProfileNames = mSyncProfileNames; KSyncProfile* temp = new KSyncProfile (); mAskForPreferences = false; for ( i = 0; i < syncProfileNames.count(); ++i ) { mCurrentSyncProfile = i; temp->setName(syncProfileNames[mCurrentSyncProfile]); temp->readConfig(&config); - bool includeInRingSync; + bool includeInRingSync = false; switch(mTargetApp) { case (KAPI): includeInRingSync = temp->getIncludeInRingSyncAB(); break; case (KOPI): includeInRingSync = temp->getIncludeInRingSync(); break; case (PWMPI): includeInRingSync = temp->getIncludeInRingSyncPWM(); break; default: qDebug("KSM::ringSync: invalid apptype selected"); break; } if ( includeInRingSync && ( i < 1 || i > 2 )) { mParent->topLevelWidget()->setCaption(i18n("Profile ")+syncProfileNames[mCurrentSyncProfile]+ i18n(" is synced ... ")); ++syncedProfiles; mSyncWithDesktop = false; // mAskForPreferences = temp->getAskForPreferences(); mWriteBackFile = temp->getWriteBackFile(); mWriteBackExistingOnly = temp->getWriteBackExisting(); mIsKapiFile = temp->getIsKapiFile(); mWriteBackInFuture = 0; if ( temp->getWriteBackFuture() ) { mWriteBackInFuture = temp->getWriteBackFutureWeeks( ); mWriteBackInPast = temp->getWriteBackPastWeeks( ); } mFilterInCal = temp->getFilterInCal(); mFilterOutCal = temp->getFilterOutCal(); mFilterInAB = temp->getFilterInAB(); mFilterOutAB = temp->getFilterOutAB(); mShowSyncSummary = false; mCurrentSyncDevice = syncProfileNames[i] ; mCurrentSyncName = mLocalMachineName; if ( i == 0 ) { mIsKapiFile = false; #ifdef DESKTOP_VERSION syncKDE(); #else syncSharp(); #endif } else { if ( temp->getIsLocalFileSync() ) { switch(mTargetApp) { case (KAPI): if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) ) mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB(); break; case (KOPI): if ( syncWithFile( temp->getRemoteFileName( ), false ) ) mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName(); break; case (PWMPI): if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) ) mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM(); break; default: qDebug("KSM: invalid apptype selected"); break; } } else { if ( temp->getIsPhoneSync() ) { mPhoneDevice = temp->getPhoneDevice( ) ; mPhoneConnection = temp->getPhoneConnection( ); mPhoneModel = temp->getPhoneModel( ); syncPhone(); } else if ( temp->getIsPiSync() ) { if ( mTargetApp == KAPI ) { mPassWordPiSync = temp->getRemotePwAB(); mActiveSyncPort = temp->getRemotePortAB(); mActiveSyncIP = temp->getRemoteIPAB(); } else if ( mTargetApp == KOPI ) { mPassWordPiSync = temp->getRemotePw(); mActiveSyncPort = temp->getRemotePort(); mActiveSyncIP = temp->getRemoteIP(); } else { mPassWordPiSync = temp->getRemotePwPWM(); mActiveSyncPort = temp->getRemotePortPWM(); mActiveSyncIP = temp->getRemoteIPPWM(); } syncPi(); while ( !mPisyncFinished ) { //qDebug("waiting "); qApp->processEvents(); } timer.start(); while ( timer.elapsed () < 2000 ) { qApp->processEvents(); } } else syncRemote( temp, false ); } } timer.start(); mParent->topLevelWidget()->setCaption(i18n("Multiple sync in progress ... please wait!") ); while ( timer.elapsed () < 2000 ) { qApp->processEvents(); #ifndef _WIN32_ sleep (1); #endif } } } delete temp; return syncedProfiles; } void KSyncManager::syncRemote( KSyncProfile* prof, bool ask) { QString question; if ( ask ) { question = i18n("Do you really want\nto remote sync\nwith profile \n")+ prof->getName()+" ?\n"; if ( QMessageBox::information( mParent, i18n("Sync"), question, i18n("Yes"), i18n("No"), 0, 0 ) != 0 ) return; } QString preCommand; QString localTempFile; QString postCommand; switch(mTargetApp) { case (KAPI): preCommand = prof->getPreSyncCommandAB(); postCommand = prof->getPostSyncCommandAB(); localTempFile = prof->getLocalTempFileAB(); break; case (KOPI): preCommand = prof->getPreSyncCommand(); postCommand = prof->getPostSyncCommand(); localTempFile = prof->getLocalTempFile(); break; case (PWMPI): preCommand = prof->getPreSyncCommandPWM(); postCommand = prof->getPostSyncCommandPWM(); localTempFile = prof->getLocalTempFilePWM(); break; default: qDebug("KSM::syncRemote: invalid apptype selected"); break; } int fi; if ( (fi = preCommand.find("$PWD$")) > 0 ) { QString pwd = getPassword(); preCommand = preCommand.left( fi )+ pwd + preCommand.mid( fi+5 ); } int maxlen = 30; if ( QApplication::desktop()->width() > 320 ) maxlen += 25; mParent->topLevelWidget()->setCaption ( i18n( "Copy remote file to local machine..." ) ); int fileSize = 0; int result = system ( preCommand ); // 0 : okay // 256: no such file or dir // qDebug("KSM::Sync: Remote copy result(0 = okay): %d ",result ); if ( result != 0 ) { unsigned int len = maxlen; while ( len < preCommand.length() ) { preCommand.insert( len , "\n" ); len += maxlen +2; } question = i18n("Sorry, the copy command failed!\nCommand was:\n%1\n \nTry command on console to get more\ndetailed info about the reason.\n").arg (preCommand) ; QMessageBox::information( mParent, i18n("Sync - ERROR"), question, i18n("Okay!")) ; mParent->topLevelWidget()->setCaption ("KDE-Pim"); return; } mParent->topLevelWidget()->setCaption ( i18n( "Copying succeed." ) ); //qDebug(" file **%s** ",prof->getLocalTempFile().latin1() ); if ( syncWithFile( localTempFile, true ) ) { if ( mWriteBackFile ) { int fi; if ( (fi = postCommand.find("$PWD$")) > 0 ) { QString pwd = getPassword(); postCommand = postCommand.left( fi )+ pwd + postCommand.mid( fi+5 ); } mParent->topLevelWidget()->setCaption ( i18n( "Writing back file ..." ) ); result = system ( postCommand ); qDebug("KSM::Sync:Writing back file result: %d ", result); if ( result != 0 ) { mParent->topLevelWidget()->setCaption ( i18n( "Writing back file result: " )+QString::number( result ) ); return; } else { mParent->topLevelWidget()->setCaption ( i18n( "Syncronization sucessfully completed" ) ); } } } return; } bool KSyncManager::edit_pisync_options() { QDialog dia( mParent, "dia", true ); dia.setCaption( i18n("Pi-Sync options for device: " ) +mCurrentSyncDevice ); QVBoxLayout lay ( &dia ); lay.setSpacing( 5 ); lay.setMargin( 3 ); QLabel lab1 ( i18n("Password for remote access:"), &dia); lay.addWidget( &lab1 ); QLineEdit le1 (&dia ); lay.addWidget( &le1 ); QLabel lab2 ( i18n("Remote IP address:"), &dia); lay.addWidget( &lab2 ); QLineEdit le2 (&dia ); lay.addWidget( &le2 ); QLabel lab3 ( i18n("Remote port number:"), &dia); lay.addWidget( &lab3 ); QLineEdit le3 (&dia ); lay.addWidget( &le3 ); QPushButton pb ( "OK", &dia); lay.addWidget( &pb ); connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) ); le1.setText( mPassWordPiSync ); le2.setText( mActiveSyncIP ); le3.setText( mActiveSyncPort ); if ( dia.exec() ) { mPassWordPiSync = le1.text(); mActiveSyncPort = le3.text(); mActiveSyncIP = le2.text(); return true; } return false; } bool KSyncManager::edit_sync_options() { QDialog dia( mParent, "dia", true ); dia.setCaption( i18n("Device: " ) +mCurrentSyncDevice ); QButtonGroup gr ( 1, Qt::Horizontal, i18n("Sync preferences"), &dia); QVBoxLayout lay ( &dia ); lay.setSpacing( 2 ); lay.setMargin( 3 ); lay.addWidget(&gr); QRadioButton loc ( i18n("Take local entry on conflict"), &gr ); QRadioButton rem ( i18n("Take remote entry on conflict"), &gr ); QRadioButton newest( i18n("Take newest entry on conflict"), &gr ); QRadioButton ask( i18n("Ask for every entry on conflict"), &gr ); QRadioButton f_loc( i18n("Force: Take local entry always"), &gr ); QRadioButton f_rem( i18n("Force: Take remote entry always"), &gr ); //QRadioButton both( i18n("Take both on conflict"), &gr ); QPushButton pb ( "OK", &dia); lay.addWidget( &pb ); connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) ); switch ( mSyncAlgoPrefs ) { case 0: loc.setChecked( true); break; case 1: rem.setChecked( true ); break; case 2: newest.setChecked( true); break; case 3: ask.setChecked( true); break; case 4: f_loc.setChecked( true); break; case 5: f_rem.setChecked( true); break; case 6: // both.setChecked( true); break; default: break; } if ( dia.exec() ) { mSyncAlgoPrefs = rem.isChecked()*1+newest.isChecked()*2+ ask.isChecked()*3+ f_loc.isChecked()*4+ f_rem.isChecked()*5;//+ both.isChecked()*6 ; return true; } return false; } QString KSyncManager::getPassword( ) { QString retfile = ""; QDialog dia ( mParent, "input-dialog", true ); QLineEdit lab ( &dia ); lab.setEchoMode( QLineEdit::Password ); QVBoxLayout lay( &dia ); lay.setMargin(7); lay.setSpacing(7); lay.addWidget( &lab); dia.setFixedSize( 230,50 ); dia.setCaption( i18n("Enter password") ); QPushButton pb ( "OK", &dia); lay.addWidget( &pb ); connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) ); dia.show(); int res = dia.exec(); if ( res ) retfile = lab.text(); dia.hide(); qApp->processEvents(); return retfile; } void KSyncManager::confSync() { static KSyncPrefsDialog* sp = 0; if ( ! sp ) { sp = new KSyncPrefsDialog( mParent, "syncprefs", true ); } sp->usrReadConfig(); #ifndef DESKTOP_VERSION sp->showMaximized(); #else sp->show(); #endif sp->exec(); QStringList oldSyncProfileNames = mSyncProfileNames; mSyncProfileNames = sp->getSyncProfileNames(); mLocalMachineName = sp->getLocalMachineName (); int ii; for ( ii = 0; ii < oldSyncProfileNames.count(); ++ii ) { if ( ! mSyncProfileNames.contains( oldSyncProfileNames[ii] ) ) mImplementation->removeSyncInfo( oldSyncProfileNames[ii] ); } QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) ); } void KSyncManager::syncKDE() { mSyncWithDesktop = true; emit save(); switch(mTargetApp) { case (KAPI): { #ifdef DESKTOP_VERSION QString command = qApp->applicationDirPath () + "/kdeabdump"; #else QString command = "kdeabdump"; #endif if ( ! QFile::exists ( command ) ) command = "kdeabdump"; QString fileName = QDir::homeDirPath ()+"/.kdeaddressbookdump.vcf"; system ( command.latin1()); if ( syncWithFile( fileName,true ) ) { if ( mWriteBackFile ) { command += " --read"; system ( command.latin1()); } } } break; case (KOPI): { #ifdef DESKTOP_VERSION QString command = qApp->applicationDirPath () + "/kdecaldump"; #else QString command = "kdecaldump"; #endif if ( ! QFile::exists ( command ) ) command = "kdecaldump"; QString fileName = QDir::homeDirPath ()+"/.kdecalendardump.ics"; system ( command.latin1()); if ( syncWithFile( fileName,true ) ) { if ( mWriteBackFile ) { command += " --read"; system ( command.latin1()); } } } break; case (PWMPI): break; default: qDebug("KSM::slotSyncMenu: invalid apptype selected"); break; } } void KSyncManager::syncSharp() { if ( ! syncExternalApplication("sharp") ) qDebug("KSM::ERROR sync sharp "); } bool KSyncManager::syncExternalApplication(QString resource) { emit save(); if ( mAskForPreferences ) if ( !edit_sync_options()) { mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") ); return false; } qDebug("KSM::Sync extern %s", resource.latin1()); bool syncOK = mImplementation->syncExternal(this, resource); return syncOK; } void KSyncManager::syncPhone() { syncExternalApplication("phone"); } void KSyncManager::showProgressBar(int percentage, QString caption, int total) { if (!bar->isVisible()) { bar->setCaption (caption); bar->setTotalSteps ( total ) ; bar->show(); } bar->raise(); bar->setProgress( percentage ); qApp->processEvents(); } void KSyncManager::hideProgressBar() { bar->hide(); qApp->processEvents(); } bool KSyncManager::isProgressBarCanceled() { return !bar->isVisible(); } QString KSyncManager::syncFileName() { QString fn = "tempfile"; switch(mTargetApp) { case (KAPI): fn = "tempsyncab.vcf"; break; case (KOPI): fn = "tempsynccal.ics"; break; case (PWMPI): fn = "tempsyncpw.pwm"; break; default: break; } #ifdef _WIN32_ return locateLocal( "tmp", fn ); #else return (QString( "/tmp/" )+ fn ); #endif } void KSyncManager::syncPi() { mIsKapiFile = true; mPisyncFinished = false; qApp->processEvents(); if ( mAskForPreferences ) if ( !edit_pisync_options()) { mParent->topLevelWidget()->setCaption( i18n("Syncing aborted. Nothing synced.") ); return; } bool ok; Q_UINT16 port = mActiveSyncPort.toUInt(&ok); if ( ! ok ) { mParent->topLevelWidget()->setCaption( i18n("Sorry, no valid port.Syncing cancelled.") ); return; } KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, port, mActiveSyncIP, this ); connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int )), this, SLOT(deleteCommandSocket(KCommandSocket*, int)) ); mParent->topLevelWidget()->setCaption( i18n("Sending request for remote file ...") ); commandSocket->readFile( syncFileName() ); } void KSyncManager::deleteCommandSocket(KCommandSocket*s, int state) { //enum { success, errorW, errorR, quiet }; if ( state == KCommandSocket::errorR ||state == KCommandSocket::errorTO ) { mParent->topLevelWidget()->setCaption( i18n("ERROR: Receiving remote file failed.") ); delete s; if ( state == KCommandSocket::errorR ) { KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this ); connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) ); commandSocket->sendStop(); } mPisyncFinished = true; return; } else if ( state == KCommandSocket::errorW ) { mParent->topLevelWidget()->setCaption( i18n("ERROR:Writing back file failed.") ); mPisyncFinished = true; } else if ( state == KCommandSocket::successR ) { QTimer::singleShot( 1, this , SLOT ( readFileFromSocket())); } else if ( state == KCommandSocket::successW ) { mParent->topLevelWidget()->setCaption( i18n("Pi-Sync succesful!") ); mPisyncFinished = true; } delete s; } void KSyncManager::readFileFromSocket() { QString fileName = syncFileName(); mParent->topLevelWidget()->setCaption( i18n("Remote file saved to temp file.") ); if ( ! syncWithFile( fileName , true ) ) { mParent->topLevelWidget()->setCaption( i18n("Syncing failed.") ); mPisyncFinished = true; return; } KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this ); connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) ); if ( mWriteBackFile ) commandSocket->writeFile( fileName ); else { commandSocket->sendStop(); mParent->topLevelWidget()->setCaption( i18n("Pi-Sync succesful!") ); mPisyncFinished = true; } } KServerSocket:: KServerSocket ( QString pw, Q_UINT16 port, int backlog, QObject * parent, const char * name ) : QServerSocket( port, backlog, parent, name ) { mPassWord = pw; mSocket = 0; mSyncActionDialog = 0; blockRC = false; }; void KServerSocket::newConnection ( int socket ) { // qDebug("KServerSocket:New connection %d ", socket); if ( mSocket ) { qDebug("KSS::newConnection Socket deleted! "); delete mSocket; mSocket = 0; } mSocket = new QSocket( this ); connect( mSocket , SIGNAL(readyRead()), this, SLOT(readClient()) ); connect( mSocket , SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) ); mSocket->setSocket( socket ); } void KServerSocket::discardClient() { //qDebug(" KServerSocket::discardClient()"); if ( mSocket ) { delete mSocket; mSocket = 0; } //emit endConnect(); } void KServerSocket::readClient() { if ( blockRC ) return; if ( mSocket == 0 ) { qDebug("ERROR::KSS::readClient(): mSocket == 0 "); return; } //qDebug("KServerSocket::readClient()"); if ( mSocket->canReadLine() ) { QString line = mSocket->readLine(); //qDebug("KServerSocket readline: %s ", line.latin1()); QStringList tokens = QStringList::split( QRegExp("[ \r\n][ \r\n]*"), line ); if ( tokens[0] == "GET" ) { if ( tokens[1] == mPassWord ) { //emit sendFile( mSocket ); bool ok = false; QDateTime dt = KGlobal::locale()->readDateTime( tokens[2], KLocale::ISODate, &ok); if ( ok ) { KSyncManager::mRequestedSyncEvent = dt; } else KSyncManager::mRequestedSyncEvent = QDateTime(); send_file(); } else { KMessageBox::error( 0, i18n("Got send file request\nwith invalid password")); //qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() ); } } if ( tokens[0] == "PUT" ) { if ( tokens[1] == mPassWord ) { //emit getFile( mSocket ); blockRC = true; get_file(); } else { KMessageBox::error( 0, i18n("Got receive file request\nwith invalid password")); //qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() ); } } if ( tokens[0] == "STOP" ) { //emit endConnect(); end_connect(); } } } void KServerSocket::end_connect() { delete mSyncActionDialog; mSyncActionDialog = 0; } void KServerSocket::send_file() { //qDebug("MainWindow::sendFile(QSocket* s) "); if ( mSyncActionDialog ) delete mSyncActionDialog; mSyncActionDialog = new QDialog ( 0, "input-dialog", true ); mSyncActionDialog->setCaption(i18n("Received sync request")); QLabel* label = new QLabel( i18n("Synchronizing from remote ...\n\nDo not use this application!\n\nIf syncing fails\nyou can close this dialog."), mSyncActionDialog ); label->setAlignment ( Qt::AlignHCenter ); QVBoxLayout* lay = new QVBoxLayout( mSyncActionDialog ); lay->addWidget( label); lay->setMargin(7); lay->setSpacing(7); if ( KSyncManager::mRequestedSyncEvent.isValid() ) { int secs = QDateTime::currentDateTime().secsTo( KSyncManager::mRequestedSyncEvent ); if ( secs < 0 ) secs = secs * (-1); if ( secs > 30 ) //if ( true ) { QString warning = i18n("Clock skew of\nsyncing devices\nis %1 seconds!").arg( secs ); QLabel* label = new QLabel( warning, mSyncActionDialog ); label->setAlignment ( Qt::AlignHCenter ); lay->addWidget( label); if ( secs > 180 ) { if ( secs > 300 ) { if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(0, i18n("The clocks of the syncing\ndevices have a difference\n of more than 5 minutes.\nPlease adjust your clocks.\n<b>You may get wrong syncing results!<\b>\nPlease confirm synchronization!"), i18n("High clock skew!"),i18n("Synchronize!"))) { qDebug("KSS::Sync cancelled ,cs"); return ; } } QFont f = label->font(); f.setPointSize ( f.pointSize() *2 ); f. setBold (true ); QLabel* label = new QLabel( warning, mSyncActionDialog ); label->setFont( f ); warning = i18n("ADJUST\nYOUR\nCLOCKS!"); label->setText( warning ); label->setAlignment ( Qt::AlignHCenter ); lay->addWidget( label); mSyncActionDialog->setFixedSize( 230, 300); } else { mSyncActionDialog->setFixedSize( 230, 200); } } else { mSyncActionDialog->setFixedSize( 230, 120); } } else mSyncActionDialog->setFixedSize( 230, 120); mSyncActionDialog->show(); mSyncActionDialog->raise(); emit request_file(); qApp->processEvents(); QString fileName = mFileName; QFile file( fileName ); if (!file.open( IO_ReadOnly ) ) { delete mSyncActionDialog; mSyncActionDialog = 0; qDebug("KSS::error open sync file: %s ", fileName.latin1()); mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( discardClient())); return ; } mSyncActionDialog->setCaption( i18n("Sending file...") ); QTextStream ts( &file ); ts.setEncoding( QTextStream::Latin1 ); QTextStream os( mSocket ); os.setEncoding( QTextStream::Latin1 ); while ( ! ts.atEnd() ) { os << ts.readLine() << "\r\n"; } //os << ts.read(); file.close(); mSyncActionDialog->setCaption( i18n("Waiting for synced file...") ); mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( discardClient())); } void KServerSocket::get_file() { mSyncActionDialog->setCaption( i18n("Receiving synced file...") ); piTime.start(); piFileString = ""; QTimer::singleShot( 1, this , SLOT (readBackFileFromSocket( ) )); } void KServerSocket::readBackFileFromSocket() { //qDebug("readBackFileFromSocket() %d ", piTime.elapsed ()); while ( mSocket->canReadLine () ) { piTime.restart(); QString line = mSocket->readLine (); piFileString += line; //qDebug("readline: %s ", line.latin1()); mSyncActionDialog->setCaption( i18n("Received %1 bytes").arg( piFileString.length() ) ); } if ( piTime.elapsed () < 3000 ) { // wait for more //qDebug("waitformore "); QTimer::singleShot( 100, this , SLOT (readBackFileFromSocket( ) )); return; } QString fileName = mFileName; QFile file ( fileName ); if (!file.open( IO_WriteOnly ) ) { delete mSyncActionDialog; mSyncActionDialog = 0; qDebug("KSS:Error open read back file "); piFileString = ""; emit file_received( false ); blockRC = false; return ; } // mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1)); QTextStream ts ( &file ); ts.setEncoding( QTextStream::Latin1 ); mSyncActionDialog->setCaption( i18n("Writing file to disk...") ); ts << piFileString; mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( discardClient())); file.close(); piFileString = ""; emit file_received( true ); delete mSyncActionDialog; mSyncActionDialog = 0; blockRC = false; } KCommandSocket::KCommandSocket ( QString password, Q_UINT16 port, QString host, QObject * parent, const char * name ): QObject( parent, name ) { mPassWord = password; mSocket = 0; mPort = port; mHost = host; mRetVal = quiet; mTimerSocket = new QTimer ( this ); connect( mTimerSocket, SIGNAL ( timeout () ), this, SLOT ( deleteSocket() ) ); } void KCommandSocket::readFile( QString fn ) { if ( !mSocket ) { mSocket = new QSocket( this ); connect( mSocket, SIGNAL(readyRead()), this, SLOT(startReadFileFromSocket()) ); connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) ); } mFileString = ""; mFileName = fn; mFirst = true; mSocket->connectToHost( mHost, mPort ); QTextStream os( mSocket ); os.setEncoding( QTextStream::Latin1 ); QString curDt = " " +KGlobal::locale()->formatDateTime(QDateTime::currentDateTime().addSecs(-1),true, true,KLocale::ISODate ); os << "GET " << mPassWord << curDt <<"\r\n"; mTimerSocket->start( 300000 ); } void KCommandSocket::writeFile( QString fileName ) { if ( !mSocket ) { mSocket = new QSocket( this ); connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) ); connect( mSocket, SIGNAL(connected ()), this, SLOT(writeFileToSocket()) ); } mFileName = fileName ; mSocket->connectToHost( mHost, mPort ); } void KCommandSocket::writeFileToSocket() { QFile file2( mFileName ); if (!file2.open( IO_ReadOnly ) ) { mRetVal= errorW; mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( deleteSocket())); return ; } QTextStream ts2( &file2 ); ts2.setEncoding( QTextStream::Latin1 ); QTextStream os2( mSocket ); os2.setEncoding( QTextStream::Latin1 ); os2 << "PUT " << mPassWord << "\r\n";; while ( ! ts2.atEnd() ) { os2 << ts2.readLine() << "\r\n"; } mRetVal= successW; file2.close(); mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( deleteSocket())); } void KCommandSocket::sendStop() { if ( !mSocket ) { mSocket = new QSocket( this ); connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) ); } mSocket->connectToHost( mHost, mPort ); QTextStream os2( mSocket ); os2.setEncoding( QTextStream::Latin1 ); os2 << "STOP\r\n"; mSocket->close(); if ( mSocket->state() == QSocket::Idle ) QTimer::singleShot( 10, this , SLOT ( deleteSocket())); } void KCommandSocket::startReadFileFromSocket() { if ( ! mFirst ) return; mFirst = false; mTimerSocket->stop(); mFileString = ""; mTime.start(); QTimer::singleShot( 1, this , SLOT (readFileFromSocket( ) )); } void KCommandSocket::readFileFromSocket() { //qDebug("readBackFileFromSocket() %d ", mTime.elapsed ()); while ( mSocket->canReadLine () ) { mTime.restart(); QString line = mSocket->readLine (); mFileString += line; //qDebug("readline: %s ", line.latin1()); } if ( mTime.elapsed () < 3000 ) { // wait for more //qDebug("waitformore "); QTimer::singleShot( 100, this , SLOT (readFileFromSocket( ) )); return; } QString fileName = mFileName; QFile file ( fileName ); if (!file.open( IO_WriteOnly ) ) { mFileString = ""; mRetVal = errorR; qDebug("KSS:Error open temp sync file for writing: %s",fileName.latin1() ); deleteSocket(); return ; } // mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1)); QTextStream ts ( &file ); ts.setEncoding( QTextStream::Latin1 ); ts << mFileString; file.close(); mFileString = ""; mRetVal = successR; mSocket->close(); // if state is not idle, deleteSocket(); is called via // connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) ); if ( mSocket->state() == QSocket::Idle ) deleteSocket(); } void KCommandSocket::deleteSocket() { //qDebug("KCommandSocket::deleteSocket() "); if ( mTimerSocket->isActive () ) { mTimerSocket->stop(); mRetVal = errorTO; qDebug("KCS::Connection to remote host timed out"); if ( mSocket ) { mSocket->close(); //if ( mSocket->state() == QSocket::Idle ) // deleteSocket(); delete mSocket; mSocket = 0; } KMessageBox::error( 0, i18n("Connection to remote\nhost timed out!\nDid you forgot to enable\nsyncing on remote host? ")); emit commandFinished( this, mRetVal ); return; } //qDebug("KCommandSocket::deleteSocket() %d", mRetVal ); if ( mSocket) delete mSocket; mSocket = 0; emit commandFinished( this, mRetVal ); } diff --git a/libkdepim/phoneaccess.cpp b/libkdepim/phoneaccess.cpp index e24ad9e..89db22b 100644 --- a/libkdepim/phoneaccess.cpp +++ b/libkdepim/phoneaccess.cpp @@ -1,216 +1,216 @@ /* This file is part of libkdepim. Copyright (c) 2004 Lutz Rogowski <rogowski@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qstring.h> #include <qapplication.h> #include <qptrlist.h> #include <qregexp.h> #include <qfile.h> #include <qlabel.h> #include <qtextstream.h> #include <qtextcodec.h> #include <qdir.h> #include <kmessagebox.h> #include <stdlib.h> #include "phoneaccess.h" void PhoneAccess::writeConfig( QString device, QString connection, QString model ) { #ifdef _WIN32_ QString fileName = qApp->applicationDirPath () +"\\gammurc"; #else QString fileName = QDir::homeDirPath() +"/.gammurc"; #endif //qDebug("save %d ", load ); QString content = "[gammu]\n";; bool write = false; bool addPort = true, addConnection = true, addModel = true; QFile file( fileName ); if ( QFile::exists( fileName) ) { if (!file.open( IO_ReadOnly ) ) { qDebug("Error: cannot open %s ", fileName.latin1() ); return; } QString line; while ( file.readLine( line, 1024 ) > 0 ) { //qDebug("*%s* ", line.latin1() ); if ( line.left(7 ) == "[gammu]" ) { ; } else if ( line.left(4 ) == "port" ) { if ( line == "port = " + device+"\n" ) { content += line ; addPort = false; //qDebug("port found" ); } } else if ( line.left(5 ) == "model" ) { if ( line == "model = " + model +"\n") { content += line ; addModel = false; //qDebug("model found" ); } } else if ( line.left( 10 ) == "connection" ) { if ( line == "connection = " + connection +"\n") { addConnection = false; content += line ; //qDebug("con found" ); } } else { content += line ; } } file.close(); } else { if ( ! connection.isEmpty() ) { addConnection = true; } if ( ! device.isEmpty() ) { addPort = true; } if ( ! model.isEmpty() ) { addModel = true; } } if ( addConnection ) { write = true; content += "connection = "; content += connection; content += "\n"; } if ( addPort ) { write = true; content += "port = "; content += device; content += "\n"; } if ( addModel ) { write = true; content += "model = "; content += model; content += "\n"; } if ( write ) { if (!file.open( IO_WriteOnly ) ) { qDebug("Error: cannot write file %s ", fileName.latin1() ); return; } qDebug("Writing file %s ", fileName.latin1() ); QTextStream ts( &file ); ts << content ; file.close(); } } bool PhoneAccess::writeToPhone( QString fileName) { #ifdef DESKTOP_VERSION #ifdef _WIN32_ QString command ="kammu --restore " + fileName ; #else QString command ="./kammu --restore " + fileName ; #endif #else QString command ="kammu --restore " + fileName ; #endif int ret = 1; while ( ret != 0 ) { QLabel* status = new QLabel( i18n(" This may take 1-3 minutes!"), 0 ); int w = 235; int h = status->sizeHint().height()+20 ; int dw = QApplication::desktop()->width(); int dh = QApplication::desktop()->height(); if ( dw > 310 ) w = 310; status->setCaption(i18n("Writing to phone...") ); status->setGeometry( (dw-w)/2, (dh - h )/2 ,w,h ); status->show(); status->raise(); status->update(); qApp->processEvents(); status->update(); qApp->processEvents(); ret = system ( command.latin1()); delete status; qApp->processEvents(); if ( ret ) { qDebug("Error S::command returned %d.", ret); int retval = KMessageBox::warningContinueCancel(0, i18n("Error accessing device!\nPlease turn on connection\nand retry!"),i18n("KDE/Pim phone access"),i18n("Retry"),i18n("Cancel")); if ( retval != KMessageBox::Continue ) return false; } } return true; } bool PhoneAccess::readFromPhone( QString fileName) { #ifdef DESKTOP_VERSION #ifdef _WIN32_ QString command ="kammu --backup " + fileName + " -yes" ; #else QString command ="./kammu --backup " + fileName + " -yes" ; #endif #else QString command ="kammu --backup " + fileName + " -yes" ; #endif - int ret; + int ret = 1; while ( ret != 0 ) { QLabel* status = new QLabel( i18n(" This may take 1-3 minutes!"), 0 ); int w = 235; int h = status->sizeHint().height()+20 ; int dw = QApplication::desktop()->width(); int dh = QApplication::desktop()->height(); if ( dw > 310 ) w = 310; status->setCaption(i18n("Reading from phone...") ); status->setGeometry( (dw-w)/2, (dh - h )/2 ,w,h ); status->show(); status->raise(); status->update(); qApp->processEvents(); status->update(); qApp->processEvents(); ret = system ( command.latin1() ); delete status; qApp->processEvents(); if ( ret ) { qDebug("Error reading from phone:Command returned %d", ret); int retval = KMessageBox::warningContinueCancel(0, i18n("Error accessing device!\nPlease turn on connection\nand retry!"),i18n("KDE/Pim phone access"),i18n("Retry"),i18n("Cancel")); if ( retval != KMessageBox::Continue ) return false; } } qApp->processEvents(); return true; } diff --git a/microkde/kapplication.cpp b/microkde/kapplication.cpp index 21aa0a4..f05b91b 100644 --- a/microkde/kapplication.cpp +++ b/microkde/kapplication.cpp @@ -1,110 +1,111 @@ #include <stdlib.h> #include <stdio.h> #include "kapplication.h" #include "ktextedit.h" #include <qapplication.h> #include <qstring.h> #include <qfile.h> #include <qtextstream.h> #include <qdialog.h> #include <qlayout.h> #include <qtextbrowser.h> int KApplication::random() { return rand(); } //US QString KApplication::randomString(int length) { if (length <=0 ) return QString::null; QString str; while (length--) { int r=random() % 62; r+=48; if (r>57) r+=7; if (r>90) r+=6; str += char(r); // so what if I work backwards? } return str; } int KApplication::execDialog( QDialog* d ) { if (QApplication::desktop()->width() <= 640 ) d->showMaximized(); else ;//d->resize( 800, 600 ); return d->exec(); } void KApplication::showLicence() { KApplication::showFile( "KDE-Pim/Pi licence", "kdepim/licence.txt" ); } void KApplication::showFile(QString caption, QString fn) { QString text; QString fileName; #ifndef DESKTOP_VERSION fileName = getenv("QPEDIR"); fileName += "/pics/" + fn ; #else fileName = qApp->applicationDirPath () + "/" + fn; #endif QFile file( fileName ); if (!file.open( IO_ReadOnly ) ) { return ; } QTextStream ts( &file ); text = ts.read(); file.close(); KApplication::showText( caption, text ); } bool KApplication::convert2latin1(QString fileName) { QString text; QFile file( fileName ); if (!file.open( IO_ReadOnly ) ) { return false; } QTextStream ts( &file ); ts.setEncoding( QTextStream::UnicodeUTF8 ); text = ts.read(); file.close(); if (!file.open( IO_WriteOnly ) ) { return false; } QTextStream tsIn( &file ); tsIn.setEncoding( QTextStream::Latin1 ); tsIn << text.latin1(); - file.close(); + file.close(); + return true; } void KApplication::showText(QString caption, QString text) { QDialog dia( 0, "name", true ); ; dia.setCaption( caption ); QVBoxLayout* lay = new QVBoxLayout( &dia ); lay->setSpacing( 3 ); lay->setMargin( 3 ); KTextEdit tb ( &dia ); tb.setWordWrap( QMultiLineEdit::WidgetWidth ); lay->addWidget( &tb ); tb.setText( text ); #ifdef DESKTOP_VERSION dia.resize( 640, 480); #else dia.showMaximized(); #endif dia.exec(); } diff --git a/microkde/kdecore/klibloader.cpp b/microkde/kdecore/klibloader.cpp index 1394154..6d0475a 100644 --- a/microkde/kdecore/klibloader.cpp +++ b/microkde/kdecore/klibloader.cpp @@ -1,661 +1,653 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Torben Weis <weis@kde.org> Copyright (C) 2000 Michael Matz <matz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //US #include <config.h> #include <qclipboard.h> #include <qfile.h> #include <qtimer.h> #include <qobjectdict.h> #include <qwidgetlist.h> #include <qwidget.h> #include "kapplication.h" #include "klibloader.h" #include "kstandarddirs.h" #include "kdebug.h" #include "klocale.h" /*US #ifndef NDEBUG #include "ltdl.h" #endif */ //US do everything through qlibrary #ifndef DESKTOP_VERSION #include <qpe/qpeapplication.h> #include <qtopia/qlibrary.h> #else #include <qlibrary.h> #endif template class QAsciiDict<KLibrary>; #include <stdlib.h> //getenv /*US #if HAVE_DLFCN_H # include <dlfcn.h> #endif #ifdef RTLD_GLOBAL # define LT_GLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_GLOBAL DL_GLOBAL # endif #endif #ifndef LT_GLOBAL # define LT_GLOBAL 0 #endif */ /*US extern "C" { extern int lt_dlopen_flag; } */ KLibFactory::KLibFactory( QObject* parent, const char* name ) : QObject( parent, name ) { } KLibFactory::~KLibFactory() { // kdDebug(150) << "Deleting KLibFactory " << this << endl; } QObject* KLibFactory::create( QObject* parent, const char* name, const char* classname, const QStringList &args ) { QObject* obj = createObject( parent, name, classname, args ); if ( obj ) emit objectCreated( obj ); return obj; } QObject* KLibFactory::createObject( QObject*, const char*, const char*, const QStringList &) { return 0; } // ----------------------------------------------- //US KLibrary::KLibrary( const QString& libname, const QString& filename, void * handle ) KLibrary::KLibrary( const QString& libname, const QString& filename, QLibrary* handle ) { /* Make sure, we have a KLibLoader */ (void) KLibLoader::self(); m_libname = libname; m_filename = filename; m_handle = handle; m_factory = 0; m_timer = 0; } KLibrary::~KLibrary() { // kdDebug(150) << "Deleting KLibrary " << this << " " << m_libname << endl; if ( m_timer && m_timer->isActive() ) m_timer->stop(); // If any object is remaining, delete if ( m_objs.count() > 0 ) { QPtrListIterator<QObject> it( m_objs ); for ( ; it.current() ; ++it ) { kdDebug(150) << "Factory still has object " << it.current() << " " << it.current()->name () << " Library = " << m_libname << endl; disconnect( it.current(), SIGNAL( destroyed() ), this, SLOT( slotObjectDestroyed() ) ); } m_objs.setAutoDelete(true); m_objs.clear(); } if ( m_factory ) { // kdDebug(150) << " ... deleting the factory " << m_factory << endl; delete m_factory; } } QString KLibrary::name() const { return m_libname; } QString KLibrary::fileName() const { return m_filename; } KLibFactory* KLibrary::factory() { if ( m_factory ) return m_factory; QCString symname; symname.sprintf("init_%s", name().latin1() ); void* sym = symbol( symname ); if ( !sym ) { qDebug("KLibrary: The library %s does not offer an %s function", name().latin1(), symname.data()); #ifndef NDEBUG //US qDebug("KLibrary: errorcode: %s", lt_dlerror()); #endif kdWarning(150) << "KLibrary: The library " << name().latin1() << " does not offer an init_" << name().latin1() << " function" << endl; return 0; } typedef KLibFactory* (*t_func)(); t_func func = (t_func)sym; m_factory = func(); if( !m_factory ) { kdWarning(150) << "KLibrary: The library " << name() << " does not offer a KDE compatible factory" << endl; return 0; } connect( m_factory, SIGNAL( objectCreated( QObject * ) ), this, SLOT( slotObjectCreated( QObject * ) ) ); return m_factory; } void* KLibrary::symbol( const char* symname ) const { //US void* sym = lt_dlsym( (lt_dlhandle) m_handle, symname ); void* sym = m_handle->resolve( symname ); if ( !sym ) { //US kdWarning(150) << "KLibrary: " << lt_dlerror() << endl; return 0; } return sym; } bool KLibrary::hasSymbol( const char* symname ) const { //US void* sym = lt_dlsym( (lt_dlhandle) m_handle, symname ); void* sym = m_handle->resolve( symname ); return (sym != 0L ); } void KLibrary::unload() const { if (KLibLoader::s_self) KLibLoader::s_self->unloadLibrary(QFile::encodeName(name())); } void KLibrary::slotObjectCreated( QObject *obj ) { if ( !obj ) return; if ( m_timer && m_timer->isActive() ) m_timer->stop(); if ( m_objs.containsRef( obj ) ) return; // we know this object already connect( obj, SIGNAL( destroyed() ), this, SLOT( slotObjectDestroyed() ) ); m_objs.append( obj ); } void KLibrary::slotObjectDestroyed() { m_objs.removeRef( sender() ); if ( m_objs.count() == 0 ) { // kdDebug(150) << "KLibrary: shutdown timer for " << name() << " started!" // << endl; if ( !m_timer ) { m_timer = new QTimer( this, "klibrary_shutdown_timer" ); connect( m_timer, SIGNAL( timeout() ), this, SLOT( slotTimeout() ) ); } // as long as it's not stable make the timeout short, for debugging // pleasure (matz) //m_timer->start( 1000*60, true ); m_timer->start( 1000*10, true ); } } void KLibrary::slotTimeout() { if ( m_objs.count() != 0 ) return; /* Don't go through KLibLoader::unloadLibrary(), because that uses the ref counter, but this timeout means to unconditionally close this library The destroyed() signal will take care to remove us from all lists. */ delete this; } // ------------------------------------------------- /* This helper class is needed, because KLibraries can go away without being unloaded. So we need some info about KLibraries even after its death. */ class KLibWrapPrivate { public: //US KLibWrapPrivate(KLibrary *l, lt_dlhandle h); KLibWrapPrivate(KLibrary *l, QLibrary* h); KLibrary *lib; enum {UNKNOWN, UNLOAD, DONT_UNLOAD} unload_mode; int ref_count; //US lt_dlhandle handle; QLibrary *handle; QString name; QString filename; }; //US KLibWrapPrivate::KLibWrapPrivate(KLibrary *l, lt_dlhandle h) KLibWrapPrivate::KLibWrapPrivate(KLibrary *l, QLibrary* h) : lib(l), ref_count(1), handle(h), name(l->name()), filename(l->fileName()) { unload_mode = UNKNOWN; /*US if (lt_dlsym(handle, "__kde_do_not_unload") != 0) { // kdDebug(150) << "Will not unload " << name << endl; unload_mode = DONT_UNLOAD; } else if (lt_dlsym(handle, "__kde_do_unload") != 0) { unload_mode = UNLOAD; } */ //US use instead: if (h->resolve("__kde_do_not_unload") != 0) { // kdDebug(150) << "Will not unload " << name << endl; unload_mode = DONT_UNLOAD; } else if (h->resolve("__kde_do_unload") != 0) { unload_mode = UNLOAD; } } class KLibLoaderPrivate { public: QPtrList<KLibWrapPrivate> loaded_stack; QPtrList<KLibWrapPrivate> pending_close; enum {UNKNOWN, UNLOAD, DONT_UNLOAD} unload_mode; QString errorMessage; }; KLibLoader* KLibLoader::s_self = 0; KLibLoader* KLibLoader::self() { if ( !s_self ) s_self = new KLibLoader; return s_self; } void KLibLoader::cleanUp() { if ( !s_self ) return; delete s_self; s_self = 0; } KLibLoader::KLibLoader( QObject* parent, const char* name ) : QObject( parent, name ) { s_self = this; d = new KLibLoaderPrivate; //US lt_dlinit(); d->unload_mode = KLibLoaderPrivate::UNKNOWN; if (getenv("KDE_NOUNLOAD") != 0) d->unload_mode = KLibLoaderPrivate::DONT_UNLOAD; else if (getenv("KDE_DOUNLOAD") != 0) d->unload_mode = KLibLoaderPrivate::UNLOAD; d->loaded_stack.setAutoDelete( true ); } KLibLoader::~KLibLoader() { // kdDebug(150) << "Deleting KLibLoader " << this << " " << name() << endl; QAsciiDictIterator<KLibWrapPrivate> it( m_libs ); for (; it.current(); ++it ) { kdDebug(150) << "The KLibLoader contains the library " << it.current()->name << " (" << it.current()->lib << ")" << endl; d->pending_close.append(it.current()); } close_pending(0); delete d; } //static QString KLibLoader::findLibrary( const char * name/*US , const KInstance * instance*/ ) { QCString libname( name ); // only append ".la" if there is no extension // this allows to load non-libtool libraries as well // (mhk, 20000228) int pos = libname.findRev('/'); if (pos < 0) pos = 0; /*US if (libname.find('.', pos) < 0) { libname += ".la"; } */ //US in the microedition we work only with shared libraries. if (libname.find('.', pos) < 0) { #ifdef _WIN32_ libname += ".dll"; #else libname += ".so"; #endif } // only look up the file if it is not an absolute filename // (mhk, 20000228) QString libfile; if (libname[0] == '/') libfile = libname; else { //US at this point the libname must exist as real filesname. No expansions will be made later // in findResources. Because of that we prepend the lib prefix here to the name //US I add also the "lib" prefix. I do not how could this could have worked before without it? #ifndef _WIN32_ libname.insert(pos, "lib"); #endif //US libfile = instance->dirs()->findResource( "module", libname ); //qDebug("libname = %s ",libname.data() ); libfile = KGlobal::dirs()->findResource( "module", libname ); //qDebug("libfile = %s ",libfile.latin1() ); if ( libfile.isEmpty() ) { //US libfile = instance->dirs()->findResource( "lib", libname ); libfile = KGlobal::dirs()->findResource( "lib", libname ); //qDebug("libfile2 = %s ",libfile.latin1() ); #ifndef NDEBUG if ( !libfile.isEmpty() && libname.left(3) == "lib" ) // don't warn for kdeinit modules kdDebug(150) << "library " << libname << " not found under 'module' but under 'lib'" << endl; #endif } if ( libfile.isEmpty() ) { #ifndef NDEBUG kdDebug(150) << "library=" << libname << ": No file names " << libname.data() << " found in paths." << endl; self()->d->errorMessage = i18n("Library files for \"%1\" not found in paths").arg(libname); qDebug("KLibLoader::library could not find library: %s", libname.data()); #endif } else self()->d->errorMessage = QString::null; } //qDebug("return libfile = %s ",libfile.latin1() ); return libfile; } KLibrary* KLibLoader::globalLibrary( const char *name ) { KLibrary *tmp; /*US int olt_dlopen_flag = lt_dlopen_flag; lt_dlopen_flag |= LT_GLOBAL; kdDebug(150) << "Loading the next library global with flag " << lt_dlopen_flag << "." << endl; */ tmp = library(name); /*US lt_dlopen_flag = olt_dlopen_flag; */ return tmp; } KLibrary* KLibLoader::library( const char *name ) { if (!name) return 0; KLibWrapPrivate* wrap = m_libs[name]; if (wrap) { /* Nothing to do to load the library. */ wrap->ref_count++; return wrap->lib; } /* Test if this library was loaded at some time, but got unloaded meanwhile, whithout being dlclose()'ed. */ QPtrListIterator<KLibWrapPrivate> it(d->loaded_stack); for (; it.current(); ++it) { if (it.current()->name == name) wrap = it.current(); } if (wrap) { d->pending_close.removeRef(wrap); if (!wrap->lib) { /* This lib only was in loaded_stack, but not in m_libs. */ wrap->lib = new KLibrary( name, wrap->filename, wrap->handle ); } wrap->ref_count++; } else { QString libfile = findLibrary( name ); if ( libfile.isEmpty() ) return 0; #ifdef DESKTOP_VERSION QLibrary *qlib = new QLibrary( libfile.latin1() ); #else QLibrary *qlib = new QLibrary( libfile.latin1(), QLibrary::Immediately ); #endif //US lt_dlhandle handle = lt_dlopen( libfile.latin1() ); //US if ( !handle ) if ( !qlib ) { -//US const char* errmsg = lt_dlerror(); - char* errmsg; - sprintf(errmsg, "KLibLoader::library could not load library: %s", libfile.latin1()); - qDebug(errmsg); - - if(errmsg) - d->errorMessage = QString::fromLatin1(errmsg); - else - d->errorMessage = QString::null; - kdWarning(150) << "library=" << name << ": file=" << libfile << ": " << d->errorMessage << endl; - return 0; + qDebug( "KLibLoader::library could not load library: %s", libfile.latin1()); + d->errorMessage = QString::null; + return 0; } else d->errorMessage = QString::null; KLibrary *lib = new KLibrary( name, libfile, qlib ); wrap = new KLibWrapPrivate(lib, qlib); d->loaded_stack.prepend(wrap); } m_libs.insert( name, wrap ); connect( wrap->lib, SIGNAL( destroyed() ), this, SLOT( slotLibraryDestroyed() ) ); return wrap->lib; } QString KLibLoader::lastErrorMessage() const { return d->errorMessage; } void KLibLoader::unloadLibrary( const char *libname ) { KLibWrapPrivate *wrap = m_libs[ libname ]; if (!wrap) return; if (--wrap->ref_count) return; // kdDebug(150) << "closing library " << libname << endl; m_libs.remove( libname ); disconnect( wrap->lib, SIGNAL( destroyed() ), this, SLOT( slotLibraryDestroyed() ) ); close_pending( wrap ); } KLibFactory* KLibLoader::factory( const char* name ) { KLibrary* lib = library( name ); if ( !lib ) return 0; return lib->factory(); } void KLibLoader::slotLibraryDestroyed() { const KLibrary *lib = static_cast<const KLibrary *>( sender() ); QAsciiDictIterator<KLibWrapPrivate> it( m_libs ); for (; it.current(); ++it ) if ( it.current()->lib == lib ) { KLibWrapPrivate *wrap = it.current(); wrap->lib = 0; /* the KLibrary object is already away */ m_libs.remove( it.currentKey() ); close_pending( wrap ); return; } } void KLibLoader::close_pending(KLibWrapPrivate *wrap) { if (wrap && !d->pending_close.containsRef( wrap )) d->pending_close.append( wrap ); /* First delete all KLibrary objects in pending_close, but _don't_ unload the DSO behind it. */ QPtrListIterator<KLibWrapPrivate> it(d->pending_close); for (; it.current(); ++it) { wrap = it.current(); if (wrap->lib) { disconnect( wrap->lib, SIGNAL( destroyed() ), this, SLOT( slotLibraryDestroyed() ) ); delete wrap->lib; wrap->lib = 0; } } if (d->unload_mode == KLibLoaderPrivate::DONT_UNLOAD) return; bool deleted_one = false; while ((wrap = d->loaded_stack.first())) { /* Let's first see, if we want to try to unload this lib. If the env. var KDE_DOUNLOAD is set, we try to unload every lib. If not, we look at the lib itself, and unload it only, if it exports the symbol __kde_do_unload. */ if (d->unload_mode != KLibLoaderPrivate::UNLOAD && wrap->unload_mode != KLibWrapPrivate::UNLOAD) break; /* Now ensure, that the libs are only unloaded in the reverse direction they were loaded. */ if (!d->pending_close.containsRef( wrap )) { if (!deleted_one) /* Only diagnose, if we really haven't deleted anything. */ // kdDebug(150) << "try to dlclose " << wrap->name << ": not yet" << endl; break; } // kdDebug(150) << "try to dlclose " << wrap->name << ": yes, done." << endl; #if 0 #ifndef Q_WS_QWS if ( !deleted_one ) { /* Only do the hack once in this loop. WABA: *HACK* We need to make sure to clear the clipboard before unloading a DSO because the DSO could have defined an object derived from QMimeSource and placed that on the clipboard. */ /*kapp->clipboard()->clear();*/ /* Well.. let's do something more subtle... convert the clipboard context to text. That should be safe as it only uses objects defined by Qt. */ QWidgetList *widgetlist = QApplication::topLevelWidgets(); QWidget *co = widgetlist->first(); while (co) { if (qstrcmp(co->name(), "internal clipboard owner") == 0) { if (XGetSelectionOwner(co->x11Display(), XA_PRIMARY) == co->winId()) kapp->clipboard()->setText(kapp->clipboard()->text()); break; } co = widgetlist->next(); } delete widgetlist; } #else // FIXME(E): Implement in Qt Embedded #endif #endif // 0 deleted_one = true; //US lt_dlclose(wrap->handle); wrap->handle->unload(); d->pending_close.removeRef(wrap); /* loaded_stack is AutoDelete, so wrap is freed */ d->loaded_stack.remove(); } } void KLibLoader::virtual_hook( int, void* ) { /*BASE::virtual_hook( id, data );*/ } void KLibFactory::virtual_hook( int, void* ) { /*BASE::virtual_hook( id, data );*/ } //US #include "klibloader.moc" diff --git a/microkde/kdeui/ktoolbar.cpp b/microkde/kdeui/ktoolbar.cpp index 1ad1728..09ad0c8 100644 --- a/microkde/kdeui/ktoolbar.cpp +++ b/microkde/kdeui/ktoolbar.cpp @@ -1,2266 +1,2266 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Reginald Stadlbauer (reggie@kde.org) (C) 1997, 1998 Stephan Kulow (coolo@kde.org) (C) 1997, 1998 Mark Donohoe (donohoe@kde.org) (C) 1997, 1998 Sven Radej (radej@kde.org) (C) 1997, 1998 Matthias Ettrich (ettrich@kde.org) (C) 1999 Chris Schlaeger (cs@kde.org) (C) 1999 Kurt Granroth (granroth@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef KDE_USE_FINAL #undef Always #include <qdockwindow.h> #endif #include "ktoolbar.h" #include "kmainwindow.h" #include <string.h> #include <qpainter.h> #include <qtooltip.h> #include <qdrawutil.h> #include <qstring.h> #include <qrect.h> #include <qobjectlist.h> #include <qtimer.h> #include <qstyle.h> #include <qapplication.h> //US #include <config.h> #include "klineedit.h" #include "kseparator.h" #include <klocale.h> #include <kapplication.h> #include <kaction.h> #include <kstdaction.h> #include <kglobal.h> #include <kconfig.h> #include <kiconloader.h> #include <kcombobox.h> //US #include <kpopupmenu.h> //US #include <kanimwidget.h> //US #include <kipc.h> //US #include <kwin.h> #include <kdebug.h> #include <qlayout.h> #include "ktoolbarbutton.h" //US #include "kconfigbase.h" #include <qpopupmenu.h> #include <qmainwindow.h> enum { CONTEXT_TOP = 0, CONTEXT_LEFT = 1, CONTEXT_RIGHT = 2, CONTEXT_BOTTOM = 3, CONTEXT_FLOAT = 4, CONTEXT_FLAT = 5, CONTEXT_ICONS = 6, CONTEXT_TEXT = 7, CONTEXT_TEXTRIGHT = 8, CONTEXT_TEXTUNDER = 9, CONTEXT_ICONSIZES = 50 // starting point for the icon size list, put everything else before }; class KToolBarPrivate { public: KToolBarPrivate() { m_iconSize = 0; m_iconText = KToolBar::IconOnly; m_highlight = true; m_transparent = true; m_honorStyle = false; m_enableContext = true; m_xmlguiClient = 0; m_configurePlugged = false; //US oldPos = Qt::DockUnmanaged; oldPos = QMainWindow::Unmanaged; modified = m_isHorizontal = positioned = FALSE; HiddenDefault = false; IconSizeDefault = 0; IconTextDefault = "IconOnly"; IndexDefault = -1; NewLineDefault = false; OffsetDefault = -1; PositionDefault = "Top"; idleButtons.setAutoDelete(true); } int m_iconSize; KToolBar::IconText m_iconText; bool m_highlight : 1; bool m_transparent : 1; bool m_honorStyle : 1; bool m_isHorizontal : 1; bool m_enableContext : 1; bool m_configurePlugged : 1; bool modified : 1; bool positioned : 1; QWidget *m_parent; QMainWindow::ToolBarDock oldPos; KXMLGUIClient *m_xmlguiClient; struct ToolBarInfo { //US ToolBarInfo() : index( 0 ), offset( -1 ), newline( FALSE ), dock( Qt::DockTop ) {} ToolBarInfo() : index( 0 ), offset( -1 ), newline( FALSE ), dock( QMainWindow::Top ) {} //US ToolBarInfo( Qt::Dock d, int i, bool n, int o ) : index( i ), offset( o ), newline( n ), dock( d ) {} ToolBarInfo( QMainWindow::ToolBarDock d, int i, bool n, int o ) : index( i ), offset( o ), newline( n ), dock( d ) {} int index, offset; bool newline; //US Qt::Dock dock; QMainWindow::ToolBarDock dock; }; ToolBarInfo toolBarInfo; QValueList<int> iconSizes; QTimer repaintTimer; // Default Values. bool HiddenDefault; int IconSizeDefault; QString IconTextDefault; int IndexDefault; bool NewLineDefault; int OffsetDefault; QString PositionDefault; QPtrList<QWidget> idleButtons; }; KToolBarSeparator::KToolBarSeparator(Orientation o , bool l, QToolBar *parent, const char* name ) :QFrame( parent, name ), line( l ) { connect( parent, SIGNAL(orientationChanged(Orientation)), this, SLOT(setOrientation(Orientation)) ); setOrientation( o ); setBackgroundMode( parent->backgroundMode() ); setBackgroundOrigin( ParentOrigin ); } void KToolBarSeparator::setOrientation( Orientation o ) { orient = o; if ( line ) { if ( orientation() == Vertical ) setFrameStyle( HLine + Sunken ); else setFrameStyle( VLine + Sunken ); } else { setFrameStyle( NoFrame ); } } void KToolBarSeparator::styleChange( QStyle& ) { setOrientation( orient ); } QSize KToolBarSeparator::sizeHint() const { return orientation() == Vertical ? QSize( 0, 6 ) : QSize( 6, 0 ); } QSizePolicy KToolBarSeparator::sizePolicy() const { return QSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); } KToolBar::KToolBar( QWidget *parent, const char *name, bool honorStyle, bool readConfig ) #ifdef DESKTOP_VERSION : QToolBar( QString::fromLatin1( name ), parent && parent->inherits( "QMainWindow" ) ? static_cast<QMainWindow*>(parent) : 0, parent, FALSE, name ? name : "mainToolBar") #else : QPEToolBar( parent && parent->inherits( "QMainWindow" ) ? static_cast<QMainWindow*>(parent) : 0, QString::fromLatin1( name )) #endif { init( readConfig, honorStyle ); } KToolBar::KToolBar( QMainWindow *parentWindow, QMainWindow::ToolBarDock dock, bool newLine, const char *name, bool honorStyle, bool readConfig ) #ifdef DESKTOP_VERSION : QToolBar( QString::fromLatin1( name ), parentWindow, dock, newLine, name ? name : "mainToolBar") #else : QPEToolBar( parentWindow,QString::fromLatin1( name )) #endif { init( readConfig, honorStyle ); } KToolBar::KToolBar( QMainWindow *parentWindow, QWidget *dock, bool newLine, const char *name, bool honorStyle, bool readConfig ) #ifdef DESKTOP_VERSION : QToolBar( QString::fromLatin1( name ), parentWindow, dock, newLine, name ? name : "mainToolBar") #else : QPEToolBar( parentWindow,QString::fromLatin1( name )) #endif { init( readConfig, honorStyle ); } KToolBar::~KToolBar() { inshutdownprocess = true; emit toolbarDestroyed(); delete d; } void KToolBar::init( bool readConfig, bool honorStyle ) { inshutdownprocess = false; d = new KToolBarPrivate; setFullSize( TRUE ); d->m_honorStyle = honorStyle; context = 0; layoutTimer = new QTimer( this ); connect( layoutTimer, SIGNAL( timeout() ), this, SLOT( rebuildLayout() ) ); connect( &(d->repaintTimer), SIGNAL( timeout() ), this, SLOT( slotRepaint() ) ); /*US if ( kapp ) { // may be null when started inside designer connect(kapp, SIGNAL(toolbarAppearanceChanged(int)), this, SLOT(slotAppearanceChanged())); // request notification of changes in icon style kapp->addKipcEventMask(KIPC::IconChanged); connect(kapp, SIGNAL(iconChanged(int)), this, SLOT(slotIconChanged(int))); } */ // finally, read in our configurable settings if ( readConfig ) slotReadConfig(); if ( mainWindow() ) connect( mainWindow(), SIGNAL( toolBarPositionChanged( QToolBar * ) ), this, SLOT( toolBarPosChanged( QToolBar * ) ) ); // Hack to make sure we recalculate our size when we dock. //US connect( this, SIGNAL(placeChanged(QDockWindow::Place)), SLOT(rebuildLayout()) ); } int KToolBar::insertButton(const QString& icon, int id, bool enabled, const QString& text, int index/*US, KInstance *_instance*/ ) { KToolBarButton *button = new KToolBarButton( icon, id, this, 0, text/*US, _instance*/ ); insertWidgetInternal( button, index, id ); button->setEnabled( enabled ); doConnections( button ); return index; } int KToolBar::insertButton(const QString& icon, int id, const char *signal, const QObject *receiver, const char *slot, bool enabled, const QString& text, int index/*US, KInstance *_instance*/ ) { KToolBarButton *button = new KToolBarButton( icon, id, this, 0, text/*US, _instance*/); insertWidgetInternal( button, index, id ); button->setEnabled( enabled ); connect( button, signal, receiver, slot ); doConnections( button ); return index; } int KToolBar::insertButton(const QPixmap& pixmap, int id, bool enabled, const QString& text, int index ) { KToolBarButton *button = new KToolBarButton( pixmap, id, this, 0, text); insertWidgetInternal( button, index, id ); button->setEnabled( enabled ); doConnections( button ); return index; } #if 0 bar->insertButton( icon, id_, SIGNAL( clicked() ), this, SLOT( slotActivated() ), d->isEnabled(), d->plainText(), index/*US, instance*/ ); #endif int KToolBar::insertButton(const QPixmap& pixmap, int id, const char *signal, const QObject *receiver, const char *slot, bool enabled, const QString& text, int index ) { KToolBarButton *button = new KToolBarButton( pixmap, id, this, 0, text); insertWidgetInternal( button, index, id ); button->setEnabled( enabled ); connect( button, signal, receiver, slot ); doConnections( button ); return index; } int KToolBar::insertButton(const QString& icon, int id, QPopupMenu *popup, bool enabled, const QString &text, int index ) { KToolBarButton *button = new KToolBarButton( icon, id, this, 0, text ); insertWidgetInternal( button, index, id ); button->setEnabled( enabled ); button->setPopup( popup ); doConnections( button ); return index; } int KToolBar::insertButton(const QPixmap& pixmap, int id, QPopupMenu *popup, bool enabled, const QString &text, int index ) { KToolBarButton *button = new KToolBarButton( pixmap, id, this, 0, text ); insertWidgetInternal( button, index, id ); button->setEnabled( enabled ); button->setPopup( popup ); doConnections( button ); return index; } int KToolBar::insertLined (const QString& text, int id, const char *signal, const QObject *receiver, const char *slot, bool enabled , const QString& toolTipText, int size, int index ) { KLineEdit *lined = new KLineEdit ( this, 0 ); if ( !toolTipText.isEmpty() ) QToolTip::add( lined, toolTipText ); if ( size > 0 ) lined->setMinimumWidth( size ); insertWidgetInternal( lined, index, id ); connect( lined, signal, receiver, slot ); lined->setText(text); lined->setEnabled( enabled ); return index; } int KToolBar::insertCombo (const QStringList &list, int id, bool writable, const char *signal, const QObject *receiver, const char *slot, bool enabled, const QString& tooltiptext, int size, int index, QComboBox::Policy policy ) { //US KComboBox *combo = new KComboBox ( writable, this ); KComboBox *combo = new KComboBox ( this ); combo->setEditable(writable); insertWidgetInternal( combo, index, id ); combo->insertStringList (list); combo->setInsertionPolicy(policy); combo->setEnabled( enabled ); if ( !tooltiptext.isEmpty() ) QToolTip::add( combo, tooltiptext ); if ( size > 0 ) combo->setMinimumWidth( size ); if (!tooltiptext.isNull()) QToolTip::add( combo, tooltiptext ); if ( signal && receiver && slot ) connect ( combo, signal, receiver, slot ); return index; } int KToolBar::insertCombo (const QString& text, int id, bool writable, const char *signal, QObject *receiver, const char *slot, bool enabled, const QString& tooltiptext, int size, int index, QComboBox::Policy policy ) { //US KComboBox *combo = new KComboBox ( writable, this ); KComboBox *combo = new KComboBox ( this ); combo->setEditable(writable); insertWidgetInternal( combo, index, id ); combo->insertItem (text); combo->setInsertionPolicy(policy); combo->setEnabled( enabled ); if ( !tooltiptext.isEmpty() ) QToolTip::add( combo, tooltiptext ); if ( size > 0 ) combo->setMinimumWidth( size ); if (!tooltiptext.isNull()) QToolTip::add( combo, tooltiptext ); connect (combo, signal, receiver, slot); return index; } int KToolBar::insertSeparator(int index, int id) { QWidget *w = new KToolBarSeparator( orientation(), FALSE, this, "tool bar separator" ); insertWidgetInternal( w, index, id ); return index; } int KToolBar::insertLineSeparator(int index, int id) { QWidget *w = new KToolBarSeparator( orientation(), TRUE, this, "tool bar separator" ); insertWidgetInternal( w, index, id ); return index; } int KToolBar::insertWidget(int id, int /*width*/, QWidget *widget, int index) { // removeWidgetInternal( widget ); // in case we already have it ? insertWidgetInternal( widget, index, id ); return index; } /*US int KToolBar::insertAnimatedWidget(int id, QObject *receiver, const char *slot, const QString& icons, int index ) { KAnimWidget *anim = new KAnimWidget( icons, d->m_iconSize, this ); insertWidgetInternal( anim, index, id ); if ( receiver ) connect( anim, SIGNAL(clicked()), receiver, slot); return index; } KAnimWidget *KToolBar::animatedWidget( int id ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return 0; if ( (*it) && (*it)->inherits( "KAnimWidget" ) ) return (KAnimWidget*)(*it); QObjectList *l = queryList( "KAnimWidget" ); if ( !l || !l->first() ) { delete l; return 0; } for ( QObject *o = l->first(); o; o = l->next() ) { if ( o->inherits( "KAnimWidget" ) ) { delete l; return (KAnimWidget*)o; } } delete l; return 0; } */ void KToolBar::addConnection (int id, const char *signal, const QObject *receiver, const char *slot) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; if ( (*it) ) connect( (*it), signal, receiver, slot ); } void KToolBar::setItemEnabled( int id, bool enabled ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; if ( (*it) ) (*it)->setEnabled( enabled ); } void KToolBar::setButtonPixmap( int id, const QPixmap& _pixmap ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->setPixmap( _pixmap ); } void KToolBar::setButtonIcon( int id, const QString& _icon ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->setIcon( _icon ); } void KToolBar::setButtonIconSet( int id, const QIconSet& iconset ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->setIconSet( iconset ); } void KToolBar::setDelayedPopup (int id , QPopupMenu *_popup, bool toggle ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->setDelayedPopup( _popup, toggle ); } void KToolBar::setAutoRepeat (int id, bool flag) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->setAutoRepeat( flag ); } void KToolBar::setToggle (int id, bool flag ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->setToggle( flag ); } void KToolBar::toggleButton (int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->toggle(); } void KToolBar::setButton (int id, bool flag) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if ( button ) button->on( flag ); } bool KToolBar::isButtonOn (int id) const { Id2WidgetMap::ConstIterator it = id2widget.find( id ); if ( it == id2widget.end() ) return false; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); return button ? button->isOn() : false; } void KToolBar::setLinedText (int id, const QString& text) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US QLineEdit * lineEdit = dynamic_cast<QLineEdit *>( *it ); QLineEdit * lineEdit = (QLineEdit *)( *it ); if ( lineEdit ) lineEdit->setText( text ); } QString KToolBar::getLinedText (int id) const { Id2WidgetMap::ConstIterator it = id2widget.find( id ); if ( it == id2widget.end() ) return QString::null; //US QLineEdit * lineEdit = dynamic_cast<QLineEdit *>( *it ); QLineEdit * lineEdit = (QLineEdit *)( *it ); return lineEdit ? lineEdit->text() : QString::null; } void KToolBar::insertComboItem (int id, const QString& text, int index) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US QComboBox * comboBox = dynamic_cast<QComboBox *>( *it ); QComboBox * comboBox = (QComboBox *)( *it ); if (comboBox) comboBox->insertItem( text, index ); } void KToolBar::insertComboList (int id, const QStringList &list, int index) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US QComboBox * comboBox = dynamic_cast<QComboBox *>( *it ); QComboBox * comboBox = (QComboBox *)( *it ); if (comboBox) comboBox->insertStringList( list, index ); } void KToolBar::removeComboItem (int id, int index) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US QComboBox * comboBox = dynamic_cast<QComboBox *>( *it ); QComboBox * comboBox = (QComboBox *)( *it ); if (comboBox) comboBox->removeItem( index ); } void KToolBar::setCurrentComboItem (int id, int index) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US QComboBox * comboBox = dynamic_cast<QComboBox *>( *it ); QComboBox * comboBox = (QComboBox *)( *it ); if (comboBox) comboBox->setCurrentItem( index ); } void KToolBar::changeComboItem (int id, const QString& text, int index) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US QComboBox * comboBox = dynamic_cast<QComboBox *>( *it ); QComboBox * comboBox = (QComboBox *)( *it ); if (comboBox) comboBox->changeItem( text, index ); } void KToolBar::clearCombo (int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US QComboBox * comboBox = dynamic_cast<QComboBox *>( *it ); QComboBox * comboBox = (QComboBox *)( *it ); if (comboBox) comboBox->clear(); } QString KToolBar::getComboItem (int id, int index) const { Id2WidgetMap::ConstIterator it = id2widget.find( id ); if ( it == id2widget.end() ) return QString::null; //US QComboBox * comboBox = dynamic_cast<QComboBox *>( *it ); QComboBox * comboBox = (QComboBox *)( *it ); return comboBox ? comboBox->text( index ) : QString::null; } KComboBox * KToolBar::getCombo(int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return 0; //US return dynamic_cast<KComboBox *>( *it ); return (KComboBox *)( *it ); } KLineEdit * KToolBar::getLined (int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return 0; //US return dynamic_cast<KLineEdit *>( *it ); return (KLineEdit *)( *it ); } KToolBarButton * KToolBar::getButton (int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return 0; //US return dynamic_cast<KToolBarButton *>( *it ); return (KToolBarButton *)( *it ); } void KToolBar::alignItemRight (int id, bool right ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; if ( rightAligned && !right && (*it) == rightAligned ) rightAligned = 0; if ( (*it) && right ) rightAligned = (*it); } QWidget *KToolBar::getWidget (int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); return ( it == id2widget.end() ) ? 0 : (*it); } void KToolBar::setItemAutoSized (int id, bool yes ) { QWidget *w = getWidget(id); if ( w && yes ) setStretchableWidget( w ); } void KToolBar::clear () { QToolBar::clear(); widget2id.clear(); id2widget.clear(); } void KToolBar::removeItem(int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) { kdDebug(220) << "KToolBar::removeItem item " << id << " not found" << endl; return; } QWidget * w = (*it); id2widget.remove( id ); widget2id.remove( w ); widgets.removeRef( w ); delete w; } void KToolBar::removeItemDelayed(int id) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) { kdDebug(220) << "KToolBar::removeItem item " << id << " not found" << endl; return; } QWidget * w = (*it); id2widget.remove( id ); widget2id.remove( w ); widgets.removeRef( w ); w->blockSignals(true); d->idleButtons.append(w); layoutTimer->start( 50, TRUE ); } void KToolBar::hideItem (int id) { QWidget *w = getWidget(id); if ( w ) w->hide(); } void KToolBar::showItem (int id) { QWidget *w = getWidget(id); if ( w ) w->show(); } int KToolBar::itemIndex (int id) { QWidget *w = getWidget(id); return w ? widgets.findRef(w) : -1; } void KToolBar::setFullSize(bool flag ) { setHorizontalStretchable( flag ); setVerticalStretchable( flag ); } bool KToolBar::fullSize() const { return isHorizontalStretchable() || isVerticalStretchable(); } void KToolBar::enableMoving(bool flag ) { //US setMovingEnabled(flag); this->mainWindow()->setToolBarsMovable(flag); } void KToolBar::setBarPos (BarPosition bpos) { if ( !mainWindow() ) return; //US mainWindow()->moveDockWindow( this, (Dock)bpos ); mainWindow()->moveToolBar( this, (QMainWindow::ToolBarDock)bpos ); } -KToolBar::BarPosition KToolBar::barPos() +KToolBar::BarPosition KToolBar::barPos() const { if ( !(QMainWindow*)mainWindow() ) return KToolBar::Top; //US Dock dock; QMainWindow::ToolBarDock dock; int dm1, dm2; bool dm3; ((QMainWindow*)mainWindow())->getLocation( (QToolBar*)this, dock, dm1, dm3, dm2 ); //US if ( dock == DockUnmanaged ) { if ( dock == QMainWindow::Unmanaged ) { return (KToolBar::BarPosition)Top; } return (BarPosition)dock; } bool KToolBar::enable(BarStatus stat) { bool mystat = isVisible(); if ( (stat == Toggle && mystat) || stat == Hide ) hide(); else show(); return isVisible() == mystat; } void KToolBar::setMaxHeight ( int h ) { setMaximumHeight( h ); } int KToolBar::maxHeight() { return maximumHeight(); } void KToolBar::setMaxWidth (int dw) { setMaximumWidth( dw ); } int KToolBar::maxWidth() { return maximumWidth(); } void KToolBar::setTitle (const QString& _title) { setLabel( _title ); } void KToolBar::enableFloating (bool ) { } void KToolBar::setIconText(IconText it) { setIconText( it, true ); } void KToolBar::setIconText(IconText icontext, bool update) { bool doUpdate=false; if (icontext != d->m_iconText) { d->m_iconText = icontext; doUpdate=true; } if (update == false) return; if (doUpdate) emit modechange(); // tell buttons what happened // ugly hack to force a QMainWindow::triggerLayout( TRUE ) if ( mainWindow() ) { QMainWindow *mw = mainWindow(); mw->setUpdatesEnabled( FALSE ); mw->setToolBarsMovable( !mw->toolBarsMovable() ); mw->setToolBarsMovable( !mw->toolBarsMovable() ); mw->setUpdatesEnabled( TRUE ); } } KToolBar::IconText KToolBar::iconText() const { return d->m_iconText; } void KToolBar::setIconSize(int size) { setIconSize( size, true ); } void KToolBar::setIconSize(int size, bool update) { bool doUpdate=false; if ( size != d->m_iconSize ) { d->m_iconSize = size; doUpdate=true; } if (update == false) return; if (doUpdate) emit modechange(); // tell buttons what happened // ugly hack to force a QMainWindow::triggerLayout( TRUE ) if ( mainWindow() ) { QMainWindow *mw = mainWindow(); mw->setUpdatesEnabled( FALSE ); mw->setToolBarsMovable( !mw->toolBarsMovable() ); mw->setToolBarsMovable( !mw->toolBarsMovable() ); mw->setUpdatesEnabled( TRUE ); } } int KToolBar::iconSize() const { /*US if ( !d->m_iconSize ) // default value? { if (!::qstrcmp(QObject::name(), "mainToolBar")) return KGlobal::iconLoader()->currentSize(KIcon::MainToolbar); else return KGlobal::iconLoader()->currentSize(KIcon::Toolbar); } return d->m_iconSize; */ int ret = 18; if ( QApplication::desktop()->width() > 320 ) ret = 30; return ret; } void KToolBar::setEnableContextMenu(bool enable ) { d->m_enableContext = enable; } bool KToolBar::contextMenuEnabled() const { return d->m_enableContext; } void KToolBar::setItemNoStyle(int id, bool no_style ) { Id2WidgetMap::Iterator it = id2widget.find( id ); if ( it == id2widget.end() ) return; //US KToolBarButton * button = dynamic_cast<KToolBarButton *>( *it ); KToolBarButton * button = (KToolBarButton *)( *it ); if (button) button->setNoStyle( no_style ); } void KToolBar::setFlat (bool flag) { if ( !mainWindow() ) return; if ( flag ) //US mainWindow()->moveDockWindow( this, DockMinimized ); mainWindow()->moveToolBar( this, QMainWindow::Minimized ); else //US mainWindow()->moveDockWindow( this, DockTop ); mainWindow()->moveToolBar( this, QMainWindow::Top ); // And remember to save the new look later /*US if ( mainWindow()->inherits( "KMainWindow" ) ) static_cast<KMainWindow *>(mainWindow())->setSettingsDirty(); */ } int KToolBar::count() const { return id2widget.count(); } void KToolBar::saveState() { /*US // first, try to save to the xml file if ( d->m_xmlguiClient && !d->m_xmlguiClient->xmlFile().isEmpty() ) { // go down one level to get to the right tags QDomElement elem = d->m_xmlguiClient->domDocument().documentElement().toElement(); elem = elem.firstChild().toElement(); QString barname(!::qstrcmp(name(), "unnamed") ? "mainToolBar" : name()); QDomElement current; // now try to find our toolbar d->modified = false; for( ; !elem.isNull(); elem = elem.nextSibling().toElement() ) { current = elem; if ( current.tagName().lower() != "toolbar" ) continue; QString curname(current.attribute( "name" )); if ( curname == barname ) { saveState( current ); break; } } // if we didn't make changes, then just return if ( !d->modified ) return; // now we load in the (non-merged) local file QString local_xml(KXMLGUIFactory::readConfigFile(d->m_xmlguiClient->xmlFile(), true, d->m_xmlguiClient->instance())); QDomDocument local; local.setContent(local_xml); // make sure we don't append if this toolbar already exists locally bool just_append = true; elem = local.documentElement().toElement(); KXMLGUIFactory::removeDOMComments( elem ); elem = elem.firstChild().toElement(); for( ; !elem.isNull(); elem = elem.nextSibling().toElement() ) { if ( elem.tagName().lower() != "toolbar" ) continue; QString curname(elem.attribute( "name" )); if ( curname == barname ) { just_append = false; local.documentElement().replaceChild( current, elem ); break; } } if (just_append) local.documentElement().appendChild( current ); KXMLGUIFactory::saveConfigFile(local, d->m_xmlguiClient->localXMLFile(), d->m_xmlguiClient->instance() ); return; } */ // if that didn't work, we save to the config file KConfig *config = KGlobal::config(); saveSettings(config, QString::null); config->sync(); } QString KToolBar::settingsGroup() { QString configGroup; if (!::qstrcmp(name(), "unnamed") || !::qstrcmp(name(), "mainToolBar")) configGroup = "Toolbar style"; else configGroup = QString(name()) + " Toolbar style"; if ( this->mainWindow() ) { configGroup.prepend(" "); configGroup.prepend( this->mainWindow()->name() ); } return configGroup; } void KToolBar::saveSettings(KConfig *config, const QString &_configGroup) { QString configGroup = _configGroup; if (configGroup.isEmpty()) configGroup = settingsGroup(); //kdDebug(220) << "KToolBar::saveSettings group=" << _configGroup << " -> " << configGroup << endl; QString position, icontext; int index; getAttributes( position, icontext, index ); //kdDebug(220) << "KToolBar::saveSettings " << name() << " newLine=" << newLine << endl; KConfigGroupSaver saver(config, configGroup); if ( position != d->PositionDefault ) config->writeEntry("Position", position); else config->deleteEntry("Position"); if ( icontext != d->IconTextDefault ) config->writeEntry("IconText", icontext); else config->deleteEntry("IconText"); if ( iconSize() != d->IconSizeDefault ) config->writeEntry("IconSize", iconSize()); else config->deleteEntry("IconSize"); if ( isHidden() != d->HiddenDefault ) config->writeEntry("Hidden", isHidden()); else config->deleteEntry("Hidden"); if ( index != d->IndexDefault ) config->writeEntry( "Index", index ); else config->deleteEntry("Index"); //US the older version of KDE (used on the Zaurus) has no Offset property /* if ( offset() != d->OffsetDefault ) config->writeEntry( "Offset", offset() ); else */ config->deleteEntry("Offset"); //US the older version of KDE (used on the Zaurus) has no NewLine property /* if ( newLine() != d->NewLineDefault ) config->writeEntry( "NewLine", newLine() ); else */ config->deleteEntry("NewLine"); } void KToolBar::setXMLGUIClient( KXMLGUIClient *client ) { d->m_xmlguiClient = client; } void KToolBar::setText( const QString & txt ) { //US setLabel( txt + " ( " + kapp->caption() + " ) " ); setLabel( txt + " ( " + KGlobal::getAppName() + " ) " ); } QString KToolBar::text() const { return label(); } void KToolBar::doConnections( KToolBarButton *button ) { connect(button, SIGNAL(clicked(int)), this, SIGNAL( clicked( int ) ) ); connect(button, SIGNAL(doubleClicked(int)), this, SIGNAL( doubleClicked( int ) ) ); connect(button, SIGNAL(released(int)), this, SIGNAL( released( int ) ) ); connect(button, SIGNAL(pressed(int)), this, SIGNAL( pressed( int ) ) ); connect(button, SIGNAL(toggled(int)), this, SIGNAL( toggled( int ) ) ); connect(button, SIGNAL(highlighted(int, bool)), this, SIGNAL( highlighted( int, bool ) ) ); } void KToolBar::mousePressEvent ( QMouseEvent *m ) { if ( !mainWindow() ) return; QMainWindow *mw = mainWindow(); if ( mw->toolBarsMovable() && d->m_enableContext ) { if ( m->button() == RightButton ) { int i = contextMenu()->exec( m->globalPos(), 0 ); switch ( i ) { case -1: return; // popup cancelled case CONTEXT_LEFT: //US mw->moveDockWindow( this, DockLeft ); mw->moveToolBar( this, QMainWindow::Left ); break; case CONTEXT_RIGHT: //US mw->moveDockWindow( this, DockRight ); mw->moveToolBar( this, QMainWindow::Right ); break; case CONTEXT_TOP: //US mw->moveDockWindow( this, DockTop ); mw->moveToolBar( this, QMainWindow::Top ); break; case CONTEXT_BOTTOM: //US mw->moveDockWindow( this, DockBottom ); mw->moveToolBar( this, QMainWindow::Bottom ); break; case CONTEXT_FLOAT: break; case CONTEXT_FLAT: //US mw->moveDockWindow( this, DockMinimized ); mw->moveToolBar( this, QMainWindow::Minimized ); break; case CONTEXT_ICONS: setIconText( IconOnly ); break; case CONTEXT_TEXTRIGHT: setIconText( IconTextRight ); break; case CONTEXT_TEXT: setIconText( TextOnly ); break; case CONTEXT_TEXTUNDER: setIconText( IconTextBottom ); break; default: if ( i >= CONTEXT_ICONSIZES ) setIconSize( i - CONTEXT_ICONSIZES ); else return; // assume this was an action handled elsewhere, no need for setSettingsDirty() } /*US if ( mw->inherits("KMainWindow") ) static_cast<KMainWindow *>(mw)->setSettingsDirty(); */ } } } void KToolBar::rebuildLayout() { for(QWidget *w=d->idleButtons.first(); w; w=d->idleButtons.next()) w->blockSignals(false); d->idleButtons.clear(); layoutTimer->stop(); QApplication::sendPostedEvents( this, QEvent::ChildInserted ); QBoxLayout *l = boxLayout(); l->setMargin( 1 ); // clear the old layout QLayoutIterator it = l->iterator(); while ( it.current() ) { it.deleteCurrent(); } for ( QWidget *w = widgets.first(); w; w = widgets.next() ) { if ( w == rightAligned ) { continue; } if ( w->inherits( "KToolBarSeparator" ) && !( (KToolBarSeparator*)w )->showLine() ) { l->addSpacing( 6 ); w->hide(); continue; } if ( w->inherits( "QPopupMenu" ) ) continue; l->addWidget( w ); w->show(); } if ( rightAligned ) { l->addStretch(); l->addWidget( rightAligned ); rightAligned->show(); } if ( fullSize() ) { // This code sucks. It makes the last combo in a toolbar VERY big (e.g. zoom combo in kword). //if ( !stretchableWidget && widgets.last() && // !widgets.last()->inherits( "QButton" ) && !widgets.last()->inherits( "KAnimWidget" ) ) // setStretchableWidget( widgets.last() ); if ( !rightAligned ) l->addStretch(); if ( stretchableWidget ) l->setStretchFactor( stretchableWidget, 10 ); } l->invalidate(); QApplication::postEvent( this, new QEvent( QEvent::LayoutHint ) ); //#endif //DESKTOP_VERSION } void KToolBar::childEvent( QChildEvent *e ) { if ( e->child()->isWidgetType() ) { QWidget * w = (QWidget*)e->child(); if ( e->type() == QEvent::ChildInserted ) { if ( !e->child()->inherits( "QPopupMenu" ) && ::qstrcmp( "qt_dockwidget_internal", e->child()->name() ) != 0 ) { // prevent items that have been explicitly inserted by insert*() from // being inserted again if ( !widget2id.contains( w ) ) { int dummy = -1; insertWidgetInternal( w, dummy, -1 ); } } } else { removeWidgetInternal( w ); } if ( isVisibleTo( 0 ) ) { QBoxLayout *l = boxLayout(); // QLayout *l = layout(); // clear the old layout so that we don't get unnecassery layout // changes till we have rebuild the thing QLayoutIterator it = l->iterator(); while ( it.current() ) { it.deleteCurrent(); } layoutTimer->start( 50, TRUE ); } } QToolBar::childEvent( e ); } void KToolBar::insertWidgetInternal( QWidget *w, int &index, int id ) { // we can't have it in widgets, or something is really wrong //widgets.removeRef( w ); connect( w, SIGNAL( destroyed() ), this, SLOT( widgetDestroyed() ) ); if ( index == -1 || index > (int)widgets.count() ) { widgets.append( w ); index = (int)widgets.count(); } else widgets.insert( index, w ); if ( id == -1 ) id = id2widget.count(); id2widget.insert( id, w ); widget2id.insert( w, id ); } void KToolBar::repaintMe() { setUpdatesEnabled( true ); QToolBar::repaint( true ); //qDebug(" KToolBar::repaintMe() "); } void KToolBar::showEvent( QShowEvent *e ) { QToolBar::showEvent( e ); rebuildLayout(); } void KToolBar::setStretchableWidget( QWidget *w ) { QToolBar::setStretchableWidget( w ); stretchableWidget = w; } QSizePolicy KToolBar::sizePolicy() const { if ( orientation() == Horizontal ) return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); else return QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Expanding ); } QSize KToolBar::sizeHint() const { return QToolBar::sizeHint(); #if 0 QWidget::polish(); static int iii = 0; ++iii; qDebug("++++++++ KToolBar::sizeHint() %d ", iii ); int margin = static_cast<QWidget*>(ncThis)->layout()->margin(); switch( barPos() ) { case KToolBar::Top: case KToolBar::Bottom: for ( QWidget *w = widgets.first(); w; w =widgets.next() ) { if ( w->inherits( "KToolBarSeparator" ) && !( static_cast<KToolBarSeparator*>(w)->showLine() ) ) { minSize += QSize(6, 0); } else { QSize sh = w->sizeHint(); if (!sh.isValid()) sh = w->minimumSize(); minSize = minSize.expandedTo(QSize(0, sh.height())); minSize += QSize(sh.width()+1, 0); } } /*US minSize += QSize(QApplication::style().pixelMetric( QStyle::PM_DockWindowHandleExtent ), 0); */ minSize += QSize(margin*2, margin*2); break; case KToolBar::Left: case KToolBar::Right: for ( QWidget *w = widgets.first(); w; w = widgets.next() ) { if ( w->inherits( "KToolBarSeparator" ) && !( static_cast<KToolBarSeparator*>(w)->showLine() ) ) { minSize += QSize(0, 6); } else { QSize sh = w->sizeHint(); if (!sh.isValid()) sh = w->minimumSize(); minSize = minSize.expandedTo(QSize(sh.width(), 0)); minSize += QSize(0, sh.height()+1); } } /*US minSize += QSize(0, QApplication::style().pixelMetric( QStyle::PM_DockWindowHandleExtent )); */ minSize += QSize(margin*2, margin*2); break; default: minSize = QToolBar::sizeHint(); break; } return minSize; #endif } QSize KToolBar::minimumSize() const { return minimumSizeHint(); } QSize KToolBar::minimumSizeHint() const { return sizeHint(); } bool KToolBar::highlight() const { return d->m_highlight; } void KToolBar::hide() { QToolBar::hide(); } void KToolBar::show() { QToolBar::show(); } void KToolBar::resizeEvent( QResizeEvent *e ) { bool b = isUpdatesEnabled(); setUpdatesEnabled( FALSE ); QToolBar::resizeEvent( e ); if (b) d->repaintTimer.start( 100, true ); } void KToolBar::slotIconChanged(int group) { if ((group != KIcon::Toolbar) && (group != KIcon::MainToolbar)) return; if ((group == KIcon::MainToolbar) != !::qstrcmp(name(), "mainToolBar")) return; emit modechange(); if (isVisible()) updateGeometry(); } void KToolBar::slotReadConfig() { //kdDebug(220) << "KToolBar::slotReadConfig" << endl; // Read appearance settings (hmm, we used to do both here, // but a well behaved application will call applyMainWindowSettings // anyway, right ?) applyAppearanceSettings(KGlobal::config(), QString::null ); } void KToolBar::slotAppearanceChanged() { // Read appearance settings from global file. applyAppearanceSettings(KGlobal::config(), QString::null, true /* lose local settings */ ); // And remember to save the new look later /*US if ( mainWindow() && mainWindow()->inherits( "KMainWindow" ) ) static_cast<KMainWindow *>(mainWindow())->setSettingsDirty(); */ } //static bool KToolBar::highlightSetting() { QString grpToolbar(QString::fromLatin1("Toolbar style")); KConfigGroupSaver saver(KGlobal::config(), grpToolbar); return KGlobal::config()->readBoolEntry(QString::fromLatin1("Highlighting"),true); } //static bool KToolBar::transparentSetting() { QString grpToolbar(QString::fromLatin1("Toolbar style")); KConfigGroupSaver saver(KGlobal::config(), grpToolbar); return KGlobal::config()->readBoolEntry(QString::fromLatin1("TransparentMoving"),true); } //static KToolBar::IconText KToolBar::iconTextSetting() { QString grpToolbar(QString::fromLatin1("Toolbar style")); KConfigGroupSaver saver(KGlobal::config(), grpToolbar); QString icontext = KGlobal::config()->readEntry(QString::fromLatin1("IconText"),QString::fromLatin1("IconOnly")); if ( icontext == "IconTextRight" ) return IconTextRight; else if ( icontext == "IconTextBottom" ) return IconTextBottom; else if ( icontext == "TextOnly" ) return TextOnly; else return IconOnly; } void KToolBar::applyAppearanceSettings(KConfig *config, const QString &_configGroup, bool forceGlobal) { QString configGroup = _configGroup.isEmpty() ? settingsGroup() : _configGroup; //kdDebug(220) << "KToolBar::applyAppearanceSettings: configGroup=" << configGroup << endl; // We have application-specific settings in the XML file, // and nothing in the application's config file // -> don't apply the global defaults, the XML ones are preferred // See applySettings for a full explanation /*US :we do not support xml files if ( d->m_xmlguiClient && !d->m_xmlguiClient->xmlFile().isEmpty() && !config->hasGroup(configGroup) ) { //kdDebug(220) << "skipping global defaults, using XML ones instead" << endl; return; } */ if ( !config->hasGroup(configGroup) ) { //kdDebug(220) << "skipping global defaults, using XML ones instead" << endl; return; } KConfig *gconfig = KGlobal::config(); /*US static const QString &attrIconText = KGlobal::staticQString("IconText"); static const QString &attrHighlight = KGlobal::staticQString("Highlighting"); static const QString &attrTrans = KGlobal::staticQString("TransparentMoving"); static const QString &attrSize = KGlobal::staticQString("IconSize"); */ // we actually do this in two steps. // First, we read in the global styles [Toolbar style] (from the KControl module). // Then, if the toolbar is NOT 'mainToolBar', we will also try to read in [barname Toolbar style] bool highlight; int transparent; QString icontext; int iconsize = 0; // this is the first iteration QString grpToolbar(QString::fromLatin1("Toolbar style")); { // start block for KConfigGroupSaver KConfigGroupSaver saver(gconfig, grpToolbar); // first, get the generic settings //US highlight = gconfig->readBoolEntry(attrHighlight, true); highlight = gconfig->readBoolEntry("Highlighting", true); //US transparent = gconfig->readBoolEntry(attrTrans, true); transparent = gconfig->readBoolEntry("TransparentMoving", true); // we read in the IconText property *only* if we intend on actually // honoring it if (d->m_honorStyle) //US d->IconTextDefault = gconfig->readEntry(attrIconText, d->IconTextDefault); d->IconTextDefault = gconfig->readEntry("IconText", d->IconTextDefault); else d->IconTextDefault = "IconOnly"; // Use the default icon size for toolbar icons. //US d->IconSizeDefault = gconfig->readNumEntry(attrSize, d->IconSizeDefault); d->IconSizeDefault = gconfig->readNumEntry("IconSize", d->IconSizeDefault); if ( !forceGlobal && config->hasGroup(configGroup) ) { config->setGroup(configGroup); // first, get the generic settings //US highlight = config->readBoolEntry(attrHighlight, highlight); highlight = config->readBoolEntry("Highlighting", highlight); //US transparent = config->readBoolEntry(attrTrans, transparent); transparent = config->readBoolEntry("TransparentMoving", transparent); // now we always read in the IconText property //US icontext = config->readEntry(attrIconText, d->IconTextDefault); icontext = config->readEntry("IconText", d->IconTextDefault); // now get the size //US iconsize = config->readNumEntry(attrSize, d->IconSizeDefault); iconsize = config->readNumEntry("IconSize", d->IconSizeDefault); } else { iconsize = d->IconSizeDefault; icontext = d->IconTextDefault; } // revert back to the old group } // end block for KConfigGroupSaver bool doUpdate = false; IconText icon_text; if ( icontext == "IconTextRight" ) icon_text = IconTextRight; else if ( icontext == "IconTextBottom" ) icon_text = IconTextBottom; else if ( icontext == "TextOnly" ) icon_text = TextOnly; else icon_text = IconOnly; // check if the icon/text has changed if (icon_text != d->m_iconText) { //kdDebug(220) << "KToolBar::applyAppearanceSettings setIconText " << icon_text << endl; setIconText(icon_text, false); doUpdate = true; } // ...and check if the icon size has changed if (iconsize != d->m_iconSize) { setIconSize(iconsize, false); doUpdate = true; } QMainWindow *mw = mainWindow(); // ...and if we should highlight if ( highlight != d->m_highlight ) { d->m_highlight = highlight; doUpdate = true; } // ...and if we should move transparently if ( mw && transparent != (!mw->opaqueMoving()) ) { mw->setOpaqueMoving( !transparent ); } if (doUpdate) emit modechange(); // tell buttons what happened if (isVisible ()) updateGeometry(); } void KToolBar::applySettings(KConfig *config, const QString &_configGroup) { //kdDebug(220) << "KToolBar::applySettings group=" << _configGroup << endl; QString configGroup = _configGroup.isEmpty() ? settingsGroup() : _configGroup; /* Let's explain this a bit more in details. The order in which we apply settings is : Global config / <appnamerc> user settings if no XMLGUI is used Global config / App-XML attributes / <appnamerc> user settings if XMLGUI is used So in the first case, we simply read everything from KConfig as below, but in the second case we don't do anything here if there is no app-specific config, and the XMLGUI uses the static methods of this class to get the global defaults. Global config doesn't include position (index, offset, newline and hidden/shown). */ // First the appearance stuff - the one which has a global config applyAppearanceSettings( config, _configGroup ); // ...and now the position stuff if ( config->hasGroup(configGroup) ) { KConfigGroupSaver cgs(config, configGroup); /*US static const QString &attrPosition = KGlobal::staticQString("Position"); static const QString &attrIndex = KGlobal::staticQString("Index"); static const QString &attrOffset = KGlobal::staticQString("Offset"); static const QString &attrNewLine = KGlobal::staticQString("NewLine"); static const QString &attrHidden = KGlobal::staticQString("Hidden"); QString position = config->readEntry(attrPosition, d->PositionDefault); int index = config->readNumEntry(attrIndex, d->IndexDefault); int offset = config->readNumEntry(attrOffset, d->OffsetDefault); bool newLine = config->readBoolEntry(attrNewLine, d->NewLineDefault); bool hidden = config->readBoolEntry(attrHidden, d->HiddenDefault); */ QString position = config->readEntry("Position", d->PositionDefault); int index = config->readNumEntry("Index", d->IndexDefault); int offset = config->readNumEntry("Offset", d->OffsetDefault); bool newLine = config->readBoolEntry("NewLine", d->NewLineDefault); bool hidden = config->readBoolEntry("Hidden", d->HiddenDefault); /*US Dock pos(DockTop); if ( position == "Top" ) pos = DockTop; else if ( position == "Bottom" ) pos = DockBottom; else if ( position == "Left" ) pos = DockLeft; else if ( position == "Right" ) pos = DockRight; else if ( position == "Floating" ) pos = DockTornOff; else if ( position == "Flat" ) pos = DockMinimized; */ QMainWindow::ToolBarDock pos(QMainWindow::Top); if ( position == "Top" ) pos = QMainWindow::Top; else if ( position == "Bottom" ) pos = QMainWindow::Bottom; else if ( position == "Left" ) pos = QMainWindow::Left; else if ( position == "Right" ) pos = QMainWindow::Right; else if ( position == "Floating" ) pos = QMainWindow::TornOff; else if ( position == "Flat" ) pos = QMainWindow::Minimized; //kdDebug(220) << "KToolBar::applySettings hidden=" << hidden << endl; if (hidden) hide(); else show(); if ( mainWindow() ) { QMainWindow *mw = mainWindow(); //kdDebug(220) << "KToolBar::applySettings updating ToolbarInfo" << endl; d->toolBarInfo = KToolBarPrivate::ToolBarInfo( pos, index, newLine, offset ); // moveDockWindow calls QDockArea which does a reparent() on us with // showIt = true, so we loose our visibility status bool doHide = isHidden(); //US mw->moveDockWindow( this, pos, newLine, index, offset ); mw->moveToolBar( this, pos, newLine, index, offset ); //kdDebug(220) << "KToolBar::applySettings " << name() << " moveDockWindow with pos=" << pos << " newLine=" << newLine << " idx=" << index << " offs=" << offset << endl; if ( doHide ) hide(); } if (isVisible ()) updateGeometry(); } } bool KToolBar::event( QEvent *e ) { if ( (e->type() == QEvent::LayoutHint) && isUpdatesEnabled() ) d->repaintTimer.start( 100, true ); if (e->type() == QEvent::ChildInserted ) { // By pass QToolBar::event, // it will show() the inserted child and we don't want to // do that until we have rebuild the layout. childEvent((QChildEvent *)e); return true; } return QToolBar::event( e ); } void KToolBar::slotRepaint() { setUpdatesEnabled( FALSE ); // Send a resizeEvent to update the "toolbar extension arrow" // (The button you get when your toolbar-items don't fit in // the available space) QResizeEvent ev(size(), size()); resizeEvent(&ev); //#ifdef DESKTOP_VERSION QApplication::sendPostedEvents( this, QEvent::LayoutHint ); //#endif //DESKTOP_VERSION setUpdatesEnabled( TRUE ); repaint( TRUE ); } void KToolBar::toolBarPosChanged( QToolBar *tb ) { if ( tb != this ) return; //US if ( d->oldPos == DockMinimized ) if ( d->oldPos == QMainWindow::Minimized ) rebuildLayout(); d->oldPos = (QMainWindow::ToolBarDock)barPos(); /*US if ( mainWindow() && mainWindow()->inherits( "KMainWindow" ) ) static_cast<KMainWindow *>(mainWindow())->setSettingsDirty(); */ } /*US void KToolBar::loadState( const QDomElement &element ) { //kdDebug(220) << "KToolBar::loadState " << this << endl; if ( !mainWindow() ) return; { QCString text = element.namedItem( "text" ).toElement().text().utf8(); if ( text.isEmpty() ) text = element.namedItem( "Text" ).toElement().text().utf8(); if ( !text.isEmpty() ) setText( i18n( text ) ); } { QCString attrFullWidth = element.attribute( "fullWidth" ).lower().latin1(); if ( !attrFullWidth.isEmpty() ) setFullSize( attrFullWidth == "true" ); } Dock dock = DockTop; { QCString attrPosition = element.attribute( "position" ).lower().latin1(); //kdDebug(220) << "KToolBar::loadState attrPosition=" << attrPosition << endl; if ( !attrPosition.isEmpty() ) { if ( attrPosition == "top" ) dock = DockTop; else if ( attrPosition == "left" ) dock = DockLeft; else if ( attrPosition == "right" ) dock = DockRight; else if ( attrPosition == "bottom" ) dock = DockBottom; else if ( attrPosition == "floating" ) dock = DockTornOff; else if ( attrPosition == "flat" ) dock = DockMinimized; } } { QCString attrIconText = element.attribute( "iconText" ).lower().latin1(); if ( !attrIconText.isEmpty() ) { //kdDebug(220) << "KToolBar::loadState attrIconText=" << attrIconText << endl; if ( attrIconText == "icontextright" ) setIconText( KToolBar::IconTextRight ); else if ( attrIconText == "textonly" ) setIconText( KToolBar::TextOnly ); else if ( attrIconText == "icontextbottom" ) setIconText( KToolBar::IconTextBottom ); else if ( attrIconText == "icononly" ) setIconText( KToolBar::IconOnly ); } else // Use global setting setIconText( iconTextSetting() ); } { QString attrIconSize = element.attribute( "iconSize" ).lower(); if ( !attrIconSize.isEmpty() ) d->IconSizeDefault = attrIconSize.toInt(); setIconSize( d->IconSizeDefault ); } { QString attrIndex = element.attribute( "index" ).lower(); if ( !attrIndex.isEmpty() ) d->IndexDefault = attrIndex.toInt(); } { QString attrOffset = element.attribute( "offset" ).lower(); if ( !attrOffset.isEmpty() ) d->OffsetDefault = attrOffset.toInt(); } { QString attrNewLine = element.attribute( "newline" ).lower(); if ( !attrNewLine.isEmpty() ) d->NewLineDefault = attrNewLine == "true"; } { QString attrHidden = element.attribute( "hidden" ).lower(); if ( !attrHidden.isEmpty() ) d->HiddenDefault = attrHidden == "true"; } d->toolBarInfo = KToolBarPrivate::ToolBarInfo( dock, d->IndexDefault, d->NewLineDefault, d->OffsetDefault ); mainWindow()->addDockWindow( this, dock, d->NewLineDefault ); //US mainWindow()->moveDockWindow( this, dock, d->NewLineDefault, d->IndexDefault, d->OffsetDefault ); mainWindow()->moveToolBar( this, dock, d->NewLineDefault, d->IndexDefault, d->OffsetDefault ); // Apply the highlight button setting d->m_highlight = highlightSetting(); // Apply transparent-toolbar-moving setting (ok, this is global to the mainwindow, // but we do it only if there are toolbars...) if ( transparentSetting() != !mainWindow()->opaqueMoving() ) mainWindow()->setOpaqueMoving( !transparentSetting() ); if ( d->HiddenDefault ) hide(); else show(); getAttributes( d->PositionDefault, d->IconTextDefault, d->IndexDefault ); } */ void KToolBar::getAttributes( QString &position, QString &icontext, int &index ) { // get all of the stuff to save switch ( barPos() ) { case KToolBar::Flat: position = "Flat"; break; case KToolBar::Bottom: position = "Bottom"; break; case KToolBar::Left: position = "Left"; break; case KToolBar::Right: position = "Right"; break; case KToolBar::Floating: position = "Floating"; break; case KToolBar::Top: default: position = "Top"; break; } if ( mainWindow() ) { QMainWindow::ToolBarDock dock; bool newLine; int offset; mainWindow()->getLocation( this, dock, index, newLine, offset ); } switch (d->m_iconText) { case KToolBar::IconTextRight: icontext = "IconTextRight"; break; case KToolBar::IconTextBottom: icontext = "IconTextBottom"; break; case KToolBar::TextOnly: icontext = "TextOnly"; break; case KToolBar::IconOnly: default: icontext = "IconOnly"; break; } } /*US void KToolBar::saveState( QDomElement ¤t ) { QString position, icontext; int index = -1; getAttributes( position, icontext, index ); current.setAttribute( "noMerge", "1" ); current.setAttribute( "position", position ); current.setAttribute( "iconText", icontext ); current.setAttribute( "index", index ); current.setAttribute( "offset", offset() ); current.setAttribute( "newline", newLine() ); if ( isHidden() ) current.setAttribute( "hidden", "true" ); d->modified = true; } */ void KToolBar::positionYourself( bool force ) { if (force) d->positioned = false; if ( d->positioned || !mainWindow() ) { //kdDebug(220) << "KToolBar::positionYourself d->positioned=true ALREADY DONE" << endl; return; } // we can't test for ForceHide after moveDockWindow because QDockArea // does a reparent() with showIt == true bool doHide = isHidden(); //kdDebug(220) << "positionYourself " << name() << " dock=" << d->toolBarInfo.dock << " newLine=" << d->toolBarInfo.newline << " offset=" << d->toolBarInfo.offset << endl; /*US mainWindow()->moveDockWindow( this, d->toolBarInfo.dock, d->toolBarInfo.newline, d->toolBarInfo.index, d->toolBarInfo.offset ); */ mainWindow()->moveToolBar( this, d->toolBarInfo.dock, d->NewLineDefault, d->IndexDefault, d->OffsetDefault ); if ( doHide ) hide(); // This method can only have an effect once - unless force is set d->positioned = TRUE; } //US KPopupMenu *KToolBar::contextMenu() QPopupMenu *KToolBar::contextMenu() { if ( context ) return context; // Construct our context popup menu. Name it qt_dockwidget_internal so it // won't be deleted by QToolBar::clear(). //US context = new KPopupMenu( this, "qt_dockwidget_internal" ); context = new QPopupMenu( this, "qt_dockwidget_internal" ); //US context->insertTitle(i18n("Toolbar Menu")); //US KPopupMenu *orient = new KPopupMenu( context, "orient" ); QPopupMenu *orient = new QPopupMenu( context, "orient" ); orient->insertItem( i18n("toolbar position string","Top"), CONTEXT_TOP ); orient->insertItem( i18n("toolbar position string","Left"), CONTEXT_LEFT ); orient->insertItem( i18n("toolbar position string","Right"), CONTEXT_RIGHT ); orient->insertItem( i18n("toolbar position string","Bottom"), CONTEXT_BOTTOM ); orient->insertSeparator(-1); //orient->insertItem( i18n("toolbar position string","Floating"), CONTEXT_FLOAT ); orient->insertItem( i18n("min toolbar", "Flat"), CONTEXT_FLAT ); //US KPopupMenu *mode = new KPopupMenu( context, "mode" ); QPopupMenu *mode = new QPopupMenu( context, "mode" ); mode->insertItem( i18n("Icons Only"), CONTEXT_ICONS ); mode->insertItem( i18n("Text Only"), CONTEXT_TEXT ); mode->insertItem( i18n("Text Alongside Icons"), CONTEXT_TEXTRIGHT ); mode->insertItem( i18n("Text Under Icons"), CONTEXT_TEXTUNDER ); //US KPopupMenu *size = new KPopupMenu( context, "size" ); QPopupMenu *size = new QPopupMenu( context, "size" ); size->insertItem( i18n("Default"), CONTEXT_ICONSIZES ); // Query the current theme for available sizes QValueList<int> avSizes; /*US KIconTheme *theme = KGlobal::instance()->iconLoader()->theme(); if (!::qstrcmp(QObject::name(), "mainToolBar")) avSizes = theme->querySizes( KIcon::MainToolbar); else avSizes = theme->querySizes( KIcon::Toolbar); */ avSizes << 16; avSizes << 32; d->iconSizes = avSizes; QValueList<int>::Iterator it; for (it=avSizes.begin(); it!=avSizes.end(); it++) { QString text; if ( *it < 19 ) text = i18n("Small (%1x%2)").arg(*it).arg(*it); else if (*it < 25) text = i18n("Medium (%1x%2)").arg(*it).arg(*it); else text = i18n("Large (%1x%2)").arg(*it).arg(*it); //we use the size as an id, with an offset size->insertItem( text, CONTEXT_ICONSIZES + *it ); } context->insertItem( i18n("Orientation"), orient ); orient->setItemChecked(CONTEXT_TOP, true); context->insertItem( i18n("Text Position"), mode ); context->setItemChecked(CONTEXT_ICONS, true); context->insertItem( i18n("Icon Size"), size ); /*US if (mainWindow()->inherits("KMainWindow")) { if ( (static_cast<KMainWindow*>(mainWindow())->toolBarMenuAction()) && (static_cast<KMainWindow*>(mainWindow())->hasMenuBar()) ) (static_cast<KMainWindow*>(mainWindow()))->toolBarMenuAction()->plug(context); } */ connect( context, SIGNAL( aboutToShow() ), this, SLOT( slotContextAboutToShow() ) ); return context; } void KToolBar::slotContextAboutToShow() { if (!d->m_configurePlugged) { // try to find "configure toolbars" action KXMLGUIClient *xmlGuiClient = d->m_xmlguiClient; if ( !xmlGuiClient && mainWindow() && mainWindow()->inherits( "KMainWindow" ) ) xmlGuiClient = (KXMLGUIClient *)mainWindow(); if ( xmlGuiClient ) { KAction *configureAction = xmlGuiClient->actionCollection()->action(KStdAction::stdName(KStdAction::ConfigureToolbars)); if ( configureAction ) { configureAction->plug(context); d->m_configurePlugged = true; } } } for(int i = CONTEXT_ICONS; i <= CONTEXT_TEXTUNDER; ++i) context->setItemChecked(i, false); switch( d->m_iconText ) { case IconOnly: default: context->setItemChecked(CONTEXT_ICONS, true); break; case IconTextRight: context->setItemChecked(CONTEXT_TEXTRIGHT, true); break; case TextOnly: context->setItemChecked(CONTEXT_TEXT, true); break; case IconTextBottom: context->setItemChecked(CONTEXT_TEXTUNDER, true); break; } QValueList<int>::ConstIterator iIt = d->iconSizes.begin(); QValueList<int>::ConstIterator iEnd = d->iconSizes.end(); for (; iIt != iEnd; ++iIt ) context->setItemChecked( CONTEXT_ICONSIZES + *iIt, false ); context->setItemChecked( CONTEXT_ICONSIZES, false ); context->setItemChecked( CONTEXT_ICONSIZES + d->m_iconSize, true ); for ( int i = CONTEXT_TOP; i <= CONTEXT_FLAT; ++i ) context->setItemChecked( i, false ); switch ( barPos() ) { case KToolBar::Flat: context->setItemChecked( CONTEXT_FLAT, true ); break; case KToolBar::Bottom: context->setItemChecked( CONTEXT_BOTTOM, true ); break; case KToolBar::Left: context->setItemChecked( CONTEXT_LEFT, true ); break; case KToolBar::Right: context->setItemChecked( CONTEXT_RIGHT, true ); break; case KToolBar::Floating: context->setItemChecked( CONTEXT_FLOAT, true ); break; case KToolBar::Top: context->setItemChecked( CONTEXT_TOP, true ); break; default: break; } } void KToolBar::widgetDestroyed() { removeWidgetInternal( (QWidget*)sender() ); } void KToolBar::removeWidgetInternal( QWidget * w ) { if ( inshutdownprocess ) return; widgets.removeRef( w ); QMap< QWidget*, int >::Iterator it = widget2id.find( w ); if ( it == widget2id.end() ) return; id2widget.remove( *it ); widget2id.remove( it ); } void KToolBar::virtual_hook( int, void* ) { /*BASE::virtual_hook( id, data );*/ } //US #include "ktoolbar.moc" diff --git a/microkde/kdeui/ktoolbar.h b/microkde/kdeui/ktoolbar.h index 61b5ea3..49ff856 100644 --- a/microkde/kdeui/ktoolbar.h +++ b/microkde/kdeui/ktoolbar.h @@ -1,1108 +1,1108 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Reginald Stadlbauer (reggie@kde.org) (C) 1997, 1998 Stephan Kulow (coolo@kde.org) (C) 1997, 1998 Sven Radej (radej@kde.org) (C) 1997, 1998 Mark Donohoe (donohoe@kde.org) (C) 1997, 1998 Matthias Ettrich (ettrich@kde.org) (C) 1999, 2000 Kurt Granroth (granroth@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef KTOOLBAR_H #define KTOOLBAR_H #ifndef DESKTOP_VERSION #define private public #include <qtoolbar.h> #undef private #include <qpe/qpetoolbar.h> #else #include <qtoolbar.h> #endif #include <qmainwindow.h> #include <qcombobox.h> #include <qmap.h> #include <qptrlist.h> #include <kglobal.h> #include <qguardedptr.h> #include <qframe.h> #include <qiconset.h> class QDomElement; class QSize; class QPixmap; class QPopupMenu; class QStringList; class QDomDocument; class QTimer; class KLineEdit; class KToolBar; class KToolBarButton; class KToolBoxManager; //US class KAnimWidget; //US class KPopupMenu; //US class KInstance; class KComboBox; class KXMLGUIClient; class KToolBarPrivate; class KToolBarSeparator : public QFrame { Q_OBJECT public: KToolBarSeparator( Orientation, bool l, QToolBar *parent, const char* name=0 ); QSize sizeHint() const; Orientation orientation() const { return orient; } QSizePolicy sizePolicy() const; bool showLine() const { return line; } public slots: void setOrientation( Orientation ); protected: void styleChange( QStyle& ); private: Orientation orient; bool line; }; /** * A KDE-style toolbar. * * KToolBar can be dragged around in and between different docks. * * A KToolBar can contain all sorts of widgets. * * KToolBar can be used as a standalone widget, but @ref KMainWindow * provides easy factories and management of one or more toolbars. * Once you have a KToolBar object, you can insert items into it with the * insert... methods, or remove them with the @ref removeItem() method. This * can be done at any time; the toolbar will be automatically updated. * There are also many methods to set per-child properties like alignment * and toggle behaviour. * * KToolBar uses a global config group to load toolbar settings on * construction. It will reread this config group on a * @ref KApplication::appearanceChanged() signal. * * @short Floatable toolbar with auto resize. * @version $Id$ * @author Reginald Stadlbauer <reggie@kde.org>, Stephan Kulow <coolo@kde.org>, Sven Radej <radej@kde.org>. */ // strange things are happening ... so I have to use strange define methods ... // porting KToolBar back to Qt2 really needs some strange hacks #ifndef DESKTOP_VERSION #define QToolBar QPEToolBar #endif class KToolBar : public QToolBar { Q_OBJECT Q_ENUMS( IconText BarPosition ) Q_PROPERTY( IconText iconText READ iconText WRITE setIconText ) Q_PROPERTY( BarPosition barPos READ barPos WRITE setBarPos ) Q_PROPERTY( bool fullSize READ fullSize WRITE setFullSize ) Q_PROPERTY( int iconSize READ iconSize WRITE setIconSize ) Q_PROPERTY( QString text READ text WRITE setText ) #ifndef DESKTOP_VERSION #undef QToolBar #endif public: enum IconText{IconOnly = 0, IconTextRight, TextOnly, IconTextBottom}; /** * The state of the status bar. * @deprecated **/ enum BarStatus{Toggle, Show, Hide}; /** * Possible bar positions. **/ enum BarPosition{ Unmanaged, Floating, Top, Bottom, Right, Left, Flat}; /** * Constructor. * This constructor is used by the XML-GUI. If you use it, you need * to call QMainWindow::addToolBar to specify the position of the toolbar. * So it's simpler to use the other constructor. * * The toolbar will read in various global config settings for * things like icon size and text position, etc. However, some of * the settings will be honored only if @ref #_honor_mode is set to * true. All other toolbars will be IconOnly and use Medium icons. * * @param parent The standard toolbar parent (usually a * @ref KMainWindow) * @param name The standard internal name * @param honor_style If true, then global settings for IconSize and IconText will be honored * @param readConfig whether to apply the configuration (global and application-specific) */ KToolBar( QWidget *parent, const char *name = 0, bool honor_style = FALSE, bool readConfig = TRUE ); /** * Constructor for non-XML-GUI applications. * * The toolbar will read in various global config settings for * things like icon size and text position, etc. However, some of * the settings will be honored only if @ref #_honor_mode is set to * true. All other toolbars will be IconOnly and use Medium icons. * * @param parentWindow The window that should be the parent of this toolbar * @param dock The position of the toolbar. Usually QMainWindow::Top. * @param newLine If true, start a new line in the dock for this toolbar. * @param name The standard internal name * @param honor_style If true, then global settings for IconSize and IconText will be honored * @param readConfig whether to apply the configuration (global and application-specific) */ KToolBar( QMainWindow *parentWindow, QMainWindow::ToolBarDock dock /*= QMainWindow::Top*/, bool newLine = false, const char *name = 0, bool honor_style = FALSE, bool readConfig = TRUE ); /** * Constructor for non-XML-GUI applications. * * The toolbar will read in various global config settings for * things like icon size and text position, etc. However, some of * the settings will be honored only if @ref #_honor_mode is set to * true. All other toolbars will be IconOnly and use Medium icons. * * @param parentWindow The window that should be the parent of this toolbar * @param dock Another widget than the mainwindow to dock toolbar to. * @param newLine If true, start a new line in the dock for this toolbar. * @param name The standard internal name * @param honor_style If true, then global settings for IconSize and IconText will be honored * @param readConfig whether to apply the configuration (global and application-specific) */ KToolBar( QMainWindow *parentWindow, QWidget *dock, bool newLine = false, const char *name = 0, bool honor_style = FALSE, bool readConfig = TRUE ); virtual ~KToolBar(); /** * Insert a button (a @ref KToolBarButton) with a pixmap. The * pixmap is loaded by the button itself based on the global icon * settings. * * You should connect to one or more signals in KToolBar: * @ref clicked() , @ref pressed() , @ref released() , or * @ref highlighted() and if the button is a toggle button * (@ref setToggle() ) @ref toggled() . Those signals have @p id * of a button that caused the signal. If you want to bind a popup * to button, see @ref setButton(). * * @param icon The name of the icon to use as the active pixmap * @param id The id of this button * @param enabled Enable or disable the button at startup * @param text The tooltip or toolbar text (depending on state) * @param index The position of the button. (-1 = at end). * * @return The item index. */ int insertButton(const QString& icon, int id, bool enabled = true, const QString& text = QString::null, int index=-1/*US , KInstance *_instance = KGlobal::instance()*/); /** * This is the same as above, but with specified signals and * slots to which this button will be connected. * * You can add more signals with @ref addConnection(). * * @param icon The name of the icon to use as the active pixmap * @param id The id of this button * @param signal The signal to connect to * @param receiver The slot's parent * @param enabled Enable or disable the button at startup * @param text The tooltip or toolbar text (depending on state) * @param index The position of the button. (-1 = at end). * * @return The item index. */ int insertButton(const QString& icon, int id, const char *signal, const QObject *receiver, const char *slot, bool enabled = true, const QString& text = QString::null, int index=-1/*US, KInstance *_instance = KGlobal::instance()*/ ); /** * Inserts a button (a @ref KToolBarButton) with the specified * pixmap. This pixmap will be used as the "active" one and the * disabled and default ones will be autogenerated. * * It is recommended that you use the insertButton function that * allows you to specify the icon name rather then the pixmap * itself. Specifying the icon name is much more flexible. * * You should connect to one or more signals in KToolBar: * @ref clicked() , @ref pressed() , @ref released() , or * @ref highlighted() and if the button is a toggle button * (@ref setToggle() ) @ref toggled() . Those signals have @p id * of a button that caused the signal. If you want to bind a popup * to button, see @ref setButton(). * * @param pixmap The active pixmap * @param id The id of this button * @param enabled Enable or disable the button at startup * @param text The tooltip or toolbar text (depending on state) * @param index The position of the button. (-1 = at end). * * @return The item index. */ int insertButton(const QPixmap& pixmap, int id, bool enabled = true, const QString& text = QString::null, int index=-1 ); /** * This is the same as above, but with specified signals and * slots to which this button will be connected. * * You can add more signals with @ref addConnection(). * * @param icon The name of the icon to use as the active pixmap * @param id The id of this button * @param signal The signal to connect to * @param receiver The slot's parent * @param enabled Enable or disable the button at startup * @param text The tooltip or toolbar text (depending on state) * @param index The position of the button. (-1 = at end). * * @return The item index. */ int insertButton(const QPixmap& pixmap, int id, const char *signal, const QObject *receiver, const char *slot, bool enabled = true, const QString& text = QString::null, int index=-1 ); /** * Inserts a button with popupmenu. * * Button will have small * triangle. You have to connect to popup's signals. The * signals @ref KButton::pressed(), @ref KButton::released(), * @ref KButton::clicked() or @ref KButton::doubleClicked() are @p not * emmited by * this button (see @ref setDelayedPopup() for that). * You can add custom popups which inherit @ref QPopupMenu to get popups * with tables, drawings etc. Just don't fiddle with events there. */ int insertButton(const QString& icon, int id, QPopupMenu *popup, bool enabled, const QString&_text, int index=-1); /** * Inserts a button with popupmenu. * * Button will have small * triangle. You have to connect to popup's signals. The * signals @ref KButton::pressed(), @ref KButton::released(), * @ref KButton::clicked() or @ref KButton::doubleClicked() are @p not * emmited by * this button (see @ref setDelayedPopup() for that). * You can add custom popups which inherit @ref QPopupMenu to get popups * with tables, drawings etc. Just don't fiddle with events there. */ int insertButton(const QPixmap& pixmap, int id, QPopupMenu *popup, bool enabled, const QString&_text, int index=-1); /** * Inserts a @ref KLineEdit. You have to specify signals and slots to * which KLineEdit will be connected. KLineEdit has all slots QLineEdit * has, plus signals @ref KLineEdit::completion and @ref KLineEdit::textRotation * KLineEdit can be set to autoresize itself to full free width * in toolbar, that is to last right aligned item. For that, * toolbar must be set to full width (which it is by default). * @see setFullWidth() * @see setItemAutoSized() * @see KLineEdit * @return Item index. */ int insertLined (const QString& text, int id, const char *signal, const QObject *receiver, const char *slot, bool enabled = true, const QString& toolTipText = QString::null, int size = 70, int index =-1); /** * Inserts a @ref KComboBox with list. * * Can be writable, but cannot contain * pixmaps. By default inserting policy is AtBottom, i.e. typed items * are placed at the bottom of the list. Can be autosized. If the size * argument is specified as -1, the width of the combobox is automatically * computed. * * @see setFullWidth() * @see setItemAutoSized() * @see KComboBox * @return Item index. */ int insertCombo (const QStringList &list, int id, bool writable, const char *signal, const QObject *receiver, const char *slot, bool enabled=true, const QString& tooltiptext=QString::null, int size=70, int index=-1, QComboBox::Policy policy = QComboBox::AtBottom); /** * Insert a @ref KComboBox with text. * * The rest is the same as above. * @see setItemAutoSized() * * @see KComboBox * @return Item index. */ int insertCombo (const QString& text, int id, bool writable, const char *signal, QObject *recevier, const char *slot, bool enabled=true, const QString& tooltiptext=QString::null, int size=70, int index=-1, QComboBox::Policy policy = QComboBox::AtBottom); /** * Inserts a separator into the toolbar with the given id. * Returns the separator's index */ int insertSeparator( int index = -1, int id = -1 ); /** * Inserts a line separator into the toolbar with the given id. * Returns the separator's index */ int insertLineSeparator( int index = -1, int id = -1 ); /** * Inserts a user-defined widget. The widget @p must have this * toolbar as its parent. * * Widget must have a QWidget for base class. Widget can be * autosized to full width. If you forget about it, you can get a * pointer to this widget with @ref getWidget(). * @see setItemAutoSized() * @return Item index. */ int insertWidget(int id, int width, QWidget *_widget, int index=-1); /** * Inserts an animated widget. A @ref KAnimWidget will be created * internally using the icon name you provide. * This will emit a signal (clicked()) whenever the * animation widget is clicked. * * @see animatedWidget() * * @param id The id for this toolbar item * @param receiver The parent of your slot * @param slot The slot to receive the clicked() signal * @param icons The name of the animation icon group to use * @param index The item index * * @return The item index */ /*US int insertAnimatedWidget(int id, QObject *receiver, const char *slot, const QString& icons, int index = -1); */ /** * This will return a pointer to the given animated widget, if it * exists. * * @see insertAnimatedWidget * * @param id The id for the widget you want to get a pointer to * * @return A pointer to the current animated widget or 0L */ //US KAnimWidget *animatedWidget( int id ); /** * Adds connections to items. * * It is important that you * know the @p id of particular item. Nothing happens if you forget @p id. */ void addConnection (int id, const char *signal, const QObject *receiver, const char *slot); /** * Enables/disables item. */ void setItemEnabled( int id, bool enabled ); /** * Sets the icon for a button. * * Can be used while button is visible. */ void setButtonIcon( int id, const QString& _icon ); /** * Sets button pixmap. * * Can be used while button is visible. */ void setButtonPixmap( int id, const QPixmap& _pixmap ); /** * Sets a button icon from a QIconSet. * * Can be used while button is visible. */ void setButtonIconSet( int id, const QIconSet& iconset ); /** * Sets a delayed popup for a button. * * Delayed popup is what you see in * Netscape Navigator's Previous and Next buttons: If you click them you * go back * or forth. If you press them long enough, you get a history-menu. * This is exactly what we do here. * * You will insert normal a button with connection (or use signals from * toolbar): * <pre> * bar->insertButton(icon, id, SIGNAL(clicked ()), this, * SLOT (slotClick()), true, "click or wait for popup"); * </pre> And then add a delayed popup: * <pre> * bar->setDelayedPopup (id, historyPopup); </pre> * * Don't add delayed popups to buttons which have normal popups. * * You may add popups which are derived from @ref QPopupMenu. You may * add popups that are already in the menu bar or are submenus of * other popups. */ void setDelayedPopup (int id , QPopupMenu *_popup, bool toggle = false); /** * Turns a button into an autorepeat button. * * Toggle buttons, buttons with menus, or * buttons with delayed menus cannot be made into autorepeat buttons. * Moreover, you can and will receive * only the signal clicked(), but not pressed() or released(). * When the user presses this button, you will receive the signal clicked(), * and if the button is still pressed after some time, * you will receive more clicked() signals separated by regular * intervals. Since this uses @ref QButton::setAutoRepeat() , * I can't quantify 'some'. */ void setAutoRepeat (int id, bool flag=true); /** * Turns button into a toggle button if @p flag is true. */ void setToggle (int id, bool flag = true); /** * Toggles a togglebutton. * * If the button is a toggle button (see @ref setToggle()) * the button state will be toggled. This will also cause the toolbar to * emit the signal @ref KButton::toggled() with parameter @p id. You must connect to * this signal, or use @ref addConnection() to connect directly to the * button signal @ref KButton::toggled(). */ void toggleButton (int id); /** * Sets a toggle button state. * * If the button is a toggle button (see @ref setToggle()) * this will set its state flag. This will also emit the signal * @ref KButton::toggled(). * * @see setToggle() */ void setButton (int id, bool flag); /** * @return @p true if button is on, @p false if button is off or if the * button is not a toggle button. * @see setToggle() */ bool isButtonOn (int id) const; /** * Sets the text of a line editor. * * Cursor is set at end of text. */ void setLinedText (int id, const QString& text); /** * Returns a line editor text. */ QString getLinedText (int id) const; /** * Inserts @p text in combobox @p id at position @p index. */ void insertComboItem (int id, const QString& text, int index); /** * Inserts @p list in combobox @p id at position @p index. */ void insertComboList (int id, const QStringList &list, int index); /** * Removes item @p index from combobox @p id. */ void removeComboItem (int id, int index); /** * Sets item @p index to be current item in combobox @p id. */ void setCurrentComboItem (int id, int index); /** * Changes item @p index in combobox @p id to text. * * @p index = -1 refers current item (one displayed in the button). */ void changeComboItem (int id, const QString& text, int index=-1); /** * Clears the combobox @p id. * * Does not delete it or hide it. */ void clearCombo (int id); /** * Returns text of item @p index from combobox @p id. * * @p index = -1 refers to current item. */ QString getComboItem (int id, int index=-1) const; /** * Returns a pointer to the combobox. * * Example: * <pre> * KComboBox *combo = toolbar->getCombo(combo_id); * </pre> * That way you can get access to other public methods * that @ref KComboBox provides. */ KComboBox * getCombo(int id); /** * Returns a pointer to KToolBarLined. * * Example: * <pre> * KLineEdit * lined = toolbar->getKToolBarLined(lined_id); * </pre> * That way you can get access to other public methods * that @ref KLineEdit provides. @ref KLineEdit is the same thing * as @ref QLineEdit plus completion signals. */ KLineEdit * getLined (int id); /** * Returns a pointer to KToolBarButton. * * Example: * <pre> * KToolBarButton * button = toolbar->getButton(button_id); * </pre> * That way you can get access to other public methods * that @ref KToolBarButton provides. * * Using this method is not recommended. */ KToolBarButton * getButton (int id); /** * Align item to the right. * * This works only if toolbar is set to full width. * @see setFullWidth() */ void alignItemRight (int id, bool right = true); /** * Returns a pointer to an inserted widget. * * Wrong ids are not tested. * You can do with this whatever you want, * except change its height (hardcoded). If you change its width * you will probably have to call QToolBar::updateRects(true) * @see QWidget * @see updateRects() * * KDE4: make this const! */ QWidget *getWidget (int id); /** * Set item autosized. * * This works only if the toolbar is set to full width. * Only @p one item can be autosized, and it has to be * the last left-aligned item. Items that come after this must be right * aligned. Items that can be right aligned are Lineds, Frames, Widgets and * Combos. An autosized item will resize itself whenever the toolbar geometry * changes to the last right-aligned item (or to end of toolbar if there * are no right-aligned items.) * @see setFullWidth() * @see alignItemRight() */ void setItemAutoSized (int id, bool yes = true); /** * Remove all items. * * The toolbar is redrawn after it. */ void clear (); /** * Remove item @p id. * * Item is deleted. Toolbar is redrawn after it. */ void removeItem (int id); /** * Remove item @p id. * * Item is deleted when toolbar is redrawn. */ void removeItemDelayed (int id); /** * Hide item. */ void hideItem (int id); /** * Show item. */ void showItem (int id); /** * Returns the index of the given item. * * KDE4: make this const! */ int itemIndex (int id); /** * Set toolbar to full parent size (default). * * In full size mode the bar * extends over the parent's full width or height. If the mode is disabled * the toolbar tries to take as much space as it needs without wrapping, but * it does not exceed the parent box. You can force a certain width or * height with @ref setMaxWidth() or @ref setMaxHeight(). * * If you want to use right-aligned items or auto-sized items you must use * full size mode. */ void setFullSize(bool flag = true); /** * @return @p true if the full-size mode is enabled. Otherwise * it returns @false. */ bool fullSize() const; /** * @deprecated use setMovingEnabled(bool) instead. * Enable or disable moving of toolbar. */ void enableMoving(bool flag = true); /** * Set position of toolbar. * @see BarPosition() */ void setBarPos (BarPosition bpos); /** * Returns position of toolbar. */ - BarPosition barPos(); + BarPosition barPos() const; /** * @deprecated * Show, hide, or toggle toolbar. * * This method is provided for compatibility only, * please use show() and/or hide() instead. * @see BarStatus */ bool enable(BarStatus stat); /** * @deprecated * Use setMaximumHeight() instead. */ void setMaxHeight (int h); // Set max height for vertical toolbars /** * @deprecated * Use maximumHeight() instead. * Returns the value that was set with @ref setMaxHeight(). */ int maxHeight(); /** * @deprecated * Use setMaximumWidth() instead. * Set maximal width of horizontal (top or bottom) toolbar. */ void setMaxWidth (int dw); /** * @deprecated * Use maximumWidth() instead. * Returns the value that was set with @ref setMaxWidth(). */ int maxWidth(); /** * Set title for toolbar when it floats. * * Titles are however not (yet) * visible. You can't change toolbar's title while it's floating. */ void setTitle (const QString& _title); /** * @deprecated * Use enableMoving() instead. */ void enableFloating (bool arrrrrrgh); /** * Set the kind of painting for buttons. * * Choose from: * @li IconOnly (only icons), * @li IconTextRight (icon and text, text is left from icons), * @li TextOnly (only text), * @li IconTextBottom (icons and text, text is under icons). * @see IconText * */ void setIconText(IconText it); // Note: don't merge with the next one, it breaks Qt properties /** * Similar to @ref setIconText(IconText it) but allows you to * disable or enable updating. If @p update is false, then the * buttons will not be updated. This is useful only if you know * that you will be forcing an update later. */ void setIconText(IconText it, bool update); /** * @return The current text style for buttons. */ IconText iconText() const; /** * Set the icon size to load. Usually you should not call * this, the icon size is taken care of by KIconLoader * and globally configured. * By default, the toolbar will load icons of size 32 for main * toolbars and 22 for other toolbars * @see KIconLoader. * * @param size The size to use */ void setIconSize(int size); // Note: don't merge with the next one, it breaks Qt properties /** * Same as @ref setIconText(int size) but allows you * to disable the toolbar update. * * @param size The size to use * @param update If true, then the toolbar will be updated after * this */ void setIconSize(int size, bool update); /** * @return The current icon size for buttons. */ int iconSize() const; /** * This allows you to enable or disable the context menu. * * @param enable If false, then the context menu will be disabled */ void setEnableContextMenu(bool enable = true); /** * Returns whether or not the context menu is disabled * * @return The context menu state */ bool contextMenuEnabled() const; /** * This will inform a toolbar button to ignore certain style * changes. Specifically, it will ignore IconText (always IconOnly) * and will not allow image effects to apply. * * @param id The button to exclude from styles * @param no_style If true, then it is excluded (default: true). */ void setItemNoStyle(int id, bool no_style = true); void setFlat (bool flag); /** * @return the number of items in the toolbar */ int count() const; /** * Instruct the toolbar to save it's current state to either the app * config file or to the XML-GUI resource file (whichever has * precedence). */ void saveState(); /** * Save the toolbar settings to group @p configGroup in @p config. */ void saveSettings(KConfig *config, const QString &configGroup); /** * Read the toolbar settings from group @p configGroup in @p config * and apply them. */ void applySettings(KConfig *config, const QString &configGroup); /** * Tell the toolbar what XML-GUI resource file it should use to save * it's state. The state of the toolbar (position, size, etc) is * saved in KConfig files if the application does not use XML-GUI.. * but if the app does, then it's saved the XML file. This function * allows this to happen. * * @param xmlfile The XML-GUI resource file to write to * @param xml The DOM document for the XML-GUI building */ // void setXML(const QString& xmlfile, const QDomDocument& xml); /* @internal */ void setXMLGUIClient( KXMLGUIClient *client ); /** * Assign a (translated) text to this toolbar. This is used * for the tooltip on the handle, and when listing the toolbars. */ void setText( const QString & txt ); /** * @return the toolbar's text. */ QString text() const; void setStretchableWidget( QWidget *w ); QSizePolicy sizePolicy() const; bool highlight() const; QSize sizeHint() const; QSize minimumSizeHint() const; QSize minimumSize() const; void hide(); void show(); void updateRects( bool = FALSE ) {} //US void loadState( const QDomElement &e ); //US void saveState( QDomElement &e ); /** * @internal */ void positionYourself( bool force = false); signals: /** * Emitted when button @p id is clicked. */ void clicked(int id); /** * Emitted when button @p id is double-clicked. * * Note: you will always * recive two @ref clicked() , @ref pressed() and @ref released() signals. * There is no way to avoid it - at least no easy way. * If you need to resolve this all you can do is set up timers * which wait for @ref QApplication::doubleClickInterval() to expire. * If in that time you don't get this signal, you may belive that * button was only clicked and not double-clicked. * And please note that butons with popup menus do not emit this signal, * but those with delayed popup do. */ void doubleClicked (int id); /** * Emitted when button @p id is pressed. */ void pressed(int); /** * Emits when button @p id is released. */ void released(int); /** * Emitted when a toggle button changes state. * * Emitted also if you change state * with @ref setButton() or @ref toggleButton() * If you make a button normal again, with * setToggle(false), this signal won't * be emitted. */ void toggled(int); /** * This signal is emitted when item id gets highlighted/unhighlighted * (i.e when mouse enters/exits). * * Note that this signal is emitted from * all buttons (normal, disabled and toggle) even when there is no visible * change in buttons (i.e., buttons do not raise when mouse enters). * The parameter @p isHighlighted is @p true when mouse enters and @p false when * mouse exits. */ void highlighted(int id, bool isHighlighted); /** * This signal is emitted when item id gets highlighted/unhighlighted * (i.e when mouse enters/exits). * * Note that this signal is emitted from * all buttons (normal, disabled and toggle) even when there is no visible * change in buttons (i.e., buttons do not raise when mouse enters). */ void highlighted(int id ); /** * Emitted when toolbar changes position, or when * an item is removed from toolbar. * * If you subclass @ref KMainWindow and reimplement * @ref KMainWindow::resizeEvent() be sure to connect to * this signal. Note: You can connect this signal to a slot that * doesn't take parameter. */ void moved( BarPosition ); /** * @internal * This signal is emitted when toolbar detects changing of * following parameters: * highlighting, button-size, button-mode. This signal is * internal, aimed to buttons. */ void modechange (); /** * This signal is emitted when the toolbar is getting deleted, * and before ~KToolbar finishes (so it's still time to remove * widgets from the toolbar). * Used by KWidgetAction. * @since 3.2 */ void toolbarDestroyed(); public: /** * @return global setting for "Highlight buttons under mouse" */ void repaintMe(); static bool highlightSetting(); /** * @return global setting for "Toolbars transparent when moving" */ static bool transparentSetting(); /** * @return global setting for "Icon Text" */ static IconText iconTextSetting(); public slots: virtual void setIconText( const QString &txt ) { QToolBar::setIconText( txt ); } void slotRepaint(); protected: void mousePressEvent( QMouseEvent * ); void childEvent( QChildEvent *e ); void showEvent( QShowEvent *e ); void resizeEvent( QResizeEvent *e ); bool event( QEvent *e ); void applyAppearanceSettings(KConfig *config, const QString &_configGroup, bool forceGlobal = false); QString settingsGroup(); private slots: void rebuildLayout(); void slotReadConfig (); void slotAppearanceChanged(); void slotIconChanged(int); void toolBarPosChanged( QToolBar *tb ); void slotContextAboutToShow(); void widgetDestroyed(); private: void init( bool readConfig = true, bool honorStyle = false ); void doConnections( KToolBarButton *button ); void insertWidgetInternal( QWidget *w, int &index, int id ); void removeWidgetInternal( QWidget *w ); void getAttributes( QString &position, QString &icontext, int &index ); //US KPopupMenu *contextMenu(); QPopupMenu *contextMenu(); QMap<QWidget*, int > widget2id; typedef QMap<int, QWidget* > Id2WidgetMap; Id2WidgetMap id2widget; //US KPopupMenu *context; QPopupMenu *context; QPtrList<QWidget> widgets; QTimer *layoutTimer; QGuardedPtr<QWidget> stretchableWidget, rightAligned; protected: virtual void virtual_hook( int id, void* data ); private: KToolBarPrivate *d; bool inshutdownprocess; }; #endif |