alarmdialog.cpp 31.8 KB
Newer Older
1
/*
Allen Winter's avatar
Allen Winter committed
2
  This file is part of the KDE reminder agent.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

  Copyright (c) 2000,2003 Cornelius Schumacher <schumacher@kde.org>
  Copyright (c) 2008-2009 Allen Winter <winter@kde.org>
  Copyright (c) 2009-2010 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.net>

  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.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "alarmdialog.h"
#include "korganizer_interface.h"
29
#include "mailclient.h"
30

31
#include <calendarsupport/next/incidenceviewer.h>
32
#include <calendarsupport/kcalprefs.h>
33
#include <calendarsupport/identitymanager.h>
34 35
#include <calendarsupport/utils.h>

36 37 38
#include <incidenceeditor-ng/incidencedialog.h>
#include <incidenceeditor-ng/incidencedialogfactory.h>

39 40 41
#include <KCalCore/Event>
#include <KCalCore/Todo>
#include <KCalUtils/IncidenceFormatter>
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

#include <KPIMIdentities/Identity>
#include <KPIMIdentities/IdentityManager>

#include <Akonadi/Item>

#include <Mailtransport/TransportManager>

#include <KComboBox>
#include <KDebug>
#include <KHBox>
#include <KLocale>
#include <KMessageBox>
#include <KNotification>
#include <KSharedConfig>
#include <KSystemTimeZone>
#include <KToolInvocation>
#include <KWindowSystem>

#include <phonon/mediaobject.h>
#include <QLabel>
63
#include <QKeyEvent>
64 65 66 67 68 69 70 71 72 73 74
#include <QSpinBox>
#include <QTreeWidget>
#include <QVBoxLayout>

using namespace KPIMIdentities;
using namespace KCalCore;
using namespace KCalUtils;

static int defSuspendVal = 5;
static int defSuspendUnit = 0; // 0=>minutes, 1=>hours, 2=>days, 3=>weeks

75
class ReminderTree : public QTreeWidget
76 77
{
  public:
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    ReminderTree( QWidget *parent ) : QTreeWidget( parent )
    {
    }

    /*reimp*/
    void mouseReleaseEvent( QMouseEvent *event );
};

void ReminderTree::mouseReleaseEvent( QMouseEvent *event )
{
  QTreeWidgetItem *item = itemAt( event->pos() );
  if ( item ) {
    if ( event->button() == Qt::LeftButton ) {
      emit itemActivated( item, 0 );
    } else if ( event->button() == Qt::RightButton ) {
      emit customContextMenuRequested( event->pos() );
    }
  }
}

class ReminderTreeItem : public QTreeWidgetItem
{
  public:
    ReminderTreeItem( const Akonadi::Item &incidence, QTreeWidget *parent )
102
      : QTreeWidgetItem( parent ), mIncidence( incidence ), mNotified( false )
103 104
    {
    }
105
    bool operator<( const QTreeWidgetItem & other ) const;
106 107 108 109 110 111 112 113 114 115

    QString mDisplayText;

    const Akonadi::Item mIncidence;
    QDateTime mRemindAt;
    KDateTime mTrigger;
    KDateTime mHappening;
    bool mNotified;
};

116 117 118 119 120 121
struct ConfItem {
  QString uid;
  KUrl akonadiUrl;
  QDateTime remindAt;
};

122
bool ReminderTreeItem::operator<( const QTreeWidgetItem &other ) const
123 124 125 126
{
  switch( treeWidget()->sortColumn() ) {
  case 1: // happening datetime
  {
127
    const ReminderTreeItem *item = static_cast<const ReminderTreeItem *>( &other );
128 129 130 131
    return item->mHappening.secsTo( mHappening );
  }
  case 2: // trigger datetime
  {
132
    const ReminderTreeItem *item = static_cast<const ReminderTreeItem *>( &other );
133 134 135 136 137 138 139
    return item->mTrigger.secsTo( mTrigger );
  }
  default:
    return QTreeWidgetItem::operator < ( other );
  }
}

140
typedef QList<ReminderTreeItem *> ReminderList;
141

