Sticky timers are loaded with zero timer at startup
[kitchenalert] / src / kitchenalertmainwindow.cpp
index 18c4e2f..f74da41 100644 (file)
@@ -2,7 +2,7 @@
 
         KitchenAlert
 
-        Copyright (C) 2010  Heli Hyvättinen
+        Copyright (C) 2010-2011  Heli Hyvättinen
 
         This file is part of KitchenAlert.
 
 #include "createtimersequencedialog.h"
 #include "selectsounddialog.h"
 
-
-
 #include <QDebug>
 
 #include <QAction>
 #include <QMenuBar>
 #include <QMessageBox>
+#include <QSettings>
 #include <QFileDialog>
-#include <QFile>
-#include <QIcon>
 
+#include <QStringListModel>
+#include <QListView>
+#include "stickydialog.h"
 
 
 KitchenAlertMainWindow::KitchenAlertMainWindow(QWidget *parent) :
     QMainWindow(parent),
     ui(new Ui::KitchenAlertMainWindow)
     {
-    ui->setupUi(this);
-
-    setWindowIcon(QIcon(":/icon64.png"));
-
-  //load sticky alerts to the model here...
+      
+  defaultSaveDirectory_ = "/home/user/KitchenAlert";    
 
+  ui->setupUi(this);
 
+  setWindowIcon(QIcon(":/kitchenalert.png"));
 
   //alerts' tableview setup
 
-
   ui->ComingAlertsTableView->setModel(&model_);
   ui->ComingAlertsTableView->setSelectionMode(QAbstractItemView::SingleSelection);
   ui->ComingAlertsTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
 
+  ui->ComingAlertsTableView->horizontalHeader()->hide();
+//  ui->ComingAlertsTableView->verticalHeader()->setVisible(true);
 
-  //Commented out for testing their potebtial effect for slowdown:
-
-  //  ui->ComingAlertsTableView->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
-//  ui->ComingAlertsTableView->horizontalHeader()->resizeSection(0,460);
-//  ui->ComingAlertsTableView->horizontalHeader()->resizeSection(1,140);
-//  ui->ComingAlertsTableView->horizontalHeader()->resizeSection(2,100);
-
-//  ui->ComingAlertsTableView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
-
-
-
-
-//  ui->ComingAlertsTableView->verticalHeader()->setDefaultSectionSize(40); //Needed with fixed cell height only
-
-
-
+  ui->ComingAlertsTableView->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
+  ui->ComingAlertsTableView->horizontalHeader()->resizeSection(0,535);
+  ui->ComingAlertsTableView->horizontalHeader()->resizeSection(1,140);
+  ui->ComingAlertsTableView->horizontalHeader()->resizeSection(2,100);
 
-  ui->ComingAlertsTableView->horizontalHeader()->hide();
-  ui->ComingAlertsTableView->setWordWrap(true);
+  ui->ComingAlertsTableView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
 
 
-  //Buttons used when a timer is selected are disabled by default and enabled upon selection
+  //Buttons used to reacting to an alarm are hidden by default
 
   disableSelectionDependentButtons();
 
-  connect(ui->ComingAlertsTableView->selectionModel(),SIGNAL(selectionChanged(QItemSelection,QItemSelection)),this,SLOT(timerSelected(QItemSelection,QItemSelection)));
 
-  //connect buttons to respective functions
-  connect(ui->CreateNewScheduleButton, SIGNAL (pressed()), this, SLOT (newTimerSequence()));
+  connect(ui->ComingAlertsTableView->selectionModel(),SIGNAL(selectionChanged(QItemSelection,QItemSelection)),this,SLOT(timerSelected(QItemSelection,QItemSelection)));
+  connect(ui->CreateNewScheduleButton, SIGNAL (clicked()), this, SLOT (newTimerSequence()));
   connect(ui->DoneButton,SIGNAL(clicked()),this,SLOT(stop()));
   connect(ui->RestartButton,SIGNAL(clicked()),this,SLOT(restart()));
   connect(ui->SnoozeButton,SIGNAL(clicked()),this, SLOT(snooze()));
   connect(ui->RemoveButton,SIGNAL(clicked()),this,SLOT(remove()));
   connect(ui->SaveButton,SIGNAL(clicked()),this,SLOT(saveTimer()));
-  connect(ui->loadButton,SIGNAL(clicked()),this,SLOT(loadTimer()));
+  connect(ui->OpenButton,SIGNAL(clicked()),this,SLOT(loadTimer()));
 
   // menu setup
 
@@ -113,6 +99,13 @@ KitchenAlertMainWindow::KitchenAlertMainWindow(QWidget *parent) :
   QAction * p_AboutAction = new QAction(tr("About"),this);
   connect(p_AboutAction,SIGNAL(triggered()),this,SLOT(openAbout()));
   menuBar()->addAction(p_AboutAction);
+
+  QAction * p_StickyAction = new QAction(tr("Edit sticky timers"),this);
+  connect(p_StickyAction, SIGNAL(triggered()),this,SLOT(openStickyDialog()));
+  menuBar()->addAction(p_StickyAction);
+
+  QTimer::singleShot(0,this,SLOT(loadStickies())); //Load sticky timers after construction to speed the application showing up
+
     }
 
 KitchenAlertMainWindow::~KitchenAlertMainWindow()
