-
Notifications
You must be signed in to change notification settings - Fork 0
/
clockit.cpp
656 lines (518 loc) · 18.4 KB
/
clockit.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
/*
*
* Copyright (C) 2020 David Beccue
*
* 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 3 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, see https://www.gnu.org/licenses/.
*
*/
#include <QtWidgets>
#include <QFile>
#include <QDebug>
#include <time.h>
#include "clockit.h"
#include "tmp/ui/ui_clockit.h"
#include "preferences.h"
#include "viewentries.h"
#include "version.h"
// #define DEBUG_OUTPUT
/**
* @brief This is constructor for the dialog for choosing drive letter and browsing for folder to mount
*
* ClockIt appears when user click Configure in the taskbar icon menu
*/
ClockIt::ClockIt(QWidget *parent) :
QDialog(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint),
ui(new Ui::ClockIt)
{
ui->setupUi(this);
srand( time(0L) );
// this->setStyleSheet(" #ClockIt { border-image: url(images/background.png); } ");
pixmapBackground = new QPixmap;
pixmapBackground->load(":images/background.png");
http = new QNetworkAccessManager;
connect( http, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
readDefaultSettings();
connect( &clockedInElsewhereTimer, SIGNAL(timeout()), this, SLOT(updateClockStatus()) );
connect( ui->buttonBox, SIGNAL(accepted()), this, SLOT(okClicked()) );
QShortcut *shortcut = new QShortcut(QKeySequence(tr("Ctrl+O")), this );
connect( shortcut, SIGNAL(activated()), this, SLOT(okClicked()) );
ui->dtClockInTime->setCalendarPopup(true);
ui->dtClockOutTime->setCalendarPopup(true);
ui->dtClockInTime->setDisplayFormat("yyyy-MM-dd hh:mm");
ui->dtClockOutTime->setDisplayFormat("yyyy-MM-dd hh:mm");
createActions();
createTrayIcon();
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
setIcon();
trayIcon->show();
trayIcon->setToolTip("Clock Status Unknown");
queryUserName();
queryProjects(); // get the initial Projects
updateClockStatus(); // get the initial clock status of this user
/** describe all supported output formats */
QString fileFormats = "( ";
for ( int i = 0; i < QImageWriter::supportedImageFormats().count(); i++ ) {
fileFormats += "*."; /* Insert wildcard */
fileFormats += QString( QImageWriter::supportedImageFormats().at(i) ).toLower(); /* Insert the format */
fileFormats += " "; /* Insert a space */
}
fileFormats += ")";
#ifdef DEBUG_OUTPUT
qDebug() << "Supported formats for writing include: " << fileFormats;
#endif
}
ClockIt::~ClockIt()
{
delete http;
delete ui;
}
void ClockIt::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
/**
* @brief Unmount drive on quit and decrease file size
*/
void ClockIt::quitApp()
{
qApp->quit();
}
/**
* @brief Unmount drive on quit and decrease file size
*/
void ClockIt::about()
{
QMessageBox msgbox;
msgbox.setWindowTitle( "WorkClock" );
msgbox.setText(
QString("Version: ") + glbRevision + "\n" +
QString("Last Updated on: ") + glbDateLastModified + "\n\n" +
QString("The software included in this product contains copyrighted software that is licensed under the GPLv3.\n\nYou may obtain the complete Corresponding Source code from our distribution site at https://github.com/dabbler/punchclock.git")
);
msgbox.setInformativeText( "\n(C) Copyright 2017 Peregrine LLC\n" );
msgbox.exec();
}
/* transparent bitmapped background functions */
void ClockIt::paintEvent(QPaintEvent * event)
{
Q_UNUSED(event);
QPainter painter(this);
if ( pixmapBackground && ! pixmapBackground->isNull() ) {
*pixmapBackground = pixmapBackground->scaled(width(), height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
painter.drawPixmap(0, 0, *pixmapBackground);
}
}
void ClockIt::resizeEvent(QResizeEvent * /* event */ )
{
if ( pixmapBackground && ! pixmapBackground->isNull() ) {
*pixmapBackground = pixmapBackground->scaled(width(), height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
setMask(pixmapBackground->mask());
}
setWindowOpacity(0.90);
}
void ClockIt::mousePressEvent(QMouseEvent * event)
{
isDragging = false;
if ( event->button() == Qt::LeftButton ) {
dragPosition = event->globalPos() - frameGeometry().topLeft();
isDragging = true;
event->accept();
}
}
void ClockIt::mouseMoveEvent(QMouseEvent * event)
{
if ( event->buttons() & Qt::LeftButton ) {
if ( isDragging ) {
move(event->globalPos() - dragPosition);
event->accept();
}
}
}
/**
* @brief Set Icon
*
* Sets icon in the tray
*
*/
void ClockIt::setIcon()
{
QIcon icon;
icon.addFile(":/images/clock.png");
trayIcon->setIcon(icon);
}
/**
* @brief TrayIcon activation reason
*
*/
void ClockIt::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch ( reason ) {
case QSystemTrayIcon::Trigger:
// qDebug() << "iconActivated(Trigger)";
punchClock();
break;
case QSystemTrayIcon::DoubleClick:
// qDebug() << "iconActivated(DoubleClick)";
viewEntries();
break;
case QSystemTrayIcon::MiddleClick:
// qDebug() << "iconActivated(MiddleClick)";
editPreferences();
break;
case QSystemTrayIcon::Context:
// qDebug() << "iconActivated(Context)";
break;
default:
break;
}
}
/**
* @brief Create Actions
*
*/
void ClockIt::createActions()
{
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), this, SLOT(quitApp()));
aboutAction = new QAction(tr("&About"), this);
connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
punchClockAction = new QAction (tr("&Punch Clock"), this);
connect(punchClockAction, SIGNAL(triggered()), this, SLOT(punchClock()));
viewEntriesAction = new QAction(tr("&View Entries"), this);
connect(viewEntriesAction, SIGNAL(triggered()), this, SLOT(viewEntries()));
configAction = new QAction (tr("&Configure"), this);
connect(configAction, SIGNAL(triggered()), this, SLOT(editPreferences()));
}
/**
* @brief Create Tray Icon Menu
*
*/
void ClockIt::createTrayIcon()
{
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(punchClockAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(viewEntriesAction);
trayIconMenu->addAction(configAction);
trayIconMenu->addAction(aboutAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
}
/**
* @brief Shows the configuration dialog when Configure is selected
*
*/
void ClockIt::viewEntries()
{
ViewEntries v(this);
v.exec();
}
/**
* @brief Shows the configuration dialog when Configure is selected
*
*/
void ClockIt::editPreferences()
{
Preferences prefs(this);
allUserNames.clear();
allProjects.clear();
ui->comboProject->clear();
prefs.exec();
readDefaultSettings();
queryProjects(); // get the updated list of Projects
updateClockStatus();
}
void ClockIt::readDefaultSettings()
{
QSettings settings("WorkClock", "Config");
project = Preferences::getProject();
if ( ! project.isEmpty() ) {
ui->comboProject->setCurrentText( project );
}
}
void ClockIt::okClicked()
{
float elapsedHours = (float) ui->dtClockInTime->dateTime().secsTo( ui->dtClockOutTime->dateTime() ) / (60.0 * 60.0);
QString urlStr = "/punchclock.php";
urlStr += "?login=" + QUrl::toPercentEncoding( Preferences::getUserName() );
urlStr += "&description=" + QUrl::toPercentEncoding(ui->efDescription->toPlainText());
urlStr += "&project_id=" + QString::number( allProjects.key(project) );
urlStr += "&project_name=" + QUrl::toPercentEncoding(ui->comboProject->currentText());
urlStr += "&" + QString("hours=%1").arg(elapsedHours,0,'f',3);
if ( ui->dtClockInTime->isEnabled() ) {
urlStr += "&start_time=" + QUrl::toPercentEncoding(ui->dtClockInTime->dateTime().toString("yyyy-MM-dd hh:mm:ss"));
}
if ( ui->dtClockOutTime->isEnabled() ) {
urlStr += "&end_time=" + QUrl::toPercentEncoding(ui->dtClockOutTime->dateTime().toString("yyyy-MM-dd hh:mm:ss"));
if ( ui->efDescription->toPlainText().isEmpty() ) {
QMessageBox msgbox;
msgbox.setWindowTitle( "Clock Out Problem" );
msgbox.setText( "Clock Out NOT successful" );
msgbox.setInformativeText( "You must enter a description of all the tasks worked on during this period." );
msgbox.exec();
return;
}
}
#ifdef DEBUG_OUTPUT
qDebug() << "okClicked() -> get(" << glbHostUrl + urlStr << ")";
#endif
QNetworkReply *reply = http->get( QNetworkRequest(QUrl(glbHostUrl + urlStr )));
reply->setProperty("whichone", QVariant("clockInsertion") );
}
void ClockIt::updateClockStatus()
{
fieldLock();
QNetworkReply *reply = http->get( QNetworkRequest(QUrl(QString(glbHostUrl) + "/clockread.php?login=" + QUrl::toPercentEncoding( Preferences::getUserName() ))) );
reply->setProperty("whichone", QVariant("clockReading") );
/* Check every 5 minutes if the user Clocked IN or OUT from the website instead of here. This was useful to ensure privacy for screen capturing whenever the user is not Clocked IN. */
clockedInElsewhereTimer.start( TIME_CHECKING_FOR_CLOCKED_IN_ELSEWHERE );
}
int ClockIt::isClockedIn()
{
return (trayIcon->toolTip() == "Clocked In");
}
void ClockIt::punchClock()
{
if ( isVisible() ) {
hide();
} else {
ui->dtClockInTime->setDateTime( QDateTime::fromString(clockFields["start_time"],"yyyy-MM-dd hh:mm:ss") );
#ifdef CONSTRAIN_CLOCK_IN_OUT_TIMES
ui->dtClockOutTime->setMinimumDateTime( QDateTime::fromString(clockFields["start_time"],"yyyy-MM-dd hh:mm:ss") );
ui->dtClockOutTime->setMaximumDateTime( QDateTime::currentDateTime() );
#endif
ui->dtClockOutTime->setDateTime( QDateTime::currentDateTime() );
ui->dtClockInTime->setDateTime( QDateTime::fromString(clockFields["start_time"],"yyyy-MM-dd hh:mm:ss") );
ui->dtClockOutTime->setDateTime( QDateTime::currentDateTime() );
updateClockStatus();
ui->editLongAgo->setText("");
show(); /* the punch clock dialog box */
/* show that the UI is NOT ready to be used yet (not until the web returns the right values for the fields) */
fieldLock();
}
}
void ClockIt::fieldLock()
{
ui->efDescription->setEnabled(false);
ui->dtClockInTime->setEnabled(false);
ui->dtClockOutTime->setEnabled(false);
ui->clockout->setEnabled(false);
}
void ClockIt::fieldUnlock()
{
ui->efDescription->setEnabled(true);
ui->dtClockInTime->setEnabled(true);
ui->dtClockOutTime->setEnabled(true);
ui->clockout->setEnabled(true);
}
void ClockIt::on_comboProject_editTextChanged(const QString &txt )
{
if ( ! txt.isEmpty() ) {
#ifdef DEBUG_OUTPUT
qDebug() << "on_comboProject_editTextChanged() " << txt;
#endif
on_comboProject_activated(txt);
}
}
void ClockIt::on_comboProject_activated(const QString &theProject )
{
#ifdef DEBUG_OUTPUT
qDebug() << "on_comboProject_activated(" << theProject << ")";
#endif
if ( ! theProject.isEmpty() ) {
project = theProject;
QSettings settings("WorkClock", "Config");
settings.setValue("project", theProject );
}
}
void ClockIt::replyFinished( QNetworkReply *reply )
{
#ifdef DEBUG_OUTPUT
if ( reply->error() ) {
qDebug() << "ERROR!";
qDebug() << reply->error();
qDebug() << reply;
} else {
qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString();
qDebug() << reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString();;
qDebug() << reply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
// qDebug() << reply->readAll();
}
#endif
QString strWhichOne = reply->property("whichone").toString();
#ifdef DEBUG_OUTPUT
qDebug() << "ClockIt::httpResponse(" << reply->error() << ") for " << strWhichOne;
#endif
if ( reply->error() ) {
#ifdef DEBUG_OUTPUT
qDebug() << reply->error();
#endif
showMessage( "TimeCard Status", QString("%1").arg(reply->error()), 0 );
return;
}
if ( strWhichOne == "userId" ) {
userId = QString( reply->readAll() );
#ifdef DEBUG_OUTPUT
qDebug() << "userId = " << userId;
#endif
QSettings settings("WorkClock", "Config");
settings.setValue("userId", userId );
}
if ( strWhichOne == "Projects" ) {
QStringList allProjIdNames = QString( reply->readAll() ).split("\n", QString::SkipEmptyParts);
allProjIdNames.sort(Qt::CaseInsensitive);
#ifdef DEBUG_OUTPUT
qDebug() << "comboProject->addItems(" << allProjIdNames << ")";
#endif
foreach ( QString p, allProjIdNames ) {
QStringList projIdName = p.split("\t", QString::SkipEmptyParts);
allProjects[ projIdName.value(1).toInt() ] = projIdName.value(0);
}
QStringList projNames = allProjects.values();
projNames.sort(Qt::CaseInsensitive);
ui->comboProject->clear();
ui->comboProject->addItems( projNames );
ui->comboProject->setCurrentText( project );
}
if ( strWhichOne == "UserName" ) {
allUserNames = QString( reply->readAll() ).split(":", QString::SkipEmptyParts);
allUserNames.sort(Qt::CaseInsensitive);
}
if ( strWhichOne == "clockInsertion" ) {
#ifdef DEBUG_OUTPUT
qDebug() << "Clock Insert:" << reply->readAll();
#endif
/* retrieve the updated clock status */
updateClockStatus();
}
if ( strWhichOne == "clockReading" ) {
/* show that the UI is now ready to be used */
fieldUnlock();
QString webResp = reply->readAll();
clockFields.clear();
foreach ( QString kv, webResp.split("\03", QString::SkipEmptyParts) ) {
clockFields[ kv.split("\02").value(0) ] = kv.split("\02").value(1);
}
/* if both start and end time are filled, then we want to clock-in with a brand new record */
if ( ! clockFields["start_time"].isEmpty() && ! clockFields["end_time"].isEmpty() ) {
clockFields.clear();
}
#ifdef DEBUG_OUTPUT
qDebug() << "Clock Reading:" << clockFields;
qDebug() << "Current project:" << project;
qDebug() << "All Projects:" << allProjects;
#endif
/** initialize the state of the dialog box to be shown */
ui->efDescription->setText( clockFields["description"] );
if ( clockFields["project_id"] > 0 ) {
ui->comboProject->setCurrentText( allProjects[ clockFields["project_id"].toInt() ] );
} else {
if ( ! project.isEmpty() ) {
ui->comboProject->setCurrentText( project );
}
}
ui->dtClockInTime->setEnabled(true);
ui->dtClockOutTime->setEnabled(true);
ui->dtClockInTime->setVisible(true);
ui->dtClockOutTime->setVisible(true);
ui->clockout->setVisible(true);
/* if we are currently clocked OUT... */
if ( clockFields["start_time"].isEmpty() ) {
trayIcon->setToolTip("Clocked Out");
ui->dtClockInTime->setDateTime( QDateTime::currentDateTime() );
ui->dtClockOutTime->setEnabled(false);
ui->dtClockOutTime->setVisible(false);
ui->clockout->setVisible(false);
trayIcon->setToolTip("Clocked Out");
} else { /* otherwise, we are presently clocked IN... */
float secsDiff = ui->dtClockInTime->dateTime().secsTo( QDateTime::currentDateTime() ) / 3600.0;
QString s = QString("Clocked In\nHours worked: %1").arg(QString::number(secsDiff,'g',3));
trayIcon->setToolTip(s);
}
}
reply->deleteLater();
}
void ClockIt::queryProjects()
{
#ifdef DEBUG_OUTPUT
qDebug() << "ClockIt::queryProjects()";
#endif
/* keep looking for all the Projects, in case the connection to the web site failed */
QSettings settings("WorkClock", "Config");
QNetworkReply *reply = http->get( QNetworkRequest(QUrl(QString(glbHostUrl) + QString("/projects.php"))));
reply->setProperty("whichone", QVariant("Projects") );
}
void ClockIt::queryUserName()
{
#ifdef DEBUG_OUTPUT
qDebug() << "ClockIt::queryUserName()";
#endif
/* keep looking for all the Projects, in case the connection to the web site failed */
if ( allUserNames.isEmpty() ) {
QSettings settings("WorkClock", "Config");
QNetworkReply *reply = http->get( QNetworkRequest(QUrl(QString(glbHostUrl) + QString("/userid.php?employee=%1").arg(settings.value("employeeFilterNumber").toInt() ))));
reply->setProperty("whichone", QVariant("UserName") );
}
}
void ClockIt::showMessage(QString msgTitle, QString msgBody, int iconType)
{
#ifdef DEBUG_OUTPUT
qDebug() << "showMessage(" << msgTitle << "," << msgBody << ")";
#endif
QSystemTrayIcon::MessageIcon mIcon = QSystemTrayIcon::MessageIcon(iconType);
trayIcon->showMessage(msgTitle, msgBody, mIcon, 2000);
}
void ClockIt::on_editLongAgo_textChanged( const QString &txt )
{
if ( isClockedIn() ) {
if ( txt.toFloat() < 0.000001 ) {
ui->dtClockOutTime->setDateTime( QDateTime::currentDateTime() );
} else {
ui->dtClockOutTime->setDateTime( ui->dtClockInTime->dateTime().addSecs( (qint64) ( 3600 * txt.toFloat()) ) );
}
} else {
ui->dtClockInTime->setDateTime( QDateTime::currentDateTime().addSecs( (qint64) (-3600 * txt.toFloat()) ) );
}
}
void ClockIt::showHours()
{
if ( isClockedIn() ) {
float secsDiff = ui->dtClockInTime->dateTime().secsTo( ui->dtClockOutTime->dateTime() ) / 3600.0;
QString s = QString("Hours worked: %1").arg(QString::number(secsDiff,'g',3));
qDebug() << "showHours() " + s;
ui->lblHoursWorked->setText( QString("Hours worked: %1").arg(QString::number(secsDiff,'g',3)) );
} else {
ui->lblHoursWorked->setText("");
}
}
void ClockIt::on_dtClockOutTime_dateTimeChanged(const QDateTime &dateTime)
{
showHours();
}
void ClockIt::on_dtClockInTime_dateTimeChanged(const QDateTime &dateTime)
{
showHours();
}