142
AlarmDialog::AlarmDialog( const Akonadi::ETMCalendar::Ptr &calendar, QWidget *parent )
143 144 145 146 147 148 149 150
  : KDialog( parent, Qt::WindowStaysOnTopHint ),
    mCalendar( calendar ), mSuspendTimer( this )
{
  // User1 => Edit...
  // User2 => Dismiss All
  // User3 => Dismiss Selected
  //    Ok => Suspend

151
  connect( calendar.data(), SIGNAL(calendarChanged()), SLOT(slotCalendarChanged()) );
152

153
  KIconLoader::global()->addAppDir( QLatin1String("korgac") );
154 155 156 157 158 159 160 161 162 163 164 165

  KSharedConfig::Ptr config = KGlobal::config();
  KConfigGroup generalConfig( config, "General" );
  QPoint pos = generalConfig.readEntry( "Position", QPoint( 0, 0 ) );

  QWidget *topBox = new QWidget( this );
  if ( !pos.isNull() ) {
    mPos = pos;
    topBox->move( mPos );
  }
  setMainWidget( topBox );
  setCaption( i18nc( "@title:window", "Reminders" ) );
166
  setWindowIcon( KIcon( QLatin1String("korgac") ) );
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  setButtons( Ok | User1 | User2 | User3 );
  setDefaultButton( NoDefault );
  setButtonText( User3, i18nc( "@action:button", "Dismiss Reminder" ) );
  setButtonToolTip( User3, i18nc( "@info:tooltip",
                                  "Dismiss the reminders for the selected incidences" ) );
  setButtonText( User2, i18nc( "@action:button", "Dismiss All" ) );
  setButtonToolTip( User2, i18nc( "@info:tooltip",
                                  "Dismiss the reminders for all listed incidences" ) );
  setButtonText( User1, i18nc( "@action:button", "Edit..." ) );
  setButtonToolTip( User1, i18nc( "@info:tooltip",
                                  "Edit the selected incidence" ) );
  setButtonText( Ok, i18nc( "@action:button", "Suspend" ) );
  setButtonToolTip( Ok, i18nc( "@info:tooltip",
                               "Suspend the reminders for the selected incidences "
                               "by the specified interval" ) );

  // Try to keep the dialog small and non-obtrusive.
  setMinimumWidth( 575 );
  setMinimumHeight( 300 );

  QVBoxLayout *mTopLayout = new QVBoxLayout( topBox );

  QLabel *label = new QLabel(
    i18nc( "@label",
           "Reminders: "
           "Click on a title to toggle the details viewer for that item" ),
    topBox );
  mTopLayout->addWidget( label );

196
  mIncidenceTree = new ReminderTree( topBox );
197 198
  mIncidenceTree->setColumnCount( 3 );
  mIncidenceTree->setSortingEnabled( true );
199
  const QStringList headerLabels =
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    ( QStringList( i18nc( "@title:column reminder title", "Title" ) )
      << i18nc( "@title:column happens at date/time", "Date Time" )
      << i18nc( "@title:column trigger date/time", "Trigger Time" ) );
  mIncidenceTree->setHeaderLabels( headerLabels );
  mIncidenceTree->headerItem()->setToolTip(
    0,
    i18nc( "@info:tooltip", "The event or to-do title" ) );
  mIncidenceTree->headerItem()->setToolTip(
    1,
    i18nc( "@info:tooltip", "The reminder is set for this date/time" ) );
  mIncidenceTree->headerItem()->setToolTip(
    2,
    i18nc( "@info:tooltip", "The date/time the reminder was triggered" ) );

  mIncidenceTree->setWordWrap( true );
  mIncidenceTree->setAllColumnsShowFocus( true );
  mIncidenceTree->setSelectionMode( QAbstractItemView::ExtendedSelection );
217
  mIncidenceTree->setRootIsDecorated( false );
218 219 220 221 222 223 224

  mTopLayout->addWidget( mIncidenceTree );

  connect( mIncidenceTree, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
           SLOT(update()) );
  connect( mIncidenceTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
           SLOT(edit()) );
Allen Winter's avatar
Allen Winter committed
225
  connect( mIncidenceTree, SIGNAL(customContextMenuRequested(QPoint)), SLOT(popupItemMenu(QPoint)) );
226

227
  mDetailView = new CalendarSupport::IncidenceViewer( mCalendar.data(), topBox );
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  QString s;
  s = i18nc( "@info default incidence details string",
             "<emphasis>Select an event or to-do from the list above "
             "to view its details here.</emphasis>" );
  mDetailView->setDefaultMessage( s );
  mTopLayout->addWidget( mDetailView );
  mDetailView->hide();
  mLastItem = 0;

  KHBox *suspendBox = new KHBox( topBox );
  suspendBox->setSpacing( spacingHint() );
  mTopLayout->addWidget( suspendBox );

  QLabel *l = new QLabel( i18nc( "@label:spinbox", "Suspend &duration:" ), suspendBox );

  mSuspendSpin = new QSpinBox( suspendBox );
  mSuspendSpin->setRange( 1, 9999 );
  mSuspendSpin->setValue( defSuspendVal );  // default suspend duration
  mSuspendSpin->setToolTip(
    i18nc( "@info:tooltip",
           "Suspend the reminders by this amount of time" ) );
  mSuspendSpin->setWhatsThis(
    i18nc( "@info:whatsthis",
           "Each reminder for the selected incidences will be suspended "
           "by this number of time units. You can choose the time units "
           "(typically minutes) in the adjacent selector." ) );

  l->setBuddy( mSuspendSpin );

  mSuspendUnit = new KComboBox( suspendBox );
  mSuspendUnit->addItem( i18nc( "@item:inlistbox suspend in terms of minutes", "minute(s)" ) );
  mSuspendUnit->addItem( i18nc( "@item:inlistbox suspend in terms of hours", "hour(s)" ) );
  mSuspendUnit->addItem( i18nc( "@item:inlistbox suspend in terms of days", "day(s)" ) );
  mSuspendUnit->addItem( i18nc( "@item:inlistbox suspend in terms of weeks", "week(s)" ) );
  mSuspendUnit->setToolTip(
    i18nc( "@info:tooltip",
           "Suspend the reminders using this time unit" ) );
  mSuspendUnit->setWhatsThis(
    i18nc( "@info:whatsthis",
           "Each reminder for the selected incidences will be suspended "
           "using this time unit. You can set the number of time units "
           "in the adjacent number entry input." ) );

  mSuspendUnit->setCurrentIndex( defSuspendUnit );

  connect( &mSuspendTimer, SIGNAL(timeout()), SLOT(wakeUp()) );

  connect( this, SIGNAL(okClicked()), this, SLOT(slotOk()) );
  connect( this, SIGNAL(user1Clicked()), this, SLOT(slotUser1()) );
  connect( this, SIGNAL(user2Clicked()), this, SLOT(slotUser2()) );
  connect( this, SIGNAL(user3Clicked()), this, SLOT(slotUser3()) );
279 280

  mIdentityManager = new CalendarSupport::IdentityManager;
281 282 283 284 285
}

