kalarm

functions.cpp

00001 /*
00002  *  functions.cpp  -  miscellaneous functions
00003  *  Program:  kalarm
00004  *  Copyright (C) 2001 - 2005 by David Jarvie <software@astrojar.org.uk>
00005  *
00006  *  This program is free software; you can redistribute it and/or modify
00007  *  it under the terms of the GNU General Public License as published by
00008  *  the Free Software Foundation; either version 2 of the License, or
00009  *  (at your option) any later version.
00010  *
00011  *  This program is distributed in the hope that it will be useful,
00012  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
00014  *  GNU General Public License for more details.
00015  *
00016  *  You should have received a copy of the GNU General Public License along
00017  *  with this program; if not, write to the Free Software Foundation, Inc.,
00018  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00019  */
00020 
00021 #include "kalarm.h"
00022 
00023 #include <qdeepcopy.h>
00024 #include <qdir.h>
00025 #include <qregexp.h>
00026 
00027 #include <kconfig.h>
00028 #include <kaction.h>
00029 #include <kglobal.h>
00030 #include <klocale.h>
00031 #include <kstdguiitem.h>
00032 #include <kstdaccel.h>
00033 #include <kmessagebox.h>
00034 #include <kfiledialog.h>
00035 #include <dcopclient.h>
00036 #include <kdebug.h>
00037 
00038 #include <libkcal/event.h>
00039 #include <libkcal/icalformat.h>
00040 #include <libkpimidentities/identitymanager.h>
00041 #include <libkpimidentities/identity.h>
00042 #include <libkcal/person.h>
00043 
00044 #include "alarmcalendar.h"
00045 #include "alarmevent.h"
00046 #include "alarmlistview.h"
00047 #include "daemon.h"
00048 #include "kalarmapp.h"
00049 #include "kamail.h"
00050 #include "mainwindow.h"
00051 #include "messagewin.h"
00052 #include "preferences.h"
00053 #include "shellprocess.h"
00054 #include "templatelistview.h"
00055 #include "templatemenuaction.h"
00056 #include "functions.h"
00057 
00058 
00059 namespace
00060 {
00061 bool        resetDaemonQueued = false;
00062 QCString    korganizerName = "korganizer";
00063 QString     korgStartError;
00064 const char* KORG_DCOP_OBJECT  = "KOrganizerIface";
00065 const char* KORG_DCOP_WINDOW  = "KOrganizer MainWindow";
00066 const char* KMAIL_DCOP_WINDOW = "kmail-mainwindow#1";
00067 
00068 bool sendToKOrganizer(const KAEvent&);
00069 bool deleteFromKOrganizer(const QString& eventID);
00070 inline bool runKOrganizer()   { return KAlarm::runProgram("korganizer", KORG_DCOP_WINDOW, korganizerName, korgStartError); }
00071 }
00072 
00073 
00074 namespace KAlarm
00075 {
00076 
00077 /******************************************************************************
00078 *  Display a main window with the specified event selected.
00079 */
00080 MainWindow* displayMainWindowSelected(const QString& eventID)
00081 {
00082     MainWindow* win = MainWindow::firstWindow();
00083     if (!win)
00084     {
00085         if (theApp()->checkCalendarDaemon())    // ensure calendar is open and daemon started
00086         {
00087             win = MainWindow::create();
00088             win->show();
00089         }
00090     }
00091     else
00092     {
00093         // There is already a main window, so make it the active window
00094         bool visible = win->isVisible();
00095         if (visible)
00096             win->hide();        // in case it's on a different desktop
00097         if (!visible  ||  win->isMinimized())
00098             win->showNormal();
00099         win->raise();
00100         win->setActiveWindow();
00101     }
00102     if (win  &&  !eventID.isEmpty())
00103         win->selectEvent(eventID);
00104     return win;
00105 }
00106 
00107 /******************************************************************************
00108 * Create a New Alarm KAction.
00109 */
00110 KAction* createNewAlarmAction(const QString& label, QObject* receiver, const char* slot, KActionCollection* actions, const char* name)
00111 {
00112     return new KAction(label, "filenew", KStdAccel::openNew(), receiver, slot, actions, name);
00113 }
00114 
00115 /******************************************************************************
00116 * Create a New From Template KAction.
00117 */
00118 TemplateMenuAction* createNewFromTemplateAction(const QString& label, QObject* receiver, const char* slot, KActionCollection* actions, const char* name)
00119 {
00120     return new TemplateMenuAction(label, "new_from_template", receiver, slot, actions, name);
00121 }
00122 
00123 /******************************************************************************
00124 * Add a new active (non-expired) alarm.
00125 * Save it in the calendar file and add it to every main window instance.
00126 * If 'selectionView' is non-null, the selection highlight is moved to the new
00127 * event in that listView instance.
00128 * 'event' is updated with the actual event ID.
00129 */
00130 UpdateStatus addEvent(KAEvent& event, AlarmListView* selectionView, bool useEventID, bool allowKOrgUpdate)
00131 {
00132     kdDebug(5950) << "KAlarm::addEvent(): " << event.id() << endl;
00133     if (!theApp()->checkCalendarDaemon())    // ensure calendar is open and daemon started
00134         return UPDATE_ERROR;
00135 
00136     // Save the event details in the calendar file, and get the new event ID
00137     AlarmCalendar* cal = AlarmCalendar::activeCalendar();
00138     cal->addEvent(event, useEventID);
00139     cal->save();
00140 
00141     UpdateStatus ret = UPDATE_OK;
00142     if (allowKOrgUpdate  &&  event.copyToKOrganizer())
00143     {
00144         if (!sendToKOrganizer(event))    // tell KOrganizer to show the event
00145             ret = UPDATE_KORG_ERR;
00146     }
00147 
00148     // Update the window lists
00149     AlarmListView::addEvent(event, selectionView);
00150     return ret;
00151 }
00152 
00153 /******************************************************************************
00154 * Save the event in the expired calendar file and adjust every main window instance.
00155 * The event's ID is changed to an expired ID if necessary.
00156 */
00157 bool addExpiredEvent(KAEvent& event)
00158 {
00159     kdDebug(5950) << "KAlarm::addExpiredEvent(" << event.id() << ")\n";
00160     AlarmCalendar* cal = AlarmCalendar::expiredCalendarOpen();
00161     if (!cal)
00162         return false;
00163     bool archiving = (KAEvent::uidStatus(event.id()) == KAEvent::ACTIVE);
00164     if (archiving)
00165         event.setSaveDateTime(QDateTime::currentDateTime());   // time stamp to control purging
00166     KCal::Event* kcalEvent = cal->addEvent(event);
00167     cal->save();
00168 
00169     // Update window lists
00170     if (!archiving)
00171         AlarmListView::addEvent(event, 0);
00172     else if (kcalEvent)
00173         AlarmListView::modifyEvent(KAEvent(*kcalEvent), 0);
00174     return true;
00175 }
00176 
00177 /******************************************************************************
00178 * Add a new template.
00179 * Save it in the calendar file and add it to every template list view.
00180 * If 'selectionView' is non-null, the selection highlight is moved to the new
00181 * event in that listView instance.
00182 * 'event' is updated with the actual event ID.
00183 */
00184 bool addTemplate(KAEvent& event, TemplateListView* selectionView)
00185 {
00186     kdDebug(5950) << "KAlarm::addTemplate(): " << event.id() << endl;
00187 
00188     // Add the template to the calendar file
00189     AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
00190     if (!cal)
00191         return false;
00192     cal->addEvent(event);
00193     cal->save();
00194     cal->emitEmptyStatus();
00195 
00196     // Update the window lists
00197     TemplateListView::addEvent(event, selectionView);
00198     return true;
00199 }
00200 
00201 /******************************************************************************
00202 * Modify an active (non-expired) alarm in the calendar file and in every main
00203 * window instance.
00204 * The new event will have a different event ID from the old one.
00205 * If 'selectionView' is non-null, the selection highlight is moved to the
00206 * modified event in that listView instance.
00207 */
00208 UpdateStatus modifyEvent(KAEvent& oldEvent, const KAEvent& newEvent, AlarmListView* selectionView)
00209 {
00210     kdDebug(5950) << "KAlarm::modifyEvent(): '" << oldEvent.id() << endl;
00211 
00212     if (!newEvent.valid())
00213         return deleteEvent(oldEvent, true);
00214     else
00215     {
00216         UpdateStatus ret = UPDATE_OK;
00217         if (oldEvent.copyToKOrganizer())
00218         {
00219             // Tell KOrganizer to delete its old event.
00220             // But ignore errors, because the user could have manually
00221             // deleted it since KAlarm asked KOrganizer to set it up.
00222             deleteFromKOrganizer(oldEvent.id());
00223         }
00224 
00225         // Update the event in the calendar file, and get the new event ID
00226         AlarmCalendar* cal = AlarmCalendar::activeCalendar();
00227         cal->deleteEvent(oldEvent.id());
00228         cal->addEvent(const_cast<KAEvent&>(newEvent), true);
00229         cal->save();
00230 
00231         if (newEvent.copyToKOrganizer())
00232         {
00233             if (!sendToKOrganizer(newEvent))    // tell KOrganizer to show the new event
00234                 ret = UPDATE_KORG_ERR;
00235         }
00236 
00237         // Update the window lists
00238         AlarmListView::modifyEvent(oldEvent.id(), newEvent, selectionView);
00239         return ret;
00240     }
00241 }
00242 
00243 /******************************************************************************
00244 * Update an active (non-expired) alarm from the calendar file and from every
00245 * main window instance.
00246 * The new event will have the same event ID as the old one.
00247 * If 'selectionView' is non-null, the selection highlight is moved to the
00248 * updated event in that listView instance.
00249 * The event is not updated in KOrganizer, since this function is called when an
00250 * existing alarm is rescheduled (due to recurrence or deferral).
00251 */
00252 void updateEvent(KAEvent& event, AlarmListView* selectionView, bool archiveOnDelete, bool incRevision)
00253 {
00254     kdDebug(5950) << "KAlarm::updateEvent(): " << event.id() << endl;
00255 
00256     if (!event.valid())
00257         deleteEvent(event, archiveOnDelete);
00258     else
00259     {
00260         // Update the event in the calendar file.
00261         if (incRevision)
00262             event.incrementRevision();    // ensure alarm daemon sees the event has changed
00263         AlarmCalendar* cal = AlarmCalendar::activeCalendar();
00264         cal->updateEvent(event);
00265         cal->save();
00266 
00267         // Update the window lists
00268         AlarmListView::modifyEvent(event, selectionView);
00269     }
00270 }
00271 
00272 /******************************************************************************
00273 * Update a template in the calendar file and in every template list view.
00274 * If 'selectionView' is non-null, the selection highlight is moved to the
00275 * updated event in that listView instance.
00276 */
00277 void updateTemplate(const KAEvent& event, TemplateListView* selectionView)
00278 {
00279     AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
00280     if (cal)
00281     {
00282         cal->updateEvent(event);
00283         cal->save();
00284 
00285         TemplateListView::modifyEvent(event.id(), event, selectionView);
00286     }
00287 }
00288 
00289 /******************************************************************************
00290 * Delete an alarm from the calendar file and from every main window instance.
00291 * If the event is archived, the event's ID is changed to an expired ID if necessary.
00292 */
00293 UpdateStatus deleteEvent(KAEvent& event, bool archive)
00294 {
00295     QString id = event.id();
00296     kdDebug(5950) << "KAlarm::deleteEvent(): " << id << endl;
00297 
00298     // Update the window lists
00299     AlarmListView::deleteEvent(id);
00300 
00301     UpdateStatus ret = UPDATE_OK;
00302 
00303     // Delete the event from the calendar file
00304     if (KAEvent::uidStatus(id) == KAEvent::EXPIRED)
00305     {
00306         AlarmCalendar* cal = AlarmCalendar::expiredCalendarOpen();
00307         if (cal)
00308             cal->deleteEvent(id, true);   // save calendar after deleting
00309     }
00310     else
00311     {
00312         if (event.copyToKOrganizer())
00313         {
00314             // The event was shown in KOrganizer, so tell KOrganizer to
00315             // delete it. But ignore errors, because the user could have
00316             // manually deleted it from KOrganizer since it was set up.
00317             deleteFromKOrganizer(event.id());
00318         }
00319         if (archive  &&  event.toBeArchived())
00320             addExpiredEvent(event);     // this changes the event ID to an expired ID
00321         AlarmCalendar* cal = AlarmCalendar::activeCalendar();
00322         cal->deleteEvent(id);
00323         cal->save();
00324     }
00325     return ret;
00326 }
00327 
00328 /******************************************************************************
00329 * Delete a template from the calendar file and from every template list view.
00330 */
00331 void deleteTemplate(const KAEvent& event)
00332 {
00333     QString id = event.id();
00334 
00335     // Delete the template from the calendar file
00336     AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
00337     if (cal)
00338     {
00339         cal->deleteEvent(id);
00340         cal->save();
00341         cal->emitEmptyStatus();
00342     }
00343 
00344     // Update the window lists
00345     TemplateListView::deleteEvent(id);
00346 }
00347 
00348 /******************************************************************************
00349 * Delete an alarm from the display calendar.
00350 */
00351 void deleteDisplayEvent(const QString& eventID)
00352 {
00353     kdDebug(5950) << "KAlarm::deleteDisplayEvent(" << eventID << ")\n";
00354 
00355     if (KAEvent::uidStatus(eventID) == KAEvent::DISPLAYING)
00356     {
00357         AlarmCalendar* cal = AlarmCalendar::displayCalendarOpen();
00358         if (cal)
00359             cal->deleteEvent(eventID, true);   // save calendar after deleting
00360     }
00361 }
00362 
00363 /******************************************************************************
00364 * Undelete an expired alarm, and update every main window instance.
00365 * The archive bit is set to ensure that it gets re-archived if it is deleted again.
00366 * If 'selectionView' is non-null, the selection highlight is moved to the
00367 * restored event in that listView instance.
00368 */
00369 UpdateStatus reactivateEvent(KAEvent& event, AlarmListView* selectionView, bool useEventID)
00370 {
00371     QString id = event.id();
00372     kdDebug(5950) << "KAlarm::reactivateEvent(): " << id << endl;
00373 
00374     // Delete the event from the expired calendar file
00375     if (KAEvent::uidStatus(id) == KAEvent::EXPIRED)
00376     {
00377         QDateTime now = QDateTime::currentDateTime();
00378         if (event.occursAfter(now, true))
00379         {
00380             if (event.recurs())
00381                 event.setNextOccurrence(now, true);   // skip any recurrences in the past
00382             event.setArchive();    // ensure that it gets re-archived if it is deleted
00383 
00384             // Save the event details in the calendar file, and get the new event ID
00385             AlarmCalendar* cal = AlarmCalendar::activeCalendar();
00386             cal->addEvent(event, useEventID);
00387             cal->save();
00388 
00389             UpdateStatus ret = UPDATE_OK;
00390             if (event.copyToKOrganizer())
00391             {
00392                 if (!sendToKOrganizer(event))    // tell KOrganizer to show the event
00393                     ret = UPDATE_KORG_ERR;
00394             }
00395 
00396             // Update the window lists
00397             AlarmListView::undeleteEvent(id, event, selectionView);
00398 
00399             cal = AlarmCalendar::expiredCalendarOpen();
00400             if (cal)
00401                 cal->deleteEvent(id, true);   // save calendar after deleting
00402             return ret;
00403         }
00404     }
00405     return UPDATE_ERROR;
00406 }
00407 
00408 /******************************************************************************
00409 * Enable or disable an alarm in the calendar file and in every main window instance.
00410 * The new event will have the same event ID as the old one.
00411 * If 'selectionView' is non-null, the selection highlight is moved to the
00412 * updated event in that listView instance.
00413 */
00414 void enableEvent(KAEvent& event, AlarmListView* selectionView, bool enable)
00415 {
00416     kdDebug(5950) << "KAlarm::enableEvent(" << enable << "): " << event.id() << endl;
00417 
00418     if (enable != event.enabled())
00419     {
00420         event.setEnabled(enable);
00421 
00422         // Update the event in the calendar file
00423         AlarmCalendar* cal = AlarmCalendar::activeCalendar();
00424         cal->updateEvent(event);
00425         cal->save();
00426 
00427         // If we're disabling a display alarm, close any message window
00428         if (!enable  &&  event.displayAction())
00429         {
00430             MessageWin* win = MessageWin::findEvent(event.id());
00431             delete win;
00432         }
00433 
00434         // Update the window lists
00435         AlarmListView::modifyEvent(event, selectionView);
00436     }
00437 }
00438 
00439 /******************************************************************************
00440 * Display an error message corresponding to a specified alarm update error code.
00441 */
00442 void displayUpdateError(QWidget* parent, UpdateError code, bool multipleAlarms)
00443 {
00444     QString errmsg;
00445     switch (code)
00446     {
00447         case KORG_ERR_ADD:
00448             errmsg = multipleAlarms ? i18n("Unable to show alarms in KOrganizer")
00449                                     : i18n("Unable to show alarm in KOrganizer");
00450             break;
00451         case KORG_ERR_MODIFY:
00452             errmsg = i18n("Unable to update alarm in KOrganizer");
00453             break;
00454         case KORG_ERR_DELETE:
00455             errmsg = multipleAlarms ? i18n("Unable to delete alarms from KOrganizer")
00456                                     : i18n("Unable to delete alarm from KOrganizer");
00457             break;
00458     }
00459     KMessageBox::error(parent, errmsg);
00460 }
00461 
00462 /******************************************************************************
00463 *  Returns a list of all alarm templates.
00464 *  If shell commands are disabled, command alarm templates are omitted.
00465 */
00466 QValueList<KAEvent> templateList()
00467 {
00468     QValueList<KAEvent> templates;
00469     AlarmCalendar* cal = AlarmCalendar::templateCalendarOpen();
00470     if (cal)
00471     {
00472         bool includeCmdAlarms = ShellProcess::authorised();
00473         KCal::Event::List events = cal->events();
00474         for (KCal::Event::List::ConstIterator it = events.begin();  it != events.end();  ++it)
00475         {
00476             KCal::Event* kcalEvent = *it;
00477             KAEvent event(*kcalEvent);
00478             if (includeCmdAlarms  ||  event.action() != KAEvent::COMMAND)
00479                 templates.append(event);
00480         }
00481     }
00482     return templates;
00483 }
00484 
00485 /******************************************************************************
00486 * To be called after an alarm has been edited.
00487 * Prompt the user to re-enable alarms if they are currently disabled, and if
00488 * it's an email alarm, warn if no 'From' email address is configured.
00489 */
00490 void outputAlarmWarnings(QWidget* parent, const KAEvent* event)
00491 {
00492     if (event  &&  event->action() == KAEvent::EMAIL
00493     &&  Preferences::emailAddress().isEmpty())
00494         KMessageBox::information(parent, i18n("Please set the 'From' email address...",
00495                                               "%1\nPlease set it in the Preferences dialog.").arg(KAMail::i18n_NeedFromEmailAddress()));
00496 
00497     if (!Daemon::monitoringAlarms())
00498     {
00499         if (KMessageBox::warningYesNo(parent, i18n("Alarms are currently disabled.\nDo you want to enable alarms now?"),
00500                                       QString::null, i18n("Enable"), i18n("Keep Disabled"),
00501                                       QString::fromLatin1("EditEnableAlarms"))
00502                         == KMessageBox::Yes)
00503             Daemon::setAlarmsEnabled();
00504     }
00505 }
00506 
00507 /******************************************************************************
00508 * Reset the alarm daemon and reload the calendar.
00509 * If the daemon is not already running, start it.
00510 */
00511 void resetDaemon()
00512 {
00513     kdDebug(5950) << "KAlarm::resetDaemon()" << endl;
00514     if (!resetDaemonQueued)
00515     {
00516         resetDaemonQueued = true;
00517         theApp()->processQueue();
00518     }
00519 }
00520 
00521 /******************************************************************************
00522 * This method must only be called from the main KAlarm queue processing loop,
00523 * to prevent asynchronous calendar operations interfering with one another.
00524 *
00525 * If resetDaemon() has been called, reset the alarm daemon and reload the calendars.
00526 * If the daemon is not already running, start it.
00527 */
00528 void resetDaemonIfQueued()
00529 {
00530     if (resetDaemonQueued)
00531     {
00532         kdDebug(5950) << "KAlarm::resetDaemonIfNeeded()" << endl;
00533         AlarmCalendar::activeCalendar()->reload();
00534         AlarmCalendar::expiredCalendar()->reload();
00535 
00536         // Close any message windows for alarms which are now disabled
00537         KAEvent event;
00538         KCal::Event::List events = AlarmCalendar::activeCalendar()->events();
00539         for (KCal::Event::List::ConstIterator it = events.begin();  it != events.end();  ++it)
00540         {
00541             KCal::Event* kcalEvent = *it;
00542             event.set(*kcalEvent);
00543             if (!event.enabled()  &&  event.displayAction())
00544             {
00545                 MessageWin* win = MessageWin::findEvent(event.id());
00546                 delete win;
00547             }
00548         }
00549 
00550         MainWindow::refresh();
00551         if (!Daemon::reset())
00552             Daemon::start();
00553         resetDaemonQueued = false;
00554     }
00555 }
00556 
00557 /******************************************************************************
00558 *  Start KMail if it isn't already running, and optionally iconise it.
00559 *  Reply = reason for failure to run KMail (which may be the empty string)
00560 *        = null string if success.
00561 */
00562 QString runKMail(bool minimise)
00563 {
00564     QCString dcopName;
00565     QString errmsg;
00566     if (!runProgram("kmail", (minimise ? KMAIL_DCOP_WINDOW : ""), dcopName, errmsg))
00567         return i18n("Unable to start KMail\n(%1)").arg(errmsg);
00568     return QString::null;
00569 }
00570 
00571 /******************************************************************************
00572 *  Start another program for DCOP access if it isn't already running.
00573 *  If 'windowName' is not empty, the program's window of that name is iconised.
00574 *  On exit, 'dcopName' contains the DCOP name to access the application, and
00575 *  'errorMessage' contains an error message if failure.
00576 *  Reply = true if the program is now running.
00577 */
00578 bool runProgram(const QCString& program, const QCString& windowName, QCString& dcopName, QString& errorMessage)
00579 {
00580     if (!kapp->dcopClient()->isApplicationRegistered(program))
00581     {
00582         // KOrganizer is not already running, so start it
00583         if (KApplication::startServiceByDesktopName(QString::fromLatin1(program), QString::null, &errorMessage, &dcopName))
00584         {
00585             kdError(5950) << "runProgram(): couldn't start " << program << " (" << errorMessage << ")\n";
00586             return false;
00587         }
00588         // Minimise its window - don't use hide() since this would remove all
00589         // trace of it from the panel if it is not configured to be docked in
00590         // the system tray.
00591         kapp->dcopClient()->send(dcopName, windowName, "minimize()", QString::null);
00592     }
00593     else if (dcopName.isEmpty())
00594         dcopName = program;
00595     errorMessage = QString::null;
00596     return true;
00597 }
00598 
00599 /******************************************************************************
00600 *  Read the size for the specified window from the config file, for the
00601 *  current screen resolution.
00602 *  Reply = true if size set in the config file, in which case 'result' is set
00603 *        = false if no size is set, in which case 'result' is unchanged.
00604 */
00605 bool readConfigWindowSize(const char* window, QSize& result)
00606 {
00607     KConfig* config = KGlobal::config();
00608     config->setGroup(QString::fromLatin1(window));
00609     QWidget* desktop = KApplication::desktop();
00610     QSize s = QSize(config->readNumEntry(QString::fromLatin1("Width %1").arg(desktop->width()), 0),
00611                     config->readNumEntry(QString::fromLatin1("Height %1").arg(desktop->height()), 0));
00612     if (s.isEmpty())
00613         return false;
00614     result = s;
00615     return true;
00616 }
00617 
00618 /******************************************************************************
00619 *  Write the size for the specified window to the config file, for the
00620 *  current screen resolution.
00621 */
00622 void writeConfigWindowSize(const char* window, const QSize& size)
00623 {
00624     KConfig* config = KGlobal::config();
00625     config->setGroup(QString::fromLatin1(window));
00626     QWidget* desktop = KApplication::desktop();
00627     config->writeEntry(QString::fromLatin1("Width %1").arg(desktop->width()), size.width());
00628     config->writeEntry(QString::fromLatin1("Height %1").arg(desktop->height()), size.height());
00629     config->sync();
00630 }
00631 
00632 /******************************************************************************
00633 * Convert the supplied KAlarm version string to a version number.
00634 * Reply = version number (double digit for each of major, minor & issue number,
00635 *         e.g. 010203 for 1.2.3
00636 *       = 0 if invalid version string.
00637 */
00638 int getVersionNumber(const QString& version, QString* subVersion)
00639 {
00640     // N.B. Remember to change  Version(int major, int minor, int rev)
00641     //      if the representation returned by this method changes.
00642     if (subVersion)
00643         *subVersion = QString::null;
00644     QStringList nums = QStringList::split(QChar('.'), version, true);
00645     int count = nums.count();
00646     if (count < 2  ||  count > 3)
00647         return 0;
00648     bool ok;
00649     int vernum = nums[0].toInt(&ok) * 10000;    // major version
00650     if (!ok)
00651         return 0;
00652     int v = nums[1].toInt(&ok);                 // minor version
00653     if (!ok)
00654         return 0;
00655     vernum += (v < 99 ? v : 99) * 100;
00656     if (count == 3)
00657     {
00658         // Issue number: allow other characters to follow the last digit
00659         QString issue = nums[2];
00660         if (!issue.at(0).isDigit())
00661             return 0;
00662         v = issue.toInt();   // issue number
00663         vernum += (v < 99 ? v : 99);
00664         if (subVersion)
00665         {
00666             int i;
00667             for (i = 1;  const_cast<const QString&>(issue).at(i).isDigit();  ++i) ;
00668             *subVersion = issue.mid(i);
00669         }
00670     }
00671     return vernum;
00672 }
00673 
00674 /******************************************************************************
00675 * Check from its mime type whether a file appears to be a text or image file.
00676 * If a text file, its type is distinguished.
00677 * Reply = file type.
00678 */
00679 FileType fileType(const QString& mimetype)
00680 {
00681     static const char* applicationTypes[] = {
00682         "x-shellscript", "x-nawk", "x-awk", "x-perl", "x-python",
00683         "x-desktop", "x-troff", 0 };
00684     static const char* formattedTextTypes[] = {
00685         "html", "xml", 0 };
00686 
00687     if (mimetype.startsWith(QString::fromLatin1("image/")))
00688         return Image;
00689     int slash = mimetype.find('/');
00690     if (slash < 0)
00691         return Unknown;
00692     QString type = mimetype.mid(slash + 1);
00693     const char* typel = type.latin1();
00694     if (mimetype.startsWith(QString::fromLatin1("application")))
00695     {
00696         for (int i = 0;  applicationTypes[i];  ++i)
00697             if (!strcmp(typel, applicationTypes[i]))
00698                 return TextApplication;
00699     }
00700     else if (mimetype.startsWith(QString::fromLatin1("text")))
00701     {
00702         for (int i = 0;  formattedTextTypes[i];  ++i)
00703             if (!strcmp(typel, formattedTextTypes[i]))
00704                 return TextFormatted;
00705         return TextPlain;
00706     }
00707     return Unknown;
00708 }
00709 
00710 /******************************************************************************
00711 * Display a modal dialogue to choose an existing file, initially highlighting
00712 * any specified file.
00713 * @param initialFile The file to initially highlight - must be a full path name or URL.
00714 * @param defaultDir The directory to start in if @p initialFile is empty. If empty,
00715 *                   the user's home directory will be used. Updated to the
00716 *                   directory containing the selected file, if a file is chosen.
00717 * @param mode OR of KFile::Mode values, e.g. ExistingOnly, LocalOnly.
00718 * Reply = URL selected. If none is selected, URL.isEmpty() is true.
00719 */
00720 QString browseFile(const QString& caption, QString& defaultDir, const QString& initialFile,
00721                    const QString& filter, int mode, QWidget* parent, const char* name)
00722 {
00723     QString initialDir = !initialFile.isEmpty() ? QString(initialFile).remove(QRegExp("/[^/]*$"))
00724                        : !defaultDir.isEmpty()  ? defaultDir
00725                        :                          QDir::homeDirPath();
00726     KFileDialog fileDlg(initialDir, filter, parent, name, true);
00727     fileDlg.setOperationMode(mode & KFile::ExistingOnly ? KFileDialog::Opening : KFileDialog::Saving);
00728     fileDlg.setMode(KFile::File | mode);
00729     fileDlg.setCaption(caption);
00730     if (!initialFile.isEmpty())
00731         fileDlg.setSelection(initialFile);
00732     if (fileDlg.exec() != QDialog::Accepted)
00733         return QString::null;
00734     KURL url = fileDlg.selectedURL();
00735     defaultDir = url.path();
00736     return url.prettyURL();
00737 }
00738 
00739 /******************************************************************************
00740 *  Return the first day of the week for the user's locale.
00741 *  Reply = 1 (Mon) .. 7 (Sun).
00742 */
00743 int localeFirstDayOfWeek()
00744 {
00745     static int firstDay = 0;
00746     if (!firstDay)
00747         firstDay = KGlobal::locale()->weekStartDay();
00748     return firstDay;
00749 }
00750 
00751 /******************************************************************************
00752 *  Return the supplied string with any accelerator code stripped out.
00753 */
00754 QString stripAccel(const QString& text)
00755 {
00756     unsigned len = text.length();
00757     QString out = QDeepCopy<QString>(text);
00758     QChar *corig = (QChar*)out.unicode();
00759     QChar *cout  = corig;
00760     QChar *cin   = cout;
00761     while (len)
00762     {
00763         if ( *cin == '&' )
00764         {
00765             ++cin;
00766             --len;
00767             if ( !len )
00768                 break;
00769         }
00770         *cout = *cin;
00771         ++cout;
00772         ++cin;
00773         --len;
00774     }
00775     unsigned newlen = cout - corig;
00776     if (newlen != out.length())
00777         out.truncate(newlen);
00778     return out;
00779 }
00780 
00781 } // namespace KAlarm
00782 
00783 
00784 namespace {
00785 
00786 /******************************************************************************
00787 *  Tell KOrganizer to put an alarm in its calendar.
00788 *  It will be held by KOrganizer as a simple event, without alarms - KAlarm
00789 *  is still responsible for alarming.
00790 */
00791 bool sendToKOrganizer(const KAEvent& event)
00792 {
00793     KCal::Event* kcalEvent = event.event();
00794     QString uid = KAEvent::uid(event.id(), KAEvent::KORGANIZER);
00795     kcalEvent->setUid(uid);
00796     kcalEvent->clearAlarms();
00797     QString userEmail;
00798     switch (event.action())
00799     {
00800         case KAEvent::MESSAGE:
00801         case KAEvent::FILE:
00802         case KAEvent::COMMAND:
00803             kcalEvent->setSummary(event.cleanText());
00804             userEmail = Preferences::emailAddress();
00805             break;
00806         case KAEvent::EMAIL:
00807         {
00808             QString from = event.emailFromKMail().isEmpty()
00809                          ? Preferences::emailAddress()
00810                          : KAMail::identityManager()->identityForName(event.emailFromKMail()).fullEmailAddr();
00811             AlarmText atext;
00812             atext.setEmail(event.emailAddresses(", "), from, QString::null, QString::null, event.emailSubject(), QString::null);
00813             kcalEvent->setSummary(atext.displayText());
00814             userEmail = from;
00815             break;
00816         }
00817     }
00818     kcalEvent->setOrganizer(KCal::Person(QString::null, userEmail));
00819 
00820     // Translate the event into string format
00821     KCal::ICalFormat format;
00822     format.setTimeZone(QString::null, false);
00823     QString iCal = format.toICalString(kcalEvent);
00824 kdDebug(5950)<<"Korg->"<<iCal<<endl;
00825     delete kcalEvent;
00826 
00827     // Send the event to KOrganizer
00828     if (!runKOrganizer())     // start KOrganizer if it isn't already running
00829         return false;
00830     QByteArray  data, replyData;
00831     QCString    replyType;
00832     QDataStream arg(data, IO_WriteOnly);
00833     arg << iCal;
00834     if (kapp->dcopClient()->call(korganizerName, KORG_DCOP_OBJECT, "addIncidence(QString)", data, replyType, replyData)
00835     &&  replyType == "bool")
00836     {
00837         bool result;
00838         QDataStream reply(replyData, IO_ReadOnly);
00839         reply >> result;
00840         if (result)
00841         {
00842             kdDebug(5950) << "sendToKOrganizer(" << uid << "): success\n";
00843             return true;
00844         }
00845     }
00846     kdError(5950) << "sendToKOrganizer(): KOrganizer addEvent(" << uid << ") dcop call failed\n";
00847     return false;
00848 }
00849 
00850 /******************************************************************************
00851 *  Tell KOrganizer to delete an event from its calendar.
00852 */
00853 bool deleteFromKOrganizer(const QString& eventID)
00854 {
00855     if (!runKOrganizer())     // start KOrganizer if it isn't already running
00856         return false;
00857     QString newID = KAEvent::uid(eventID, KAEvent::KORGANIZER);
00858     QByteArray  data, replyData;
00859     QCString    replyType;
00860     QDataStream arg(data, IO_WriteOnly);
00861     arg << newID << true;
00862     if (kapp->dcopClient()->call(korganizerName, KORG_DCOP_OBJECT, "deleteIncidence(QString,bool)", data, replyType, replyData)
00863     &&  replyType == "bool")
00864     {
00865         bool result;
00866         QDataStream reply(replyData, IO_ReadOnly);
00867         reply >> result;
00868         if (result)
00869         {
00870             kdDebug(5950) << "deleteFromKOrganizer(" << newID << "): success\n";
00871             return true;
00872         }
00873     }
00874     kdError(5950) << "sendToKOrganizer(): KOrganizer deleteEvent(" << newID << ") dcop call failed\n";
00875     return false;
00876 }
00877 
00878 } // namespace
KDE Home | KDE Accessibility Home | Description of Access Keys