-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathcsvapplication.cpp
More file actions
3611 lines (3144 loc) · 115 KB
/
csvapplication.cpp
File metadata and controls
3611 lines (3144 loc) · 115 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
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
/*
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Copyright (C) 2025 Stefan Fischerländer
*
* This file is part of Tablecruncher.
*
* Tablecruncher 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.
*
* Tablecruncher 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 Tablecruncher. If not, see <https://www.gnu.org/licenses/>.
*/
#include "colorthemes.hh"
#include "csvapplication.hh"
#include "csvmenu.hh"
#include "csvparser.hh"
#include "csvwindow.hh"
#include "helper.hh"
#include "icons/abouticon.xpm"
#include "macro.hh"
#include <algorithm>
#include <deque>
#include <filesystem>
#include <fstream>
#include <httplib.h>
#include <utf8.h>
/************************************************************************************
*
* CsvApplication
*
************************************************************************************/
// I think this global function is very bad style ... TODO XXX
void updateMacroLogBuffer(void *logVoid, std::string str) {
Fl_Text_Display *logDisplay = ((Fl_Text_Display *) logVoid);
if( logDisplay ) {
logDisplay->buffer()->append(str.c_str());
}
}
extern CsvWindow windows[];
extern CsvApplication app;
extern Fl_Preferences preferences;
extern Fl_Preferences macros;
extern Macro macro;
/**
* Constructor
*/
CsvApplication::CsvApplication() {
std::string prefTheme = getPreference(&preferences, TCRUNCHER_PREF_THEME, "Bright");
std::string prefFont = getPreference(&preferences, TCRUNCHER_PREF_GRID_TEXT_FONT, TCRUNCHER_FALLBACK_FONT);
struct My_Fl_Button::buttonColorStruct colorsDefaultButton;
colorsDefaultButton.background = ColorThemes::getColor(prefTheme, "button_bg");
colorsDefaultButton.label = ColorThemes::getColor(prefTheme, "button_text");
colorsDefaultButton.border = ColorThemes::getColor(prefTheme, "button_border");
colorsDefaultButton.windowBg = ColorThemes::getColor(prefTheme, "win_bg");
colorsDefaultButton.borderWidth = ColorThemes::getColor(prefTheme, "button_border_width");
struct My_Fl_Button::buttonColorStruct colorsHighlightButton;
colorsHighlightButton.background = ColorThemes::getColor(prefTheme, "hightlight_button_bg");
colorsHighlightButton.label = ColorThemes::getColor(prefTheme, "hightlight_button_text");
colorsHighlightButton.border = ColorThemes::getColor(prefTheme, "hightlight_button_border");
colorsHighlightButton.windowBg = ColorThemes::getColor(prefTheme, "win_bg");
colorsHighlightButton.borderWidth = ColorThemes::getColor(prefTheme, "highlight_button_border_width");
// Improve tooltip layout
Fl_Tooltip::textcolor( ColorThemes::getColor(prefTheme, "header_row_text") );
Fl_Tooltip::color( ColorThemes::getColor(prefTheme, "win_bg") );
Fl_Tooltip::delay( 0.2 );
Fl_Tooltip::size( 12 );
Fl_Tooltip::margin_width(6); // default: 3
Fl_Tooltip::margin_height(4); // default: 3
// Grid fonts
#ifdef __APPLE__
const char* TCRUNCHER_FONTS_ARR[] = {"Andale Mono", "Courier New", "Helvetica", "Menlo", "Monaco"};
const int TCRUNCHER_FONTS_ARR_COUNT = 5;
#else
const char* TCRUNCHER_FONTS_ARR[] = {"Consolas", "Courier New", "Helvetica"};
const int TCRUNCHER_FONTS_ARR_COUNT = 3;
#endif
// Fl::set_font(9901, "Monaco");
for( int i = 0; i < TCRUNCHER_FONTS_ARR_COUNT; ++i ) {
Fl::set_font(TCRUNCHER_FONT_NUMBER + i, TCRUNCHER_FONTS_ARR[i]);
fontMapping[std::string(TCRUNCHER_FONTS_ARR[i])] = TCRUNCHER_FONT_NUMBER + i;
}
//
// Create Search Window
searchWin = new My_Fl_Search_Window(600,350);
searchWin->label("Find and Replace");
searchWin->color(ColorThemes::getColor(prefTheme, "win_bg"));
searchInput = new Fl_Input(120,20,370,20, "Find:");
searchInput->box(FL_BORDER_BOX);
searchInput->labelcolor(ColorThemes::getColor(prefTheme, "win_text"));
replaceInput = new Fl_Input(120,70,370,20, "Replace:");
replaceInput->box(FL_BORDER_BOX);
replaceInput->labelcolor(ColorThemes::getColor(prefTheme, "win_text"));
findButton = new My_Fl_Button(120,210,100,24, "Find Next");
findButton->colors = colorsHighlightButton;
findButton->callback(find_substring_CB, TCRUNCHER_MYFLCHOICE_MAGICAL);
findButton->shortcut(FL_Enter);
replaceButton = new My_Fl_Button(120,250,100,24, "Replace");
replaceButton->colors = colorsDefaultButton;
replaceButton->callback(find_replaceFind_CB, NULL);
replaceFindButton = new My_Fl_Button(240,250,120,24, "Replace+Find");
replaceFindButton->colors = colorsDefaultButton;
replaceFindButton->callback(find_replaceFind_CB, NULL);
replaceAllButton = new My_Fl_Button(380,250,110,24, "Replace All");
replaceAllButton->colors = colorsDefaultButton;
replaceAllButton->callback(find_replaceAll_CB, CsvApplication::ReplaceAllType::REPLACE);
flagMatchingButton = new My_Fl_Button(120,290,170,24, "Flag Matching Rows");
flagMatchingButton->colors = colorsDefaultButton;
flagMatchingButton->callback(find_replaceAll_CB, CsvApplication::ReplaceAllType::FLAG);
unflagMatchingButton = new My_Fl_Button(310,290,180,24, "Unflag Matching Rows");
unflagMatchingButton->colors = colorsDefaultButton;
unflagMatchingButton->callback(find_replaceAll_CB, CsvApplication::ReplaceAllType::UNFLAG);
ignoreCase = new Fl_Check_Button(120,150,100,24, "Ignore Case");
ignoreCase->labelcolor(ColorThemes::getColor(prefTheme, "win_text"));
useRegex = new Fl_Check_Button(310,150,180,24, "Use regular expression");
useRegex->labelcolor(ColorThemes::getColor(prefTheme, "win_text"));
searchWinLabel = new Fl_Box(120,320,300,20);
searchWinLabel->box(FL_NO_BOX);
searchWinLabel->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
searchWinLabel->labelcolor(ColorThemes::getColor(prefTheme, "win_text"));
searchWinLabel->redraw();
searchWinScope = new Fl_Box(120,110,200,24, "Scope: Full Table");
searchWinScope->box(FL_NO_BOX);
searchWinScope->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
searchWinScope->labelcolor(ColorThemes::getColor(prefTheme, "win_text"));
searchWinScope->redraw();
// ... completed
searchWin->end();
// Create Sort Window
sortWin = new My_Fl_Small_Window(640,180);
sortWin->end();
#ifdef __APPLE__
// Set application window
appMenuBar = new CsvMenu();
appMenuBar->init();
static Fl_Menu_Item appMenuItems[] = {
{ "Preferences...", FL_COMMAND + ',', CsvApplication::AppMenuPreferencesCB, 0, 0, 0, 0, 0, 0 },
{ "Check for Updates", 0, CsvApplication::checkUpdateCB, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
Fl_Mac_App_Menu::custom_application_menu_items(appMenuItems);
// mini window that stays open when the last data window is closed
remainOpenWin = new My_Fl_Small_Window((Fl::w() - 300)/2, (Fl::h() -200)/2, 300, 200, TCRUNCHER_APP_NAME);
remainOpenWin->color(ColorThemes::getColor(prefTheme, "win_bg"));
remainQuitButton = new My_Fl_Button(75,88,150,24, "Quit Application");
remainQuitButton->colors = colorsHighlightButton;
remainQuitButton->clear_visible_focus();
remainQuitButton->callback(closeRemainOpenWindow, NULL);
remainOpenWin->end();
remainOpenWin->hide();
#endif
// imWorkingWindow
imWorkingWindow = new My_Fl_Small_Window(400,120,"Processing ...");
imWorkingWindow->color(ColorThemes::getColor(app.getTheme(), "win_bg"));
imWorkingButton = new Fl_Button(10,10,380,100,"Please stand by while I'm working ...");
imWorkingButton->box(FL_NO_BOX);
imWorkingButton->visible_focus(0);
imWorkingWindow->end();
imWorkingWindow->hide();
try {
physMemSize = Helper::getPhysMemSize();
} catch(...) {}
plusPng = xpmResizer(ui_icons::icon_plus, macroWinImgButtonSize);
minusPng = xpmResizer(ui_icons::icon_minus, macroWinImgButtonSize);
// Custom Fonts
customFonts.gridText = Helper::getFltkFontCode(getPreference(&preferences, TCRUNCHER_PREF_GRID_TEXT_FONT, "FL_HELVETICA"));
// fill Open Recent menu from preferences file
for( int i = TCRUNCHER_PREF_RECENT_FILES_NUM - 1; i >= 0; --i ) {
std::string tmp_key = TCRUNCHER_PREF_RECENT_FILES_STUB + std::to_string(i);
std::string tmp_val = getPreference(&preferences, tmp_key, "");
if( tmp_val != "" ) {
std::filesystem::path recent_file(tmp_val);
if( std::filesystem::exists(recent_file) ) {
recentFiles.add(tmp_val);
}
}
}
#ifdef __APPLE__
appMenuBar->updateOpenRecentMenu(recentFiles.getRecentFiles());
#endif
app.getPreference(&preferences, TCRUNCHER_PREF_UPDATE_CHECK_ALLOWED, "no");
}
/**
* Destructor
*/
CsvApplication::~CsvApplication() {
delete searchInput;
delete replaceInput;
delete findButton;
delete replaceButton;
delete replaceFindButton;
delete replaceAllButton;
delete flagMatchingButton;
delete unflagMatchingButton;
delete ignoreCase;
delete useRegex;
delete searchWinLabel;
delete searchWinScope;
delete searchWin;
delete sortWin;
#ifdef __APPLE__
delete appMenuBar;
delete remainQuitButton;
delete remainOpenWin;
#endif
delete imWorkingButton;
delete imWorkingWindow;
}
std::map<std::string,int> CsvApplication::getFontMapping() {
return fontMapping;
}
void CsvApplication::changeFontSize(int changeMode) {
switch(changeMode) {
case 0:
windows[getTopWindow()].grid->defaultFont();
break;
case 1:
windows[getTopWindow()].grid->biggerFont();
break;
case -1:
windows[getTopWindow()].grid->smallerFont();
break;
}
}
/**
Callback for Preferences in Application Menu
*/
void CsvApplication::AppMenuPreferencesCB(Fl_Widget *, void *) {
std::string prefCheckUpdates = app.getPreference(&preferences, TCRUNCHER_PREF_UPDATE_CHECK_ALLOWED, "no");
My_Fl_Small_Window win(500, 150);
Fl_Check_Button updateCheckAllowed( 30, 30, 260, 25," Regularly check for updates");
updateCheckAllowed.visible_focus(0);
updateCheckAllowed.labelcolor(ColorThemes::getColor(app.getTheme(), "win_text"));
updateCheckAllowed.callback(CsvApplication::updateCheckButtonCB, NULL);
if( app.isUpdateCheckAllowed() ) {
updateCheckAllowed.value(1);
} else {
updateCheckAllowed.value(0);
}
// Fl_Choice gridTextFontChoice( 100, 60, 260, 30, "Grid font");
// // gridTextFontChoice.callback(choice_cb, 0);
// gridTextFontChoice.add("Helvetica");
// gridTextFontChoice.add("Courier");
// gridTextFontChoice.add("Times");
// gridTextFontChoice.add("Monaco");
win.set_modal();
win.label("Tablecruncher Preferences");
win.color(ColorThemes::getColor(app.getTheme(), "win_bg"));
win.show();
while( win.shown() ) {
Fl::wait();
}
}
void CsvApplication::updateCheckButtonCB(Fl_Widget *w, void *) {
Fl_Check_Button *but = (Fl_Check_Button*)w;
if( but->value() ) {
app.setUpdateCheck(true);
preferences.set(TCRUNCHER_PREF_UPDATE_CHECK_ALLOWED, "yes");
} else {
app.setUpdateCheck(false);
preferences.set(TCRUNCHER_PREF_UPDATE_CHECK_ALLOWED, "no");
}
}
/**
Returns true if onboarding finished
*/
bool CsvApplication::showOnboardingProcess() {
#ifdef _WIN64
return true;
#endif
int choice;
std::string msg;
// Step 1: Ask for update permission
msg = "<b>Step 1/2</b><br> <br>Should Tablecruncher check automatically for updates once a week?<br> <br><font size='2'>You may change your selection later via <i>Tablecruncher > Preferences...</i></font>";
choice = myFlChoice("Welcome to Tablecruncher", msg, {"Yes", "No", "Cancel"}, 100, 200);
if( choice == -1 || choice == 2) {
return false;
}
if( choice == 0 ) {
setUpdateCheck(true);
preferences.set(TCRUNCHER_PREF_UPDATE_CHECK_ALLOWED, "yes");
} else if( choice == 1 ) {
setUpdateCheck(false);
preferences.set(TCRUNCHER_PREF_UPDATE_CHECK_ALLOWED, "no");
}
// Step 2: Inform about GPL
msg = "<b>Step 2/2</b><br> <br>Tablecruncher is licensed under GPL v3";
choice = myFlChoice("Welcome to Tablecruncher", msg, {"OK", "Cancel"}, 100, 200);
if( choice == -1 || choice == 1) {
return false;
}
return true;
}
/**
* Creates a new window
* https://stackoverflow.com/questions/5887615/creating-an-array-of-object-pointers-c
*/
int CsvApplication::createNewWindow() {
int newWindowIndex = -1;
// Look for an unused window slot
for(int slot = 0; slot < TCRUNCHER_MAX_WINDOWS; ++slot) {
if( !windows[slot].getWindowSlotUsed() ) {
newWindowIndex = slot;
break;
}
}
if( newWindowIndex == -1 ) {
#ifdef DEBUG
dumpWindows();
#endif
CsvApplication::myFlChoice("", "Maximum number of windows already open.", {"Okay"});
return -1;
}
windows[newWindowIndex].create(createdWindowCount++);
updateMenu(newWindowIndex);
#ifdef __APPLE__
remainOpenWin->hide();
#endif
// setMenuBar(windows[newWindowIndex].win);
windows[newWindowIndex].applyTheme();
windows[newWindowIndex].win->show();
return newWindowIndex;
}
size_t CsvApplication::getCreatedWindowCount() {
return createdWindowCount;
}
void CsvApplication::openFileCB(Fl_Widget *, void *) {
app.openFile(false);
}
void CsvApplication::saveFileCB(Fl_Widget *, void *) {
app.saveFile(false);
}
void CsvApplication::saveFileAsCB(Fl_Widget *, void *) {
app.saveFile(true);
}
void CsvApplication::splitCsvCB(Fl_Widget *, void *) {
app.splitCsvFiles();
}
void CsvApplication::exportJsonCB(Fl_Widget *, void *) {
app.saveFile(true, SaveType::JSON);
}
void CsvApplication::exportFlaggedCB(Fl_Widget *, void *) {
app.saveFile(true, SaveType::CSV, true);
}
void CsvApplication::checkDataConsistencyCB(Fl_Widget *, void *) {
app.checkDataConsistency();
}
void CsvApplication::showInfoWindowCB(Fl_Widget *, void *) {
windows[app.getTopWindow()].showInfoWindow();
}
void CsvApplication::addColBeforeCB(Fl_Widget *, void *) {
app.addCol(true);
}
void CsvApplication::addColCB(Fl_Widget *, void *) {
app.addCol(false);
}
void CsvApplication::addRowAboveCB(Fl_Widget *, void *) {
app.addRow(true);
}
void CsvApplication::addRowCB(Fl_Widget *, void *) {
app.addRow(false);
}
void CsvApplication::delColsCB(Fl_Widget *, void *) {
app.delCols();
}
void CsvApplication::delRowsCB(Fl_Widget *, void *) {
app.delRows();
}
void CsvApplication::quitApplicationCB(Fl_Widget *, void *) {
app.quitApplication(true);
}
void CsvApplication::closeRemainOpenWindow(Fl_Widget *, void *) {
if( app.nfcIsOpen )
return;
app.quitApplication(true);
}
void CsvApplication::undoCB(Fl_Widget *, void *) {
int winIndex = app.getTopWindow();
if( windows[winIndex].hasUndoStates() ) {
app.showImWorkingWindow("Undoing last step ...");
windows[winIndex].undo();
app.hideImWorkingWindow();
} else {
// myFlChoice("Info", "No Undo state available.", {"Okay"});
}
}
void CsvApplication::disableUndoCB(Fl_Widget *, void *, bool confirmDialog) {
int winIndex = app.getTopWindow();
int choice = 0;
if( confirmDialog ) {
choice = CsvApplication::myFlChoice("Confirmation", "Do you really want to disable Undo functionality?<br><small>Only recommended for really large tables.</small>", {"Yes", "No"});
}
if( choice == 0 ) {
windows[winIndex].disableUndo();
app.updateMenu(winIndex);
}
}
void CsvApplication::enableUndoCB(Fl_Widget *, void *) {
int winIndex = app.getTopWindow();
windows[winIndex].enableUndo();
app.updateMenu(winIndex);
}
void CsvApplication::setCsvPropertiesCB(Fl_Widget *, void *) {
CsvDefinition definition;
int winIndex = app.getTopWindow();
definition = windows[winIndex].table->getDefinition();
definition = setTypeByUser(definition, NULL, "Change Type");
windows[winIndex].table->setDefinition(definition);
windows[winIndex].setTypeButton(definition);
}
/*
* Asks user for a file and opens it.
* askUser Should the user be asked about CSV format?
* reopen Should the file be opened in the same window? Caution: Changes are overwritten.
*/
void CsvApplication::openFile(bool askUser, bool reopen) {
int winIndex;
std::string fn;
Fl_Native_File_Chooser fnfc;
fnfc.title("Pick a file");
fnfc.type(Fl_Native_File_Chooser::BROWSE_FILE);
fnfc.filter("CSV Files\t*.{txt,csv,tsv}");
fnfc.directory(workDir.c_str());
if( reopen ) {
winIndex = app.getTopWindow();
if( winIndex >= 0 ) {
fn = windows[winIndex].getPath();
windows[winIndex].loadFile(fn, true, true);
}
} else {
nfcIsOpen = true;
switch ( fnfc.show() ) {
case -1:
#ifdef DEBUG
printf("ERROR: %s\n", fnfc.errmsg());
#endif
break; // ERROR
case 1:
#ifdef DEBUG
printf("CANCEL\n");
#endif
break; // CANCEL
default:
#ifdef DEBUG
printf("PICKED: %s\n", fnfc.filename());
#endif
fn = fnfc.filename();
openFile(fn, askUser);
}
nfcIsOpen = false;
}
}
void CsvApplication::openFile(std::string path, bool askUser) {
int winIndex = app.getTopWindow();
bool fileLoaded;
bool createdNewWindow = false;
if( windows[winIndex].isUsed() ) {
winIndex = app.createNewWindow();
createdNewWindow = true;
}
if( winIndex >= 0 && winIndex <= TCRUNCHER_MAX_WINDOWS ) {
windows[winIndex].win->show();
fileLoaded = windows[winIndex].loadFile(path, askUser);
if( fileLoaded ) {
app.setWorkDir( Helper::getDirectory(path) );
windows[winIndex].setUsed(true);
windows[winIndex].setWindowSlotUsed(true);
// load file preferences
windows[winIndex].readWindowPreferences();
windows[winIndex].grid->redraw();
Fl::check();
// automatically arrange column widths
app.arrangeColumnsCB(NULL, NULL);
// add file to recent files
recentFiles.add(path);
updateMenu(winIndex);
} else {
if( createdNewWindow )
closeWindow(winIndex);
}
}
}
void CsvApplication::openRecentFile(size_t index) {
std::string filepath = recentFiles.get(index);
if( filepath != "" ) {
app.openFile(filepath, false);
}
}
bool CsvApplication::splitCsvFiles() {
int winIndex = getTopWindow();
bool retOkay, mySaveState = false;
long numOfRowsPerFile = 0;
long numOfRows = windows[winIndex].table->getNumberRows();
long fromRow, toRow;
std::ifstream fileExistsTest;
std::string numOfRowsPerFileStr, filename, msg;
std::string pathWithoutExtension,extension;
// TODO Return if no file has been opened or saved so far
// TODO Ask if numOfFiles gets to big
std::tie(retOkay, numOfRowsPerFileStr) = myFlAskString("Number of lines per file", "Split");
if( retOkay ) {
try {
if( numOfRowsPerFileStr.find_first_not_of("0123456789") == std::string::npos ) {
numOfRowsPerFile = std::stoi(numOfRowsPerFileStr);
} else {
numOfRowsPerFile = 0;
}
} catch(...) {} // intentional empty clause
if( numOfRowsPerFile > 0 ) {
int numOfFiles = (int) std::ceil((double)numOfRows / numOfRowsPerFile);
int digitalExtensionLength = std::ceil(std::log10(numOfFiles));
if( numOfFiles > 1 ) {
std::tie(pathWithoutExtension,extension) = Helper::getPathWithoutExtension(windows[winIndex].getPath());
// Test if one of the splitted files already exists
bool splitFileExists = false;
for(int i=0; i<numOfFiles; ++i) {
filename = splittedFileName(pathWithoutExtension, extension, i, digitalExtensionLength);
fileExistsTest.open(filename.c_str());
if( fileExistsTest.good() ) {
splitFileExists = true;
msg = "File " + Helper::getBasename(filename) + " does already exist!";
myFlChoice("Error", msg, {"Okay"});
break;
}
}
if( !splitFileExists ) {
showImWorkingWindow("Splitting CSV file ...");
for(int i=0; i<numOfFiles; ++i) {
fromRow = i * numOfRowsPerFile;
if( i < numOfFiles -1 ) {
toRow = fromRow + numOfRowsPerFile - 1;
} else {
toRow = -1;
}
filename = splittedFileName(pathWithoutExtension, extension, i, digitalExtensionLength);
mySaveState = windows[winIndex].table->saveCsv(filename, &CsvWindow::updateStatusbarCB, &windows[winIndex], false, fromRow, toRow);
}
hideImWorkingWindow();
msg = "The splitted CSV files have been stored. (No of Files: "+std::to_string(numOfFiles)+")";
myFlChoice("Files stored", msg, {"Okay"});
}
} else {
myFlChoice("Error", "The number of rows per splitted file has to be lower than the number of rows in the original file.", {"Okay"});
}
} else {
myFlChoice("Error", "Invalid number given!", {"Okay"});
}
}
return mySaveState;
}
std::string CsvApplication::splittedFileName(std::string pathWithoutExtension, std::string extension, int num, int digitalExtensionLength) {
return pathWithoutExtension + ".split-" + Helper::padInteger(num,digitalExtensionLength) + "." + extension;
}
/*
Saves top-most window
saveAs User clicked "Save As", default: false
type What format to save data to, default: CsvApplication::SaveType CSV
flaggedOnly Only export flagged rows
*/
bool CsvApplication::saveFile(bool saveAs, CsvApplication::SaveType type, bool flaggedOnly) {
Fl_Native_File_Chooser fnfc;
int winIndex = getTopWindow();
std::string path; // path as stored in CsvWindow
std::string fn = ""; // path as chosen by user
bool repeatLoop = false;
std::ifstream fileExistsTest;
int choice;
std::string baseFilename, pathFilename;
bool ret = false;
std::string fileFilter = "CSV Files\t*.{txt,csv,tsv}";
std::string defaultExtension = ".csv";
if( type == CsvApplication::SaveType::JSON ) {
fileFilter = "JSON Files\t*.{json}";
defaultExtension = ".json";
}
path = windows[winIndex].getPath();
// Check if there are flagged rows when exporting flagged rows
if( flaggedOnly && windows[winIndex].table->countFlaggedRows() == 0 ) {
CsvApplication::myFlChoice("", "There are no flagged rows!", {"Okay"});
return false;
}
// Ask for path where file should be stored
if( path == "" || saveAs ) {
do {
repeatLoop = false;
fn = "";
fnfc.title("Pick a file");
fnfc.type(Fl_Native_File_Chooser::BROWSE_SAVE_FILE);
#ifdef DEBUG
std::cerr << " fnfc.filter" << std::endl;
#endif
fnfc.filter(fileFilter.c_str());
fnfc.directory(workDir.c_str());
switch ( fnfc.show() ) {
case -1:
#ifdef DEBUG
printf("ERROR: %s\n", fnfc.errmsg());
#endif
break; // ERROR
case 1:
#ifdef DEBUG
printf("CANCEL\n");
#endif
break; // CANCEL
default:
#ifdef DEBUG
printf("PICKED: %s\n", fnfc.filename());
#endif
fn = fnfc.filename();
// calculate path and add extension if necessary
pathFilename = fn.substr(0, fn.find_last_of("/\\")+1);
baseFilename = fn.substr(fn.find_last_of("/\\") + 1);
if( baseFilename.find(".") == std::string::npos ) {
// no dot in filename – needs an extension
baseFilename.append(defaultExtension);
}
fn = pathFilename + baseFilename;
}
// File exists?
fileExistsTest.open(fn.c_str());
if( fileExistsTest.good() ) {
// File exists!
choice = myFlChoice("Confirmation", "File already exists. Overwrite it?", {"Yes", "No"});
if( choice == 1 ) // overwrite == no
repeatLoop = true; // ask for another file name
if( choice == -1 ) { // ESC => don't save and don't ask again
fn = "";
repeatLoop = false;
}
fileExistsTest.close();
}
} while(repeatLoop);
} else {
fn = path;
}
// a path has been chosen
if( fn != "" ) {
int mySaveState = CsvTable::saveReturnCode::SAVE_ERROR;
windows[winIndex].updateStatusbar("Saving ...");
if( type == CsvApplication::SaveType::CSV ) {
showImWorkingWindow("Saving CSV file ...");
mySaveState = windows[winIndex].table->saveCsv(fn, &CsvWindow::updateStatusbarCB, &windows[winIndex], flaggedOnly);
windows[winIndex].storeWindowPreferences();
hideImWorkingWindow();
} else if( type == CsvApplication::SaveType::JSON ) {
showImWorkingWindow("Exporting JSON ...");
mySaveState = windows[winIndex].table->exportJSON(fn, &CsvWindow::updateStatusbarCB, &windows[winIndex]);
hideImWorkingWindow();
}
if( mySaveState == CsvTable::saveReturnCode::SAVE_OKAY ) {
if( type == CsvApplication::SaveType::CSV && !flaggedOnly ) {
windows[winIndex].setName(Helper::getBasename(fn));
windows[winIndex].setPath(fn);
windows[winIndex].setChanged(false);
windows[winIndex].setUndoSaveState();
app.setWorkDir( Helper::getDirectory(fn) );
}
windows[winIndex].updateStatusbar("Finished saving.");
ret = true;
} else {
CsvApplication::myFlChoice("", "Could not save file!", {"Okay"});
windows[winIndex].updateStatusbar("Could not save file.");
}
}
return ret;
}
/**
* Closes the window indicated by windowIndex; default is -1 and closes the top-most window
*/
void CsvApplication::closeWindow(int windowIndex, bool forceClose) {
int choice;
if( windowIndex == -1 ) {
windowIndex = app.topWindow;
}
if( windows[windowIndex].isUsed() && windows[windowIndex].isChanged() ) {
choice = myFlChoice("Confirmation", "File has been modified. Save?", {"Yes", "No", "Cancel"});
switch( choice ) {
case 0: // yes: call saveFile()
if( !saveFile() ) {
return;
}
break;
case 1: // no: do nothing and continue to close window
break;
case -1:
case 2: // cancel
return;
break;
default: // ESC: cancel
return;
}
}
if( nfcIsOpen )
return;
if( windows[windowIndex].getWindowSlotUsed() ) {
// This window has been in use and is showing
windows[windowIndex].storeWindowPreferences();
My_Fl_Double_Window *nextWinPtr = (My_Fl_Double_Window *) Fl::next_window(windows[windowIndex].win);
if( nextWinPtr == NULL && !forceClose ) {
#ifdef __APPLE__
remainOpenWin->show();
#endif
}
windows[windowIndex].setPath("");
windows[windowIndex].setWindowSlotUsed(false);
windows[windowIndex].createdWindowCount = 0;
windows[windowIndex].table->clearTable();
if( nextWinPtr ) {
nextWinPtr->take_focus();
}
windows[windowIndex].win->hide();
// delete undoList
windows[windowIndex].clearUndoList();
}
}
void CsvApplication::quitApplication(bool forceClose) {
searchWin->hide();
if( forceClose ) {
#ifdef __APPLE__
remainOpenWin->hide();
#endif
}
// Store Open Recent…
for( size_t i = 0; i < TCRUNCHER_PREF_RECENT_FILES_NUM; ++i ) {
std::string tmp_key = TCRUNCHER_PREF_RECENT_FILES_STUB + std::to_string(i);
std::string tmp_val = "";
tmp_val = recentFiles.get(i);
preferences.set( tmp_key.c_str(), tmp_val.c_str() );
}
// Close windows
for( int i = 0; i < TCRUNCHER_MAX_WINDOWS; ++i ) {
if( windows[i].getWindowSlotUsed() ) {
// std::cerr << "Closing window: " << windows[i].getPath() << std::endl;
closeWindow(i, forceClose);
}
}
}
int CsvApplication::getWindowByPointer(Fl_Widget *widget) {
for( int i = 0; i < TCRUNCHER_MAX_WINDOWS; ++i ) {
if( windows[i].win == widget ) {
return i;
}
}
return -1;
}
/**
* Sets the new topWindow or the first slot it encounters.
* (Hint: topWindow can get -1 if all slots are not used – should not occur)
*/
void CsvApplication::setTopWindow(int topWindow) {
if( topWindow == -1 ) {
for( int slot = 0; slot < TCRUNCHER_MAX_WINDOWS; ++slot ) {
if( windows[slot].getWindowSlotUsed() ) {
topWindow = slot;
break;
}
}
}
if( topWindow >= 0) {
this->topWindow = topWindow;
setUndoMenuItem( windows[topWindow].hasUndoStates() );
}
}
int CsvApplication::getTopWindow() {
return topWindow;
}
/*
* Guesses the definition of the given stream, returning some confidence value with it
*/
std::pair<CsvDefinition, float> CsvApplication::guessDefinition(std::istream *input) {
const int MAXLINES = 10; // number of lines to read for every test
float confidence;
CsvParser *parser = new CsvParser();
CsvDataStorage localStorage;
// Define definitions for probing
std::vector< std::tuple<CsvDefinition,int,int> > definitions;
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
definitions.push_back( std::tuple<CsvDefinition, int, int>(CsvDefinition(),0,0) );
std::get<0>(definitions.at(0)).delimiter = ',';
std::get<0>(definitions.at(1)).delimiter = ';';
std::get<0>(definitions.at(2)).delimiter = '\t';
std::get<0>(definitions.at(3)).delimiter = '|';
std::get<0>(definitions.at(4)).delimiter = ':';
std::get<0>(definitions.at(5)).delimiter = ',';
std::get<0>(definitions.at(6)).delimiter = ';';
std::get<0>(definitions.at(6)).delimiter = '*';
std::get<0>(definitions.at(5)).escape = '\\';
std::get<0>(definitions.at(6)).escape = '\\';
// get statistics for all probing definitions
for( size_t i = 0; i < definitions.size(); ++i ) {
std::pair<int, int> statistics;
// reset stream
input->clear(); // WHY????
input->seekg(0);
// clear localTable
localStorage.clear();
parser->parseCsvStream( input, localStorage, &(std::get<0>(definitions.at(i))), MAXLINES, false );
statistics = tableStatistics(localStorage);
// not so commonly used seperators and escape characters: decrease statistics value
if(
std::get<0>(definitions.at(i)).delimiter == ':' ||
std::get<0>(definitions.at(i)).delimiter == '|' ||
std::get<0>(definitions.at(i)).escape == '\\' ||
std::get<0>(definitions.at(i)).escape == '*'
) {
statistics.first = statistics.first * 70 / 100;
}
std::get<1>(definitions.at(i)) = statistics.first;
if( statistics.first <= 1 && statistics.second == 0) {
// if statistics is (1,0), sort it at the end
std::get<2>(definitions.at(i)) = 999;
} else {
std::get<2>(definitions.at(i)) = statistics.second;
}
#ifdef DEBUG
printf("CSV = '%c' => %d / %d\n", std::get<0>(definitions.at(i)).delimiter, statistics.first, statistics.second);
#endif
}
// sort probes: 3rd element INC, 2nd element DESC (C++14)
std::sort(begin(definitions), end(definitions), [](auto &t1, auto &t2) {
if( std::get<2>(t1) == std::get<2>(t2) ) {
return std::get<1>(t1) > std::get<1>(t2);
}
return std::get<2>(t1) < std::get<2>(t2);
});
confidence = 1.0;
// if there's no definition with zero variance: reduce confidence
if( std::get<2>(definitions[0]) > 0 ) {
confidence /= 2;
}
// if there are at least two definitions with the same number of columns: reduce confidence
if( std::get<1>(definitions[0]) == std::get<1>(definitions[1]) ) {
confidence /= 2;
}
// improve confidence, if it's a typical CSV separator
if( std::get<0>(definitions.at(0)).delimiter == ',' || std::get<0>(definitions.at(0)).delimiter == '\t' ) {
confidence += (1.0 - confidence) * 0.5;
}
// clear and reset
delete(parser);
input->clear();
input->seekg(0);
return {std::get<0>(definitions.at(0)), confidence};
}
/*
* Returns {Number of Cols, Some kind of Variance} of the data in localStorage
* Variance: number of rows that are shorter than the longest row
*
* @return std::pair (Number of Columns, Number of rows that are shorter than longest row)
*/
std::pair<table_index_t, table_index_t> CsvApplication::tableStatistics(CsvDataStorage localStorage) {
table_index_t maxCols = 0;
table_index_t shorterRows = 0;
// table is empty
if( localStorage.rows() == 0 ) {
return {0, 0};
}
// table has just one row
if( localStorage.rows() == 1) {
return { static_cast<table_index_t>(localStorage.rawRow(0).size()), 0 };
}
// get maximum columns
for( table_index_t r = 1; r < localStorage.rows(); ++r ) {
if( (table_index_t) localStorage.rawRow(r).size() > maxCols ) {
maxCols = localStorage.rawRow(r).size();
}
}
// count number of shorter rows
for( table_index_t r = 1; r < localStorage.rows(); ++r ) {
if( (table_index_t) localStorage.rawRow(r).size() < maxCols ) {
++shorterRows;
}
}
return {maxCols, shorterRows};
}