@@ -143,37 +136,33 @@ void KitchenAlertMainWindow::newTimerSequence()
     if (createdialog.exec() == QDialog::Accepted) //if user pressed OK
     {
 
-        //get user input from the dialog
-
-
-       QList<Timer *>  alltimers = createdialog.getTimers();
 
-       // take first timer (currently the only one!)
+       QList<Timer *>  alltimers = createdialog.getTimers();  //get user input from the dialog
 
+       Timer* timer1 = alltimers.at(0); // take first timer (currently the only one!)
 
-       Timer* timer1 = alltimers.at(0);
-
-
-       //connect alert
 
 
        connect(timer1,SIGNAL(alert(QModelIndex)),this,SLOT(alert(QModelIndex)));
 
 
-       //Disable buttons, as selection is cleared when view is refreshed to show the new timer
 
-       disableSelectionDependentButtons();
+       connect(this,SIGNAL(defaultSoundEnabled()),timer1,SLOT(enableDefaultSound()));
+       connect(this,SIGNAL(soundChanged(QString)),timer1,SLOT(changeAlertSound(QString)));
 
 
-       // give timers to the model
 
-       model_.addTimers(alltimers);
+        model_.addTimers(alltimers); // give timers to the model, they are started automatically by default
 
+ //       ui->ComingAlertsTableView->resizeColumnsToContents();
 
-       //start the timer when it's safely in the model (consider moving this to the model's addTimers function)
 
+        //Disable buttons, as selection is cleared when view is refreshed to show the new timer
+        //But only if the timer has not already alerted and thus been selected
+
+        if (!selectedRow().isValid())
+            disableSelectionDependentButtons();
 
-       timer1->start();
 
 
     }
@@ -192,27 +181,32 @@ void KitchenAlertMainWindow::alert(QModelIndex indexOfAlerter)
 
     // The program is brought to front and activated when alerted
 
-    raise();
+
     activateWindow();
 
+// removing everything below does not solve the bug #6752!
+
+    raise();  //this may be unnecessary
+
     // The alerting timer is selected
     ui->ComingAlertsTableView->selectionModel()->select(QItemSelection(indexOfAlerter,indexOfAlerter),QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows );
-//    qDebug() << "Should be selected now";
 
+    //Scrolls the view so that the alerting timer is visible
+    ui->ComingAlertsTableView->scrollTo(indexOfAlerter);
 
-    //Snooze button is enabled
+   // qDebug() << "Should be selected now";
 
 
-    ui->SnoozeButton->setEnabled(true);
+    //Snooze button is enabled
 
-    //The alert sound is played (consider moving this operation inside timer, as now stopping one alert will silence all alerting alerts)
 
-    alertSound_.play();
+    ui->SnoozeButton->setEnabled(true);
+//qDebug ("Snooze on when alerting");
 
 }
 
 