AlarmDialog::~AlarmDialog()
{
  mIncidenceTree->clear();
286
  delete mIdentityManager;
287 288
}

289
ReminderTreeItem *AlarmDialog::searchByItem( const Akonadi::Item &incidence )
290
{
291
  ReminderTreeItem *found = 0;
292 293
  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
294
    ReminderTreeItem *item = static_cast<ReminderTreeItem *>( *it );
295 296 297 298 299 300 301 302 303 304 305 306 307 308
    if ( item->mIncidence == incidence ) {
      found = item;
      break;
    }
    ++it;
  }
  return found;
}

static QString cleanSummary( const QString &summary )
{
  static QString etc = i18nc( "@label an elipsis", "..." );
  int maxLen = 30;
  QString retStr = summary;
309
  retStr.replace( QLatin1Char('\n'), QLatin1Char(' ') );
310 311 312 313 314 315 316 317 318 319 320 321 322
  if ( retStr.length() > maxLen ) {
    maxLen -= etc.length();
    retStr = retStr.left( maxLen );
    retStr += etc;
  }
  return retStr;
}

void AlarmDialog::addIncidence( const Akonadi::Item &incidenceitem,
                                const QDateTime &reminderAt,
                                const QString &displayText )
{
  Incidence::Ptr incidence = CalendarSupport::incidence( incidenceitem );
323
  ReminderTreeItem *item = searchByItem( incidenceitem );
324
  if ( !item ) {
325
    item = new ReminderTreeItem( incidenceitem, mIncidenceTree );
326 327 328 329 330 331 332 333 334 335
  }
  item->mNotified = false;
  item->mHappening = KDateTime();
  item->mRemindAt = reminderAt;
  item->mTrigger = KDateTime::currentLocalDateTime();
  item->mDisplayText = displayText;
  item->setText( 0, cleanSummary( incidence->summary() ) );

  Event::Ptr event;
  Todo::Ptr todo;
336 337 338 339 340 341

  QString displayStr;
  const KDateTime dateTime = triggerDateForIncidence( incidence, reminderAt,
                                                      displayStr );

  if ( incidence->type() == Incidence::TypeEvent ) {
342
    item->setIcon( 0, SmallIcon( QLatin1String("view-calendar-day") ) );
343
  } else if ( incidence->type() == Incidence::TypeTodo ) {
344
    item->setIcon( 0, SmallIcon( QLatin1String("view-calendar-tasks")) );
345
  }
346 347 348 349

  item->mHappening = dateTime;
  item->setText( 1, displayStr );

350 351 352
  item->setText( 2, IncidenceFormatter::dateTimeToString(
                   item->mTrigger, false, true, KDateTime::Spec::LocalZone() ) );
  QString tip =
353
    IncidenceFormatter::toolTipStr(
354
      CalendarSupport::displayName( mCalendar.data(), incidenceitem.parentCollection() ),
355 356 357
      incidence,
      item->mRemindAt.date(), true,
      KDateTime::Spec::LocalZone() );
358
  if ( !item->mDisplayText.isEmpty() ) {
359
    tip += QLatin1String("<br>") + item->mDisplayText;
360 361 362 363 364 365 366
  }
  item->setToolTip( 0, tip );
  item->setToolTip( 1, tip );
  item->setToolTip( 2, tip );
  item->setData( 0, QTreeWidgetItem::UserType, false );

  mIncidenceTree->setCurrentItem( item );
367
  showDetails( item );
368
  slotSave();
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
}

