/
log_uploader.cpp
1428 lines (1212 loc) · 40.4 KB
/
log_uploader.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
/*
* log_uploader.cpp
* PHD Guiding
*
* Created by Andy Galasso
* Copyright (c) 2018 Andy Galasso
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of Open PHD Guiding, openphdguiding.org, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "log_uploader.h"
#include "phd.h"
#include <algorithm>
#include <curl/curl.h>
#include <fstream>
#include <sstream>
#include <wx/clipbrd.h>
#include <wx/dir.h>
#include <wx/hyperlink.h>
#include <wx/regex.h>
#include <wx/richtooltip.h>
#include <wx/tokenzr.h>
#include <wx/wfstream.h>
#include <wx/zipstrm.h>
#if LIBCURL_VERSION_MAJOR < 7 || (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR < 32)
# define OLD_CURL
#endif
#ifdef _MSC_VER
# define strncasecmp strnicmp
#endif
struct WindowUpdateLocker
{
wxWindow *m_win;
WindowUpdateLocker(wxWindow *win) : m_win(win) { win->Freeze(); }
~WindowUpdateLocker()
{
m_win->Thaw();
m_win->Refresh();
}
};
enum SummaryState
{
ST_BEGIN,
ST_LOADING,
ST_LOADED,
};
struct Session
{
wxString timestamp;
wxDateTime start;
GuideLogSummaryInfo summary;
SummaryState summary_loaded = ST_BEGIN;
bool has_guide = false;
bool has_debug = false;
};
static std::vector<Session> s_session;
// grid sort order defined by these maps between grid row and session index
static std::vector<int> s_grid_row; // map session index to grid row
static std::vector<int> s_session_idx; // map grid row => session index
enum
{
COL_SELECT,
COL_NIGHTOF,
COL_GUIDE,
COL_CAL,
COL_GA,
NUM_COLUMNS
};
enum
{
// always show some rows, otherwise the grid looks weird surrounded by lots of empty space
// the grid needs at least 2 rows, otherwise the the bool cell editor and/or renderer do not work properly
MIN_ROWS = 16,
};
// state machine to allow scanning logs during idle event processing
//
struct LogScanner
{
wxGrid *m_grid;
std::deque<int> m_q; // indexes remaining to be checked
std::ifstream m_ifs;
wxDateTime m_guiding_starts;
void Init(wxGrid *grid);
void FindNextRow();
bool DoWork(unsigned int millis);
};
void LogScanner::Init(wxGrid *grid)
{
m_grid = grid;
// load work queue in sorted order
for (auto idx : s_session_idx)
{
if (s_session[idx].summary_loaded != ST_LOADED)
m_q.push_back(idx);
}
m_guiding_starts = wxInvalidDateTime;
FindNextRow();
}
static wxString DebugLogName(const Session& session)
{
return "PHD2_DebugLog_" + session.timestamp + ".txt";
}
static wxString GuideLogName(const Session& session)
{
return "PHD2_GuideLog_" + session.timestamp + ".txt";
}
static wxString FormatTimeSpan(const wxTimeSpan& dt)
{
int days = dt.GetDays();
if (days > 1)
return wxString::Format(_("%dd"), days); // 2d or more
int hrs = dt.GetHours();
if (days == 1)
return wxString::Format(_("%dhr"), hrs); // 24-47h
// < 24h
int mins = dt.GetMinutes();
mins -= hrs * 60;
if (hrs > 0)
return wxString::Format(_("%dhr%dmin"), hrs, mins);
// < 1h
if (mins > 0)
return wxString::Format(_("%dmin"), mins);
// < 1min
return wxString::Format(_("%dsec"), dt.GetSeconds());
}
static wxString FormatGuideFor(const Session& session)
{
switch (session.summary_loaded) {
case ST_BEGIN: default:
return wxEmptyString;
case ST_LOADING:
return _("loading...");
case ST_LOADED:
if (session.summary.valid &&
session.summary.guide_cnt > 0)
{
// looks better in the grid with some padding
return " " +
FormatTimeSpan(wxTimeSpan(0 /* hrs */, 0 /* minutes */, session.summary.guide_dur)) +
" ";
}
else
return _("None");
}
}
static void FillActivity(wxGrid *grid, int row, const Session& session, bool resize)
{
grid->SetCellValue(row, COL_GUIDE, FormatGuideFor(session));
if (session.summary.cal_cnt)
grid->SetCellValue(row, COL_CAL, "Y");
if (session.summary.ga_cnt)
grid->SetCellValue(row, COL_GA, "Y");
if (resize)
{
grid->AutoSizeColumn(COL_GUIDE);
grid->AutoSizeColumn(COL_CAL);
grid->AutoSizeColumn(COL_GA);
}
}
void LogScanner::FindNextRow()
{
while (!m_q.empty())
{
auto idx = m_q.front();
Session& session = s_session[idx];
assert(session.has_guide);
assert(session.summary_loaded != ST_LOADED);
int row = s_grid_row[idx];
wxFileName fn(Debug.GetLogDir(), GuideLogName(session));
m_ifs.open(fn.GetFullPath().fn_str());
if (!m_ifs)
{
// should never get here since we have already scanned the list once
session.summary_loaded = ST_LOADED;
FillActivity(m_grid, row, session, true);
m_q.pop_front();
continue;
}
session.summary_loaded = ST_LOADING;
FillActivity(m_grid, row, session, true);
return;
}
}
static std::string GUIDING_BEGINS("Guiding Begins at ");
static std::string GUIDING_ENDS("Guiding Ends at ");
static std::string CALIBRATION_ENDS("Calibration complete");
static std::string GA_COMPLETE("INFO: GA Result - Dec Drift Rate=");
inline static bool StartsWith(const std::string& s, const std::string& pfx)
{
return s.length() >= pfx.length() &&
s.compare(0, pfx.length(), pfx) == 0;
}
bool LogScanner::DoWork(unsigned int millis)
{
int n = 0;
wxStopWatch swatch;
while (!m_q.empty())
{
auto idx = m_q.front();
Session& session = s_session[idx];
std::string line;
while (true)
{
if (++n % 1000 == 0)
{
if (swatch.Time() > millis)
return true;
}
if (!std::getline(m_ifs, line))
break;
if (StartsWith(line, GUIDING_BEGINS))
{
std::string datestr = line.substr(GUIDING_BEGINS.length());
m_guiding_starts.ParseISOCombined(datestr, ' ');
continue;
}
if (StartsWith(line, GUIDING_ENDS) && m_guiding_starts.IsValid())
{
std::string datestr = line.substr(GUIDING_ENDS.length());
wxDateTime end;
end.ParseISOCombined(datestr, ' ');
if (end.IsValid() && end.IsLaterThan(m_guiding_starts))
{
wxTimeSpan dt = end - m_guiding_starts;
++session.summary.guide_cnt;
session.summary.guide_dur += dt.GetSeconds().GetValue();
}
m_guiding_starts = wxInvalidDateTime;
continue;
}
if (StartsWith(line, CALIBRATION_ENDS))
{
++session.summary.cal_cnt;
continue;
}
if (StartsWith(line, GA_COMPLETE))
{
++session.summary.ga_cnt;
continue;
}
}
session.summary.valid = true;
session.summary_loaded = ST_LOADED;
FillActivity(m_grid, s_grid_row[idx], session, true);
m_ifs.close();
m_q.pop_front();
FindNextRow();
}
return false;
}
class LogUploadDialog : public wxDialog
{
public:
int m_step;
int m_nrSelected;
wxStaticText *m_text;
wxHtmlWindow *m_html;
wxGrid *m_grid;
wxHyperlinkCtrl *m_recent;
wxButton *m_back;
wxButton *m_upload;
LogScanner m_scanner;
void OnCellLeftClick(wxGridEvent& event);
void OnColSort(wxGridEvent& event);
void OnRecentClicked(wxHyperlinkEvent& event);
void OnBackClick(wxCommandEvent& event);
void OnUploadClick(wxCommandEvent& event);
void OnLinkClicked(wxHtmlLinkEvent& event);
void OnIdle(wxIdleEvent& event);
void ConfirmUpload();
void ExecUpload();
LogUploadDialog(wxWindow *parent);
~LogUploadDialog();
};
inline static wxDateTime::wxDateTime_t Val(const wxString& s, size_t start, size_t len)
{
unsigned long val = 0;
wxString(s, start, len).ToULong(&val);
return val;
}
static wxDateTime SessionStart(const wxString& timestamp)
{
wxDateTime::wxDateTime_t day = Val(timestamp, 8, 2);
wxDateTime::Month month = static_cast<wxDateTime::Month>(wxDateTime::Jan + Val(timestamp, 5, 2) - 1);
wxDateTime::wxDateTime_t year = Val(timestamp, 0, 4);
wxDateTime::wxDateTime_t hour = Val(timestamp, 11, 2);
wxDateTime::wxDateTime_t minute = Val(timestamp, 13, 2);
wxDateTime::wxDateTime_t second = Val(timestamp, 15, 2);
return wxDateTime(day, month, year, hour, minute, second);
}
static wxString FormatNightOf(const wxDateTime& t)
{
return t.Format(" %A %x "); // looks better in the grid with some padding
}
static wxString FormatTimestamp(const wxDateTime& t)
{
return t.Format("%Y-%m-%d %H:%M:%S");
}
static bool ParseTime(wxDateTime *t, const char *str)
{
int y, mon, d, h, m, s;
if (sscanf(str, "%d-%d-%d %d:%d:%d", &y, &mon, &d, &h, &m, &s) != 6)
return false;
*t = wxDateTime(d, static_cast<wxDateTime::Month>(wxDateTime::Jan + mon - 1), y, h, m, s);
return true;
}
static bool GuideLogEndTimeSlow(std::ifstream& ifs, wxDateTime *dt)
{
bool guiding = false;
wxDateTime start;
bool found = false;
wxDateTime latest;
std::string line;
while (std::getline(ifs, line))
{
if (guiding)
{
if (strncasecmp(line.c_str(), "Guiding Ends at ", 16) == 0)
{
guiding = false;
continue;
}
int n;
double dt;
if (sscanf(line.c_str(), "%d,%lf,", &n, &dt) == 2)
{
latest = start + wxTimeSpan(0, 0, (long) dt);
found = true;
}
}
else
{
if (strncasecmp(line.c_str(), "Guiding Begins at ", 18) == 0 &&
ParseTime(&start, line.c_str() + 18))
{
latest = start;
found = true;
guiding = true;
}
}
}
if (found)
*dt = latest;
return found;
}
static void QuickInitSummary(Session& s)
{
if (!s.has_guide)
{
s.summary_loaded = ST_LOADED;
return;
}
const wxString& logDir = Debug.GetLogDir();
wxFileName fn(logDir, GuideLogName(s));
wxFFile file(fn.GetFullPath());
if (!file.IsOpened())
{
s.summary_loaded = ST_LOADED;
return;
}
s.summary.LoadSummaryInfo(file);
if (s.summary.valid)
s.summary_loaded = ST_LOADED;
}
static void ReallyFlush(const wxFFile& ffile)
{
#ifdef __WINDOWS__
// On Windows the Flush() calls made by GuidingLog and DebugLog are not sufficient
// to get the changes onto the filesystem without some contortions
if (ffile.IsOpened())
FlushFileBuffers((HANDLE) _get_osfhandle(_fileno(ffile.fp())));
#endif
}
static void FlushLogs()
{
ReallyFlush(Debug);
ReallyFlush(GuideLog.File());
}
static int GetSortCol(wxGrid *grid)
{
int col = -1;
for (int i = 0; i < grid->GetNumberCols(); i++)
if (grid->IsSortingBy(i)) {
col = i;
break;
}
return col;
}
struct SessionCompare
{
bool asc;
SessionCompare(bool asc_) : asc(asc_) { }
bool operator()(int a, int b) const {
if (!asc) std::swap(a, b);
return s_session[a].start < s_session[b].start;
}
};
static void DoSort(wxGrid *grid)
{
if (GetSortCol(grid) != COL_NIGHTOF)
return;
size_t const nr_sessions = s_session.size();
// grab the selections
std::vector<bool> selected(nr_sessions);
for (int r = 0; r < nr_sessions; r++)
selected[s_session_idx[r]] = !grid->GetCellValue(r, COL_SELECT).IsEmpty();
// sort row indexes
std::sort(s_session_idx.begin(), s_session_idx.end(), SessionCompare(grid->IsSortOrderAscending()));
// rebuild mapping of indexes to rows
for (int r = 0; r < nr_sessions; r++)
s_grid_row[s_session_idx[r]] = r;
// (re)load the grid
grid->ClearGrid();
for (int r = 0; r < nr_sessions; r++)
{
const Session& session = s_session[s_session_idx[r]];
grid->SetCellValue(r, COL_NIGHTOF, FormatNightOf(wxGetApp().ImagingDay(session.start)));
FillActivity(grid, r, session, false);
if (session.has_guide || session.has_debug)
{
grid->SetCellEditor(r, COL_SELECT, new wxGridCellBoolEditor());
grid->SetCellRenderer(r, COL_SELECT, new wxGridCellBoolRenderer());
grid->SetCellValue(r, COL_SELECT, selected[s_session_idx[r]] ? "1" : "");
grid->SetReadOnly(r, COL_SELECT, false);
}
else
{
grid->SetCellEditor(r, COL_SELECT, grid->GetDefaultEditor());
grid->SetCellRenderer(r, COL_SELECT, grid->GetDefaultRenderer());
grid->SetReadOnly(r, COL_SELECT, true);
}
}
}
static void LoadGrid(wxGrid *grid)
{
wxBusyCursor spin;
FlushLogs();
std::map<wxString, Session> logs;
const wxString& logDir = Debug.GetLogDir();
wxArrayString a;
int nr = wxDir::GetAllFiles(logDir, &a, "*.txt", wxDIR_FILES);
// PHD2_GuideLog_2017-12-09_044510.txt
{
wxRegEx re("PHD2_GuideLog_[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}\\.txt$");
for (int i = 0; i < nr; i++)
{
const wxString& l = a[i];
if (!re.Matches(l))
continue;
// omit zero-size guide logs
wxStructStat st;
int ret = ::wxStat(l, &st);
if (ret != 0)
continue;
if (st.st_size == 0)
continue;
size_t start, len;
re.GetMatch(&start, &len, 0);
wxString timestamp(l, start + 14, 17);
auto it = logs.find(timestamp);
if (it == logs.end())
{
Session s;
s.timestamp = timestamp;
s.start = SessionStart(timestamp);
s.has_guide = true;
logs[timestamp] = s;
}
else
{
it->second.has_guide = true;
}
}
}
// PHD2_DebugLog_2017-12-09_044510.txt
{
wxRegEx re("PHD2_DebugLog_[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}\\.txt$");
for (int i = 0; i < nr; i++)
{
const wxString& l = a[i];
if (!re.Matches(l))
continue;
size_t start, len;
re.GetMatch(&start, &len, 0);
wxString timestamp = l.substr(start + 14, 17);
auto it = logs.find(timestamp);
if (it == logs.end())
{
Session s;
s.timestamp = timestamp;
s.start = SessionStart(timestamp);
s.has_debug = true;
logs[timestamp] = s;
}
else
{
it->second.has_debug = true;
}
}
}
s_session.clear();
s_session_idx.clear();
s_grid_row.clear();
int r = 0;
for (auto it = logs.begin(); it != logs.end(); ++it, ++r)
{
Session& session = it->second;
QuickInitSummary(session);
s_session.push_back(session);
s_session_idx.push_back(r);
s_grid_row.push_back(r);
}
// resize grid to hold all sessions (though it may already be large enough)
if (grid->GetNumberRows() < s_session.size())
grid->AppendRows(s_session.size() - grid->GetNumberRows());
DoSort(grid); // loads grid
}
void LogUploadDialog::OnIdle(wxIdleEvent& event)
{
bool more = m_scanner.DoWork(100);
event.RequestMore(more);
}
struct Uploaded
{
wxString url;
time_t when;
};
static std::deque<Uploaded> s_recent;
static void LoadRecentUploads()
{
s_recent.clear();
// url1 timestamp1 ... urlN timestampN
wxString s = pConfig->Global.GetString("/log_uploader/recent", wxEmptyString);
wxArrayString ary = ::wxStringTokenize(s);
for (size_t i = 0; i + 1 < ary.size(); i += 2)
{
Uploaded t;
t.url = ary[i];
unsigned long val;
if (!ary[i + 1].ToULong(&val))
continue;
t.when = static_cast<time_t>(val);
s_recent.push_back(t);
}
}
static void SaveUploadInfo(const wxString& url, const wxDateTime& time)
{
for (auto it = s_recent.begin(); it != s_recent.end(); ++it)
{
if (it->url == url)
{
s_recent.erase(it);
break;
}
}
enum { MAX_RECENT = 5 };
while (s_recent.size() >= MAX_RECENT)
s_recent.pop_front();
Uploaded t;
t.url = url;
t.when = time.GetTicks();
s_recent.push_back(t);
std::ostringstream os;
for (auto it = s_recent.begin(); it != s_recent.end(); ++it)
{
if (it != s_recent.begin())
os << ' ';
os << it->url << ' ' << it->when;
}
pConfig->Global.SetString("/log_uploader/recent", os.str());
}
#define STEP1_TITLE _("Upload Log Files - Select logs")
#define STEP2_TITLE _("Upload Log Files - Confirm upload")
#define STEP3_TITLE_OK _("Upload Log Files - Upload complete")
#define STEP3_TITLE_FAIL _("Upload Log Files - Upload not completed")
#define STEP1_MESSAGE _( \
"When asking for help in the PHD2 Forum it is important to include your PHD2 logs. This tool will " \
"help you upload your log files so they can be seen in the forum.\n" \
"The first step is to select which files to upload.\n" \
)
LogUploadDialog::LogUploadDialog(wxWindow *parent)
:
wxDialog(parent, wxID_ANY, STEP1_TITLE, wxDefaultPosition, wxSize(580, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER),
m_step(1),
m_nrSelected(0)
{
SetSizeHints(wxDefaultSize, wxDefaultSize);
m_text = new wxStaticText(this, wxID_ANY, STEP1_MESSAGE, wxDefaultPosition, wxDefaultSize, 0);
m_html = new wxHtmlWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHW_SCROLLBAR_AUTO);
m_html->Hide();
m_grid = new wxGrid(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0);
// Grid
m_grid->CreateGrid(MIN_ROWS, NUM_COLUMNS);
m_grid->EnableEditing(false);
m_grid->EnableGridLines(true);
m_grid->EnableDragGridSize(false);
m_grid->SetMargins(0, 0);
m_grid->SetSelectionMode(wxGrid::wxGridSelectRows);
m_grid->SetDefaultCellAlignment(wxALIGN_CENTRE, wxALIGN_BOTTOM); // doesn't work?
// Columns
m_grid->SetColSize(COL_SELECT, 40);
m_grid->SetColSize(COL_NIGHTOF, 200);
m_grid->SetColSize(COL_GUIDE, 85);
m_grid->SetColSize(COL_CAL, 40);
m_grid->SetColSize(COL_GA, 40);
m_grid->EnableDragColMove(false);
m_grid->EnableDragColSize(true);
m_grid->SetColLabelSize(30);
m_grid->SetColLabelValue(COL_SELECT, _("Select"));
m_grid->SetColLabelValue(COL_NIGHTOF, _("Night Of"));
m_grid->SetColLabelValue(COL_GUIDE, _("Guided"));
m_grid->SetColLabelValue(COL_CAL, _("Calibration"));
m_grid->SetColLabelValue(COL_GA, _("Guide Asst."));
m_grid->SetColLabelAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
m_grid->SetSortingColumn(COL_NIGHTOF, false /* descending */);
m_grid->UseNativeColHeader(true);
wxGridCellAttr *attr;
// log selection
attr = new wxGridCellAttr();
attr->SetReadOnly(true);
m_grid->SetColAttr(COL_SELECT, attr);
// Rows
m_grid->EnableDragRowSize(true);
m_grid->SetRowLabelSize(0);
m_grid->SetRowLabelAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
m_recent = new wxHyperlinkCtrl(this, wxID_ANY, _("Recent uploads"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE);
LoadRecentUploads();
if (s_recent.empty())
m_recent->Hide();
m_back = new wxButton(this, wxID_ANY, _("< Back"), wxDefaultPosition, wxDefaultSize, 0);
m_back->Hide();
m_upload = new wxButton(this, wxID_ANY, _("Next >"), wxDefaultPosition, wxDefaultSize, 0);
m_upload->Enable(false);
wxBoxSizer *sizer0 = new wxBoxSizer(wxVERTICAL); // top-level sizer
wxBoxSizer *sizer1 = new wxBoxSizer(wxVERTICAL); // sizer containing the grid
wxBoxSizer *sizer2 = new wxBoxSizer(wxHORIZONTAL); // sizer containing the buttons below the grid
sizer1->Add(m_grid, 0, wxALL | wxEXPAND, 5);
sizer2->Add(m_recent, 0, wxALL, 5);
sizer2->Add(0, 0, 1, wxEXPAND, 5);
sizer2->Add(m_back, 0, wxALL | wxALIGN_CENTER_HORIZONTAL, 5);
sizer2->Add(m_upload, 0, wxALL | wxALIGN_CENTER_HORIZONTAL, 5);
sizer0->Add(m_text, 1, wxALL | wxEXPAND, 5);
sizer0->Add(m_html, 1, wxALL | wxEXPAND, 5);
sizer0->Add(sizer1, 1, wxEXPAND, 5);
sizer0->Add(sizer2, 0, wxEXPAND, 5);
SetSizer(sizer0);
Layout();
Centre(wxBOTH);
// Connect Events
m_recent->Connect(wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler(LogUploadDialog::OnRecentClicked), nullptr, this);
m_back->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(LogUploadDialog::OnBackClick), nullptr, this);
m_upload->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(LogUploadDialog::OnUploadClick), nullptr, this);
m_grid->Connect(wxEVT_GRID_CELL_LEFT_CLICK, wxGridEventHandler(LogUploadDialog::OnCellLeftClick), nullptr, this);
m_grid->Connect(wxEVT_GRID_COL_SORT, wxGridEventHandler(LogUploadDialog::OnColSort), nullptr, this);
m_html->Connect(wxEVT_COMMAND_HTML_LINK_CLICKED, wxHtmlLinkEventHandler(LogUploadDialog::OnLinkClicked), nullptr, this);
Connect(wxEVT_IDLE, wxIdleEventHandler(LogUploadDialog::OnIdle), nullptr, this);
LoadGrid(m_grid);
m_grid->AutoSizeColumns();
m_scanner.Init(m_grid);
}
LogUploadDialog::~LogUploadDialog()
{
// Disconnect Events
m_recent->Disconnect(wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler(LogUploadDialog::OnRecentClicked), nullptr, this);
m_back->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(LogUploadDialog::OnBackClick), nullptr, this);
m_upload->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(LogUploadDialog::OnUploadClick), nullptr, this);
m_grid->Disconnect(wxEVT_GRID_CELL_LEFT_CLICK, wxGridEventHandler(LogUploadDialog::OnCellLeftClick), nullptr, this);
m_grid->Disconnect(wxEVT_GRID_COL_SORT, wxGridEventHandler(LogUploadDialog::OnColSort), nullptr, this);
m_html->Disconnect(wxEVT_COMMAND_HTML_LINK_CLICKED, wxHtmlLinkEventHandler(LogUploadDialog::OnLinkClicked), nullptr, this);
Disconnect(wxEVT_IDLE, wxIdleEventHandler(LogUploadDialog::OnIdle), nullptr, this);
}
static void ToggleCellValue(LogUploadDialog *dlg, int row, int col)
{
wxGrid *grid = dlg->m_grid;
bool const newval = grid->GetCellValue(row, col).IsEmpty();
grid->SetCellValue(row, col, newval ? "1" : "");
if (newval)
{
if (++dlg->m_nrSelected == 1)
dlg->m_upload->Enable(true);
}
else
{
if (--dlg->m_nrSelected == 0)
dlg->m_upload->Enable(false);
}
}
void LogUploadDialog::OnCellLeftClick(wxGridEvent& event)
{
if (event.AltDown() || event.ControlDown() || event.MetaDown() || event.ShiftDown())
{
event.Skip();
return;
}
int r;
if ((r = event.GetRow()) < s_session.size() &&
event.GetCol() == COL_SELECT &&
(s_session[s_session_idx[r]].has_guide ||
s_session[s_session_idx[r]].has_debug))
{
ToggleCellValue(this, r, event.GetCol());
}
event.Skip();
}
void LogUploadDialog::OnColSort(wxGridEvent& event)
{
int col = event.GetCol();
if (col != COL_NIGHTOF)
{
event.Veto();
return;
}
if (m_grid->IsSortingBy(col))
m_grid->SetSortingColumn(col, !m_grid->IsSortOrderAscending()); // toggle asc/desc
else
m_grid->SetSortingColumn(col, true);
m_grid->BeginBatch();
DoSort(m_grid);
m_grid->EndBatch();
event.Skip();
}
struct AutoChdir
{
wxString m_prev;
AutoChdir(const wxString& dir)
{
m_prev = wxFileName::GetCwd();
wxFileName::SetCwd(dir);
}
~AutoChdir()
{
wxFileName::SetCwd(m_prev);
}
};
struct FileData
{
FileData(const wxString& name, const wxDateTime& ts) : filename(name), timestamp(ts) { }
wxString filename;
wxDateTime timestamp;
};
enum UploadErr
{
UPL_OK,
UPL_INTERNAL_ERROR,
UPL_CONNECTION_ERROR,
UPL_COMPRESS_ERROR,
UPL_SIZE_ERROR,
};
struct BgUpload : public RunInBg
{
std::vector<FileData> m_input;
wxFFile m_ff;
CURL *m_curl;
std::ostringstream m_response;
UploadErr m_err;
BgUpload(wxWindow *parent) : RunInBg(parent, _("Upload"), _("Uploading log files ...")), m_curl(nullptr), m_err(UPL_INTERNAL_ERROR) {}
~BgUpload() override;
bool Entry() override;
};
static size_t readfn(char *buffer, size_t size, size_t nitems, void *p)
{
BgUpload *upload = static_cast<BgUpload *>(p);
return upload->IsCanceled() ? CURL_READFUNC_ABORT : upload->m_ff.Read(buffer, size * nitems);
}
static size_t writefn(char *ptr, size_t size, size_t nmemb, void *p)
{
BgUpload *upload = static_cast<BgUpload *>(p);
size_t len = size * nmemb;
upload->m_response.write(ptr, len);
return upload->IsCanceled() ? 0 : len;
}
#if defined(OLD_CURL)
static int progressfn(void *p, double dltotal, double dlnow, double ultotal, double ulnow)
#else
static int progressfn(void *p, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
#endif
{
BgUpload *upload = static_cast<BgUpload *>(p);
if (ultotal)
{
double pct = (double) ulnow / (double) ultotal * 100.0;
upload->SetMessage(wxString::Format(_("Uploading ... %.f%%"), pct));
}
return upload->IsCanceled() ? 1 : 0;
}
BgUpload::~BgUpload()
{
if (m_curl)
curl_easy_cleanup(m_curl);
}
static bool InterruptibleWrite(BgUpload *upload, wxOutputStream& out, wxInputStream& in)
{
while (true)
{
char buf[4096];
size_t sz = in.Read(buf, WXSIZEOF(buf)).LastRead();
if (!sz)
return true;
if (upload->IsCanceled())
return false;
if (out.Write(buf, sz).LastWrite() != sz)
{
Debug.Write("Upload log: error writing to zip file\n");
upload->m_err = UPL_COMPRESS_ERROR;
return false;
}
if (upload->IsCanceled())
return false;
}
}
static bool AddFile(BgUpload *upload, wxZipOutputStream& zip, const wxString& filename, const wxDateTime& dt)
{
wxFFileInputStream is(filename);
if (!is.IsOk())
{
Debug.Write(wxString::Format("Upload log: could not open %s\n", filename));
upload->m_err = UPL_COMPRESS_ERROR;
return false;
}
zip.PutNextEntry(filename, dt);
return InterruptibleWrite(upload, zip, is);
}
static long QueryMaxSize(BgUpload *upload)
{
curl_easy_setopt(upload->m_curl, CURLOPT_URL, "https://openphdguiding.org/logs/upload?limits");
upload->SetMessage(_("Connecting ..."));
int waitSecs[] = { 1, 5, 15, };
for (int tries = 0; ; tries++)
{
CURLcode res = curl_easy_perform(upload->m_curl);