-void KitchenAlertMainWindow::timerSelected(QItemSelection selected,QItemSelection deselected)
+void KitchenAlertMainWindow::timerSelected(QItemSelection selected,QItemSelection)
 {
     ui->DoneButton->setEnabled(true);
     ui->RestartButton->setEnabled(true);
@@ -220,7 +214,7 @@ void KitchenAlertMainWindow::timerSelected(QItemSelection selected,QItemSelectio
     ui->SaveButton->setEnabled(true);
 
 
-    //enabled only when alerting
+    //snooze button enabled only when alerting
     QModelIndexList indexes = selected.indexes();
 
     //the selection model only allows selecting one row at the time & we only need to know the row, so we can just take the first one
@@ -230,8 +224,13 @@ void KitchenAlertMainWindow::timerSelected(QItemSelection selected,QItemSelectio
         if (model_.isThisTimerAlerting(index) == true)
         {
              ui->SnoozeButton->setEnabled(true);
+//qDebug() << "Snooze on";
+        }
+        else
+        {
+            ui->SnoozeButton->setDisabled(true);
+//qDebug() << "Snooze off";
         }
-        else ui->SnoozeButton->setDisabled(true);
     }
 
 }
@@ -244,7 +243,7 @@ void KitchenAlertMainWindow::snooze()
         model_.snoozeTimer(row);
     }
     ui->SnoozeButton->setDisabled(true);
-    alertSound_.stop();
+
 
 }
 
@@ -256,8 +255,14 @@ void KitchenAlertMainWindow::restart()
 
         model_.startTimer(row);
     }
-    ui->SnoozeButton->setDisabled(true);
-    alertSound_.stop();
+
+
+   if (model_.isThisTimerAlerting(row) == false) //This has to be checked, because 00:00:00 alerts alert *before* the program execution reaches here
+    {
+        ui->SnoozeButton->setDisabled(true);
+    }
+ //   qDebug () << "disabled snooze because of restart";
+
 
 }
 
@@ -269,61 +274,79 @@ void KitchenAlertMainWindow::stop()
         model_.stopTimer(row);
     }
     ui->SnoozeButton->setDisabled(true);
-    alertSound_.stop();
-    qDebug() << "Stopped.";
+
 }
 
 QModelIndex KitchenAlertMainWindow::selectedRow()
 {
+    //Returns the cells in row 0 that have the whole row selected (the selection mode used allows only selecting whole rows
+
     QModelIndexList chosenRows = ui->ComingAlertsTableView->selectionModel()->selectedRows();
 
     //The selection mode used allows only one row to be selected at time, so we just take the first
-    //There are indexes for all columns in the row in the list, but as we only use the row, it does not matter which one we take
+
 
     return chosenRows.value(0); //gives an invalid QModelIndex if the list is empty
 }
 
 void KitchenAlertMainWindow::openSelectSoundDialog()
 {
+
     SelectSoundDialog dialog;
    if ( dialog.exec() == QDialog::Accepted) //if user pressed OK
     {
+       QSettings settings ("KitchenAlert","KitchenAlert");
+      
        if (dialog.isDefaultSoundChecked() == true)
-           alertSound_.setDefaultSound();
-       else
-        alertSound_.setSound(dialog.getSoundFileName());
+       { 
+        
+          settings.setValue("UseDefaultSound",true); 
+           emit defaultSoundEnabled();
+       }   
+      else
+       {
+           QString filename = dialog.getSoundFileName();
+           settings.setValue("UseDefaultSound",false);
+           settings.setValue("soundfile",filename);
+           emit soundChanged(filename);
+       }
 
-   //opening a dialog clears the selection so the selection dependen buttons must be disabled
     }
-    disableSelectionDependentButtons();
+
 }
 
 void KitchenAlertMainWindow::openAbout()
 {
     QMessageBox::about(this,tr("About KitchenAlert"),tr("<p>Version %1"
-                                                        "<p>Copyright &copy; Heli Hyv&auml;ttinen 2010"
+                                                        "<p>Copyright &copy; Heli Hyv&auml;ttinen 2010-2011"
                                                          "<p>License: General Public License v3"
-                                                         "<p>Bugtracker and project page: https://garage.maemo.org/projects/kitchenalert/").arg(QApplication::applicationVersion()));
+                                                         "<p>Web page: http://kitchenalert.garage.maemo.org/"
+                                                         "<p>Bugtracker: https://garage.maemo.org/projects/kitchenalert/").arg(QApplication::applicationVersion()));
 }
 
 bool KitchenAlertMainWindow::event(QEvent *event)
 {
-    QMainWindow::event(event);
+
 
     switch (event->type())
     {
         case QEvent::WindowActivate:
 
             model_.setUpdateViewOnChanges(true);
-              break;
+//            ui->debugLabel->setText("Returned to the application!");
+            break;
 
        case QEvent::WindowDeactivate:
             model_.setUpdateViewOnChanges(false);
+//            ui->debugLabel->setText("");
             break;
 
        default:
             break;
+
     }
+
+    return QMainWindow::event(event); // Send the event to the base class implementation (also when handling the event in this function): necessary for the program to work!
 }
 
 void KitchenAlertMainWindow::disableSelectionDependentButtons()
