-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcsv_dialog.cpp
More file actions
544 lines (498 loc) · 15.9 KB
/
Copy pathcsv_dialog.cpp
File metadata and controls
544 lines (498 loc) · 15.9 KB
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
#include "csv_dialog.hpp"
// Generated at configure time
#include <algorithm>
#include <fstream>
#include <limits>
#include <nlohmann/json.hpp>
#include <set>
#include <string>
#include <vector>
#include "csv_manifest.hpp"
#include "dataload_csv_ui.hpp"
#include "datetimehelp_ui.hpp"
int CsvDialog::timeColumnIndex() const {
if (time_mode_ == TimeMode::Column && selected_column_index_ >= 0) {
return selected_column_index_;
}
return -1;
}
int CsvDialog::combinedColumnIndex() const {
if (time_mode_ == TimeMode::Combined) {
return combined_index_;
}
return -1;
}
void CsvDialog::setFilePath(const std::string& filepath) {
filepath_ = filepath;
analyzeFile();
}
std::string CsvDialog::manifest() const {
return kCsvManifest;
}
std::string CsvDialog::ui_content() const {
return kDataLoadCsvUi;
}
std::string CsvDialog::widget_data() {
PJ::WidgetData wd;
// Delimiter
std::vector<std::string> delimiters = {"\",\" (comma)", "\";\" (semicolon)", "\" \" (space)", "\"\\t\" (tab)"};
wd.setItems("comboBox", delimiters);
wd.setCurrentIndex("comboBox", delimiterToIndex(delimiter_));
// Time axis radios
wd.setChecked("radioButtonIndex", time_mode_ == TimeMode::RowNumber);
wd.setChecked("radioButtonSelect", time_mode_ == TimeMode::Column);
wd.setChecked("radioButtonDateTimeColumns", time_mode_ == TimeMode::Combined);
// Column list
wd.setListItems("listWidgetSeries", column_names_);
wd.setEnabled("listWidgetSeries", time_mode_ == TimeMode::Column);
if (time_mode_ == TimeMode::Column && selected_column_index_ >= 0 &&
selected_column_index_ < static_cast<int>(column_names_.size())) {
wd.setSelectedItems("listWidgetSeries", {column_names_[static_cast<size_t>(selected_column_index_)]});
}
// Combined pairs
std::vector<std::string> combo_items;
for (const auto& p : combined_pairs_) {
combo_items.push_back(p.virtual_name);
}
wd.setItems("combinedCombo", combo_items);
if (combined_index_ >= 0) {
wd.setCurrentIndex("combinedCombo", combined_index_);
}
wd.setEnabled("radioButtonDateTimeColumns", !combined_pairs_.empty());
wd.setEnabled("combinedCombo", time_mode_ == TimeMode::Combined && !combined_pairs_.empty());
wd.setVisible("combinedCombo", !combined_pairs_.empty());
// Timestamp format
wd.setChecked("radioAutoTime", !use_custom_format_);
wd.setChecked("radioCustomTime", use_custom_format_);
wd.setText("lineEditDateFormat", custom_format_);
wd.setEnabled("lineEditDateFormat", use_custom_format_);
wd.setEnabled("checkBoxAutoCloseHelp", use_custom_format_);
wd.setChecked("checkBoxAutoCloseHelp", close_after_help_);
// Format live preview
if (use_custom_format_ && !custom_format_.empty()) {
wd.setText("labelFormatPreview", "Example (2024-01-15 14:30:45): " + computeFormatPreview(custom_format_));
} else {
wd.setText("labelFormatPreview", "");
}
// Preview table
wd.setTableHeaders("tableView", column_names_);
wd.setTableRows("tableView", preview_rows_);
// Preview warning (shared label — text set by analyzeFile)
wd.setVisible("labelWarning", !warning_message_.empty());
if (!warning_message_.empty()) {
wd.setText("labelWarning", warning_message_);
}
// OK enabled?
bool ok = (time_mode_ == TimeMode::RowNumber) || (time_mode_ == TimeMode::Column && selected_column_index_ >= 0) ||
(time_mode_ == TimeMode::Combined && combined_index_ >= 0);
wd.setOkEnabled("buttonBox", ok);
if (accept_requested_) {
accept_requested_ = false;
wd.requestAccept();
}
if (show_help_requested_) {
show_help_requested_ = false;
help_was_shown_ = true;
wd.requestSubDialog(kDateTimeHelpUi);
}
return wd.toJson();
}
bool CsvDialog::onIndexChanged(std::string_view widget_name, int index) {
if (widget_name == "comboBox") {
delimiter_ = indexToDelimiter(index);
analyzeFile();
return true;
}
if (widget_name == "combinedCombo") {
combined_index_ = index;
return true;
}
return false;
}
bool CsvDialog::onToggled(std::string_view widget_name, bool checked) {
if (!checked) {
return false;
}
if (widget_name == "radioButtonIndex") {
time_mode_ = TimeMode::RowNumber;
return true;
}
if (widget_name == "radioButtonSelect") {
time_mode_ = TimeMode::Column;
return true;
}
if (widget_name == "radioButtonDateTimeColumns") {
time_mode_ = TimeMode::Combined;
return true;
}
if (widget_name == "radioAutoTime") {
use_custom_format_ = false;
return true;
}
if (widget_name == "radioCustomTime") {
use_custom_format_ = true;
return true;
}
if (widget_name == "checkBoxAutoCloseHelp") {
close_after_help_ = checked;
return true;
}
return false;
}
bool CsvDialog::onSelectionChanged(std::string_view widget_name, const std::vector<std::string>& selected) {
if (widget_name == "listWidgetSeries" && !selected.empty()) {
for (int i = 0; i < static_cast<int>(column_names_.size()); i++) {
if (column_names_[static_cast<size_t>(i)] == selected[0]) {
selected_column_index_ = i;
analyzeFile();
return true;
}
}
}
return false;
}
bool CsvDialog::onItemDoubleClicked(std::string_view widget_name, int index) {
if (widget_name == "listWidgetSeries" && time_mode_ == TimeMode::Column && index >= 0 &&
index < static_cast<int>(column_names_.size())) {
selected_column_index_ = index;
accept_requested_ = true;
return true;
}
return false;
}
bool CsvDialog::onClicked(std::string_view widget_name) {
if (widget_name == "dateTimeHelpButton") {
show_help_requested_ = true;
return true;
}
return false;
}
bool CsvDialog::onTick() {
if (help_was_shown_ && close_after_help_) {
help_was_shown_ = false;
accept_requested_ = true;
return true;
}
return false;
}
bool CsvDialog::onTextChanged(std::string_view widget_name, std::string_view text) {
if (widget_name == "lineEditDateFormat") {
custom_format_ = std::string(text);
return true;
}
return false;
}
void CsvDialog::onAccepted(std::string_view /*json*/) {
if (time_mode_ == TimeMode::Column && selected_column_index_ >= 0 &&
selected_column_index_ < static_cast<int>(column_names_.size())) {
auto& name = column_names_[static_cast<size_t>(selected_column_index_)];
column_history_.erase(std::remove(column_history_.begin(), column_history_.end(), name), column_history_.end());
column_history_.insert(column_history_.begin(), name);
if (column_history_.size() > 10) {
column_history_.resize(10);
}
}
}
std::string CsvDialog::saveConfig() const {
nlohmann::json cfg;
cfg["filepath"] = filepath_;
cfg["delimiter"] = std::string(1, delimiter_);
cfg["time_mode"] = timeModeToString(time_mode_);
cfg["time_column_index"] = selected_column_index_;
cfg["combined_column_index"] = combined_index_;
cfg["custom_time_format"] = custom_format_;
cfg["use_custom_format"] = use_custom_format_;
cfg["close_after_help"] = close_after_help_;
cfg["column_history"] = column_history_;
return cfg.dump();
}
bool CsvDialog::loadConfig(std::string_view config_json) {
auto cfg = nlohmann::json::parse(config_json, nullptr, false);
if (cfg.is_discarded()) {
return false;
}
filepath_ = cfg.value("filepath", std::string{});
auto d = cfg.value("delimiter", std::string(","));
delimiter_ = d.empty() ? ',' : d[0];
time_mode_ = stringToTimeMode(cfg.value("time_mode", std::string("row_number")));
selected_column_index_ = cfg.value("time_column_index", -1);
combined_index_ = cfg.value("combined_column_index", -1);
custom_format_ = cfg.value("custom_time_format", std::string{});
use_custom_format_ = cfg.value("use_custom_format", false);
close_after_help_ = cfg.value("close_after_help", false);
if (cfg.contains("column_history") && cfg["column_history"].is_array()) {
column_history_ = cfg["column_history"].get<std::vector<std::string>>();
}
// Validate: a mode that requires a selection is useless without one — fall back to row_number
if (time_mode_ == TimeMode::Column && selected_column_index_ < 0) {
time_mode_ = TimeMode::RowNumber;
}
if (time_mode_ == TimeMode::Combined && combined_index_ < 0) {
time_mode_ = TimeMode::RowNumber;
}
if (!filepath_.empty()) {
analyzeFile();
}
return true;
}
void CsvDialog::analyzeFile() {
column_names_.clear();
combined_pairs_.clear();
preview_rows_.clear();
if (filepath_.empty()) {
return;
}
std::ifstream file(filepath_);
if (!file.is_open()) {
return;
}
// Read header
std::string header_line;
if (!std::getline(file, header_line)) {
return;
}
if (!header_line.empty() && header_line.back() == '\r') {
header_line.pop_back();
}
if (delimiter_ == '\0') {
delimiter_ = PJ::CSV::DetectDelimiter(header_line);
}
// Check for duplicate column names before deduplication
{
std::vector<std::string> raw_parts;
PJ::CSV::SplitLine(header_line, delimiter_, raw_parts);
std::set<std::string> seen;
has_duplicate_columns_ = false;
for (const auto& part : raw_parts) {
if (!seen.insert(part).second) {
has_duplicate_columns_ = true;
break;
}
}
}
column_names_ = PJ::CSV::ParseHeaderLine(header_line, delimiter_);
// Build preview rows: first 100 data lines (like the original)
std::string line;
std::vector<std::string> parts;
std::vector<PJ::CSV::ColumnTypeInfo> first_row_types;
int count = 0;
while (std::getline(file, line) && count < 100) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (line.empty()) {
continue;
}
PJ::CSV::SplitLine(line, delimiter_, parts);
preview_rows_.push_back(parts);
// Detect types from first row
if (count == 0) {
first_row_types.resize(column_names_.size());
for (size_t i = 0; i < parts.size() && i < first_row_types.size(); i++) {
if (!parts[i].empty()) {
first_row_types[i] = PJ::CSV::DetectColumnType(parts[i]);
}
}
combined_pairs_ = PJ::CSV::DetectCombinedDateTimeColumns(column_names_, first_row_types);
}
count++;
}
// Compute preview warning message
warning_message_.clear();
// Check for duplicate column names in header
if (has_duplicate_columns_) {
warning_message_ =
"WARNING: duplicate column names detected in the header. Suffixes have been added "
"automatically to make them unique.";
}
// Check for rows with wrong column count
if (warning_message_.empty()) {
for (const auto& row : preview_rows_) {
if (row.size() != column_names_.size()) {
warning_message_ =
"WARNING: some rows in the preview have a different number of columns than the "
"header. Those rows will be skipped during loading.";
break;
}
}
}
// Check for non-monotonic timestamps in selected column (numeric only)
if (warning_message_.empty() && time_mode_ == TimeMode::Column && selected_column_index_ >= 0 &&
selected_column_index_ < static_cast<int>(column_names_.size())) {
double prev_val = std::numeric_limits<double>::lowest();
for (const auto& row : preview_rows_) {
auto col = static_cast<size_t>(selected_column_index_);
if (col >= row.size() || row[col].empty()) {
continue;
}
try {
double val = std::stod(row[col]);
if (val < prev_val) {
warning_message_ =
"WARNING: timestamps in the selected column are not monotonically increasing. "
"Data will be sorted automatically after loading.";
break;
}
prev_val = val;
} catch (...) {
break; // Non-numeric timestamps: skip check
}
}
}
// If the current mode was "combined" but this file has no detectable pairs,
// fall back to row_number to avoid an invalid state.
if (time_mode_ == TimeMode::Combined && combined_pairs_.empty()) {
time_mode_ = TimeMode::RowNumber;
combined_index_ = -1;
}
// Auto-select the first combined pair if none is selected yet.
if (!combined_pairs_.empty() && combined_index_ < 0) {
combined_index_ = 0;
}
}
// Interprets a Qt date/time format string against the fixed example
// 2024-01-15 14:30:45 and returns the formatted result.
// Supports: yyyy yy MMMM MMM MM M dddd ddd dd d HH H hh h mm m ss s zzz z AP ap A a
// and single-quoted literals.
std::string CsvDialog::computeFormatPreview(const std::string& fmt) {
const int year = 2024, month = 1, day = 15, hour = 14, min = 30, sec = 45;
const int weekday = 0; // Monday (2024-01-15)
static const char* month_long[] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
static const char* month_short[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
static const char* wday_long[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
static const char* wday_short[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
auto pad2 = [](int v) -> std::string { return (v < 10 ? "0" : "") + std::to_string(v); };
auto match = [&](size_t pos, const char* tok) -> bool {
size_t n = 0;
while (tok[n]) {
++n;
}
return fmt.size() - pos >= n && fmt.compare(pos, n, tok) == 0;
};
std::string out;
size_t i = 0;
while (i < fmt.size()) {
if (fmt[i] == '\'') {
++i;
while (i < fmt.size() && fmt[i] != '\'') {
out += fmt[i++];
}
if (i < fmt.size()) {
++i;
}
} else if (match(i, "yyyy")) {
out += std::to_string(year);
i += 4;
} else if (match(i, "yy")) {
out += pad2(year % 100);
i += 2;
} else if (match(i, "MMMM")) {
out += month_long[month - 1];
i += 4;
} else if (match(i, "MMM")) {
out += month_short[month - 1];
i += 3;
} else if (match(i, "MM")) {
out += pad2(month);
i += 2;
} else if (fmt[i] == 'M') {
out += std::to_string(month);
++i;
} else if (match(i, "dddd")) {
out += wday_long[weekday];
i += 4;
} else if (match(i, "ddd")) {
out += wday_short[weekday];
i += 3;
} else if (match(i, "dd")) {
out += pad2(day);
i += 2;
} else if (fmt[i] == 'd') {
out += std::to_string(day);
++i;
} else if (match(i, "HH")) {
out += pad2(hour);
i += 2;
} else if (fmt[i] == 'H') {
out += std::to_string(hour);
++i;
} else if (match(i, "hh")) {
int h = hour % 12;
if (!h) {
h = 12;
}
out += pad2(h);
i += 2;
} else if (fmt[i] == 'h') {
int h = hour % 12;
if (!h) {
h = 12;
}
out += std::to_string(h);
++i;
} else if (match(i, "mm")) {
out += pad2(min);
i += 2;
} else if (fmt[i] == 'm') {
out += std::to_string(min);
++i;
} else if (match(i, "ss")) {
out += pad2(sec);
i += 2;
} else if (fmt[i] == 's') {
out += std::to_string(sec);
++i;
} else if (match(i, "zzz")) {
out += "000";
i += 3;
} else if (fmt[i] == 'z') {
out += "0";
++i;
} else if (match(i, "AP")) {
out += (hour < 12 ? "AM" : "PM");
i += 2;
} else if (match(i, "ap")) {
out += (hour < 12 ? "am" : "pm");
i += 2;
} else if (fmt[i] == 'A') {
out += (hour < 12 ? "AM" : "PM");
++i;
} else if (fmt[i] == 'a') {
out += (hour < 12 ? "am" : "pm");
++i;
} else {
out += fmt[i++];
}
}
return out;
}
int CsvDialog::delimiterToIndex(char d) {
switch (d) {
case ',':
return 0;
case ';':
return 1;
case ' ':
return 2;
case '\t':
return 3;
default:
return 0;
}
}
char CsvDialog::indexToDelimiter(int idx) {
switch (idx) {
case 0:
return ',';
case 1:
return ';';
case 2:
return ' ';
case 3:
return '\t';
default:
return ',';
}
}