-
Notifications
You must be signed in to change notification settings - Fork 8
/
camcopsapp.cpp
3376 lines (2799 loc) · 111 KB
/
camcopsapp.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) 2012, University of Cambridge, Department of Psychiatry.
Created by Rudolf Cardinal (rnc1001@cam.ac.uk).
This file is part of CamCOPS.
CamCOPS 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.
CamCOPS 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 CamCOPS. If not, see <https://www.gnu.org/licenses/>.
*/
// #define DEBUG_DROP_TABLES_NOT_EXPLICITLY_CREATED
// #define DANGER_DEBUG_PASSWORD_DECRYPTION
// #define DANGER_DEBUG_WIPE_PASSWORDS
// #define DEBUG_CSS_SIZES
// #define DEBUG_EMIT
// #define DEBUG_SCREEN_STACK
// #define DEBUG_ALL_APPLICATION_EVENTS
#include "camcopsapp.h"
#include <QApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QIcon>
#include <QLibraryInfo>
#include <QMainWindow>
#include <QMetaType>
#include <QNetworkReply>
#include <QProcessEnvironment>
#include <QPushButton>
#include <QScreen>
#include <QSqlDatabase>
#include <QSqlDriverCreator>
#include <QStackedWidget>
#include <QStandardPaths>
#include <QTextStream>
#include <QTranslator>
#include <QUrl>
#include <QUuid>
#include "common/appstrings.h"
#include "common/dbconst.h" // for NONEXISTENT_PK
#include "common/languages.h"
#include "common/platform.h"
#include "common/preprocessor_aid.h" // IWYU pragma: keep
#include "common/textconst.h"
#include "common/uiconst.h"
#include "common/varconst.h"
#include "core/networkmanager.h"
#include "crypto/cryptofunc.h"
#include "db/ancillaryfunc.h"
#include "db/databasemanager.h"
#include "db/dbfunc.h"
#include "db/dbnestabletransaction.h"
#include "db/whereconditions.h"
#include "db/whichdb.h"
#include "dbobjects/allowedservertable.h"
#include "dbobjects/blob.h"
#include "dbobjects/extrastring.h"
#include "dbobjects/idnumdescription.h"
#include "dbobjects/patientidnum.h"
#include "dbobjects/patientsorter.h"
#include "dbobjects/storedvar.h"
#include "diagnosis/icd9cm.h"
#include "diagnosis/icd10.h"
#include "dialogs/modedialog.h"
#include "dialogs/patientregistrationdialog.h"
#include "dialogs/scrollmessagebox.h"
// #include "layouts/layouts.h"
#include "lib/convert.h"
#include "lib/datetime.h"
#include "lib/filefunc.h"
#include "lib/slowguiguard.h"
#include "lib/stringfunc.h"
#include "lib/uifunc.h"
#include "lib/version.h"
#include "menu/mainmenu.h"
#include "menu/singleusermenu.h"
#include "qobjects/slownonguifunctioncaller.h"
#include "qobjects/urlhandler.h"
#include "questionnairelib/commonoptions.h"
#include "questionnairelib/questionnaire.h"
#include "tasklib/inittasks.h"
#include "tasklib/taskschedule.h"
#include "tasklib/taskscheduleitem.h"
#include "version/camcopsversion.h"
#ifdef DEBUG_ALL_APPLICATION_EVENTS
#include "qobjects/debugeventwatcher.h"
#endif
#ifdef USE_SQLCIPHER
#include "db/sqlcipherdriver.h"
#endif
const QString APPSTRING_TASKNAME("camcops"); // task name used for generic but downloaded tablet strings
const QString APP_NAME("camcops"); // e.g. subdirectory of ~/.local/share; DO NOT ALTER
const QString APP_PRETTY_NAME("CamCOPS"); // main window title and suffix on dialog window titles
const QString CONNECTION_DATA("data");
const QString CONNECTION_SYS("sys");
const int DEFAULT_SERVER_PORT = 443; // HTTPS
const QString ENVVAR_DB_DIR("CAMCOPS_DATABASE_DIRECTORY");
const int UPLOAD_INTERVAL_SECONDS = 10 * 60; // 10 minutes
CamcopsApp::CamcopsApp(int& argc, char* argv[]) :
QApplication(argc, argv),
m_p_task_factory(nullptr),
m_lockstate(LockState::Locked), // default unless we get in via encryption password
m_p_main_window(nullptr),
m_p_window_stack(nullptr),
m_p_hidden_stack(nullptr),
m_maximized_before_fullscreen(true), // true because openMainWindow() goes maximized
m_patient(nullptr),
m_storedvars_available(false),
m_netmgr(nullptr),
m_qt_logical_dpi(uiconst::DEFAULT_DPI),
m_qt_physical_dpi(uiconst::DEFAULT_DPI),
m_network_gui_guard(nullptr)
{
setLanguage(QLocale::system().name()); // try languages::DANISH
setApplicationName(APP_NAME);
setApplicationDisplayName(APP_PRETTY_NAME);
setApplicationVersion(camcopsversion::CAMCOPS_CLIENT_VERSION.toString());
#ifdef DEBUG_ALL_APPLICATION_EVENTS
new DebugEventWatcher(this, DebugEventWatcher::All);
#endif
m_last_automatic_upload_time = QDateTime(); // initially invalid
}
CamcopsApp::~CamcopsApp()
{
// https://doc.qt.io/qt-6.5/objecttrees.html
// Only delete things that haven't been assigned a parent
delete m_network_gui_guard;
delete m_p_main_window;
}
// ============================================================================
// Operating mode
// ============================================================================
bool CamcopsApp::isSingleUserMode() const
{
return getMode() == varconst::MODE_SINGLE_USER;
}
bool CamcopsApp::isClinicianMode() const
{
return getMode() == varconst::MODE_CLINICIAN;
}
int CamcopsApp::getMode() const
{
return varInt(varconst::MODE);
}
void CamcopsApp::setMode(const int mode)
{
const int old_mode = getMode();
const bool mode_changed = mode != old_mode;
const bool single_user_mode = mode == varconst::MODE_SINGLE_USER;
// Things we might do even if the new mode is the same as the old mode
// (e.g. at startup):
if (single_user_mode) {
disableNetworkLogging();
setVar(varconst::OFFER_UPLOAD_AFTER_EDIT, true);
} else {
enableNetworkLogging();
}
// Things we only do if the mode has actually changed:
if (mode_changed) {
setVar(varconst::MODE, mode);
if (single_user_mode) {
setDefaultPatient();
}
if (m_p_main_window) {
// If the mode has been set on startup, we won't have a main window
// yet to attach the menu to, so we create it later.
recreateMainMenu();
}
emit modeChanged(mode);
}
}
void CamcopsApp::setModeFromUser()
{
if (modeChangeForbidden()) { // alerts the user as to why, if not allowed
return;
}
const int old_mode = getMode();
int new_mode;
// Single user mode specified on the command line or if the app was
// launched via a deep link on Android (starting http://camcops/)
if (old_mode == varconst::MODE_NOT_SET && m_default_single_user_mode) {
new_mode = varconst::MODE_SINGLE_USER;
} else {
new_mode = getModeFromUser();
if (new_mode == old_mode) {
// No change, nothing to do
return;
}
}
if (!agreeTerms(new_mode)) {
// User changed mode but didn't agree to terms. Will exit the app if
// called on startup, otherwise stick with the old mode
if (!hasAgreedTerms()) {
uifunc::stopApp(tr("OK. Goodbye."), tr("You refused the conditions."));
}
// had agreed to terms for the old mode, so don't change
return;
}
wipeDataForModeChange();
setMode(new_mode);
if (new_mode == varconst::MODE_SINGLE_USER) {
registerPatientWithServer();
}
}
int CamcopsApp::getModeFromUser()
{
const int old_mode = getMode();
ModeDialog dialog(old_mode);
const int reply = dialog.exec();
if (reply != QDialog::Accepted) {
// Dialog cancelled
if (old_mode == varconst::MODE_NOT_SET) {
// Exit the app if called on startup
uifunc::stopApp(
tr("You did not select how you would like to use CamCOPS")
);
}
}
return dialog.mode();
}
bool CamcopsApp::modeChangeForbidden() const
{
if (isClinicianMode()) {
// Switch from clinician mode to single-user mode
if (patientRecordsPresent()) {
uifunc::alert(
tr("You cannot change mode when there are patient records present")
);
return true;
}
}
if (taskRecordsPresent()) {
// Switch in either direction
uifunc::alert(
tr("You cannot change mode when there are tasks still to be uploaded")
);
return true;
}
return false;
}
bool CamcopsApp::taskRecordsPresent() const
{
return m_p_task_factory->anyTasksPresent();
}
void CamcopsApp::wipeDataForModeChange()
{
// When we switch from clinician mode to single-user mode:
// - We should have no patients (*).
// - We should have no tasks (*).
// - We must wipe network security details.
// - [We will also want the user to register using the single-user-mode
// registration interface.]
// - We should wipe task schedules.
//
// When we switch from single-user mode to clinician mode:
// - There will be one patient, but that's OK. We will delete the record.
// - We should have no tasks (*).
// - We must wipe network security details -- the "single-user" accounts
// are not necessarily trusted to create data for new patients.
// (Otherwise the theoretical vulnerability is that a registered user
// obtains their username, cracks their obscured password, and enters
// them into the clinician mode, allowing upload of data for arbitrary
// patients.)
//
// At present the client verifies this, but ideally we should verify that
// server-side, too; see todo.rst.
//
// - We can wipe task schedules.
//
// (*) Pre-checked by modeChangeForbidden().
// Deselect any selected patient
deselectPatient();
// Server security details
setVar(varconst::SERVER_USERNAME, "");
setVar(varconst::SERVER_USERPASSWORD_OBSCURED, "");
setVar(varconst::SINGLE_PATIENT_PROQUINT, "");
setVar(varconst::SINGLE_PATIENT_ID, dbconst::NONEXISTENT_PK);
// Task schedules
m_sysdb->deleteFrom(TaskScheduleItem::TABLENAME);
m_sysdb->deleteFrom(TaskSchedule::TABLENAME);
// Delete patient records (given the pre-checks, as above, this will only
// delete a single-user-mode patient record with no associated tasks).
m_datadb->deleteFrom(PatientIdNum::PATIENT_IDNUM_TABLENAME);
m_datadb->deleteFrom(Patient::TABLENAME);
}
bool CamcopsApp::patientRecordsPresent() const
{
return nPatients() > 0;
}
int CamcopsApp::getSinglePatientId() const
{
return var(varconst::SINGLE_PATIENT_ID).toInt();
}
void CamcopsApp::setSinglePatientId(const int id)
{
setVar(varconst::SINGLE_PATIENT_ID, id);
}
bool CamcopsApp::registerPatientWithServer()
{
if (isPatientSelected()) {
if (!confirmDeletePatient()) {
return false;
}
deleteSelectedPatient();
deleteTaskSchedules();
recreateMainMenu();
}
// The values we will attempt to register with:
QUrl new_server_url;
QString new_patient_proquint;
if (!m_default_server_url.isEmpty() &&
!m_default_patient_proquint.isEmpty()) {
// These defaults may have been passed in as command-line options;
// see processCommandLineArguments().
new_server_url = m_default_server_url;
new_patient_proquint = m_default_patient_proquint;
} else {
// Start with a blank URL, or a URL from a previous failed attempt, to
// assist in reducing data entry following network/registration failure.
QUrl old_server_url = QUrl();
const QString old_patient_proquint = varString(varconst::SINGLE_PATIENT_PROQUINT);
if (!old_patient_proquint.isEmpty()) {
old_server_url.setScheme("https");
old_server_url.setHost(varString(varconst::SERVER_ADDRESS));
old_server_url.setPort(varInt(varconst::SERVER_PORT));
old_server_url.setPath(varString(varconst::SERVER_PATH));
}
PatientRegistrationDialog dialog(nullptr, old_server_url, old_patient_proquint);
const int reply = dialog.exec();
if (reply != QDialog::Accepted) {
return false;
}
new_server_url = dialog.serverUrl();
new_patient_proquint = dialog.patientProquint();
}
setVar(varconst::SERVER_ADDRESS, new_server_url.host());
const int default_port = DEFAULT_SERVER_PORT;
setVar(varconst::SERVER_PORT, new_server_url.port(default_port));
setVar(varconst::SERVER_PATH, new_server_url.path());
setVar(varconst::SINGLE_PATIENT_PROQUINT, new_patient_proquint);
setVar(varconst::DEVICE_FRIENDLY_NAME,
QString("Single user device %1").arg(deviceId()));
// Currently defaults to no validation, though the user can enable through
// the advanced settings if they so wish.
setVar(varconst::VALIDATE_SSL_CERTIFICATES,
varconst::VALIDATE_SSL_CERTIFICATES_IN_SINGLE_USER_MODE);
reconnectNetManager(&CamcopsApp::patientRegistrationFailed,
&CamcopsApp::patientRegistrationFinished);
showNetworkGuiGuard(tr("Registering patient..."));
networkManager()->registerPatient();
return true;
}
bool CamcopsApp::confirmDeletePatient() const
{
ScrollMessageBox msgbox(
QMessageBox::Warning,
tr("Delete patient"),
tr(
"Registering a new patient will delete the current patient and "
"any associated data. Are you sure you want to do this?"
) + "\n\n",
m_p_main_window);
QAbstractButton* delete_button = msgbox.addButton(
tr("Yes, delete"), QMessageBox::YesRole);
msgbox.addButton(tr("No, cancel"), QMessageBox::NoRole);
msgbox.exec();
if (msgbox.clickedButton() != delete_button) {
return false;
}
return true;
}
void CamcopsApp::deleteSelectedPatient()
{
m_patient->deleteFromDatabase();
setSinglePatientId(dbconst::NONEXISTENT_PK);
setDefaultPatient();
}
void CamcopsApp::deleteTaskSchedules()
{
TaskSchedulePtrList schedules = getTaskSchedules();
for (const TaskSchedulePtr& schedule : schedules) {
schedule->deleteFromDatabase();
}
}
void CamcopsApp::updateTaskSchedules(const bool alert_unfinished_tasks)
{
if (tasksInProgress()) {
if (alert_unfinished_tasks) {
uifunc::alert(
tr("You cannot update your task schedules when there are "
"unfinished tasks")
);
}
return;
}
showNetworkGuiGuard(tr("Updating task schedules..."));
reconnectNetManager(&CamcopsApp::updateTaskSchedulesFailed,
&CamcopsApp::updateTaskSchedulesFinished);
networkManager()->updateTaskSchedulesAndPatientDetails();
}
void CamcopsApp::patientRegistrationFailed(
const NetworkManager::ErrorCode error_code,
const QString& error_string)
{
deleteNetworkGuiGuard();
const QString base_message = tr("There was a problem with your registration.");
QString additional_message = "";
switch (error_code) {
case NetworkManager::ServerError:
case NetworkManager::JsonParseError:
additional_message = error_string;
break;
case NetworkManager::IncorrectReplyFormat:
additional_message = tr("Did you enter the correct CamCOPS server location?");
break;
case NetworkManager::GenericNetworkError:
additional_message = tr(
"%1\n\n"
"Are you connected to the internet?\n\n"
"Did you enter the correct CamCOPS server location?"
).arg(error_string);
break;
default:
// Shouldn't get here
break;
}
maybeRetryNetworkOperation(base_message, additional_message,
NetworkOperation::RegisterPatient);
}
void CamcopsApp::patientRegistrationFinished()
{
// Clear these after initial registration
m_default_server_url = QString();
m_default_patient_proquint = QString();
deleteNetworkGuiGuard();
// Creating the single patient from the server details will trigger
// "needs upload" and the upload icon will be displayed. We don't want
// to see the icon because we will wait until there are tasks to upload
// before uploading the patient
setNeedsUpload(false);
recreateMainMenu();
}
void CamcopsApp::updateTaskSchedulesFailed(
const NetworkManager::ErrorCode error_code,
const QString& error_string)
{
deleteNetworkGuiGuard();
handleNetworkFailure(
error_code,
error_string,
tr("There was a problem updating your task schedules."),
NetworkOperation::UpdateTaskSchedules
);
}
void CamcopsApp::updateTaskSchedulesFinished()
{
deleteNetworkGuiGuard();
// Updating the single patient from the server details will trigger
// "needs upload" and the upload icon will be displayed. We don't want
// to see the icon because we will wait until there are tasks to upload
// before uploading the patient
setNeedsUpload(false);
recreateMainMenu();
}
void CamcopsApp::uploadFailed(const NetworkManager::ErrorCode error_code,
const QString& error_string)
{
deleteNetworkGuiGuard();
handleNetworkFailure(
error_code,
error_string,
tr("There was a problem sending your completed tasks to the server."),
NetworkOperation::Upload
);
}
void CamcopsApp::uploadFinished()
{
deleteNetworkGuiGuard();
const bool alert_unfinished_tasks = false;
updateTaskSchedules(alert_unfinished_tasks);
recreateMainMenu();
}
void CamcopsApp::showNetworkGuiGuard(const QString& text)
{
if (!isLoggingNetwork()) {
m_network_gui_guard = new SlowGuiGuard(*this, m_p_main_window, text);
}
}
void CamcopsApp::deleteNetworkGuiGuard()
{
if (m_network_gui_guard) {
delete m_network_gui_guard;
m_network_gui_guard = nullptr;
}
}
void CamcopsApp::retryUpload()
{
const bool needs_upload = needsUpload();
qDebug() << Q_FUNC_INFO
<< "Last automatic upload time" << m_last_automatic_upload_time
<< "needsUpload()" << needs_upload;
if (needs_upload) {
const auto now = QDateTime::currentDateTimeUtc();
if (!m_last_automatic_upload_time.isValid() ||
m_last_automatic_upload_time.secsTo(now) > UPLOAD_INTERVAL_SECONDS) {
upload();
m_last_automatic_upload_time = now;
}
}
}
void CamcopsApp::handleNetworkFailure(const NetworkManager::ErrorCode error_code,
const QString& error_string,
const QString& base_message,
CamcopsApp::NetworkOperation operation)
{
QString additional_message = "";
switch (error_code) {
case NetworkManager::IncorrectReplyFormat:
// If we've managed to register our patient and the server is replying
// but in the wrong way then something bad has happened.
additional_message = tr(
"Unexpectedly, your server settings have changed."
);
break;
case NetworkManager::ServerError:
additional_message = error_string;
break;
case NetworkManager::GenericNetworkError:
additional_message = tr(
"%1\n\nAre you connected to the internet?"
).arg(error_string);
break;
default:
break;
}
maybeRetryNetworkOperation(base_message, additional_message, operation);
}
void CamcopsApp::maybeRetryNetworkOperation(const QString base_message,
const QString additional_message,
CamcopsApp::NetworkOperation operation)
{
const bool try_again_with_log = uifunc::confirm(
QString("%1\n\n%2").arg(base_message, additional_message),
tr("Error"),
tr("Try again with error log"),
TextConst::cancel()
);
if (!try_again_with_log) {
recreateMainMenu();
return;
}
enableNetworkLogging();
switch (operation) {
case NetworkOperation::RegisterPatient:
registerPatientWithServer();
break;
case NetworkOperation::UpdateTaskSchedules:
// it doesn't matter if we pass alert_unfinished_tasks as True or False
// here. We wouldn't be here if there were unfinished tasks.
updateTaskSchedules();
break;
case NetworkOperation::Upload:
upload();
break;
default:
// Shouldn't get here
break;
}
}
TaskSchedulePtrList CamcopsApp::getTaskSchedules()
{
TaskSchedulePtrList task_schedules;
TaskSchedule specimen(*this, *m_sysdb, dbconst::NONEXISTENT_PK); // this is why function can't be const
const WhereConditions where; // but we don't specify any
const SqlArgs sqlargs = specimen.fetchQuerySql(where);
const QueryResult result = m_sysdb->query(sqlargs);
const int nrows = result.nRows();
for (int row = 0; row < nrows; ++row) {
TaskSchedulePtr t(new TaskSchedule(*this, *m_sysdb, dbconst::NONEXISTENT_PK));
t->setFromQuery(result, row, true);
task_schedules.append(t);
}
return task_schedules;
}
void CamcopsApp::setLanguage(const QString& language_code,
const bool store_to_database)
{
qInfo() << "Setting language to:" << language_code;
// 1. Store the new code
m_current_language = language_code;
if (store_to_database && m_storedvars_available) {
setVar(varconst::LANGUAGE, language_code);
}
// 2. Clear the string cache
clearExtraStringCache();
// There are polymorphic versions of QTranslator::load(). See
// https://doc.qt.io/qt-6.5/qtranslator.html#load
// 3. Qt translator
if (m_qt_translator) {
removeTranslator(m_qt_translator.data());
m_qt_translator = nullptr;
}
const QString qt_filename = QString("qt_%1.qm").arg(language_code);
const QString qt_directory = QLibraryInfo::path(QLibraryInfo::TranslationsPath);
m_qt_translator = QSharedPointer<QTranslator>(new QTranslator());
bool loaded = m_qt_translator->load(qt_filename, qt_directory);
if (loaded) {
installTranslator(m_qt_translator.data());
qInfo() << "Loaded Qt translator" << qt_filename
<< "from" << qt_directory;
} else {
qWarning() << "Failed to load Qt translator" << qt_filename
<< "from" << qt_directory;
}
// 4. App translator
if (m_app_translator) {
removeTranslator(m_app_translator.data());
m_app_translator = nullptr;
}
if (language_code != languages::DEFAULT_LANGUAGE) {
const QString cc_filename = QString("camcops_%1.qm").arg(language_code);
const QString cc_directory(":/translations");
m_app_translator = QSharedPointer<QTranslator>(new QTranslator());
loaded = m_app_translator->load(cc_filename, cc_directory);
if (loaded) {
installTranslator(m_app_translator.data());
qInfo() << "Loaded CamCOPS translator" << cc_filename
<< "from" << cc_directory;
} else {
qWarning() << "Failed to load CamCOPS translator" << cc_filename
<< "from" << cc_directory;
}
}
// 5. Set the locale (so that e.g. calendar widgets use the right
// language).
QLocale::setDefault(QLocale(language_code));
}
QString CamcopsApp::getLanguage() const
{
return m_current_language;
}
int CamcopsApp::run()
{
// We do the minimum possible; then we fire up the GUI; then we run
// everything that we can in a different thread through backgroundStartup.
// This makes the GUI startup more responsive.
// Baseline C++ things
convert::registerTypesForQVariant();
convert::registerOtherTypesForSignalsSlots();
// Listen for application launch from URL
auto url_handler = UrlHandler::getInstance();
connect(url_handler, &UrlHandler::defaultSingleUserModeSet,
this, &CamcopsApp::setDefaultSingleUserMode);
connect(url_handler, &UrlHandler::defaultServerLocationSet,
this, &CamcopsApp::setDefaultServerLocation);
connect(url_handler, &UrlHandler::defaultAccessKeySet,
this, &CamcopsApp::setDefaultAccessKey);
// Command-line arguments
int retcode = 0;
if (!processCommandLineArguments(retcode)) {
// processCommandLineArguments() may exit directly if there's a syntax
// error, in which case we won't even get here
return retcode; // exit with failure/success
}
// Say hello to the console
announceStartup();
// Set window icon
initGuiOne();
// Connect to our database
registerDatabaseDrivers();
openOrCreateDatabases();
QString new_user_password;
bool user_cancelled_please_quit = false;
const bool changed_user_password = connectDatabaseEncryption(
new_user_password, user_cancelled_please_quit);
if (user_cancelled_please_quit) {
qCritical() << "User cancelled attempt";
return 0; // will quit
}
// Make storedvar table (used by menus for font size etc.)
makeStoredVarTable();
createStoredVars();
// Since that might have changed our language, reset it.
setLanguage(varString(varconst::LANGUAGE));
// Set the tablet internal password to match the database password, if
// we've just changed it. Uses a storedvar.
#ifdef DANGER_DEBUG_WIPE_PASSWORDS
#ifndef SQLCIPHER_ENCRYPTION_ON
// Can't mess around with the user password when it's also the database p/w
qDebug() << "DANGER: wiping user-mode password";
setHashedPassword(varconst::USER_PASSWORD_HASH, "");
#endif
qDebug() << "DANGER: wiping privileged-mode password";
setHashedPassword(varconst::PRIV_PASSWORD_HASH, "");
#endif
#ifdef SQLCIPHER_ENCRYPTION_ON
if (changed_user_password) {
setHashedPassword(varconst::USER_PASSWORD_HASH, new_user_password);
}
#else
Q_UNUSED(changed_user_password)
#endif
// Set the stylesheet.
initGuiTwoStylesheet(); // AFTER storedvar creation
// Do the rest of the database configuration, task registration, etc.,
// with a "please wait" dialog.
{
SlowNonGuiFunctionCaller slow_caller(
std::bind(&CamcopsApp::backgroundStartup, this),
nullptr, // no m_p_main_window yet
tr("Configuring internal database"),
TextConst::pleaseWait());
}
openMainWindow(); // uses HelpMenu etc. and so must be AFTER TASK REGISTRATION
makeNetManager(); // needs to be after main window created, and on GUI thread
if (varInt(varconst::MODE) == varconst::MODE_NOT_SET) {
// e.g. fresh database; which mode to use?
setModeFromUser();
} else {
// We know our mode from last time.
// Ensure all mode-specific things are set:
setModeFromSavedState();
}
return exec(); // Main Qt event loop
}
void CamcopsApp::setDefaultSingleUserMode(const QString& value)
{
// Set from URL or command line so string not boolean
m_default_single_user_mode = (value.toLower() == "true");
}
void CamcopsApp::setDefaultServerLocation(const QString& url)
{
m_default_server_url = QUrl(url);
}
void CamcopsApp::setDefaultAccessKey(const QString& key)
{
m_default_patient_proquint = key;
}
void CamcopsApp::setModeFromSavedState()
{
setMode(varInt(varconst::MODE));
maybeRegisterPatient();
}
void CamcopsApp::maybeRegisterPatient()
{
if (needToRegisterSinglePatient()) {
if (!registerPatientWithServer()) {
// User cancelled patient registration dialog
// They can try again with the "Register me" button
// or switch to clinician mode ("More options")
recreateMainMenu();
}
} else {
if (isSingleUserMode()) {
setDefaultPatient();
}
}
}
void CamcopsApp::backgroundStartup()
{
// WORKER THREAD. BEWARE.
const Version old_version = upgradeDatabaseBeforeTablesMade();
makeOtherTables();
registerTasks(); // AFTER storedvar creation, so tasks can read them
upgradeDatabaseAfterTasksRegistered(old_version); // AFTER tasks registered
makeTaskTables();
// Should we drop tables we're unaware of? Clearly we should never do this
// on the server. Doing so on the client prevents the client trying to
// upload duff tables to the server (giving an error that will confuse the
// user). How could we get superfluous tables? Two situations are: (a)
// users fiddling, and (b) me adding a task, running the client, disabling
// the task... Consider also the situation of a DOWNGRADE in client; should
// we destroy "newer" data we're ignorant of? Probably not.
#ifdef DEBUG_DROP_TABLES_NOT_EXPLICITLY_CREATED
m_datadb->dropTablesNotExplicitlyCreatedByUs();
m_sysdb->dropTablesNotExplicitlyCreatedByUs();
#endif
}
// ============================================================================
// Initialization
// ============================================================================
QString CamcopsApp::defaultDatabaseDir() const
{
return QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).first();
// Under Linux: ~/.local/share/camcops/; the last part of this path is
// determined by the call to QCoreApplication::setApplicationName(), or if
// that hasn't been set, the executable name.
}
bool CamcopsApp::processCommandLineArguments(int& retcode)
{
const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
// https://stackoverflow.com/questions/3886105/how-to-print-to-console-when-using-qt
QTextStream out(stdout);
// QTextStream err(stderr);
// const int retcode_fail = 1;
const int retcode_success = 0;
retcode = retcode_success; // default failure code
// ------------------------------------------------------------------------
// Build parser
// ------------------------------------------------------------------------
QCommandLineParser parser;
// -h, --help
parser.addHelpOption();
// -v, --version
parser.addVersionOption();
// --dbdir <DBDIR>
QString default_database_dir = defaultDatabaseDir();
if (env.contains("GENERATING_CAMCOPS_DOCS")) {
default_database_dir = "/path/to/client/database/dir";