void AlarmDialog::slotOk()
{
  suspend();
}

void AlarmDialog::slotUser1()
{
  edit();
}

void AlarmDialog::slotUser2()
{
  dismissAll();
}

void AlarmDialog::slotUser3()
{
  dismissCurrent();
}

void AlarmDialog::dismissCurrent()
{
  dismiss( selectedItems() );

  if ( activeCount() == 0 ) {
    accept();
  } else {
    update();
  }
  emit reminderCount( activeCount() );
}

void AlarmDialog::dismissAll()
{
  ReminderList selections;

  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
    if ( !(*it)->isDisabled() ) { //do not disable suspended reminders
410
      selections.append( static_cast<ReminderTreeItem *>( *it ) );
411 412 413 414 415 416 417 418 419 420 421 422
    }
    ++it;
  }
  dismiss( selections );

  setTimer();
  accept();
  emit reminderCount( activeCount() );
}

void AlarmDialog::dismiss( ReminderList selections )
{
423
  QList<Akonadi::Item::Id> ids;
424 425 426 427 428 429 430 431
  for ( ReminderList::Iterator it = selections.begin(); it != selections.end(); ++it ) {
    kDebug() << "removing " << CalendarSupport::incidence( (*it)->mIncidence )->summary();
    if ( mIncidenceTree->itemBelow( *it ) ) {
      mIncidenceTree->setCurrentItem( mIncidenceTree->itemBelow( *it ) );
    } else if ( mIncidenceTree->itemAbove( *it ) ) {
      mIncidenceTree->setCurrentItem( mIncidenceTree->itemAbove( *it ) );
    }
    mIncidenceTree->removeItemWidget( *it, 0 );
432
    ids.append( (*it)->mIncidence.id() );
433 434
    delete *it;
  }
435

436
  removeFromConfig( ids );
437 438 439 440 441 442 443 444 445
}

void AlarmDialog::edit()
{
  ReminderList selection = selectedItems();
  if ( selection.count() != 1 ) {
    return;
  }
  Incidence::Ptr incidence = CalendarSupport::incidence( selection.first()->mIncidence );
446
  if ( !mCalendar->hasRight( selection.first()->mIncidence, Akonadi::Collection::CanChangeItem ) ) {
447 448 449 450 451 452 453 454
    KMessageBox::sorry(
      this,
      i18nc( "@info",
             "\"%1\" is a read-only item so modifications are not possible.",
             cleanSummary( incidence->summary() ) ) );
    return;
  }

Allen Winter's avatar
Allen Winter committed
455
#if !defined(KDEPIM_MOBILE_UI)
456 457 458 459
  openIncidenceEditorNG( selection.first()->mIncidence );
#else
  openIncidenceEditorThroughKOrganizer( incidence );
#endif
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
}

void AlarmDialog::suspend()
{
  if ( !isVisible() ) { //do nothing if the dialog is hidden
    return;
  }

  int unit = 1;
  switch ( mSuspendUnit->currentIndex() ) {
    case 3: // weeks
      unit *=  7;
    case 2: // days
      unit *= 24;
    case 1: // hours
      unit *= 60;
    case 0: // minutes
      unit *= 60;
    default:
      break;
  }

482
  ReminderTreeItem *selitem = 0;
483 484 485 486 487
  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
    if ( (*it)->isSelected() && !(*it)->isDisabled() ) { //suspend selected, non-suspended reminders
      (*it)->setSelected( false );
      (*it)->setDisabled( true );
488
      ReminderTreeItem *item = static_cast<ReminderTreeItem *>( *it );
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
      item->mRemindAt = QDateTime::currentDateTime().addSecs( unit * mSuspendSpin->value() );
      item->mHappening = KDateTime( item->mRemindAt, KDateTime::Spec::LocalZone() );
      item->mNotified = false;
      (*it)->setText( 1, KGlobal::locale()->formatDateTime( item->mHappening ) );
      selitem = item;
    }
    ++it;
  }

  if ( selitem ) {
    if ( mIncidenceTree->itemBelow( selitem ) ) {
      mIncidenceTree->setCurrentItem( mIncidenceTree->itemBelow( selitem ) );
    } else if ( mIncidenceTree->itemAbove( selitem ) ) {
      mIncidenceTree->setCurrentItem( mIncidenceTree->itemAbove( selitem ) );
    }
  }

  // save suspended alarms too so they can be restored on restart
  // kolab/issue4108
  slotSave();

  setTimer();
  if ( activeCount() == 0 ) {
    accept();
  } else {
    update();
  }
  emit reminderCount( activeCount() );
}

