-
Notifications
You must be signed in to change notification settings - Fork 446
/
Pages.cpp
3452 lines (2875 loc) · 123 KB
/
Pages.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 Mark Liversedge (liversedge@gmail.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Athlete.h"
#include <QtGui>
#include <QIntValidator>
#include <assert.h>
#include "Pages.h"
#include "Units.h"
#include "Settings.h"
#include "UserMetricParser.h"
#include "Colors.h"
#include "AddDeviceWizard.h"
#include "AddCloudWizard.h"
#include "DeviceTypes.h"
#include "DeviceConfiguration.h"
#include "ColorButton.h"
#include "SpecialFields.h"
#include "DataProcessor.h"
#include "OAuthDialog.h"
#include "RideAutoImportConfig.h"
#include "HelpWhatsThis.h"
#include "GcUpgrade.h"
#include "Dropbox.h"
#include "GoogleDrive.h"
#include "LocalFileStore.h"
#include "Secrets.h"
#include "Utils.h"
#ifdef GC_WANT_PYTHON
#include "PythonEmbed.h"
#include "FixPySettings.h"
#endif
#ifdef GC_HAS_CLOUD_DB
#include "CloudDBUserMetric.h"
#endif
#include "MainWindow.h"
extern ConfigDialog *configdialog_ptr;
//
// Main Config Page - tabs for each sub-page
//
GeneralPage::GeneralPage(Context *context) : context(context)
{
// layout without too wide margins
QVBoxLayout *mainLayout = new QVBoxLayout(this);
QGridLayout *configLayout = new QGridLayout;
mainLayout->addLayout(configLayout);
mainLayout->addStretch();
setContentsMargins(0,0,0,0);
mainLayout->setSpacing(0);
mainLayout->setContentsMargins(0,0,0,0);
configLayout->setSpacing(10 *dpiXFactor);
//
// Language Selection
//
langLabel = new QLabel(tr("Language"));
langCombo = new QComboBox();
langCombo->addItem(tr("English"));
langCombo->addItem(tr("French"));
langCombo->addItem(tr("Japanese"));
langCombo->addItem(tr("Portugese (Brazil)"));
langCombo->addItem(tr("Italian"));
langCombo->addItem(tr("German"));
langCombo->addItem(tr("Russian"));
langCombo->addItem(tr("Czech"));
langCombo->addItem(tr("Spanish"));
langCombo->addItem(tr("Portugese"));
langCombo->addItem(tr("Chinese (Simplified)"));
langCombo->addItem(tr("Chinese (Traditional)"));
langCombo->addItem(tr("Dutch"));
langCombo->addItem(tr("Swedish"));
// Default to system locale
QVariant lang = appsettings->value(this, GC_LANG, QLocale::system().name());
if(lang.toString().startsWith("en")) langCombo->setCurrentIndex(0);
else if(lang.toString().startsWith("fr")) langCombo->setCurrentIndex(1);
else if(lang.toString().startsWith("ja")) langCombo->setCurrentIndex(2);
else if(lang.toString().startsWith("pt-br")) langCombo->setCurrentIndex(3);
else if(lang.toString().startsWith("it")) langCombo->setCurrentIndex(4);
else if(lang.toString().startsWith("de")) langCombo->setCurrentIndex(5);
else if(lang.toString().startsWith("ru")) langCombo->setCurrentIndex(6);
else if(lang.toString().startsWith("cs")) langCombo->setCurrentIndex(7);
else if(lang.toString().startsWith("es")) langCombo->setCurrentIndex(8);
else if(lang.toString().startsWith("pt")) langCombo->setCurrentIndex(9);
else if(lang.toString().startsWith("zh-cn")) langCombo->setCurrentIndex(10);
else if (lang.toString().startsWith("zh-tw")) langCombo->setCurrentIndex(11);
else if (lang.toString().startsWith("nl")) langCombo->setCurrentIndex(12);
else if (lang.toString().startsWith("sv")) langCombo->setCurrentIndex(13);
else langCombo->setCurrentIndex(0);
configLayout->addWidget(langLabel, 0,0, Qt::AlignRight);
configLayout->addWidget(langCombo, 0,1, Qt::AlignLeft);
//
// Units
//
QLabel *unitlabel = new QLabel(tr("Unit"));
unitCombo = new QComboBox();
unitCombo->addItem(tr("Metric"));
unitCombo->addItem(tr("Imperial"));
if (GlobalContext::context()->useMetricUnits)
unitCombo->setCurrentIndex(0);
else
unitCombo->setCurrentIndex(1);
configLayout->addWidget(unitlabel, 1,0, Qt::AlignRight);
configLayout->addWidget(unitCombo, 1,1, Qt::AlignLeft);
metricRunPace = new QCheckBox(tr("Metric Run Pace"), this);
metricRunPace->setCheckState(appsettings->value(this, GC_PACE, GlobalContext::context()->useMetricUnits).toBool() ? Qt::Checked : Qt::Unchecked);
configLayout->addWidget(metricRunPace, 2,1, Qt::AlignLeft);
metricSwimPace = new QCheckBox(tr("Metric Swim Pace"), this);
metricSwimPace->setCheckState(appsettings->value(this, GC_SWIMPACE, GlobalContext::context()->useMetricUnits).toBool() ? Qt::Checked : Qt::Unchecked);
configLayout->addWidget(metricSwimPace, 3,1, Qt::AlignLeft);
//
// Garmin crap
//
// garmin Smart Recording options
QVariant garminHWMark = appsettings->value(this, GC_GARMIN_HWMARK);
garminSmartRecord = new QCheckBox(tr("Use Garmin Smart Recording"), this);
QVariant isGarminSmartRecording = appsettings->value(this, GC_GARMIN_SMARTRECORD, Qt::Checked);
garminSmartRecord->setCheckState(isGarminSmartRecording.toInt() > 0 ? Qt::Checked : Qt::Unchecked);
// by default, set the threshold to 25 seconds
if (garminHWMark.isNull() || garminHWMark.toInt() == 0) garminHWMark.setValue(25);
QLabel *garminHWLabel = new QLabel(tr("Smart Recording Threshold (secs)"));
garminHWMarkedit = new QLineEdit(garminHWMark.toString(),this);
garminHWMarkedit->setInputMask("009");
configLayout->addWidget(garminSmartRecord, 4,1, Qt::AlignLeft);
configLayout->addWidget(garminHWLabel, 5,0, Qt::AlignRight);
configLayout->addWidget(garminHWMarkedit, 5,1, Qt::AlignLeft);
// Elevation hysterisis GC_ELEVATION_HYSTERISIS
QVariant elevationHysteresis = appsettings->value(this, GC_ELEVATION_HYSTERESIS);
if (elevationHysteresis.isNull() || elevationHysteresis.toFloat() == 0.0)
elevationHysteresis.setValue(3.0); // default is 1 meter
QLabel *hystlabel = new QLabel(tr("Elevation hysteresis (meters)"));
hystedit = new QLineEdit(elevationHysteresis.toString(),this);
hystedit->setInputMask("9.00");
configLayout->addWidget(hystlabel, 6,0, Qt::AlignRight);
configLayout->addWidget(hystedit, 6,1, Qt::AlignLeft);
// wbal formula preference
QLabel *wbalFormLabel = new QLabel(tr("W' bal formula"));
wbalForm = new QComboBox(this);
wbalForm->addItem(tr("Differential"));
wbalForm->addItem(tr("Integral"));
if (appsettings->value(this, GC_WBALFORM, "diff").toString() == "diff") wbalForm->setCurrentIndex(0);
else wbalForm->setCurrentIndex(1);
configLayout->addWidget(wbalFormLabel, 7,0, Qt::AlignRight);
configLayout->addWidget(wbalForm, 7,1, Qt::AlignLeft);
//
// Warn to save on exit
warnOnExit = new QCheckBox(tr("Warn for unsaved activities on exit"), this);
warnOnExit->setChecked(appsettings->value(NULL, GC_WARNEXIT, true).toBool());
configLayout->addWidget(warnOnExit, 8,1, Qt::AlignLeft);
//
// Open last Athlete
openLastAthlete = new QCheckBox(tr("Start with last opened Athlete"), this);
openLastAthlete->setChecked(appsettings->value(NULL, GC_OPENLASTATHLETE, true).toBool());
configLayout->addWidget(openLastAthlete, 9,1, Qt::AlignLeft);
//
// Run API web services when running
//
int offset=1;
#ifdef GC_WANT_HTTP
startHttp = new QCheckBox(tr("Enable API Web Services"), this);
startHttp->setChecked(appsettings->value(NULL, GC_START_HTTP, false).toBool());
configLayout->addWidget(startHttp, 9+offset,1, Qt::AlignLeft);
offset += 1;
#endif
#ifdef GC_WANT_R
embedR = new QCheckBox(tr("Enable R"), this);
embedR->setChecked(appsettings->value(NULL, GC_EMBED_R, true).toBool());
configLayout->addWidget(embedR, 9+offset,1, Qt::AlignLeft);
offset += 1;
connect(embedR, SIGNAL(stateChanged(int)), this, SLOT(embedRchanged(int)));
#endif
#ifdef GC_WANT_PYTHON
embedPython = new QCheckBox(tr("Enable Python"), this);
embedPython->setChecked(appsettings->value(NULL, GC_EMBED_PYTHON, true).toBool());
configLayout->addWidget(embedPython, 9+offset,1, Qt::AlignLeft);
connect(embedPython, SIGNAL(stateChanged(int)), this, SLOT(embedPythonchanged(int)));
offset += 1;
#endif
opendata = new QCheckBox(tr("Share to the OpenData project"), this);
QString grant = appsettings->cvalue(context->athlete->cyclist, GC_OPENDATA_GRANTED, "X").toString();
opendata->setChecked(grant == "Y");
configLayout->addWidget(opendata, 9+offset,1, Qt::AlignLeft);
if (grant == "X") opendata->hide();
offset += 1;
//
// Athlete directory (home of athletes)
//
QVariant athleteDir = appsettings->value(this, GC_HOMEDIR);
athleteLabel = new QLabel(tr("Athlete Library"));
athleteDirectory = new QLineEdit;
athleteDirectory->setText(athleteDir.toString() == "0" ? "" : athleteDir.toString());
athleteWAS = athleteDirectory->text(); // remember what we started with ...
athleteBrowseButton = new QPushButton(tr("Browse"));
//XXathleteBrowseButton->setFixedWidth(120);
configLayout->addWidget(athleteLabel, 9 + offset,0, Qt::AlignRight);
configLayout->addWidget(athleteDirectory, 9 + offset,1);
configLayout->addWidget(athleteBrowseButton, 9 + offset,2);
connect(athleteBrowseButton, SIGNAL(clicked()), this, SLOT(browseAthleteDir()));
#ifdef GC_WANT_R
//
// R Home directory
//
QVariant rDir = appsettings->value(this, GC_R_HOME, "");
// fix old bug..
if (rDir == "0") rDir = "";
rLabel = new QLabel(tr("R Installation Directory"));
rDirectory = new QLineEdit;
rDirectory->setText(rDir.toString());
rBrowseButton = new QPushButton(tr("Browse"));
//XXrBrowseButton->setFixedWidth(120);
configLayout->addWidget(rLabel, 10 + offset,0, Qt::AlignRight);
configLayout->addWidget(rDirectory, 10 + offset,1);
configLayout->addWidget(rBrowseButton, 10 + offset,2);
offset++;
connect(rBrowseButton, SIGNAL(clicked()), this, SLOT(browseRDir()));
#endif
#ifdef GC_WANT_PYTHON
//
// Python Home directory
//
QVariant pythonDir = appsettings->value(this, GC_PYTHON_HOME, "");
// fix old bug..
pythonLabel = new QLabel(tr("Python Home"));
pythonDirectory = new QLineEdit;
pythonDirectory->setText(pythonDir.toString());
pythonBrowseButton = new QPushButton(tr("Browse"));
configLayout->addWidget(pythonLabel, 10 + offset,0, Qt::AlignRight);
configLayout->addWidget(pythonDirectory, 10 + offset,1);
configLayout->addWidget(pythonBrowseButton, 10 + offset,2);
offset++;
bool embedPython = appsettings->value(NULL, GC_EMBED_PYTHON, true).toBool();
embedPythonchanged(embedPython);
connect(pythonBrowseButton, SIGNAL(clicked()), this, SLOT(browsePythonDir()));
#endif
// save away initial values
b4.unit = unitCombo->currentIndex();
b4.metricRunPace = metricRunPace->isChecked();
b4.metricSwimPace = metricSwimPace->isChecked();
b4.hyst = elevationHysteresis.toFloat();
b4.wbal = wbalForm->currentIndex();
#ifdef GC_WANT_HTTP
b4.starthttp = startHttp->isChecked();
#endif
}
#ifdef GC_WANT_R
void
GeneralPage::embedRchanged(int state)
{
rBrowseButton->setVisible(state);
rDirectory->setVisible(state);
rLabel->setVisible(state);
}
#endif
#ifdef GC_WANT_PYTHON
void
GeneralPage::embedPythonchanged(int state)
{
pythonBrowseButton->setVisible(state);
pythonDirectory->setVisible(state);
pythonLabel->setVisible(state);
}
#endif
qint32
GeneralPage::saveClicked()
{
// Language
static const QString langs[] = {
"en", "fr", "ja", "pt-br", "it", "de", "ru", "cs", "es", "pt", "zh-cn", "zh-tw", "nl", "sv"
};
appsettings->setValue(GC_LANG, langs[langCombo->currentIndex()]);
// Garmin and cranks
appsettings->setValue(GC_GARMIN_HWMARK, garminHWMarkedit->text().toInt());
appsettings->setValue(GC_GARMIN_SMARTRECORD, garminSmartRecord->checkState());
// save on exit
appsettings->setValue(GC_WARNEXIT, warnOnExit->isChecked());
// open last athlete on start
appsettings->setValue(GC_OPENLASTATHLETE, openLastAthlete->isChecked());
// Directories
appsettings->setValue(GC_HOMEDIR, athleteDirectory->text());
#ifdef GC_WANT_R
appsettings->setValue(GC_R_HOME, rDirectory->text());
#endif
#ifdef GC_WANT_PYTHON
appsettings->setValue(GC_PYTHON_HOME, pythonDirectory->text());
#endif
// update to reflect the state - if hidden user hasn't been asked yet to
// its neither set or unset !
if (!opendata->isHidden()) appsettings->setCValue(context->athlete->cyclist, GC_OPENDATA_GRANTED, opendata->isChecked() ? "Y" : "N");
// Elevation
appsettings->setValue(GC_ELEVATION_HYSTERESIS, hystedit->text());
// wbal formula
appsettings->setValue(GC_WBALFORM, wbalForm->currentIndex() ? "int" : "diff");
// Units
if (unitCombo->currentIndex()==0)
appsettings->setValue(GC_UNIT, GC_UNIT_METRIC);
else if (unitCombo->currentIndex()==1)
appsettings->setValue(GC_UNIT, GC_UNIT_IMPERIAL);
appsettings->setValue(GC_PACE, metricRunPace->isChecked());
appsettings->setValue(GC_SWIMPACE, metricSwimPace->isChecked());
#ifdef GC_WANT_HTTP
// start http
appsettings->setValue(GC_START_HTTP, startHttp->isChecked());
#endif
#ifdef GC_WANT_R
appsettings->setValue(GC_EMBED_R, embedR->isChecked());
#endif
#ifdef GC_WANT_PYTHON
appsettings->setValue(GC_EMBED_PYTHON, embedPython->isChecked());
if (!embedPython->isChecked()) fixPySettings->disableFixPy();
#endif
qint32 state=0;
// general stuff changed ?
#ifdef GC_WANT_HTTP
if (b4.hyst != hystedit->text().toFloat() ||
b4.starthttp != startHttp->isChecked())
#else
if (b4.hyst != hystedit->text().toFloat())
#endif
state += CONFIG_GENERAL;
if (b4.wbal != wbalForm->currentIndex())
state += CONFIG_WBAL;
// units prefs changed?
if (b4.unit != unitCombo->currentIndex() ||
b4.metricRunPace != metricRunPace->isChecked() ||
b4.metricSwimPace != metricSwimPace->isChecked())
state += CONFIG_UNITS;
return state;
}
#ifdef GC_WANT_R
void
GeneralPage::browseRDir()
{
QString currentDir = rDirectory->text();
if (!QDir(currentDir).exists()) currentDir = "";
QString dir = QFileDialog::getExistingDirectory(this, tr("R Installation (R_HOME)"),
currentDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir != "") rDirectory->setText(dir); //only overwrite current dir, if a new was selected
}
#endif
#ifdef GC_WANT_PYTHON
void
GeneralPage::browsePythonDir()
{
QString currentDir = pythonDirectory->text();
if (!QDir(currentDir).exists()) currentDir = "";
QString dir = QFileDialog::getExistingDirectory(this, tr("Python Installation (PYTHONHOME)"),
currentDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir != "") {
QString pybin, pypath;
// is it installed there?
bool isgood = PythonEmbed::pythonInstalled(pybin, pypath, dir);
if (!isgood) {
QMessageBox nope(QMessageBox::Warning, tr("Invalid Folder"), tr("Python does not appear to be installed in that location.\n"));
nope.exec();
} else {
pythonDirectory->setText(dir); //only overwrite current dir, if a new was selected
}
}
}
#endif
void
GeneralPage::browseAthleteDir()
{
QString currentDir = athleteDirectory->text();
if (!QDir(currentDir).exists()) currentDir = "";
QString dir = QFileDialog::getExistingDirectory(this, tr("Select Athlete Library"),
currentDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir != "") athleteDirectory->setText(dir); //only overwrite current dir, if a new was selected
}
//
// Realtime devices page
//
DevicePage::DevicePage(QWidget *parent, Context *context) : QWidget(parent), context(context)
{
HelpWhatsThis *help = new HelpWhatsThis(this);
this->setWhatsThis(help->getWhatsThisText(HelpWhatsThis::Preferences_Training_TrainDevices));
QVBoxLayout *mainLayout = new QVBoxLayout(this);
DeviceTypes all;
devices = all.getList();
addButton = new QPushButton(tr("+"),this);
delButton = new QPushButton(tr("-"),this);
deviceList = new QTableView(this);
#ifdef Q_OS_MAC
addButton->setText(tr("Add"));
delButton->setText(tr("Delete"));
deviceList->setAttribute(Qt::WA_MacShowFocusRect, 0);
#else
addButton->setFixedSize(20*dpiXFactor,20*dpiYFactor);
delButton->setFixedSize(20*dpiXFactor,20*dpiYFactor);
#endif
deviceListModel = new deviceModel(this);
// replace standard model with ours
QItemSelectionModel *stdmodel = deviceList->selectionModel();
deviceList->setModel(deviceListModel);
delete stdmodel;
deviceList->setSortingEnabled(false);
deviceList->setSelectionBehavior(QAbstractItemView::SelectRows);
deviceList->horizontalHeader()->setStretchLastSection(true);
deviceList->verticalHeader()->hide();
deviceList->setEditTriggers(QAbstractItemView::NoEditTriggers);
deviceList->setSelectionMode(QAbstractItemView::SingleSelection);
mainLayout->addWidget(deviceList);
QHBoxLayout *bottom = new QHBoxLayout;
bottom->setSpacing(2 *dpiXFactor);
bottom->addStretch();
bottom->addWidget(addButton);
bottom->addWidget(delButton);
mainLayout->addLayout(bottom);
connect(addButton, SIGNAL(clicked()), this, SLOT(devaddClicked()));
connect(delButton, SIGNAL(clicked()), this, SLOT(devdelClicked()));
connect(context, SIGNAL(configChanged(qint32)), deviceListModel, SLOT(doReset()));
}
qint32
DevicePage::saveClicked()
{
// Save the device configuration...
DeviceConfigurations all;
all.writeConfig(deviceListModel->Configuration);
return 0;
}
void
DevicePage::devaddClicked()
{
DeviceConfiguration add;
AddDeviceWizard *p = new AddDeviceWizard(context);
p->show();
}
void
DevicePage::devdelClicked()
{
deviceListModel->del();
}
// add a new configuration
void
deviceModel::add(DeviceConfiguration &newone)
{
insertRows(0,1, QModelIndex());
// insert name
QModelIndex index = deviceModel::index(0,0, QModelIndex());
setData(index, newone.name, Qt::EditRole);
// insert type
index = deviceModel::index(0,1, QModelIndex());
setData(index, newone.type, Qt::EditRole);
// insert portSpec
index = deviceModel::index(0,2, QModelIndex());
setData(index, newone.portSpec, Qt::EditRole);
// insert Profile
index = deviceModel::index(0,3, QModelIndex());
setData(index, newone.deviceProfile, Qt::EditRole);
// insert virtualPowerIndex
index = deviceModel::index(0,4, QModelIndex());
setData(index, newone.postProcess, Qt::EditRole);
}
// delete an existing configuration
void
deviceModel::del()
{
// which row is selected in the table?
DevicePage *temp = static_cast<DevicePage*>(parent);
QItemSelectionModel *selectionModel = temp->deviceList->selectionModel();
QModelIndexList indexes = selectionModel->selectedRows();
QModelIndex index;
foreach (index, indexes) {
//int row = this->mapToSource(index).row();
removeRows(index.row(), 1, QModelIndex());
}
}
deviceModel::deviceModel(QObject *parent) : QAbstractTableModel(parent)
{
this->parent = parent;
// get current configuration
DeviceConfigurations all;
Configuration = all.getList();
}
void
deviceModel::doReset()
{
beginResetModel();
DeviceConfigurations all;
Configuration = all.getList();
endResetModel();
}
int
deviceModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return Configuration.size();
}
int
deviceModel::columnCount(const QModelIndex &) const
{
return 5;
}
// setup the headings!
QVariant deviceModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole) return QVariant(); // no display, no game!
if (orientation == Qt::Horizontal) {
switch (section) {
case 0:
return tr("Device Name");
case 1:
return tr("Device Type");
case 2:
return tr("Port Spec");
case 3:
return tr("Profile");
case 4:
return tr("Virtual");
default:
return QVariant();
}
}
return QVariant();
}
// return data item for row/col specified in index
QVariant deviceModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) return QVariant();
if (index.row() >= Configuration.size() || index.row() < 0) return QVariant();
if (role == Qt::DisplayRole) {
DeviceConfiguration Entry = Configuration.at(index.row());
switch(index.column()) {
case 0 : return Entry.name;
break;
case 1 :
{
DeviceTypes all;
DeviceType lookupType = all.getType (Entry.type);
return lookupType.name;
}
break;
case 2 :
return Entry.portSpec;
break;
case 3 :
return Entry.deviceProfile;
case 4 :
return Entry.postProcess;
}
}
// how did we get here!?
return QVariant();
}
// update the model with new data
bool deviceModel::insertRows(int position, int rows, const QModelIndex &index)
{
Q_UNUSED(index);
beginInsertRows(QModelIndex(), position, position+rows-1);
for (int row=0; row < rows; row++) {
DeviceConfiguration emptyEntry;
Configuration.insert(position, emptyEntry);
}
endInsertRows();
return true;
}
// delete a row!
bool deviceModel::removeRows(int position, int rows, const QModelIndex &index)
{
Q_UNUSED(index);
beginRemoveRows(QModelIndex(), position, position+rows-1);
for (int row=0; row < rows; ++row) {
Configuration.removeAt(position);
}
endRemoveRows();
return true;
}
bool deviceModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid() && role == Qt::EditRole) {
int row = index.row();
DeviceConfiguration p = Configuration.value(row);
switch (index.column()) {
case 0 : //name
p.name = value.toString();
break;
case 1 : //type
p.type = value.toInt();
break;
case 2 : // spec
p.portSpec = value.toString();
break;
case 3 : // Profile
p.deviceProfile = value.toString();
break;
case 4 : // Profile
p.postProcess = value.toInt();
break;
}
Configuration.replace(row,p);
emit(dataChanged(index, index));
return true;
}
return false;
}
//
// Train view options page
//
TrainOptionsPage::TrainOptionsPage(QWidget *parent, Context *context) : QWidget(parent), context(context)
{
HelpWhatsThis *help = new HelpWhatsThis(this);
this->setWhatsThis(help->getWhatsThisText(HelpWhatsThis::Preferences_Training_Preferences));
//
// Workout directory (train view)
//
QVariant workoutDir = appsettings->value(this, GC_WORKOUTDIR, "");
// fix old bug..
if (workoutDir == "0") workoutDir = "";
workoutLabel = new QLabel(tr("Workout and VideoSync Library"));
workoutDirectory = new QLineEdit;
workoutDirectory->setText(workoutDir.toString());
workoutBrowseButton = new QPushButton(tr("Browse"));
connect(workoutBrowseButton, SIGNAL(clicked()), this, SLOT(browseWorkoutDir()));
useSimulatedSpeed = new QCheckBox(tr("Simulate Speed From Power"), this);
useSimulatedSpeed->setChecked(appsettings->value(this, TRAIN_USESIMULATEDSPEED, true).toBool());
useSimulatedSpeed->setToolTip(tr("Simulation physics uses current athlete parameters and settings\n"
"from the virtual bicycle specifications tab. For Erg Mode workouts\n"
"the slope is assumed to be zero."));
useSimulatedHypoxia = new QCheckBox(tr("Simulate Relative Hypoxia"), this);
useSimulatedHypoxia->setChecked(appsettings->value(this, TRAIN_USESIMULATEDHYPOXIA, false).toBool());
useSimulatedHypoxia->setToolTip(tr("Power used by simulation is adjusted for hypoxia relative to\n"
"ActualTrainingAltitude value in virtual bicycle specifications\n"
"tab."));
autoConnect = new QCheckBox(tr("Auto-connect devices in Train View"), this);
autoConnect->setChecked(appsettings->value(this, TRAIN_AUTOCONNECT, false).toBool());
multiCheck = new QCheckBox(tr("Allow multiple devices in Train View"), this);
multiCheck->setChecked(appsettings->value(this, TRAIN_MULTI, false).toBool());
autoHide = new QCheckBox(tr("Auto-hide bottom bar in Train View"), this);
autoHide->setChecked(appsettings->value(this, TRAIN_AUTOHIDE, false).toBool());
lapAlert = new QCheckBox(tr("Play sound before new lap"), this);
lapAlert->setChecked(appsettings->value(this, TRAIN_LAPALERT, false).toBool());
delayLabel = new QLabel(tr("Start Countdown"));
startDelay = new QSpinBox(this);
startDelay->setMaximum(600);
startDelay->setMinimum(0);
startDelay->setSuffix(tr(" secs"));
startDelay->setValue(appsettings->value(this, TRAIN_STARTDELAY, 0).toUInt());
startDelay->setToolTip(tr("Countdown for workout start"));
QVBoxLayout *all = new QVBoxLayout(this);
QGridLayout *wdLayout = new QGridLayout;
wdLayout->addWidget(workoutLabel, 0,0, Qt::AlignRight);
wdLayout->addWidget(workoutDirectory, 0,1);
wdLayout->addWidget(workoutBrowseButton, 0,2);
all->addLayout(wdLayout);
all->addWidget(useSimulatedSpeed);
all->addWidget(useSimulatedHypoxia);
all->addWidget(multiCheck);
all->addWidget(autoConnect);
all->addWidget(autoHide);
all->addWidget(lapAlert);
QHBoxLayout *delayLayout = new QHBoxLayout;
delayLayout->addWidget(delayLabel);
delayLayout->addWidget(startDelay);
delayLayout->addStretch();
all->addLayout(delayLayout);
all->addStretch();
}
qint32
TrainOptionsPage::saveClicked()
{
// Save the train view settings...
appsettings->setValue(GC_WORKOUTDIR, workoutDirectory->text());
appsettings->setValue(TRAIN_USESIMULATEDSPEED, useSimulatedSpeed->isChecked());
appsettings->setValue(TRAIN_USESIMULATEDHYPOXIA, useSimulatedHypoxia->isChecked());
appsettings->setValue(TRAIN_MULTI, multiCheck->isChecked());
appsettings->setValue(TRAIN_AUTOCONNECT, autoConnect->isChecked());
appsettings->setValue(TRAIN_STARTDELAY, startDelay->value());
appsettings->setValue(TRAIN_AUTOHIDE, autoHide->isChecked());
appsettings->setValue(TRAIN_LAPALERT, lapAlert->isChecked());
return 0;
}
void
TrainOptionsPage::browseWorkoutDir()
{
QString currentDir = workoutDirectory->text();
if (!QDir(currentDir).exists()) currentDir = "";
QString dir = QFileDialog::getExistingDirectory(this, tr("Select Workout Library"),
currentDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir != "") workoutDirectory->setText(dir); //only overwrite current dir, if a new was selected
}
//
// Remote control page
//
RemotePage::RemotePage(QWidget *parent, Context *context) : QWidget(parent), context(context)
{
HelpWhatsThis *help = new HelpWhatsThis(this);
this->setWhatsThis(help->getWhatsThisText(HelpWhatsThis::Preferences_Training_RemoteControls));
remote = new RemoteControl;
QVBoxLayout *mainLayout = new QVBoxLayout(this);
fields = new QTreeWidget;
fields->headerItem()->setText(0, tr("Action"));
fields->headerItem()->setText(1, tr("ANT+ Command"));
fields->setColumnWidth(0,100 *dpiXFactor);
fields->setColumnWidth(1,200 *dpiXFactor);
fields->setColumnCount(2);
fields->setSelectionMode(QAbstractItemView::SingleSelection);
fields->setIndentation(0);
fields->setCurrentItem(fields->invisibleRootItem()->child(0));
mainLayout->addWidget(fields, 0,0);
// Load the native command list
QList <RemoteCmd> nativeCmds = remote->getNativeCmds();
// Load the ant command list
QList<RemoteCmd> antCmds = remote->getAntCmds();
// Load the remote control mappings
QList<CmdMap> cmdMaps = remote->getMappings();
// create a row for each native command
int index = 0;
foreach (RemoteCmd nativeCmd, nativeCmds) {
QComboBox *comboBox = new QComboBox(this);
comboBox->addItem(tr("<unset>"));
// populate the combo box with all possible ANT commands
foreach(RemoteCmd antCmd, antCmds) {
comboBox->addItem(antCmd.getCmdStr());
}
// is this native command mapped to an ANT command?
foreach(CmdMap cmdMapping, cmdMaps) {
if (cmdMapping.getNativeCmdId() == nativeCmd.getCmdId()) {
if (cmdMapping.getAntCmdId() != 0xFFFF) {
//qDebug() << "ANT remote mapping found:" << cmdMapping.getNativeCmdId() << cmdMapping.getAntCmdId();
int i=0;
foreach(RemoteCmd antCmd, antCmds) {
i++; // increment first to skip <unset>
if (cmdMapping.getAntCmdId() == antCmd.getCmdId()) {
// set the default entry for the combo box
comboBox->setCurrentIndex(i);
}
}
}
}
}
QTreeWidgetItem *add = new QTreeWidgetItem;
fields->invisibleRootItem()->insertChild(index, add);
add->setFlags(add->flags() | Qt::ItemIsEditable);
add->setTextAlignment(0, Qt::AlignLeft | Qt::AlignVCenter);
add->setText(0, nativeCmd.getDisplayStr());
add->setTextAlignment(1, Qt::AlignHCenter | Qt::AlignVCenter);
fields->setItemWidget(add, 1, comboBox);
index++;
}
}
qint32
RemotePage::saveClicked()
{
// Save the remote control code mappings...
//qDebug() << "RemotePage::saveClicked()";
// Load the ant command list
QList<RemoteCmd> antCmds = remote->getAntCmds();
// Load the remote control mappings
QList<CmdMap> cmdMaps = remote->getMappings();
for(int i=0; i < cmdMaps.size(); i++) {
QWidget *button = fields->itemWidget(fields->invisibleRootItem()->child(i),1);
int index = ((QComboBox*)button)->currentIndex();
if (index) {
cmdMaps[i].setAntCmdId(antCmds[index-1].getCmdId());
} else {
cmdMaps[i].setAntCmdId(0xFFFF); // no command
}
}
remote->writeConfig(cmdMaps);
return 0;
}
const SimBicyclePartEntry& SimBicyclePage::GetSimBicyclePartEntry(int e)
{
// Bike mass values approximate a good current bike. Wheels are shimano c40 with conti tubeless tires.
static const SimBicyclePartEntry arr[] = {
// SpinBox Title Path to athlete value Default Value Decimal Tooltip enum
{ tr("Bicycle Mass Without Wheels (g)" ) , GC_SIM_BICYCLE_MASSWITHOUTWHEELSG, 4000, 0, tr("Mass of everything that isn't wheels, tires, skewers...")}, // BicycleWithoutWheelsG
{ tr("Front Wheel Mass (g)" ) , GC_SIM_BICYCLE_FRONTWHEELG, 739, 0, tr("Mass of front wheel excluding tires and skewers...")}, // FrontWheelG
{ tr("Front Spoke Count" ) , GC_SIM_BICYCLE_FRONTSPOKECOUNT, 24, 0, tr("")}, // FrontSpokeCount
{ tr("Front Spoke & Nipple Mass - Each (g)") , GC_SIM_BICYCLE_FRONTSPOKENIPPLEG, 5.6, 1, tr("Mass of a single spoke and nipple, washers, etc.")}, // FrontSpokeNippleG
{ tr("Front Rim Mass (g)" ) , GC_SIM_BICYCLE_FRONTRIMG, 330, 0, tr("")}, // FrontRimG
{ tr("Front Rotor Mass (g)" ) , GC_SIM_BICYCLE_FRONTROTORG, 120, 0, tr("Mass of rotor including bolts")}, // FrontRotorG
{ tr("Front Skewer Mass (g)" ) , GC_SIM_BICYCLE_FRONTSKEWERG, 40, 0, tr("")}, // FrontSkewerG
{ tr("Front Tire Mass (g)" ) , GC_SIM_BICYCLE_FRONTTIREG, 220, 0, tr("")}, // FrontTireG
{ tr("Front Tube or Sealant Mass (g)" ) , GC_SIM_BICYCLE_FRONTTUBESEALANTG, 26, 0, tr("Mass of anything inside the tire: sealant, tube...")}, // FrontTubeSealantG
{ tr("Front Rim Outer Radius (m)" ) , GC_SIM_BICYCLE_FRONTOUTERRADIUSM, .35, 3, tr("Functional outer radius of wheel, used for computing wheel circumference")}, // FrontOuterRadiusM
{ tr("Front Rim Inner Radius (m)" ) , GC_SIM_BICYCLE_FRONTRIMINNERRADIUSM, .3, 3, tr("Inner radius of rim, for computing wheel inertia")}, // FrontRimInnerRadiusM
{ tr("Rear Wheel Mass (g)" ) , GC_SIM_BICYCLE_REARWHEELG, 739, 0, tr("Mass of rear wheel excluding tires and skewers...")}, // RearWheelG
{ tr("Rear Spoke Count" ) , GC_SIM_BICYCLE_REARSPOKECOUNT, 24, 0, tr("")}, // RearSpokeCount
{ tr("Rear Spoke & Nipple Mass - Each (g)" ) , GC_SIM_BICYCLE_REARSPOKENIPPLEG, 5.6, 1, tr("Mass of a single spoke and nipple, washers, etc.")}, // RearSpokeNippleG
{ tr("Rear Rim Mass (g)" ) , GC_SIM_BICYCLE_REARRIMG, 330, 0, tr("")}, // RearRimG
{ tr("Rear Rotor Mass (g)" ) , GC_SIM_BICYCLE_REARROTORG, 120, 0, tr("Mass of rotor including bolts")}, // RearRotorG
{ tr("Rear Skewer Mass (g)" ) , GC_SIM_BICYCLE_REARSKEWERG, 40, 0, tr("Mass of skewer/axle/funbolts, etc...")}, // RearSkewerG
{ tr("Rear Tire Mass (g)" ) , GC_SIM_BICYCLE_REARTIREG, 220, 0, tr("Mass of tire not including tube or sealant")}, // RearTireG
{ tr("Rear Tube or Sealant Mass (g)" ) , GC_SIM_BICYCLE_REARTUBESEALANTG, 26, 0, tr("Mass of anything inside the tire: sealant, tube...")}, // RearTubeSealantG
{ tr("Rear Rim Outer Radius (m)" ) , GC_SIM_BICYCLE_REAROUTERRADIUSM, .35, 3, tr("Functional outer radius of wheel, used for computing wheel circumference")}, // RearOuterRadiusM
{ tr("Rear Rim Inner Radius (m)" ) , GC_SIM_BICYCLE_REARRIMINNERRADIUSM, .3, 3, tr("Inner radius of rim, for computing wheel inertia")}, // RearRimInnerRadiusM
{ tr("Rear Cassette Mass(g)" ) , GC_SIM_BICYCLE_CASSETTEG, 190, 0, tr("Mass of rear cassette, including lockring")}, // CassetteG
{ tr("Coefficient of rolling resistance" ) , GC_SIM_BICYCLE_CRR, 0.004, 4, tr("Total coefficient of rolling resistance for bicycle")}, // CRR
{ tr("Coefficient of power train loss" ) , GC_SIM_BICYCLE_Cm, 1.0, 3, tr("Power train loss between reported watts and wheel. For direct drive trainer like kickr there is no relevant loss and value shold be 1.0.")}, // Cm
{ tr("Coefficient of drag" ) , GC_SIM_BICYCLE_Cd, (1.0 - 0.0045), 5, tr("Coefficient of drag of rider and bicycle")}, // Cd
{ tr("Frontal Area (m^2)" ) , GC_SIM_BICYCLE_Am2, 0.5, 2, tr("Effective frontal area of rider and bicycle")}, // Am2
{ tr("Temperature (K)" ) , GC_SIM_BICYCLE_Tk, 293.15, 2, tr("Temperature in kelvin, used with altitude to compute air density")}, // Tk
{ tr("ActualTrainerAltitude (m)" ) , GC_SIM_BICYCLE_ACTUALTRAINERALTITUDEM, 0., 0, tr("Actual altitude of indoor trainer, in meters")} // ActualTrainerAltitudeM
};
if (e < 0 || e >= LastPart) e = 0;
return arr[e];
}
double
SimBicyclePage::GetBicyclePartValue(Context* context, int e)
{
const SimBicyclePartEntry &r = GetSimBicyclePartEntry(e);
if (!context) return r.m_defaultValue;
return appsettings->cvalue(
context->athlete->cyclist,
r.m_path,
r.m_defaultValue).toDouble();
}
void
SimBicyclePage::AddSpecBox(int ePart)
{
const SimBicyclePartEntry & entry = GetSimBicyclePartEntry(ePart);
m_LabelArr[ePart] = new QLabel(entry.m_label);
QDoubleSpinBox * pSpinBox = new QDoubleSpinBox(this);
pSpinBox->setMaximum(99999);
pSpinBox->setMinimum(0.0);
pSpinBox->setDecimals(entry.m_decimalPlaces);
pSpinBox->setValue(GetBicyclePartValue(context, ePart));
pSpinBox->setToolTip(entry.m_tooltip);
double singlestep = 1.;
for (int i = 0; i < entry.m_decimalPlaces; i++)
singlestep /= 10.;
pSpinBox->setSingleStep(singlestep);
m_SpinBoxArr[ePart] = pSpinBox;
}