@@ -333,18 +356,52 @@ void KitchenAlertMainWindow::disableSelectionDependentButtons()
     ui->RestartButton->setDisabled(true);
     ui->RemoveButton->setDisabled(true);
     ui->SaveButton->setDisabled(true);
+
+
 }
 
-void KitchenAlertMainWindow::remove()
+void KitchenAlertMainWindow::initializeAlertSound()
 {
-   QModelIndex row = selectedRow();
-   if (row.isValid())
+    QSettings settings;
+
+    bool useDefaultSound = settings.value("UseDefaultSound",true).toBool();
+    QString filename = settings.value("soundfile","").toString();
+
+    if (useDefaultSound == true)
+    {
+        openSelectSoundDialog();
+    }
+    else if (filename.isEmpty())
+    {
+        openSelectSoundDialog();
+    }
+
+   QString currentFilename = settings.value("soundfile","").toString();
+
+   if (currentFilename.isEmpty())
    {
-    model_.removeTimer(row);
-    alertSound_.stop();
-    ui->ComingAlertsTableView->clearSelection();
-    disableSelectionDependentButtons();
+        ui->debugLabel->setText("<FONT color=red>No alert sound file set. Alert sound will not be played!</FONT>");
+
    }
+
+}
+
+void KitchenAlertMainWindow::remove()
+{
+    QModelIndex row = selectedRow();
+    if (row.isValid()) //If there was no row selected invalid row was returned
+    {
+        QString text = tr("Are you sure you want to remove this timer from the list:\n");
+        text.append((row.data().toString()));
+        if (QMessageBox::question(this,tr("Confirm timer removal"),text,QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
+        {
+            model_.removeTimer(row);
+            ui->ComingAlertsTableView->clearSelection();
+            disableSelectionDependentButtons();
+
+        }
+    }
+
 }
 
 void KitchenAlertMainWindow::saveTimer()
@@ -357,11 +414,11 @@ void KitchenAlertMainWindow::saveTimer()
 
 
     //file name is asked. As the filename will be appended, there's no point in confirming owerwrite here
-    QString filename = QFileDialog::getSaveFileName(this, "", "", "*.kitchenalert",NULL,QFileDialog::DontConfirmOverwrite);
+    QString filename = QFileDialog::getSaveFileName(this, "", defaultSaveDirectory_, "*.kitchenalert",NULL,QFileDialog::DontConfirmOverwrite);
 
-    disableSelectionDependentButtons();
 
-    qDebug() << filename;
+
+//    qDebug() << filename;
 
     if (filename.isEmpty()) //user cancelled the dialog (or gave an empty name)
     {
@@ -374,7 +431,7 @@ void KitchenAlertMainWindow::saveTimer()
 
     }
 
-    qDebug() << "filename appended to " << filename;
+  //  qDebug() << "filename appended to " << filename;
 
 
     //MANUAL CONFIRMATION OF OWERWRITE
@@ -395,7 +452,6 @@ void KitchenAlertMainWindow::saveTimer()
 
 
 
-
     QString errorMessage(tr("Cannot write to file "));
     errorMessage.append(filename);
 
@@ -409,7 +465,26 @@ void KitchenAlertMainWindow::saveTimer()
 
 void KitchenAlertMainWindow::loadTimer()
 {
-    QString filename = QFileDialog::getOpenFileName(this,"","",tr("KitchenAlert timer files (*.kitchenalert)"));
+
+// If the default save directory does not exist use /home/user instead (as that's what the save dialog will use)
+// This avoids a situation where save directs to a folder that cannot be accessed with open...
+
+    QString startDirectory;
+
+    if (QFile(defaultSaveDirectory_).exists())
+    {
+        startDirectory = defaultSaveDirectory_;
+    }
+    else
+    {
+        startDirectory = "/home/user/";
+        qDebug () << "default save directory not found";
+    }
+
+
+ //Get the filename to open with a dialog
+
+    QString filename = QFileDialog::getOpenFileName(this,"",startDirectory,tr("KitchenAlert timer files (*.kitchenalert)"));
     if (!filename.isEmpty())
     {
 
@@ -418,23 +493,12 @@ void KitchenAlertMainWindow::loadTimer()
 //            filename.append(".kitchenalert");
 //        }
 
-        QString errorTitle(tr("Failed to load file "));
-        errorTitle.append(filename);
+        loadTimer(filename,true); //timer gets started
 
-        Timer * p_timer = new Timer();
-        if (!p_timer->load(filename))
-        {
-            QMessageBox::critical(this,errorTitle,tr("Unable to open file or not a valid KitchenAlert timer file."));
-            delete p_timer;
-            return;
-        }
-
-        initializeTimer(p_timer);
     }
 }
 
-
-void KitchenAlertMainWindow::initializeTimer(Timer *p_timer)
+void KitchenAlertMainWindow::initializeTimer(Timer *p_timer, bool startImmediately)
 {
 
 //connect alert
@@ -443,6 +507,12 @@ void KitchenAlertMainWindow::initializeTimer(Timer *p_timer)
 connect(p_timer,SIGNAL(alert(QModelIndex)),this,SLOT(alert(QModelIndex)));
 
 
+//connect change sound functions
+
+connect(this,SIGNAL(defaultSoundEnabled()),p_timer,SLOT(enableDefaultSound()));
+connect(this,SIGNAL(soundChanged(QString)),p_timer,SLOT(changeAlertSound(QString)));
+
+
 //Disable buttons, as selection is cleared when view is refreshed to show the new timer
 
 disableSelectionDependentButtons();
@@ -453,11 +523,53 @@ disableSelectionDependentButtons();
 QList<Timer *> timerList;
 
 timerList.append(p_timer);
-model_.addTimers(timerList);
+model_.addTimers(timerList,startImmediately); //timer gets started in the model if startImmediately is true (default)
+
+}
+
+void KitchenAlertMainWindow::openStickyDialog()
+{
+    StickyDialog stickyDialog(defaultSaveDirectory_);
 
 
-//start the timer when it's safely in the model (consider moving this to the model's addTimers function)
+    if (stickyDialog.exec()== QDialog::Accepted)
+    {
+        QSettings settings;
+        settings.setValue("sticky",stickyDialog.getStickyList());
+    }
+}
 
+bool KitchenAlertMainWindow::loadStickies()
+{
+    bool allSuccess = true;
+
+    QSettings settings;
+
+    QStringList stickies = settings.value("sticky").toStringList();
+
+
+    foreach (QString stickyFileName, stickies)
+    {
+       if (!loadTimer(stickyFileName,false)) //initializes the timer without starting it
+            allSuccess = false;
+    }
+
+    return allSuccess;
+}
+
+bool KitchenAlertMainWindow::loadTimer(QString filename, bool startImmediately)
+{
+    QString errorTitle(tr("Failed to load file "));
+    errorTitle.append(filename);
+
+    Timer * p_timer = new Timer();
+    if (!p_timer->load(filename))
+    {
+        QMessageBox::critical(this,errorTitle,tr("Unable to open file or not a valid KitchenAlert timer file."));
+        delete p_timer;
+        return false;
+    }
 
-p_timer->start();
+    initializeTimer(p_timer,startImmediately);
+    return true;
 }