void AlarmDialog::setTimer()
{
  int nextReminderAt = -1;

  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
525
    ReminderTreeItem *item = static_cast<ReminderTreeItem *>( *it );
526
    if ( item->mRemindAt > QDateTime::currentDateTime() ) {
527
      const int secs = QDateTime::currentDateTime().secsTo( item->mRemindAt );
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
      nextReminderAt = nextReminderAt <= 0 ? secs : qMin( nextReminderAt, secs );
    }
    ++it;
  }

  if ( nextReminderAt >= 0 ) {
    mSuspendTimer.stop();
    mSuspendTimer.start( 1000 * ( nextReminderAt + 1 ) );
    mSuspendTimer.setSingleShot( true );
  }
}

void AlarmDialog::show()
{
  mIncidenceTree->resizeColumnToContents( 0 );
  mIncidenceTree->resizeColumnToContents( 1 );
  mIncidenceTree->resizeColumnToContents( 2 );
  mIncidenceTree->sortItems( 1, Qt::AscendingOrder );

  // select the first item that hasn't already been notified
  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
550
    ReminderTreeItem *item = static_cast<ReminderTreeItem *>( *it );
551 552 553 554
    if ( !item->mNotified ) {
      (*it)->setSelected( true );
      break;
    }
Sergio Martins's avatar
Sergio Martins committed
555
    ++it;
556 557 558
  }

  // reset the default suspend time
559 560 561
// Allen: commented-out the following lines on 17 Sept 2013
//  mSuspendSpin->setValue( defSuspendVal );
//  mSuspendUnit->setCurrentIndex( defSuspendUnit );
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

  KDialog::show();
  if ( !mPos.isNull() ) {
    KDialog::move( mPos );
  }
  KWindowSystem::unminimizeWindow( winId(), false );
  KWindowSystem::setState( winId(), NET::KeepAbove | NET::DemandsAttention );
  KWindowSystem::setOnAllDesktops( winId(), true );
  KWindowSystem::activateWindow( winId() );

  // Audio, Procedure, and EMail alarms
  eventNotification();
}

void AlarmDialog::suspendAll()
{
  mIncidenceTree->clearSelection();
  QTreeWidgetItemIterator it( mIncidenceTree );

  // first, select all non-suspended reminders
  while ( *it ) {
    if ( !(*it)->isDisabled() ) { //do not suspend suspended reminders
      (*it)->setSelected( true );
    }
    ++it;
  }

  //suspend all selected reminders
  suspend();
}

void AlarmDialog::eventNotification()
{
  bool beeped = false;
  bool found = false;

  ReminderList list;

  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
602
    ReminderTreeItem *item = static_cast<ReminderTreeItem *>( *it );
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    ++it;
    if ( item->isDisabled() || item->mNotified ) {
      //skip suspended reminders or reminders that have been notified
      continue;
    }
    found = true;
    item->mNotified = true;
    Incidence::Ptr incidence = CalendarSupport::incidence( item->mIncidence );
    Alarm::List alarms = incidence->alarms();
    Alarm::List::ConstIterator ait;
    for ( ait = alarms.constBegin(); ait != alarms.constEnd(); ++ait ) {
      Alarm::Ptr alarm = *ait;
      // FIXME: Check whether this should be done for all multiple alarms
      if ( alarm->type() == Alarm::Procedure ) {
        // FIXME: Add a message box asking whether the procedure should really be executed
        kDebug() << "Starting program: '" << alarm->programFile() << "'";

        QString program = alarm->programFile();

        // if the program name contains spaces escape it
623
        if ( program.contains( QLatin1Char(' ') )   &&
Allen Winter's avatar
Allen Winter committed
624 625
             !( program.startsWith( QLatin1Char('\"') ) &&
                program.endsWith( QLatin1Char('\"') ) ) ) {
626
          program = QLatin1Char('\"') + program + QLatin1Char('\"');
627 628
        }

629
        QProcess::startDetached( program + QLatin1Char(' ') + alarm->programArguments() );
630 631 632
      } else if ( alarm->type() == Alarm::Audio ) {
        beeped = true;
        Phonon::MediaObject *player =
Allen Winter's avatar
Allen Winter committed
633 634
          Phonon::createPlayer( Phonon::NotificationCategory,
                                KUrl( alarm->audioFile() ) );
635 636 637 638 639
        player->setParent( this );
        connect( player, SIGNAL(finished()), player, SLOT(deleteLater()) );
        player->play();
      } else if ( alarm->type() == Alarm::Email ) {
        QString from = CalendarSupport::KCalPrefs::instance()->email();
640
        Identity id = mIdentityManager->identityForAddress( from );
641 642 643 644 645 646 647 648 649 650
        QString to;
        if ( alarm->mailAddresses().isEmpty() ) {
          to = from;
        } else {
          const Person::List addresses = alarm->mailAddresses();
          QStringList add;
          for ( Person::List::ConstIterator it = addresses.constBegin();
                it != addresses.constEnd(); ++it ) {
            add << (*it)->fullName();
          }
651
          to = add.join( QLatin1String(", ") );
652 653 654 655
        }

        QString subject;

656
        Akonadi::Item parentItem = mCalendar->item( alarm->parentUid() );
657 658 659 660 661 662 663 664 665 666 667 668 669
        Incidence::Ptr parent = CalendarSupport::incidence( parentItem );

        if ( alarm->mailSubject().isEmpty() ) {
          if ( parent->summary().isEmpty() ) {
            subject = i18nc( "@title", "Reminder" );
          } else {
            subject = i18nc( "@title", "Reminder: %1", cleanSummary( parent->summary() ) );
          }
        } else {
          subject = i18nc( "@title", "Reminder: %1", alarm->mailSubject() );
        }

        QString body =
670 671
          IncidenceFormatter::mailBodyStr(
            parent.staticCast<IncidenceBase>(), KSystemTimeZones::local() );
672
        if ( !alarm->mailText().isEmpty() ) {
673
          body += QLatin1Char('\n') + alarm->mailText();
674 675
        }
        //TODO: support attachments
676
        KOrg::MailClient mailer;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        mailer.send( id, from, to, QString(), subject, body, true, false, QString(),
                     MailTransport::TransportManager::self()->defaultTransportName() );
      }
    }
  }

  if ( !beeped && found ) {
    KNotification::beep();
  }
}

