-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsak.cpp
1942 lines (1715 loc) · 72.5 KB
/
sak.cpp
1
2
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (C) 2007 by Arrigo Zanette *
* zanettea@gmail.com *
***************************************************************************/
#include <QtGui>
#include <QCryptographicHash>
#include <QSettings>
#include <QGraphicsEllipseItem>
#include <cassert>
#include "sak.h"
#include "sakwidget.h"
#include "saksubwidget.h"
#include "sakmessageitem.h"
#include "pixmapviewer.h"
#include "timeline.h"
#include "backupper.h"
#include "piechart.h"
#ifdef USELIBGMAIL
#include "gmailstorage/gmailpyinterface.h"
#else
#include "gmailstorage/gmailmyinterface.h"
#endif
//END Task <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// GView
#include <QtOpenGL>
#if defined(Q_WS_X11)
#include <QX11Info>
namespace X11
{
#include <X11/Xlib.h>
#undef KeyPress
#undef KeyRelease
static Window CurrentFocusWindow;
static int CurrentRevertToReturn;
}
#endif
static int grabbed;
class GView : public QGraphicsView
{
public:
// GView() {
// if (QGLFormat::hasOpenGL()) {
// qDebug() << "Using OpenGL";
// QGLWidget* w = new QGLWidget;
// w->setAttribute(Qt::WA_TranslucentBackground, true);
// setViewport(w);
// }
// }
// ~GView() {
// delete this->viewport();
// }
void drawBackground(QPainter* p, const QRectF & rect) {
QBrush brush(QColor(0,0,0,200));
p->setCompositionMode(QPainter::CompositionMode_Source);
p->fillRect(rect, brush);
}
};
//BEGIN Sak basic >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Sak::Sak(QObject* parent)
: QObject(parent)
, m_timerId(0)
, m_timeoutPopup(0)
, m_getFocusTimer(0)
, m_stopped(false)
, m_settings(0)
, m_changedHit(false)
, m_changedTask(false)
, m_subtaskView(false)
{
m_desktopRect = qApp->desktop()->rect();
m_subtaskCompleter = 0;
summaryList = hitsList = 0; trayIcon=0;
init();
if (QCoreApplication::arguments().contains("--clear")) {
QHash<QString, Task>::iterator itr = m_tasks.begin();
while(itr != m_tasks.end()) {
itr->hits.clear();
itr++;
}
}
if (m_tasks.count() <= 0)
m_settings->show();
m_previewing = false;
m_changedHit = false;
m_timerId = 0;
m_autoSaveTimer = startTimer(1000 * 60 * 45); // every 45 minutes
start();
// Need to go here, or after plasma reboot the icon will disappear
trayIconMenu = new QMenu(m_settings);
//trayIconMenu->addAction(minimizeAction);
//trayIconMenu->addAction(maximizeAction);
//trayIconMenu->addAction(restoreAction);
//trayIconMenu->addSeparator();
trayIconMenu->addAction(startAction);
trayIconMenu->addAction(stopAction);
trayIconMenu->addAction(flushAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setIcon( QIcon(":/images/icon.png") );
trayIcon->setToolTip( tr("Sistema Anti Kazzeggio") );
trayIcon->show();
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->installEventFilter(this);
m_settings->setWindowIcon( QIcon(":/images/icon.png") );
m_settings->setWindowTitle("SaK - Sistema Anti Kazzeggio");
}
void Sak::init()
{
m_backupper = new Backupper;
m_incremental = new Incremental;
#ifdef USEGMAIL
m_gmail = new GmailPyInterface;
#else
m_gmail = NULL;
#endif
// load the data model
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "ZanzaSoft", "SAK");
QByteArray tasksArray = settings.value("tasks").toByteArray();
QDataStream stream(&tasksArray, QIODevice::ReadWrite);
stream.setVersion(QDataStream::Qt_4_3);
{ // read locastasks
QDir saveDir(QFileInfo(settings.fileName()).dir());
saveDir.mkdir("SakTasks");
saveDir.cd("SakTasks");
QStringList nameFilters;
nameFilters << "*.xml";
QStringList files = saveDir.entryList( nameFilters, QDir::Files);
foreach (QString taskXmlFileName, files) {
Task t( loadTaskFromFile(saveDir.filePath(taskXmlFileName)) );
m_tasks[t.title] = t;
}
}
// add subtasks, if missing
{
QHash<QString, Task>::iterator itr = m_tasks.begin();
while(itr != m_tasks.end()) {
itr->updateSubTasks();
itr++;
}
}
// reset awayTask
Task & awayTask = m_tasks["<away>"];
awayTask.title = "<away>";
awayTask.fgColor = Qt::gray;
awayTask.bgColor = Qt::white;
awayTask.icon = QPixmap(":/images/away.png");
m_editedTasks = m_tasks;
hitsTimeline = 0;
//merge piecies
interactiveMergeHits();
m_editedTasks = m_tasks;
setupSettingsWidget();
m_settings->installEventFilter(this);
hitsList->installEventFilter(this);
tasksTree->installEventFilter(this);
tasksTree->setUniformRowHeights(false);
QTreeWidgetItem* headerItem = new QTreeWidgetItem;
headerItem->setSizeHint(0 , QSize(0,0));
headerItem->setSizeHint(1 , QSize(0,0));
headerItem->setSizeHint(2 , QSize(0,0));
tasksTree->setHeaderItem(headerItem);
connect(bgColorButton, SIGNAL(clicked()), this, SLOT(selectColor()));
connect(fgColorButton, SIGNAL(clicked()), this, SLOT(selectColor()));
connect(previewButton, SIGNAL(clicked()), this, SLOT(popup()));
connect(tasksTree, SIGNAL(itemSelectionChanged()), this, SLOT(selectedTask()));
connect(tasksTree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(selectedTask()));
populateTasks();
connect(cal1, SIGNAL(clicked(QDate)), this, SLOT(selectedStartDate(QDate)));
connect(cal2, SIGNAL(clicked(QDate)), this, SLOT(selectedEndDate(QDate)));
connect(cal3, SIGNAL(clicked(QDate)), this, SLOT(selectedStartDate(QDate)));
connect(cal4, SIGNAL(clicked(QDate)), this, SLOT(selectedEndDate(QDate)));
connect(hitsList, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(hitsListItemChanged(QTreeWidgetItem*,int)));
selectedTask();
m_view = new GView;
m_view->setScene(new QGraphicsScene);
m_view->scene()->setSceneRect(m_desktopRect);
m_view->installEventFilter(this);
m_view->setFrameStyle(QFrame::NoFrame);
m_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_view->setWindowFlags(m_view->windowFlags() | Qt::WindowStaysOnTopHint | Qt::ToolTip );
//m_view->setWindowModality(Qt::ApplicationModal);
m_view->setAttribute(Qt::WA_QuitOnClose, false);
// enable transparency with Qt4.5
m_view->setAttribute(Qt::WA_TranslucentBackground, true);
m_view->setWindowIcon( QIcon(":/images/icon.png") );
m_view->setWindowTitle("SaK - Sistema Anti Kazzeggio");
m_currentInterval = durationSpinBox->value();
m_currentInterval = qMax((int)1, qMin((int)1440, m_currentInterval));
qDebug() << "SAK: pinging interval " << m_currentInterval << Task::hours(m_currentInterval) << " hours ";
hitsTimeline->setPeriod(QDateTime(cal1->selectedDate()), QDateTime(cal2->selectedDate()));
populateHitsList(createHitsList(QDateTime(cal1->selectedDate()), QDateTime(cal2->selectedDate())));
}
void Sak::start()
{
// ensure the timer is killed
if(m_timerId)
stop();
m_currentInterval = qMax((int)1, m_currentInterval);
int msecs = (int)(Task::hours(m_currentInterval)*3600.0*1000.0 / 2);
m_timerId = startTimer( msecs );
m_nextTimerEvent = QDateTime::currentDateTime().addMSecs(msecs);
startAction->setEnabled(false);
stopAction->setEnabled(true);
m_stopped=false;
}
void Sak::stop()
{
if(m_timerId) {
killTimer(m_timerId); m_timerId=-1;
}
stopAction->setEnabled(false);
startAction->setEnabled(true);
m_stopped=true;
}
void Sak::pause()
{
m_stopped=true;
stopAction->setEnabled(false);
startAction->setEnabled(true);
}
Task Sak::loadTaskFromFile(const QString& filePath)
{
QFile taskXmlFile(filePath);
Task t;
qDebug() << "Examine task file " << taskXmlFile.fileName();
if (!taskXmlFile.open(QIODevice::ReadOnly)) {
qDebug() << "Failed opening xml file " << taskXmlFile.fileName();
}
QByteArray data = taskXmlFile.readLine();
QXmlStreamReader stream(data);
QXmlStreamReader::TokenType token = stream.readNext(); // skip StartDocument
token = stream.readNext();
if ( token != QXmlStreamReader::Comment) {
qDebug() << "Skip file " << taskXmlFile.fileName() << " (want a file starting with a comment representing MD5, got" << token << ")";
return t;
}
QString md5 = stream.text().toString().trimmed();
qDebug() << "md5 = " << md5;
// check md5
data = taskXmlFile.readAll();
if ( md5 != QCryptographicHash::hash(data, QCryptographicHash::Md5).toHex() ) {
if (QMessageBox::No == QMessageBox::warning(0, "Corrupted file!",
QString("Check of file " + taskXmlFile.fileName() + " failed (maybe it has been edited by hand).\nDo you want to load it anyway?" )
,QMessageBox::Yes | QMessageBox::No) ) {
qDebug() << "Skip file " << taskXmlFile.fileName() << " (bad md5 sum)";
return t;
}
}
// read rest of data
stream.clear();
stream.addData(data);
if ( stream.readNext() != QXmlStreamReader::StartDocument) {
qDebug() << "Skip file " << taskXmlFile.fileName() << " (want start document)";
return t;
}
stream >> t;
if (stream.error() != QXmlStreamReader::NoError) {
qDebug() << "Error reading task data from file " << taskXmlFile.fileName() << ":" << stream.errorString();
return Task();
}
// QFile tmp("/tmp/" + t.title + ".xml");
// tmp.open(QIODevice::ReadWrite);
// QXmlStreamWriter ss(&tmp);
// ss.setAutoFormatting(true);
// ss.setAutoFormattingIndent(2);
// ss.writeStartDocument();
// ss << t;
// ss.writeEndDocument();
// tmp.close();
else
return t;
}
void Sak::flush()
{
if (m_changedTask)
saveTaskChanges();
if (m_changedHit)
saveHitChanges();
if (!m_settings) return;
m_backupper->doCyclicBackup();
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "ZanzaSoft", "SAK");
// QByteArray tasksArray;
// QDataStream stream(&tasksArray, QIODevice::ReadWrite);
// stream.setVersion(QDataStream::Qt_4_0);
// stream << m_tasks;
// settings.setValue("tasks", tasksArray);
settings.setValue("Ping interval", durationSpinBox->value());
settings.setValue("Message", bodyEdit->toPlainText());
settings.sync();
QDir saveDir(QFileInfo(settings.fileName()).dir());
saveDir.mkdir("SakTasks");
saveDir.cd("SakTasks");
foreach(Task t, m_tasks) {
if (t.title.isEmpty()) continue;
QFile xmlTaskSave(saveDir.filePath(t.title + ".xml"));
QByteArray taskArray;
QXmlStreamWriter stream(&taskArray);
stream.setAutoFormatting(true);
stream.setAutoFormattingIndent(2);
stream.writeStartDocument();
stream << t;
stream.writeEndDocument();
xmlTaskSave.open(QIODevice::ReadWrite | QIODevice::Truncate);
qDebug() << "Saving xml to file " << xmlTaskSave.fileName();
QByteArray hash;
hash.append("<!-- ");
hash.append( QCryptographicHash::hash(taskArray, QCryptographicHash::Md5).toHex() );
hash.append(" -->\n");
xmlTaskSave.write(hash);
xmlTaskSave.write(taskArray);
xmlTaskSave.close();
}
// remove files not matching a task
QStringList nameFilters;
nameFilters << "*.xml";
QStringList files = saveDir.entryList( nameFilters, QDir::Files);
foreach (QString taskXmlFileName, files) {
if (!m_tasks.contains(QFileInfo(taskXmlFileName).baseName())) {
qWarning()<< "Remove task " << QFileInfo(taskXmlFileName).baseName() << " from disk";
QFile(saveDir.filePath(taskXmlFileName)).remove();
}
}
m_incremental->clearAddedPieces();
}
//void Sak::saveAsDb()
//{
// if (!m_settings) return;
// QString fileName = QFileDialog::getSaveFileName();
// QFile file(fileName);
// file.remove();
// flush();
// QSettings settingsQSettings::IniFormat, QSettings::UserScope, ("ZanzaSoft", "SAK");
// QFile file1(settings.fileName());
// if (!file1.copy(fileName)) {
// qWarning() << "Error copying " << settings.fileName() << " to " << fileName << file1.errorString();
// }
//}
void Sak::exportDbCsv()
{
if (!m_settings) return;
QString fileName = QFileDialog::getSaveFileName();
QFile file(fileName);
if (!file.open(QIODevice::ReadWrite|QIODevice::Truncate)) {
QMessageBox::warning(0, "Error saving", QString("Error saving to file %1").arg(fileName));
return;
}
QTextStream stream(&file);
foreach(const Task& t, m_tasks) {
QHash< QString, QList< Task::Hit > >::const_iterator itr = t.hits.begin();
while(itr != t.hits.end()) {
QList< Task::Hit >::const_iterator hitr = itr.value().begin(), hend = itr.value().end();
while(hitr != hend) {
stream << t.title << ";" << itr.key() << ";" << hitr->timestamp.toString(DATETIMEFORMAT) << ";" << hitr->duration << ";\n";
hitr++;
}
itr++;
}
}
file.close();
}
void Sak::logInGmail()
{
m_gmail->forceLogin();
}
void Sak::saveToGmail()
{
if (!m_settings) return;
flush();
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "ZanzaSoft", "SAK");
QDir saveDir(QFileInfo(settings.fileName()).dir());
saveDir.mkdir("SakTasks");
saveDir.cd("SakTasks");
QStringList nameFilters;
nameFilters << "*.xml";
QStringList files = saveDir.entryList( nameFilters, QDir::Files);
QStringList filePaths;
foreach (QString taskXmlFileName, files) {
filePaths << saveDir.filePath(taskXmlFileName);
}
m_gmail->storeTaskFiles(filePaths);
}
void Sak::importFromGmail()
{
QStringList filePaths = m_gmail->fetchLatestTasks();
}
void Sak::open(const QStringList& _fileNames)
{
QStringList fileNames = _fileNames.size()?_fileNames:QFileDialog::getOpenFileNames(0, "Open a new task", QString(), "*.xml" );
foreach(QString fileName, fileNames) {
QFile file(fileName);
if (!file.exists()) {
QMessageBox::warning(0, "Cannot find task", QString("Cannot find task file %1").arg(fileName));
}
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "ZanzaSoft", "SAK");
QDir saveDir(QFileInfo(settings.fileName()).dir());
saveDir.mkdir("SakTasks");
saveDir.cd("SakTasks");
if ( QFile(saveDir.filePath(QFileInfo(fileName).completeBaseName())).exists() ) {
QMessageBox mbox(QMessageBox::Warning, "Save current task", "Current task will be overwritten by the new task: do you want to backup it to file before?");
QPushButton* overwriteButton = mbox.addButton("Overwrite", QMessageBox::YesRole);
QPushButton* mergeButton = mbox.addButton("Merge", QMessageBox::NoRole);
QPushButton* cancelButton = mbox.addButton("Cancel", QMessageBox::RejectRole);
mbox.setDefaultButton(cancelButton);
mbox.exec();
QAbstractButton* b = mbox.clickedButton();
if (b == cancelButton) { continue; }
else {
m_backupper->doCyclicBackup();
if (b == mergeButton) {
Task t = loadTaskFromFile(file.fileName());
QHash< QString, QList< Task::Hit > > ::const_iterator itr = t.hits.begin(), end = t.hits.end();
while(itr != end) {
QString subtask = itr.key();
foreach(Task::Hit hit, itr.value())
m_incremental->addPiece(t.title, subtask, hit.timestamp, hit.duration);
itr++;
}
interactiveMergeHits();
} else if (b == overwriteButton) {
file.copy(saveDir.filePath(QFileInfo(fileName).completeBaseName()));
}
}
}
}
if (!fileNames.isEmpty()) {
m_settings->hide();
destroy();
init();
m_settings->show();
start();
}
}
void Sak::destroy()
{
stop();
if (!m_settings) return;
flush();
m_settings->deleteLater();
m_view->scene()->deleteLater();
m_view->deleteLater();
delete m_backupper;
delete m_incremental;
delete m_gmail;
m_previewing = false;
m_changedHit = false;
m_timerId = 0;
}
Sak::~Sak()
{
killTimer(m_autoSaveTimer); m_autoSaveTimer=-1;
destroy();
}
void Sak::layoutSubTasks( const QMap<int, SakSubWidget*> sortedWidgets, int currentRank) {
QMap<int, SakSubWidget*>::const_iterator itr = sortedWidgets.begin(), end = sortedWidgets.end();
QRect r = m_desktopRect;
for(int i=0; itr != end; i++, itr++) {
int h = (*itr)->size().height();
int w = (*itr)->size().width();
(*itr)->setPos(QPointF((r.width() - w)/2, (r.height()-h)/2 + (i - currentRank - 1) * (h+2)));
}
}
int Sak::taskCounter = 0;
bool Sak::eventFilter(QObject* obj, QEvent* e)
{
// if (obj == m_view) {
// qDebug() << "event : " << e->type();
// }
if (obj == tasksTree) {
return taskTreeEventFilter(e);
} else if (obj == hitsList || obj == summaryList) {
return hitsListEventFilter(e);
} else if (obj == m_settings && e->type() == QEvent::Close) {
if (m_changedTask)
saveTaskChanges();
if (m_changedHit)
saveHitChanges();
if (trayIcon->isVisible()) {
m_settings->hide();
e->ignore();
return true;
}
} else if (obj == m_view && e->type() == QEvent::Wheel) {
QWheelEvent* we = dynamic_cast<QWheelEvent*>(e);
if (m_subtaskView) {
scrollSubTasks(we->delta() / 120);
} else scrollTasks(we->delta() / 120);
} else if (obj == m_view && e->type() == QEvent::KeyPress) {
QKeyEvent* ke = dynamic_cast<QKeyEvent*>(e);
if ((ke->modifiers() & Qt::AltModifier) && (ke->modifiers() & Qt::ControlModifier) ) {
clearView();
return true;
} else if ( ((ke->modifiers() & Qt::ControlModifier) && (ke->key() == Qt::Key_Backspace) )
|| ((ke->modifiers() & Qt::ControlModifier) && (ke->key() == Qt::Key_Left) )) {
if (m_subtaskView) {
popup();
return true;
}
} else if (m_subtaskView && ke->key() == Qt::Key_Up) {
scrollSubTasks(-1);
return true;
} else if (m_subtaskView && ke->key() == Qt::Key_Down) {
scrollSubTasks(+1);
return true;
} else if (!m_subtaskView && ke->key() == Qt::Key_Left) {
scrollTasks(-1);
return true;
} else if (!m_subtaskView && ke->key() == Qt::Key_Right) {
scrollTasks(+1);
return true;
} else if (!m_subtaskView && ke->key() == Qt::Key_Escape) {
clearView();
return true;
} else { // forward events to current widget
if (!m_subtaskView) {
if (m_widgetsIterator == m_widgets.end()) return false;
SakWidget* currentShowing = m_widgetsIterator.value();
currentShowing->keyPressEvent(ke);
return true;
} else {
// autoscroll on text completion!!!
if (m_subwidgetsIterator == m_subwidgets.end()) return false;
SakSubWidget* currentShowing = m_subwidgetsIterator.value();
currentShowing->keyPressEvent(ke);
if (m_subWidgetRank != 0 && m_subtaskCompleter) {
QString completion(m_subtaskCompleter->completionPrefix());
if (ke->text().size() == 1) {
if (ke->key() == Qt::Key_Backslash || ke->key() == Qt::Key_Backspace)
completion.chop(1);
else completion += ke->text();
m_subtaskCompleter->setCompletionPrefix(completion);
QStringList list( ((QStringListModel*)m_subtaskCompleter->model())->stringList() );
int newRank = 1 + ((QStringListModel*)m_subtaskCompleter->model())->stringList().indexOf(m_subtaskCompleter->currentIndex().row() >= 0 && completion.size() ? m_subtaskCompleter->currentCompletion() : completion);
if (m_subWidgetRank != newRank) {
scrollSubTasks(newRank - m_subWidgetRank);
if (newRank == 0) {
QLineEdit* editor = dynamic_cast<QLineEdit*>((*m_subwidgets.begin())->widget());
if (editor) {
editor->setText(completion);
}
}
}
}
} else if (m_subtaskCompleter) {
QLineEdit* editor = dynamic_cast<QLineEdit*>((*m_subwidgets.begin())->widget());
if (editor) {
m_subtaskCompleter->setCompletionPrefix(editor->text());
}
}
return true;
}
}
} else if (obj == m_view && e->type() == QEvent::Show) {
grabKeyboard();
QTimer::singleShot(500, this, SLOT(grabKeyboard()));
} else if (obj == m_view && e->type() == QEvent::Close) {
if (trayIcon->isVisible()) {
return true;
}
} else if (obj && obj == trayIcon && e->type() == QEvent::ToolTip) {
QDateTime last = m_incremental->lastTimeStamp;
int seconds = QDateTime::currentDateTime().secsTo(m_nextTimerEvent);
int hours = seconds / 3600;
int minutes = (seconds / 60) % 60;
seconds %= 60;
trayIcon->setToolTip(tr(qPrintable(QString("<h2>Sistema Anti Kazzeggio</h2>Last registered hit at <b>%1</b>.<br />%2").arg(last.toString()).arg(m_timerId > 0 ? QString("Next hit in <b>%2:%3:%4</b>").arg(hours).arg(minutes).arg(seconds) : QString("<b>Paused</b>")))));
return false;
}
return false;
}
//END basic >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//BEGIN Tasks >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void Sak::addDefaultTask()
{
QString tentativeName;
do {
tentativeName = QString("Task %1").arg(taskCounter++);
} while(m_editedTasks.contains(tentativeName));
Task& t = m_editedTasks[tentativeName];
t.title = tentativeName;
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(tentativeName));
item->setData(0,Qt::UserRole, QVariant(QMetaType::VoidStar, &t));
tasksTree->addTopLevelItem(item);
m_changedTask=true;
}
void Sak::populateTasks()
{
tasksTree->clear();
QHash<QString, Task>::iterator itr = m_editedTasks.begin(), end=m_editedTasks.end();
for(; itr!=end; itr++) {
Task& t(itr.value());
t.checkConsistency();
if (t.title.isEmpty() || t.title == "<away>") continue; // skip away task
QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(t.title));
item->setData(0, Qt::UserRole, QVariant(QMetaType::VoidStar, &t));
QIcon icon;
icon.addPixmap(t.icon);
item->setSizeHint(0, QSize(32,32));
item->setIcon(0, icon);
for(int i=0; i<3; i++) {
item->setForeground(i,t.fgColor);
item->setBackground(i,t.bgColor);
}
//item->setCheckState(1, t.active ? Qt::Checked : Qt::Unchecked);
//item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setIcon(1,QIcon(t.active ? ":/images/active.png" : ":/images/inactive.png"));
item->setText(2,QString("%1 hours worked till now (overestimated %2)").arg(t.totHours, 4, 'f', 2, ' ').arg(t.totOverestimation));
foreach(Task::SubTask st, t.subTasks) {
if (!st.title.isEmpty()) {
QTreeWidgetItem* sitem = new QTreeWidgetItem(item, QStringList(st.title));
item->setData(0, Qt::UserRole, QVariant(QMetaType::VoidStar, &st));
sitem->setSizeHint(0, QSize(32,32));
QColor fgColor = st.fgColor.isValid() ? st.fgColor : t.fgColor;
QColor bgColor = st.bgColor.isValid() ? st.bgColor : t.bgColor;
for(int i=0; i<3; i++) {
sitem->setForeground(i,fgColor);
sitem->setBackground(i,bgColor);
}
sitem->setIcon(1,QIcon(st.active ? ":/images/active.png" : ":/images/inactive.png"));
sitem->setText(2,QString("%1 hours worked till now").arg(st.totHours,4,'f',2,' '));
}
}
tasksTree->addTopLevelItem(item);
}
}
void Sak::saveTaskChanges()
{
if (m_changedTask) {
commitCurrentTask();
if ( QMessageBox::question ( 0, "Task list changed", "Task list has changed: do you want to save changes?", QMessageBox::Save | QMessageBox::Discard, QMessageBox::Discard) == QMessageBox::Save ) {
m_tasks = m_editedTasks;
} else m_editedTasks = m_tasks; //. undo changes
m_changedTask=false;
selectedStartDate(QDate());
populateTasks();
}
}
void Sak::selectColor() {
if (tasksTree->selectedItems().isEmpty()) return;
if (sender() == fgColorButton) {
QColor c = QColorDialog::getColor(fgColorButton->palette().color(QPalette::ButtonText));
if (!c.isValid()) return;
QPalette p = fgColorButton->palette();
p.setColor(QPalette::ButtonText, c);
fgColorButton->setPalette(p);
bgColorButton->setPalette(p);
} else if (sender() == bgColorButton) {
QColor c = QColorDialog::getColor(bgColorButton->palette().color(QPalette::Button));
if (!c.isValid()) return;
QPalette p = bgColorButton->palette();
p.setColor(QPalette::Button, c);
fgColorButton->setPalette(p);
bgColorButton->setPalette(p);
}
commitCurrentTask();
}
bool Sak::taskTreeEventFilter(QEvent* e)
{
if (e->type() == QEvent::ContextMenu) {
QContextMenuEvent* me = dynamic_cast<QContextMenuEvent*>(e);
if (!me) return false;
m_addTaskMenu->popup(me->globalPos());
return true;
} else if (e->type() == QEvent::KeyRelease) {
QKeyEvent* ke = dynamic_cast<QKeyEvent*>(e);
if (!ke) return false;
if ( (ke->key() != Qt::Key_Delete && ke->key() != Qt::Key_Backspace) ) return false;
if (currentSubtask!="") {
QMessageBox whatToDo(QMessageBox::Warning, "Deleting subtask", "Deleting subtask " + currentSubtask + " of task " + currentTask);
QPushButton* moveHitsToParentButton = whatToDo.addButton("Move hits to task " + currentTask, QMessageBox::AcceptRole);
QPushButton* removeHitsButton = whatToDo.addButton("Remove hits", QMessageBox::AcceptRole);
QPushButton* cancelButton = whatToDo.addButton("Cancel", QMessageBox::RejectRole);
whatToDo.setDefaultButton(cancelButton);
whatToDo.exec();
if ( whatToDo.clickedButton() == cancelButton) return true;
if (m_editedTasks.find(currentTask) == m_editedTasks.end()) return true;
m_changedTask=true;
Task& t(m_editedTasks[currentTask]);
t.subTasks.take(currentSubtask);
if (whatToDo.clickedButton() == removeHitsButton) {
t.hits.take(currentSubtask);
} else if (whatToDo.clickedButton() == moveHitsToParentButton) {
QList<Task::Hit> sorter(t.hits.take(""));
sorter << t.hits.take(currentSubtask);
qStableSort(sorter.begin(), sorter.end());
t.hits[""] = sorter;
}
} else {
// remove file from disk
m_changedTask=true;
m_editedTasks.remove(currentTask);
}
tasksTree->clear();
populateTasks();
selectedStartDate(QDate());
return true;
} else if (e->type() == QEvent::Hide) {
saveTaskChanges();
}
return false;
}
void Sak::commitCurrentTask()
{
m_changedTask=true;
if (currentSubtask.isEmpty()) {
QString currentTitle = taskTitleEditor->text();
if (!currentTitle.isEmpty()) {
if (currentTitle != currentTask) {
if (m_editedTasks.contains(currentTitle)) {
QMessageBox::warning(0, "Conflict in task names", "Conflict in task names: current task " + currentTask + ", edited title " + currentTitle);
taskTitleEditor->setText(currentTask);
return;
} else if (m_editedTasks.contains(currentTask)) {
m_editedTasks[currentTitle] = m_editedTasks.take(currentTask);
m_editedTasks[currentTitle].title = currentTitle;
}
}
} else return;
Task& t = m_editedTasks[currentTitle];
t.bgColor = bgColorButton->palette().color(QPalette::Button);
t.fgColor = fgColorButton->palette().color(QPalette::ButtonText);
t.icon = taskPixmapViewer->pixmap();
QList<QTreeWidgetItem *> items = tasksTree->findItems(currentTask,Qt::MatchExactly,0);
foreach(QTreeWidgetItem* ii, items) {
ii->setText(0, currentTitle);
ii->setIcon(0, taskPixmapViewer->pixmap());
for (int i=0; i<3; i++) {
ii->setForeground(i, QColor(t.fgColor));
ii->setBackground(i, QColor(t.bgColor));
}
}
if (dueEditor->date() != dueEditor->minimumDate())
t.dueDate = dueEditor->date();
t.estimatedHours = estimatedHoursEditor->value();
currentTask=currentTitle;
if (tasksTree->selectedItems().size() != 1) return;
QTreeWidgetItem* item = tasksTree->selectedItems()[0];
item->setText(0, taskTitleEditor->text());
QIcon icon;
icon.addPixmap(t.icon);
item->setSizeHint(0, QSize(32,32));
item->setIcon(0, icon);
for(int i=0; i<3; i++) {
item->setForeground(i,t.fgColor);
item->setBackground(i,t.bgColor);
}
} else { // subtask edited
if (!m_editedTasks.contains(currentTask)) return;
Task& t(m_editedTasks[currentTask]);
QString currentTitle = taskTitleEditor->text();
// backup data
if (!currentTitle.isEmpty()) {
if (currentTitle != currentSubtask) {
if (t.subTasks.contains(currentTitle)) {
QMessageBox::warning(0, "Conflict in subtask names", "Conflict in subtask names");
taskTitleEditor->setText(currentSubtask);
return;
} else if (t.subTasks.contains(currentSubtask)) {
t.subTasks[currentTitle] = t.subTasks.take(currentSubtask);
t.subTasks[currentTitle].title = currentTitle;
t.hits[currentTitle] = t.hits.take(currentSubtask);
}
}
} else return;
Task::SubTask& st = t.subTasks[currentTitle];
st.bgColor = bgColorButton->palette().color(QPalette::Button);
st.fgColor = fgColorButton->palette().color(QPalette::ButtonText);
QList<QTreeWidgetItem *> items = tasksTree->findItems(currentTask,Qt::MatchExactly,0);
foreach(QTreeWidgetItem* jj, items) {
for(int i=0; i<jj->childCount(); i++) {
QTreeWidgetItem* ii = jj->child(i);
if (ii->text(0) != currentSubtask) continue;
ii->setText(0, currentTitle);
for (int i=0; i<3; i++) {
ii->setForeground(i, QColor(st.fgColor));
ii->setBackground(i, QColor(st.bgColor));
}
}
}
currentSubtask = currentTitle;
if (tasksTree->selectedItems().size() != 1) return;
QTreeWidgetItem* item = tasksTree->selectedItems()[0];
item->setText(0, taskTitleEditor->text());
QIcon icon;
icon.addPixmap(t.icon);
item->setSizeHint(0, QSize(32,32));
item->setIcon(0, icon);
for(int i=0; i<3; i++) {
item->setForeground(i,st.fgColor);
item->setBackground(i,st.bgColor);
}
}
}
void Sak::selectedTask()
{
if (tasksTree->selectedItems().isEmpty()) {
taskPixmapViewer->setEnabled(false);
taskPixmapViewer->setPixmap(QPixmap());
taskTextEditor->setEnabled(false);
taskTitleEditor->setEnabled(false);
bgColorButton->setEnabled(false);
fgColorButton->setEnabled(false);
dueEditor->setEnabled(false);
estimatedHoursEditor->setEnabled(false);
return;
}
QTreeWidgetItem* selectedItem = tasksTree->selectedItems().first();
QTreeWidgetItem* parentItem = selectedItem->parent();
QString tt = selectedItem->text(0);
if (!parentItem) {
taskPixmapViewer->setEnabled(true);
dueEditor->setEnabled(true);
estimatedHoursEditor->setEnabled(true);
} else {
taskPixmapViewer->setEnabled(false);
taskPixmapViewer->setPixmap(QPixmap());
dueEditor->setEnabled(false);
estimatedHoursEditor->setEnabled(false);
}
taskTextEditor->setEnabled(true);
taskTitleEditor->setEnabled(true);
bgColorButton->setEnabled(true);
fgColorButton->setEnabled(true);
if (!parentItem) { // editing a task
if (!m_editedTasks.contains(tt)) return;
const Task& t = m_editedTasks[tt];
taskPixmapViewer->setPixmap(t.icon);
taskTextEditor->blockSignals(true);
taskTextEditor->setPlainText(t.description);
taskTextEditor->blockSignals(false);
taskTitleEditor->setText(t.title);
QPalette p;
p.setColor(QPalette::Button, t.bgColor);
p.setColor(QPalette::ButtonText, t.fgColor);
bgColorButton->setPalette(p);
fgColorButton->setPalette(p);
estimatedHoursEditor->setValue(t.estimatedHours);
dueEditor->setDate(t.dueDate.isValid() ? t.dueDate : dueEditor->minimumDate());
currentTask = t.title;
currentSubtask = "";
} else {
if (!m_editedTasks.contains(parentItem->text(0))) return;
const Task& t = m_editedTasks[parentItem->text(0)];
if (!t.subTasks.contains(tt)) return;
const Task::SubTask& st = t.subTasks[tt];
taskTextEditor->setPlainText(st.description);
taskTitleEditor->setText(st.title);
QPalette p;
p.setColor(QPalette::Button, st.bgColor.isValid() ? st.bgColor : t.bgColor);
p.setColor(QPalette::ButtonText, st.fgColor.isValid() ? st.fgColor : t.fgColor);
bgColorButton->setPalette(p);
fgColorButton->setPalette(p);
currentTask = t.title;
currentSubtask = st.title;
}
}
void Sak::doubleClickedTask(QTreeWidgetItem* i, int column)
{
if (column == 1) {
m_changedTask=true;
if (i->parent() == 0) {
QHash<QString, Task>::iterator itr = m_editedTasks.find(i->text(0));
Q_ASSERT(itr != m_editedTasks.end());
bool& active ( itr.value().active );
active = !active;
i->setIcon(column, active ? QIcon(":/images/active.png") : QIcon(":/images/inactive.png"));
} else {
QHash<QString, Task>::iterator itr = m_editedTasks.find(i->parent()->text(0));
Q_ASSERT(itr != m_editedTasks.end());
bool& active ( itr.value().subTasks[i->text(0)].active );
active = !active;
i->setIcon(column, active ? QIcon(":/images/active.png") : QIcon(":/images/inactive.png"));
}
((QTreeWidget*)sender())->update();
}
}
void Sak::timerEvent(QTimerEvent* e)
{
if (e->timerId() == m_timerId) {
if (!m_view->isVisible() && !m_settings->isVisible() && m_tasks.count() > 0) {
popup();
// close timer
killTimer(m_timerId); m_timerId=-1;
killTimer(m_timeoutPopup); m_timeoutPopup=-1;
int msecs = (int)(qMax( 30000.0, Task::hours(m_currentInterval)*3600.0*1000.0/10.0));
m_timeoutPopup = startTimer(msecs);
// restart timer
m_nextTimerEvent = QDateTime::currentDateTime().addMSecs(msecs);
} else {
if (m_settings && m_settings->isVisible() && !m_settings->isActiveWindow()) {
trayIcon->showMessage("Delayed check point", "Delayed check point due to open settings. Close the setting window!", QSystemTrayIcon::Warning, -1);
m_settings->close();