void AlarmDialog::wakeUp()
{
  bool activeReminders = false;
  QTreeWidgetItemIterator it( mIncidenceTree );
692
  QTreeWidgetItem *firstItem = 0;
693
  while ( *it ) {
694 695 696 697
    if ( !firstItem ) {
      firstItem = *it;
    }
    ReminderTreeItem *item = static_cast<ReminderTreeItem *>( *it );
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    Incidence::Ptr incidence = CalendarSupport::incidence( item->mIncidence );

    if ( item->mRemindAt <= QDateTime::currentDateTime() ) {
      if ( item->isDisabled() ) { //do not wakeup non-suspended reminders
        item->setDisabled( false );
        item->setSelected( false );
      }
      activeReminders = true;
    } else {
      item->setDisabled( true );
    }

    ++it;
  }

  if ( activeReminders ) {
    show();
  }
  setTimer();
717
  showDetails( firstItem );
718 719 720 721 722 723 724
  emit reminderCount( activeCount() );
}

void AlarmDialog::slotSave()
{
  KSharedConfig::Ptr config = KGlobal::config();
  KConfigGroup generalConfig( config, "General" );
725
  int numReminders = 0;
726 727 728

  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
729
    ReminderTreeItem *item = static_cast<ReminderTreeItem *>( *it );
730
    KConfigGroup incidenceConfig( config,
731
                                  QString::fromLatin1( "Incidence-%1" ).arg( numReminders + 1 ) );
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751

    Incidence::Ptr incidence = CalendarSupport::incidence( item->mIncidence );
    incidenceConfig.writeEntry( "AkonadiUrl", item->mIncidence.url() );
    incidenceConfig.writeEntry( "RemindAt", item->mRemindAt );
    ++numReminders;
    ++it;
  }

  generalConfig.writeEntry( "Reminders", numReminders );
  generalConfig.writeEntry( "Position", pos() );
  config->sync();
}

ReminderList AlarmDialog::selectedItems() const
{
  ReminderList list;

  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
    if ( (*it)->isSelected() ) {
752
      list.append( static_cast<ReminderTreeItem *>( *it ) );
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    }
    ++it;
  }
  return list;
}

int AlarmDialog::activeCount()
{
  int count = 0;
  QTreeWidgetItemIterator it( mIncidenceTree );
  while ( *it ) {
    if ( !(*it)->isDisabled() ) { //suspended reminders are non-active
      ++count;
    }
    ++it;
  }
  kDebug() << "computed " << count << " active reminders";
  return count;
}

void AlarmDialog::closeEvent( QCloseEvent * )
{
  slotSave();
  accept();
}

void AlarmDialog::updateButtons()
{
781
  const int count = selectedItems().count();
782 783 784 785 786 787
  kDebug() << "selected items=" << count;
  enableButton( User3, count > 0 );  // enable Dismiss, if >1 selected
  enableButton( User1, count == 1 ); // enable Edit, if only 1 selected
  enableButton( Ok, count > 0 );     // enable Suspend, if >1 selected
}

788
void AlarmDialog::toggleDetails( QTreeWidgetItem *item )
789
{
790 791 792 793
  if ( !item ) {
    return;
  }

794 795 796 797
  if ( !mDetailView->isHidden() ) {
    if ( mLastItem == item ) {
      resize( size().width(), size().height() - mDetailView->height() - 50 );
      mDetailView->hide();
798 799
    } else {
      showDetails( item );
800 801 802
    }
  } else {
    resize( size().width(), size().height() + mDetailView->height() + 50 );
803
    showDetails( item );
804 805 806 807 808
    mDetailView->show();
  }
  mLastItem = item;
}

809
void AlarmDialog::showDetails( QTreeWidgetItem *item )
810 811
{
  if ( !item ) {
812 813 814 815 816 817
    return;
  }

  ReminderTreeItem *reminderItem = dynamic_cast<ReminderTreeItem *>( item );

   if ( !reminderItem ) {
818 819
    mDetailView->setIncidence( Akonadi::Item() );
  } else {
820 821
    if ( !reminderItem->mDisplayText.isEmpty() ) {
      QString txt = QLatin1String("<qt><p><b>") + reminderItem->mDisplayText + QLatin1String("</b></p></qt>");
822 823
      mDetailView->setHeaderText( txt );
    }
824 825
    Incidence::Ptr incidence = CalendarSupport::incidence( reminderItem->mIncidence );
    mDetailView->setIncidence( reminderItem->mIncidence, reminderItem->mRemindAt.date() );
826 827 828 829 830 831
  }
}

void AlarmDialog::update()
{
  updateButtons();
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
  if ( !mIncidenceTree->selectedItems().isEmpty() ) {
    QTreeWidgetItem *item = mIncidenceTree->selectedItems().first();
    toggleDetails( item );
  }
}

void AlarmDialog::popupItemMenu( const QPoint &point )
{
  QTreeWidgetItem *item = mIncidenceTree->itemAt( point );
  if ( !item ) {
    return;
  }

  ReminderTreeItem *reminderItem = dynamic_cast<ReminderTreeItem *>( item );
  if ( reminderItem ) {
    Incidence::Ptr incidence = CalendarSupport::incidence( reminderItem->mIncidence );
  }

850 851 852 853 854 855 856 857 858 859
}

void AlarmDialog::accept()
{
  if ( activeCount() == 0 ) {
    mPos = pos();
    hide();
  }
}

860 861 862 863 864 865 866
/** static */
KDateTime AlarmDialog::triggerDateForIncidence( const Incidence::Ptr &incidence,
                                                const QDateTime &reminderAt,
                                                QString &displayStr )
{
  KDateTime result;

867 868 869 870
  if ( incidence->alarms().isEmpty() ) {
    return result;
  }

871 872 873 874 875 876 877 878 879
  Alarm::Ptr alarm = incidence->alarms().first();

  if ( incidence->recurs() ) {
    result = incidence->recurrence()->getNextDateTime(
      KDateTime( reminderAt, KDateTime::Spec::LocalZone( ) ) );

      displayStr = KGlobal::locale()->formatDateTime( result.toLocalZone() );
  }

880 881 882 883 884
  if ( !result.isValid() ) {
    result = incidence->dateTime( Incidence::RoleAlarm );
    displayStr = IncidenceFormatter::dateTimeToString( result, false,
                                                       true,
                                                       KDateTime::Spec::LocalZone() );
885 886 887 888 889
  }

  return result;
}

890 891
void AlarmDialog::slotCalendarChanged()
{
892 893 894 895
  KCalCore::Incidence::List incidences = mCalendar->incidences();
  Akonadi::Item::List items = mCalendar->itemList( incidences );
  for ( Akonadi::Item::List::ConstIterator it = items.constBegin();
        it != items.constEnd(); ++it ) {
896
    ReminderTreeItem *item = searchByItem( *it );
897 898 899 900 901

    if ( item ) {
      Incidence::Ptr incidence = CalendarSupport::incidence( *it );
      QString displayStr;

902 903 904 905 906
      // Yes, alarms can be empty, if someone edited the incidence and removed all alarms
      if ( !incidence->alarms().isEmpty() ) {
        const KDateTime dateTime = triggerDateForIncidence( incidence,
                                                            item->mRemindAt,
                                                            displayStr );
907

908 909 910 911 912 913
        const QString summary = cleanSummary( incidence->summary() );

        if ( displayStr != item->text( 1 ) || summary != item->text( 0 ) ) {
          item->setText( 1, displayStr );
          item->setText( 0, summary );
        }
914 915 916 917
      }
    }
  }
}
918

919 920 921 922 923 924 925 926 927 928 929 930
void AlarmDialog::keyPressEvent( QKeyEvent *e )
{
  const int key = e->key() | e->modifiers();

  if ( key == Qt::Key_Enter || key == Qt::Key_Return ) {
    e->ignore();
    return;
  }

  KDialog::keyPressEvent( e );
}

931
bool AlarmDialog::openIncidenceEditorThroughKOrganizer( const Incidence::Ptr &incidence )
932
{
933 934
  if ( !QDBusConnection::sessionBus().interface()->isServiceRegistered( QLatin1String("org.kde.korganizer") ) ) {
    if ( KToolInvocation::startServiceByDesktopName( QLatin1String("korganizer"), QString() ) ) {
935 936 937 938 939 940 941 942
      KMessageBox::error(
        this,
        i18nc( "@info",
               "Could not start KOrganizer so editing is not possible." ) );
      return false;
    }
  }
  org::kde::korganizer::Korganizer korganizer(
943
    QLatin1String("org.kde.korganizer"), QLatin1String("/Korganizer"), QDBusConnection::sessionBus() );
944 945 946 947 948 949 950 951 952 953 954 955

  kDebug() << "editing incidence " << incidence->summary();
  if ( !korganizer.editIncidence( incidence->uid() ) ) {
    KMessageBox::error(
      this,
      i18nc( "@info",
             "An internal KOrganizer error occurred attempting to modify \"%1\"",
             cleanSummary( incidence->summary() ) ) );
  }

  // get desktop # where korganizer (or kontact) runs
  QString object =
956 957 958
    QDBusConnection::sessionBus().interface()->isServiceRegistered( QLatin1String("org.kde.kontact") ) ?
    QLatin1String("kontact/MainWindow_1") : QLatin1String("korganizer/MainWindow_1");
  QDBusInterface korganizerObj( QLatin1String("org.kde.korganizer"), QLatin1Char('/') + object );
959
#ifdef Q_WS_X11
960
  QDBusReply<int> reply = korganizerObj.call( QLatin1String("winId") );
961 962 963 964 965 966 967 968 969 970 971 972
  if ( reply.isValid() ) {
    int window = reply;
    int desktop = KWindowSystem::windowInfo( window, NET::WMDesktop ).desktop();
    if ( KWindowSystem::currentDesktop() == desktop ) {
      KWindowSystem::minimizeWindow( winId(), false );
    } else {
      KWindowSystem::setCurrentDesktop( desktop );
    }
    KWindowSystem::activateWindow( KWindowSystem::transientFor( window ) );
  }
#elif defined(Q_WS_WIN)
  // WId is a typedef to a void* on windows
973
  QDBusReply<qlonglong> reply = korganizerObj.call( QLatin1String("winId") );
974 975 976 977 978 979 980 981 982 983 984 985
  if ( reply.isValid() ) {
    qlonglong window = reply;
    KWindowSystem::minimizeWindow( winId(), false );
    KWindowSystem::allowExternalProcessWindowActivation();
    KWindowSystem::activateWindow( reinterpret_cast<WId>(window) );
  }
#else
  // TODO (mac)
#endif
return true;
}

986 987 988
bool AlarmDialog::openIncidenceEditorNG( const Akonadi::Item &item )
{
  Incidence::Ptr incidence = CalendarSupport::incidence( item );
989 990 991
  IncidenceEditorNG::IncidenceDialog *dialog =
    IncidenceEditorNG::IncidenceDialogFactory::create(
      false, /*doesn't need initial saving*/
992
      incidence->type(), 0, this );
993 994 995 996
  dialog->load( item );
  return true;
}

997 998 999 1000 1001 1002 1003 1004 1005 1006
void AlarmDialog::removeFromConfig( const QList<Akonadi::Item::Id> &ids )
{
  KSharedConfig::Ptr config = KGlobal::config();
  KConfigGroup genGroup( config, "General" );

  const int oldNumReminders = genGroup.readEntry( "Reminders", 0 );

  QList<ConfItem> newReminders;
  // Delete everything
  for ( int i = 1; i <= oldNumReminders; ++i ) {
1007
    const QString group( QString::fromLatin1( "Incidence-%1" ).arg( i ) );
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
    KConfigGroup incGroup( config, group );
    const QString uid = incGroup.readEntry( "UID" );
    const QDateTime remindAtDate = incGroup.readEntry( "RemindAt", QDateTime() );
    const KUrl akonadiUrl = incGroup.readEntry( "AkonadiUrl" );
    const Akonadi::Item::Id id = Akonadi::Item::fromUrl( akonadiUrl ).id();
    if ( !ids.contains( id ) ) {
      ConfItem ci;
      ci.akonadiUrl = akonadiUrl;
      ci.remindAt = remindAtDate;
      ci.uid = uid;
      newReminders.append( ci );
    }
    config->deleteGroup( group );
  }

  genGroup.writeEntry( "Reminders", newReminders.count() );

Allen Winter's avatar
Allen Winter committed
1025
  //Write everything except those which have an uid we don't want
1026
  for ( int i = 0; i < newReminders.count(); ++i ) {
1027
    const QString group( QString::fromLatin1( "Incidence-%1" ).arg( i + 1 ) );
1028 1029 1030 1031 1032 1033 1034 1035 1036
    KConfigGroup incGroup( config, group );
    incGroup.writeEntry( "UID", newReminders[i].uid );
    incGroup.writeEntry( "RemindAt", newReminders[i].remindAt );
    incGroup.writeEntry( "AkonadiUrl", newReminders[i].akonadiUrl );
    incGroup.sync();
  }
  genGroup.sync();
}

1037
#include "alarmdialog.moc"