-
Notifications
You must be signed in to change notification settings - Fork 0
/
UDataPlotWindow.cpp
4137 lines (3943 loc) · 188 KB
/
UDataPlotWindow.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
//---------------------------------------------------------------------------
// Created by Peter Miller 18/7/2019 as csv file grapher (csvgraph.exe)
//
// Loosely based on an original public domain version by Frank Heinrich, mail@frank-heinrich.de
//
// Originally created using Borland Builder c++ V5
// This version compiled with Embarcadero® C++Builder 12.1
// It should be easy to move to a more recent version of C++Builder, but equally it would not be very hard to revert to earlier versions if necessary.
//
//
// Version Date : changes from previous version
// 1v0 1/1/2021 : 1st version released on github (was 16v6).
// 1v1 4/1/2021 : Bug fix in fft - DC component (zero frequency) could previoulsy become -ve if average value of waveform was -ve.
// : pdf of manual created so that readers open with bookmarks visible automatically. Manual contents unchanged.
// : added Menu/Help/Manual to display manual within csv graph (assumes csvgraph.pdf is in the same directory as csvgraph.exe)
// : if a filename is passed on the command line to csvgraph.exe it is opened at start. This allows csvgraph to be associated with csvfiles.
// 1v2 21/1/2021 : added (many) more types of linear regression eg exponential, log, power, hyperbolic, sqrt.
// : Also now traps "nan" and "inf" in csv files - previouly files containing these could be read but with give "LOG10" error when trying to display the graph.
// 1v3 27/1/2021 : Geometric Mean regression added as filter option
// 30/1/2021 : fit to y=mx added
// : y=mx+c min abs error and min abs relative error fits added.
// 2/2/2021 : added y=a*sqrt(x)+b*x+c least squares fit [ note this is the same as an order 2 poly fit to sqrt(x) but code is more efficient than doing this ]
// 2v0 6/2/2021 : change way x&y values are stored to reduce memory overhead and make it simpler to "filter" data
// : for 20M data points memory usage reduced from 357.1 MB to 140.1MB and loading/plotting 1 trace reducing from 26.375 to 22.67 secs.
// : (now uses 8 bytes per data point).
// : some speed optimisations as well (eg if adding multiple traces at once only process x values once then copy for other traces - assuming they are monotonic in input file)
// : sort optimised (worse case improved dramatically)
// : reading times (h:m:s) made more robust - will now read a general number as a float (secs) - but assumes no exponent present
// : warning - h:m:s date handling code assumes times are in order (all increasing), if they are not then day handling code may get confused...
// 2v1 20/1/2021 : investigation into speedup for myqsort() - avoid % operator, and directly sort 3 elements inline. Gives 7% speedup on average.
// : median3() function improved to use 2 or 3 compares (rather than 2 or 4).
// : myqsort() now sorts up to 4 elements inline and myswap is a macro - this gives 12% speedup over previous best.
// : option to check depth of recursion in myqsort - is < log2(nos_lines) as expected [ 16 for 16million line file].
// : myqsort random number generator reset before every sort to give consistent results.
// : myqsort() now sorts up to 6 elements inline this gives an additional 10% speedup.
// : myqsort now sorts upto 16 elements inline giving a small speedup
// : myqsort now sorts upto 32 elements inline gaining another 12% speedup.
// : added y=(a+bx)/(1+cx) (least squares fit)
// : added general least squares multiple variable linear regression (multiple-lin-reg-fn.cpp)
// : this allows y=a+b*sqrt(x)+c*x+d*x^1.5 and
// : y=(a+b*x+c*x^2)/(1+d*x+e*x^2) to be fitted
// : generic poly in sqrt(x) and rational function(poly/poly) fitting allowed with user specified order
// : better error trapping in basic linear regex (y=mx+c) for 1/x & log's
// 2v2 27/3/2021 : $T1 to Tn allowed in expressions to use values from existing traces on the graph. Traces are numbered from 1. Invalid trace numbers (too big) return 0
// : user can now set order of linear filter. Implements nth order Butterworth filter (10*order db/decade). Order=0 gives no filtering. Order =1 gives same filtering as previously.
// : "filters" for integral and derivative added
// : all filters now report progress as a % (previoulsy min abs error and min rel error did not report progress and they could be quite slow).
// : skip N lines before csv header option added for cases where csv header is not on the 1st row of the file
// : Added column numbers to X column and Y column listboxes to make it easier to select columns when names are not very descriptive (or missing).
// 2v3 3/1/2022 : can optionally use yasort2() for sorting - this has a guarantee on worse case execution time and can use all available processors to speed up sorting
// : yamedian() used which can calculate median in place without needing to copy the array of y values (but will for speed if memory is available)
// : added linear regression y=m*x*log2(x)+c
// 2v4 2/2/2022 : Fixed bug - using $Tn in situations where input x values needed to be sorted did not work correctly - fixed. Now also interpolates y value for $Tn if x values are different for new trace and $Tn
// 2v5a 10/2/2022: Fixed bug - if reading multiple columns at once optimisation that used x values from previous pass would fail if some lines were skipped - now trapped and optimisation not done in this case
// 2v5b 12/2/2022: Improved code for handling errors while reading csv files, used to just ignore errors, but now 1st 2 errors are reported in detail and total count displayed.
// : Date/time handling also improved, time is now read fully as a double and errors reported. A backwards step of up to 1 sec (eg a leap second) is allowed.
// : Any backwards step in time will cause data to be sorted, so this is visible to users even if its not directly reported as an error.
// 2v5d 14/2/2022 : files of size >2^31 bytes would give silly % complete values , final graph was OK - fixed.
// 2.5e 16/2/2022 : added "start times from 0" tick box to gui.
// 2v6 20/2/2022 : new median1 (standard median filter) algorithm based on binning (or exact for a relatively small number of data points)
// : X position of ledgends for the traces moved left to allow longer text to be read
// 2v7 15/3/2022 : prints -3dB frequency for linear filter.
// : display to user 1 example of every type of error in csv file (via rprintf)
// : if dates present on some lines then flag lines without a date as a potential error
// : new (exact) median (recursive median filter) algorithm, which falls back to sampling if the execution time becomes long.
// 2v8 24/3/2022 : strptime() function added for date/time handling
// : csvsave added % complete and buffering on output to speed up writing to file.
// : csvsave interpolates if required so x values do not need to be identical on all traces
// 2v9 4/6/2022 : bug when X_Offset used and multiple traces added at once then offset is added once for 1st trace, twice for 2nd etc.
// : first_time changed from double to long double so accuracy is improved when "start time from 0" is selected
// : gethms() and gethms_days() also both now return long doubles and are coded to convert numbers to this full resolution.
// 2v10 8/6/22 : readline() changed to limit max line length (avoids a "silly" file with a very long line using all the available memory)
// : Max length set at ~ 1 million characters so unlikley to be an issue with a real csv file
// : when outer catch(...) (in csvgraph.cpp) is executed clear flags saying functions are executing so user may be able to continue working.
// 3v0 15/8/22 : 1st 64 bit version built with C++ Builder 10.4
// 3v1 17/8/22 : clean compile for 64 bit version for both debug and release. No obvious bugs found either!
// 3v2 18/8/22 : debugging info added (sizeof int etc). Made to compile for 32 and 64 bits.
// when compiled for 64 bits:
// _WIN32 defined _WIN64 defined __BORLANDC__ defined __SIZEOF_POINTER__ == 8 Compiled for 64 bit pointers
// sizeof int=4, long=4, float=4, double=8, size_t=8,uintptr_t=8, intptr_t=8, void *=8
//
// when compiled for 32 bits:
// _WIN32 defined __BORLANDC__ defined __SIZEOF_POINTER__ == 4 Compiled for 32 bit pointers
// sizeof int=4, long=4, float=4, double=8, size_t=4,uintptr_t=4, intptr_t=4, void *=4
// Minor changes:
// When scales menu invoked multiple times, each time values would change slightly
// Allowed range of font sizes for Main title and X/Y axis titles expanded a little to 4->19 (was 8->14)
// fft now uses multiple processor cores if available.
// fft now makes better use of multiple cores + potential overflow when factorising number of points fixed.
// Refactored code so code likley to be used elsewhere is now in "..\Commom-files\"
// 3v2 was released on 14/9/2022 as 1st 64 bit release on github - 3v0 and 3v1 were internal only versions.
// 3v3 22/9/22 count_lines() returned an unsigned int - changed to size_t to allow more than 2^32 lines.
// fseek() also did not work with very large files, resulting in floating point divide by zero errors.
// Note when you run out of physical ram csvgraph will still continue (using virtual memory), but adding traces gets very slow, as does redrawing unzoomed screen. Zooming is still quick!
// 3v4 1/10/22 Fixed issue with 64 bit version about dpi awareness with multiple monitors.
// 3v5 20/10/22 an expression containing a function like max(1,2) would fail as the , would be treated as the terminator of the expression.
// Also ledgend for filtered traces with a time constant don't put (s) in as x axis might be eg hours.
// listbox updating for y variables now deals correctly with expressions.
// divide by 0 error when polynomial order =0 worked around (could not find actual issue! - but goes away when floating point exceptions turned off - see below).
// if csvgraph appears to be busy when user asks for a function like add trace then give them the option to fix this if csvgraph is not busy (eg if previous action caused an exception)
// Right mouse click now gives slope of line, and results are presented in a clearer way.
// _controlfp() {in csvgraph.cpp) used to turn off floating point exceptions (otherwise can get divide by zero errors etc)
// if filename given on command line, 64 bit version did not pick it up - fixed.
// 3v6 6/4/2023 Long column headers now cause a scroll bar to be automatically added to the X & Y listboxes so they can be fully seen
// Save x range on screen as CSV added to File menu.
// Option (tickbox) added to add basename of filename to legends of traces on the graph,
// which is useful if the same column is read from multiple files.
// Y axis title automatically added unless user specifies one (based on column header of 1st trace added).
// Added option to load X as Value/60 (sec->min), Val/3600 (sec->hrs), val/86400 (sec->days)
// Error handling for X values in a user defined date/time format improved, and trailing whitespace now allowed
// 3v7 4/6/2023
// Swapped to Builder C++ 11.3 compiler
// Fontsize TCSpinEdit caused runtime exceptions (write to invalid address) so changed to SpinEdit control which works.
// made Fonts more consistent (Arial used on graph, Segoe UI used for controls on bar on right)
// some font sizes tweaked and controls moved on bar to right to make everything fit
// Title now centered over graph (and has same width as the graph).
// Trace legends now have a "clear" background so are visible even when they overlap traces.
// Trace Legends can now be turned off (via tick box)
// Set Mantfest/DPI awareness to gdi scaling (was "none").
// 3v8 4/7/2023 csvsave where 2nd trace has less points than 1st trace caused error - fixed.
// 3v9 1/2/2024 updated to work with latest common files (interp1D()->interp1D_f() )
// can now open a file that excel already has open (and error messages are better on failing to open files)
// Better trapping of someone pressing a "command" button while a previous command is still running.
// Derivative now uses 17 point Savitzky Golay algorithm with user specified order (1->8 is actually used, can be set 0->infinity by user).
// Savitzky Golay smoothing added as a filtering option (17 or 25 points - left at 25)
// If a number is missing in a column referred to in an expression this will be flagged and the line skipped.
// added constant "nan" for expressions, if an expression evaluates to nan the line is skipped so this can be a powerful way to select points for csvgraph to display
// added "variables" x and line to expressions. x is current x value, and line is current line number.
// added 2nd deriv (d2y/d2x) to list of filters either 17 or 25 point selected by #if -> left at 25 but both checked and OK
// added "order" to legends for dy/dx and d2y/d2x (was already on Savitzky Golay smoothing legends).
// updated expression handler (expr-code.c) so nan==nan and nan!=nan works as expected in expressions.
// This allows for example $3==nan?x:nan which shows all invalid rows in column $3
// 3v10 27/2/2024 About box copyright years updated.
// smoothing splines filter option added
// sorting of x values revised so equal x values are changed to ones slightly higher (1 bit) [previoulsy equal x values were allowed].
// if input x values are increasing or equal, then now fix up to make always increasing without needing to sort
// 3v11 30/4/2024 ($1==0?0:1) was not considered a valid expression (called expr1() on brackets inside of expr0 ) - the same was ture for function arguments.
// for regression in polynomials of sqrt(x) , points with negative x are now ignored.
// allowed X as well as x in expressions ( useful as cut and paste of equations may use X )
// basic utf-8 encoded file handling for csv headers - still need to fix rprintf at ~ line 3200
// 11e - added more robust check for utf8 encoded headers
// 11f - everything now works in utf-8
// Had to set font for RichEdit to Arial !!
// 11g - csv saves column headers now in uft-8 format
// 11h - utf-8 BOM is ignored if present at the start of a csv file
// 11i - prompt user if they want uft-8 BOM at start of saved CSV file (only if headers are not plain 7 bit ASCII)
// 11j - wide string conversion functions all now null terminate output strings. Also removed unused code around utf-8 handling
// 11k - minor tweak for make compiler as 32 bits as well as 64 bit.
// - more major changes to support unicode filenames , loading works for 32 & 64 bits, save does NOT!
// 11L - save now works , however images only save as .bmp whatever extension I actually set!
// 11m - can now save jpg, png and gif images as well as bmp
// 11n - added tiff and wdp file save
// 11o - csvgraph/manual path can now be unicode - removed AnsiOf() & UnicodeOf() as not needed anymore. Most _WIN64 #if's also removed as no longer required.
// >> renamed 4v0 for release
// 4v1 24/9/2024 1st version using C++ Builder 12.1
// 1b - for x values allowed >= for "monotonic". Previoulsy required > which caused issues when we run out of resolution in a float (e.g. file csvfunbig.csv)
// 1c - better "fixup" for equal x values
// 1d - min abs/rel error fit improved (some calculations were done in double but should have been in float)
// - GMR line fit could generate a line with the wrong slope! - fixed
// 1e - let user select if equal x values are optimised or not. Only ask once if multiple traces added in a block.
// 1f - central moving average & cumulative average filters added
// 1g - central moving average filter - full (efficient) code in place
// 1h - start of new median filter code
// 1i - new median code fully working. Uses time to swap from exact to approximate algorithms.
// 1j - new median code optimised, and errors of approximate algorithms bounded
// 1k - cumulate average changed to Kalman filter as that's more useful.
// 1L - improved Kalman filter implementation
//
// TO DO:
//
// WARNING : in builder 11 with 64 bit code generation long double is only 8 bytes (the same as double!).
//
// Note if executable is called (eg) csvgraph64.exe then manual needs to be called csvgraph64.pdf
//
//---------------------------------------------------------------------------
/*----------------------------------------------------------------------------
* Copyright (c) 2019,2020,2021,2022,2023,2024 Peter Miller
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHOR OR COPYRIGHT HOLDER BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*--------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
#pragma option -w-inl /* turn off W8027 Functions containing switch are not expanded inline warning */
#include <vcl.h>
#include <Printers.hpp>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <jpeg.hpp> // for jpg image save
#include <pngimage.hpp> // for png image save
#include <GIFimg.hpp> // for gif image save
#include <Clipbrd.hpp>
#pragma hdrstop
#include "UScientificGraph.h"
#include "UScalesWindow.h"
#include "UDataPlotWindow.h"
#include "Unit1.h"
#include "About.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
// #pragma link "CSPIN"
#pragma resource "*.dfm"
#define NoForm1 /* says Form1 is defined in another file */
#include "rprintf.h"
#include "expr-code.h"
#include <sys\stat.h>
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <windows.h>
#include <commdlg.h> // to use GetOpenFileNameA
#include <dos.h>
#include <stdlib.h>
#include <float.h>
#include <values.h>
#include "matrix.h" /* must come before include of multiple-lin-reg.h */
#include "multiple-lin-reg-fn.h"
#include "time_local.h"
#include "getfloat.h"
#if 1
// I'm sorry for the next 2 lines, but otherwise I get a lot of warnings "zero as null pointer constant"
#undef NULL
#define NULL (nullptr)
#endif
extern TForm1 *Form1;
extern const char * Prog_Name;
#ifdef _WIN64
const char * Prog_Name="CSVgraph (Github) 4v1 (64 bit)"; // needs to be global as used in about box as well.
#else
const char * Prog_Name="CSVgraph (Github) 4v1 (32 bit)"; // needs to be global as used in about box as well.
#endif
#if 1 /* if 1 then use fast_strtof() rather than atof() for floating point conversion. Note in this application this is only slightly faster (1-5%) */
extern "C" float fast_strtof(const char *s,char **endptr); // if endptr != NULL returns 1st character thats not in the number
#define strtof fast_strtof /* set so we use it in place of strtof() */
#endif
#define WHITE_BACKGROUND /* if defined then use a white background, otherwise use a black background*/
#define UseVCLdialogs /* if defined used VCL dialogs, otherwise use "raw" windows ones */
#define BIG_BUF_SIZE (128*1024) /* Should be a power of 2. 1024*1024=1MB . Testing showed 4K is the min for moderate performance, and after 256k performance gets slightly worse */
/* times to read 2 columns from a 2BG file are no buf 126secs, 4k 78s, 8k 72s, 16k 71s, 32k 70s, 64k 69s, 128k 68s, 256k 68s, 512k 69s, 1024k 69s, 4096k 71s */
#define CL_BLOCK_SIZE (1024*1024) /* must be a bigish power of 2 , used for count_lines() function to quickly count lines in file 1M seems to be best on my PC */
#define P_UNUSED(x) (void)x; /* a way to avoid warning unused parameter messages from the compiler */
/* next 2 function used to support conversion to unicode vcl see https://blogs.embarcadero.com/migrating-legacy-c-builder-apps-to-c-builder-10-seattle/
*/
#define STR_CONV_BUF_SIZE 2000 // the largest string you may have to convert. depends on your project
static wchar_t* __fastcall Utf8_to_w(const char* c) // convert utf encoded string to wide chars - new function
{
static wchar_t w[STR_CONV_BUF_SIZE];
memset(w,0,sizeof(w));
MultiByteToWideChar(CP_UTF8, 0, c, -1, w, STR_CONV_BUF_SIZE-1); // utf-8 (this is a windows function ) size-1 to make sure output is always NULL terminated
return(w);
}
// the reverse function would use WideCharToMultiByte() - see https://stackoverflow.com/questions/69740993/wrong-handle-while-setting-text-to-richedit-control
// Below from https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
// modified Peter Miller 29-5-2024
// returns true for pure ascii string or valid utf8 string
static bool is_valid_utf8(const char * string);
static bool is_valid_utf8(const char * string)
{
if(!string)
return 0;
const unsigned char * bytes = (const unsigned char *)string; // in case char is signed
while(*bytes)
{
if( (// ASCII - only allow values that may reasonably be in a utf8 string
bytes[0] == 0x09 ||
bytes[0] == 0x0A ||
bytes[0] == 0x0D ||
(0x20 <= bytes[0] && bytes[0] <= 0x7E)
)
) {
bytes ++;
continue;
}
if( (// non-overlong 2-byte
(0xC2 <= bytes[0] && bytes[0] <= 0xDF) &&
(0x80 <= bytes[1] && bytes[1] <= 0xBF)
)
) {
bytes += 2;
continue;
}
if( (// excluding overlongs
bytes[0] == 0xE0 &&
(0xA0 <= bytes[1] && bytes[1] <= 0xBF) &&
(0x80 <= bytes[2] && bytes[2] <= 0xBF)
) ||
(// straight 3-byte
((0xE1 <= bytes[0] && bytes[0] <= 0xEC) ||
bytes[0] == 0xEE ||
bytes[0] == 0xEF) &&
(0x80 <= bytes[1] && bytes[1] <= 0xBF) &&
(0x80 <= bytes[2] && bytes[2] <= 0xBF)
) ||
(// excluding surrogates
bytes[0] == 0xED &&
(0x80 <= bytes[1] && bytes[1] <= 0x9F) &&
(0x80 <= bytes[2] && bytes[2] <= 0xBF)
)
) {
bytes += 3;
continue;
}
if( (// planes 1-3
bytes[0] == 0xF0 &&
(0x90 <= bytes[1] && bytes[1] <= 0xBF) &&
(0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
(0x80 <= bytes[3] && bytes[3] <= 0xBF)
) ||
(// planes 4-15
(0xF1 <= bytes[0] && bytes[0] <= 0xF3) &&
(0x80 <= bytes[1] && bytes[1] <= 0xBF) &&
(0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
(0x80 <= bytes[3] && bytes[3] <= 0xBF)
) ||
(// plane 16
bytes[0] == 0xF4 &&
(0x80 <= bytes[1] && bytes[1] <= 0x8F) &&
(0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
(0x80 <= bytes[3] && bytes[3] <= 0xBF)
)
) {
bytes += 4;
continue;
}
return false;
}
return true;
}
static char* __fastcall Utf8Of(wchar_t* w) /* convert to utf-8 encoding */
{
static char c[STR_CONV_BUF_SIZE];
memset(c, 0, sizeof(c));
WideCharToMultiByte(CP_UTF8, 0, w, -1, c, STR_CONV_BUF_SIZE-1, NULL, NULL); /* size-1 ensure result is null terminated */
return(c);
}
extern volatile int xchange_running;
extern volatile bool addtraceactive;
extern float yval,xval;
static int line_colour=0;
volatile int xchange_running=-1; // avoid running multiple instances of Edit_XoffsetChange() in parallel, but still do correct number of updates
volatile bool addtraceactive=false; // set to true when add trace active to avoid multiple clicks
static bool zoomed=false; // set when zoomed in to stop autoscaling when new traces added
static bool user_set_trace_colour=false;
static TColor user_trace_colour;
static size_t nos_lines_in_file=0; // number of lines in last file opened
static bool start_time_from_0=false; // if true use 1st time read is as ofset
float yval,xval; // current values being added to graph, xval is set before yval
// dynamic number of columns
static char **col_ptrs=NULL,**hdr_col_ptrs=NULL; // pointers to strings for each field
static char *col_names=NULL; // copy of input line, used to keep column heading strings
static unsigned int MAX_COLS=0;
static AnsiString filename;
const static char *default_x_label="Horizontal axis title";
const static char *default_y_label="Vertical axis title";
void proces_open_filename(char *fn); // open filename - just to peek at header row
// windows getfilename function
#ifndef UseVCLdialogs
static OPENFILENAME ofn; // common dialog box structure
static char szFile[260]; // buffer for file name
char *getfilename() // displays getfilename dialog and returns filename or "" if not entered
{
// Initialize OPENFILENAME
memset(&ofn,0, sizeof(ofn)); // zero memory
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Application->Handle ;// hwnd even NULL works.
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "All\0*.*\0Csv\0*.CSV\0";
ofn.nFilterIndex = 2;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.lpstrTitle= "Please select the CSV file you wish to read to draw graphs";
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn)==TRUE)
{// Got valid filename
return ofn.lpstrFile;
}
return ""; // no valid filename entered
}
#endif
#ifndef UseVCLdialogs
char *getsaveBMPfilename() // for saving files : displays getfilename dialog and returns filename or "" if not entered
{
// Initialize OPENFILENAME
memset(&ofn,0, sizeof(ofn)); // zero memory
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Application->Handle ;// hwnd even NULL works.
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Bmp\0*.BMP\0"; // allowed extensions
ofn.lpstrDefExt="BMP"; // default extension if user does not type one
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.lpstrTitle= "Please select the BMP filename you wish to save the graph in";
ofn.Flags = OFN_OVERWRITEPROMPT | OFN_NOREADONLYRETURN ;// warn user if file already exists, do not allow read only files or directories
// Display the Open dialog box.
if (GetSaveFileName(&ofn)==TRUE) // GetSaveFileName
{// Got valid filename
return ofn.lpstrFile;
}
return ""; // no valid filename entered
}
#endif
#ifndef UseVCLdialogs
char *getsaveCSVfilename() // for saving files : displays getfilename dialog and returns filename or "" if not entered
{
// Initialize OPENFILENAME
memset(&ofn,0, sizeof(ofn)); // zero memory
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Application->Handle ;// hwnd even NULL works.
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Csv\0*.CSV\0"; // allowed extensions
ofn.lpstrDefExt="CSV"; // default extension if user does not type one
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.lpstrTitle= "Please select the CSV filename you wish to save the data in";
ofn.Flags = OFN_OVERWRITEPROMPT | OFN_NOREADONLYRETURN ;// warn user if file already exists, do not allow read only files or directories
// Display the Open dialog box.
if (GetSaveFileName(&ofn)==TRUE) // GetSaveFileName
{// Got valid filename
return ofn.lpstrFile;
}
return ""; // no valid filename entered
}
#endif
// deal with drag n drop
void __fastcall TPlotWindow::WmDropFiles(TWMDropFiles& Message)
{
char buff[MAX_PATH];
HDROP hDrop = (HDROP)Message.Drop;
unsigned int numFiles = DragQueryFile(hDrop, -1, NULL, 0);
#if 1
if( numFiles==1)
{// just 1 file given - deal with it
//DragQueryFile(hDrop, 0, buff, sizeof(buff));
wchar_t wbuff[sizeof(buff)];
DragQueryFileW(hDrop, 0, wbuff, sizeof(wbuff));
char *tbuff=Utf8Of(wbuff);
strncpy(buff,tbuff,sizeof(buff)); // need to tke a copy as Utf8Of uses a static buffer and it may be called again...
// process the file in 'buff'
proces_open_filename(buff); // process file
}
else
{ ShowMessage("Error: you can only drag one file at a time onto CSVgraph");
}
#else
// accept multiple filenames - csvgraph cannot really deal with this and the code below effectively just loads the last one
for (int i=0;i < numFiles;i++)
{
DragQueryFile(hDrop, i, buff, sizeof(buff));
// process the file in 'buff'
proces_open_filename(buff); // process file
}
#endif
DragFinish(hDrop);
}
void __fastcall TPlotWindow::CreateParams(TCreateParams &Params)
{ // change format of window created by operating system
// see https://community.idera.com/developer-tools/b/blog/posts/multiple-windows-in-delphi
// and http://bcbjournal.org/bcbcaq/articles/fun3.htm
TForm::CreateParams(Params); // do all the standard builderc++ things
Params.ExStyle |= WS_EX_APPWINDOW; // also add the following flag which should make the minimise "icon" work as normally expected
#if 0
SetWindowLong(Application->Handle, GWL_EXSTYLE,
GetWindowLong(Application->Handle,GWL_EXSTYLE) & ~WS_EX_APPWINDOW | WS_EX_TOOLWINDOW ); // changes flags on application window
#endif
}
static int initial_ClientWidth,initial_ClientHeight,initial_Panel1_Width,initial_Panel1_Height; // sizes when form created
//---------------------------------------------------------------------------
// #define HIGH_DPI /* if true then application has high dpi set in project properties: application -> enable high dpi */
// #define BASE_WIDTH 1609 /* sizes assumed when windows created with form designer */
#define BASE_PWIDTH 1300 /* base panel1 width */
#define BASE_HEIGHT 980
#if 1 /* version that works with possibility to detach panel 2 */
__fastcall TPlotWindow::TPlotWindow(TComponent* Owner) : TForm(Owner)
{
Shape1->Visible = false; //mouse scaling rect
Caption = Prog_Name; //window caption
FilterType->ItemIndex=0; // select 1st item (none) otherwise no item is selected.
// save initial sizes [ used when we resize]
initial_ClientWidth=ClientWidth;
initial_ClientHeight=ClientHeight;
// initial_ClientWidth=1591 initial_ClientHeight=980 initial_Panel1_Width=1300 initial_Panel1_Height=980
Panel2->Width=Edit_y->Left + Edit_y->Width ; // make sure panel 2 is wide enough to fit widest (far right) item
Panel2->Left=ClientWidth-Panel2->Width ;
Panel1->Width =Panel2->Left-Panel1->Left; // resize if necessary so graph fits in leaving space for controls on right
Panel1->Height =initial_ClientHeight;
iBitmapHeight=Panel1->ClientHeight; //fit TScientificGraph-Bitmap in
iBitmapWidth=Panel1->ClientWidth; //TImage1-object in Panel1
//init ScientificGraph with Bitmap-
//size
initial_Panel1_Width=iBitmapWidth;
initial_Panel1_Height=iBitmapHeight;
// rprintf("initial_Panel1_Width=iBitmapWidth=%d initial_Panel1_Height=iBitmapHeight=%d\n",initial_Panel1_Width,initial_Panel1_Height);
#if 0
// code below attempts to realign right control panel but this does not work
// TRect control_area(ClientLeft,Panel1->Top,Panel1->Left+ClientWidth,Panel1->Top+Panel1->Height);// Left, Top, Right, Bottom
TRect control_area=ClientRect;
TPlotWindow::AlignControls(NULL,control_area) ;
#endif
pScientificGraph = new TScientificGraph(iBitmapWidth,iBitmapHeight);
#ifdef WHITE_BACKGROUND
pScientificGraph->ColBackGround = clWhite; //set colours, white background
pScientificGraph->ColGrid = clGray ;
pScientificGraph->ColAxis = clDkGray ;
pScientificGraph->ColText = clBlack;
Edit_title->Color=pScientificGraph->ColBackGround ; // needs to be the same as the background colour
Edit_title->Font->Color= pScientificGraph->ColText;
Label1->Font->Color= pScientificGraph->ColText;
Label2->Font->Color= pScientificGraph->ColText;
Color=clBtnFace ;
#else
pScientificGraph->ColBackGround = clBlack; //set colours, Black background
pScientificGraph->ColGrid = clOlive;
pScientificGraph->ColAxis = clRed;
pScientificGraph->ColText = clYellow;
Edit_title->Color=pScientificGraph->ColBackGround ; // needs to be the same as the background colour
Edit_title->Font->Color= pScientificGraph->ColText;
Label1->Font->Color= pScientificGraph->ColText;
Label2->Font->Color= pScientificGraph->ColText;
Color=clBtnFace ;
#endif
#define dLegendStartX_val 0.3 /* start position for graph ledgends X and Y */
#define dLegendStartY_val 0.99
#if 1 /* scale positions based on size */
// 0.1*initial_Panel1_Width/Panel1->ClientWidth;
pScientificGraph->fLeftBorder = 0.1f*BASE_PWIDTH/initial_Panel1_Width; //Borders of Plot in Bitmap in %/100 was 0.2
Edit_title->Width=Panel1->Width-Edit_title->Left-20; // allow to go to (nearly) the far edge (Title is centered)
pScientificGraph->fBottomBorder = 0.1f*BASE_HEIGHT/initial_Panel1_Height; // was 0.25
pScientificGraph->dLegendStartX=dLegendStartX_val; // Top left positions of trace legends in %/100 in Plot was 0.8 - don't need this to change if user rescaled main window
pScientificGraph->dLegendStartY=dLegendStartY_val; // was 0.95
#else
pScientificGraph->fLeftBorder = 0.1; //Borders of Plot in Bitmap in %/100 was 0.2
pScientificGraph->fBottomBorder = 0.1; // was 0.25
pScientificGraph->dLegendStartX=dLegendStartX_val; //Legend position in %/100 in Plot was 0.8
pScientificGraph->dLegendStartY=dLegendStartY_val; // was 0.95
#endif
pScientificGraph->bZeroLine=true; //zero line in plot
Edit_x->Text=default_x_label; // set default x label
Edit_y->Text=default_y_label; // set default y label
fnReDraw(); //redraw plot
}
#else
// original code does not work with panel 2 present when text is not 100%
__fastcall TPlotWindow::TPlotWindow(TComponent* Owner) : TForm(Owner)
{
int ofset= (ClientWidth-BASE_WIDTH); // adjust for change in width
Shape1->Visible = false; //mouse scaling rect
Caption = Prog_Name; //window caption
// save initial sizes [ used when we resize]
initial_ClientWidth=ClientWidth;
initial_ClientHeight=ClientHeight;
// initial_ClientWidth=1591 initial_ClientHeight=980 initial_Panel1_Width=1300 initial_Panel1_Height=980
Panel1->Width =Panel1->ClientWidth+(ofset); // resize if necessary so graph fits in leaving space for controls on right
Panel1->Height =initial_ClientHeight;
iBitmapHeight=Panel1->ClientHeight; //fit TScientificGraph-Bitmap in
iBitmapWidth=Panel1->ClientWidth; //TImage1-object in Panel1
//init ScientificGraph with Bitmap-
//size
initial_Panel1_Width=iBitmapWidth;
initial_Panel1_Height=iBitmapHeight;
// rprintf("initial_Panel1_Width=iBitmapWidth=%d initial_Panel1_Height=iBitmapHeight=%d\n",initial_Panel1_Width,initial_Panel1_Height);
if(ofset!=0)
{
#if 0
rprintf("initial_ClientWidth=%d initial_ClientHeight=%d initial_Panel1_Width=%d initial_Panel1_Height=%d, ofset=%d\n",
initial_ClientWidth,initial_ClientHeight,initial_Panel1_Width,initial_Panel1_Height,ofset);
rprintf("ListBoxX: top=%d left=%d height=%d width=%d\n",ListBoxX->Top,ListBoxX->Left , ListBoxX->Height , ListBoxX->Width );
#endif
if(ofset<0)
{// not room for all controls on the right bar, disable ones that are not essential , and move the remainder up
int voffset=Label6->Top ; // this must be subtracted from Top of remaining visible items to move them up
RadioGroup3->Visible =false;
RadioGroup2->Visible =false;
CheckBox3->Visible =false;
CheckBox1->Visible =false;
Label5->Visible =false;
Label11->Visible =false;
SpinEdit_Fontsize->Visible =false;
Label6->Top-=voffset;
Edit_y->Top-=voffset;
Label7->Top-=voffset;
Edit_x->Top-=voffset;
Label8->Top-=voffset;
StaticText_filename->Top-=voffset;
Xcol_type->Top-=voffset;
Label3->Top-=voffset;
Edit_xcol->Top-=voffset;
Label9->Top-=voffset;
Edit_Xoffset->Top-=voffset;
ListBoxX->Top-=voffset;
Label4->Top-=voffset;
Edit_ycol->Top-=voffset;
ListBoxY->Top-=voffset;
FilterType->Top-=voffset;
CheckBox_Compress->Top-=voffset;
Label10->Top-=voffset;
Edit_median_len->Top-=voffset;
Button_Filename->Top-=voffset;
Button_add_trace->Top-=voffset;
Button_clear_all_traces->Top-=voffset;
StatusText->Top-=voffset;
Label15->Top-=voffset;
Label16->Top-=voffset;
Edit_skip_lines->Top-=voffset;
}
// move all controls in bar on right
RadioGroup3->Left+=ofset;
RadioGroup2->Left+=ofset;
CheckBox3->Left+=ofset;
CheckBox1->Left+=ofset;
Label5->Left+=ofset;
Label11->Left+=ofset;
SpinEdit_Fontsize->Left+=ofset;
Label6->Left+=ofset;
Edit_y->Left+=ofset;
Label7->Left+=ofset;
Edit_x->Left+=ofset;
Label8->Left+=ofset;
StaticText_filename->Left+=ofset;
Xcol_type->Left+=ofset;
Label3->Left+=ofset;
Edit_xcol->Left +=ofset;
Label9->Left+=ofset;
Edit_Xoffset->Left+=ofset;
ListBoxX->Left += ofset;
Label4->Left+=ofset;
Edit_ycol->Left +=ofset;
ListBoxY->Left +=ofset;
FilterType->Left +=ofset;
CheckBox_Compress->Left +=ofset;
Label10->Left+=ofset;
Edit_median_len->Left +=ofset;
Button_Filename->Left +=ofset;
Button_add_trace->Left +=ofset;
Button_clear_all_traces->Left +=ofset;
StatusText->Left +=ofset;
Label5->Left+=ofset;
Label6->Left+=ofset;
Edit_skip_lines->Left+=ofset;
// rprintf("updated ListBoxX: top=%d left=%d height=%d width=%d\n",ListBoxX->Top,ListBoxX->Left , ListBoxX->Height , ListBoxX->Width );
}
#if 0
// code below attempts to realign right control panel but this does not work
// TRect control_area(ClientLeft,Panel1->Top,Panel1->Left+ClientWidth,Panel1->Top+Panel1->Height);// Left, Top, Right, Bottom
TRect control_area=ClientRect;
TPlotWindow::AlignControls(NULL,control_area) ;
#endif
pScientificGraph = new TScientificGraph(iBitmapWidth,iBitmapHeight);
#ifdef WHITE_BACKGROUND
pScientificGraph->ColBackGround = clWhite; //set colours, white background
pScientificGraph->ColGrid = clGray ;
pScientificGraph->ColAxis = clDkGray ;
pScientificGraph->ColText = clBlack;
Edit_title->Color=pScientificGraph->ColBackGround ; // needs to be the same as the background colour
Edit_title->Font->Color= pScientificGraph->ColText;
Label1->Font->Color= pScientificGraph->ColText;
Label2->Font->Color= pScientificGraph->ColText;
Color=clBtnFace ;
#else
pScientificGraph->ColBackGround = clBlack; //set colours, Black background
pScientificGraph->ColGrid = clOlive;
pScientificGraph->ColAxis = clRed;
pScientificGraph->ColText = clYellow;
Edit_title->Color=pScientificGraph->ColBackGround ; // needs to be the same as the background colour
Edit_title->Font->Color= pScientificGraph->ColText;
Label1->Font->Color= pScientificGraph->ColText;
Label2->Font->Color= pScientificGraph->ColText;
Color=clBtnFace ;
#endif
#if 1 /* scale positions based on size */
// 0.1*initial_Panel1_Width/Panel1->ClientWidth;
pScientificGraph->fLeftBorder = 0.1*BASE_PWIDTH/initial_Panel1_Width; //Borders of Plot in Bitmap in %/100 was 0.2
pScientificGraph->fBottomBorder = 0.1*BASE_HEIGHT/initial_Panel1_Height; // was 0.25
pScientificGraph->dLegendStartX=dLegendStartX_val; // Top left positions of trace legends in %/100 in Plot was 0.8 - don't need this to change if user rescaled main window
pScientificGraph->dLegendStartY=dLegendStartY_val; // was 0.95
#else
pScientificGraph->fLeftBorder = 0.1; //Borders of Plot in Bitmap in %/100 was 0.2
pScientificGraph->fBottomBorder = 0.1; // was 0.25
pScientificGraph->dLegendStartX=dLegendStartX_val; //Legend position in %/100 in Plot was 0.8
pScientificGraph->dLegendStartY=dLegendStartY_val; // was 0.95
#endif
pScientificGraph->bZeroLine=true; //zero line in plot
Edit_x->Text=default_x_label; // set default x label
Edit_y->Text=default_y_label; // set default x label
fnReDraw(); //redraw plot
}
#endif
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::FormDestroy(TObject *Sender)
{ P_UNUSED(Sender);
delete pScientificGraph; //free memory
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::FormClose(TObject *Sender,
TCloseAction &Action)
{ P_UNUSED(Sender);
P_UNUSED(Action);
DragAcceptFiles(Handle, false); // stop accepting drag n drop files
exit(1); // close this screen exits application
// Action = caMinimize; //not allowed to close the window
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ResizeExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnResize(); //resize graph
Image1->Picture->Assign(pScientificGraph->pBitmap); //copy bitmap
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ShiftYMinusExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnShiftYMinus(); //shift
Image1->Picture->Assign(pScientificGraph->pBitmap); //copy bitmap
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ShiftYPlusExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnShiftYPlus(); //see above
Image1->Picture->Assign(pScientificGraph->pBitmap);
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ShiftXMinusExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnShiftXMinus(); //see above
Image1->Picture->Assign(pScientificGraph->pBitmap);
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ShiftXPlusExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnShiftXPlus(); //see above
Image1->Picture->Assign(pScientificGraph->pBitmap);
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ZoomOutYExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnZoomOutY(); //see above
Image1->Picture->Assign(pScientificGraph->pBitmap);
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ZoomInYExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnZoomInY(); //see above
Image1->Picture->Assign(pScientificGraph->pBitmap);
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ZoomOutXExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnZoomOutXFromLeft(); //see above
Image1->Picture->Assign(pScientificGraph->pBitmap);
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::ZoomInXExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnZoomInXFromLeft(); //see above
Image1->Picture->Assign(pScientificGraph->pBitmap);
zoomed=true;
}
//---------------------------------------------------------------------------
void __fastcall TPlotWindow::Scales1Click(TObject *Sender)
{ P_UNUSED(Sender);
pScalesWindow = new TScalesWindow(this,pScientificGraph); //Input Window
pScalesWindow->ShowModal();
pScientificGraph->fnOptimizeGrids(); //grids
pScientificGraph->fnPaint(); //repaint
Image1->Picture->Assign(pScientificGraph->pBitmap); //assign
zoomed=true;
}
//------------------------------------------------------------------------------
void __fastcall TPlotWindow::AutoScaleExecute(TObject *Sender)
{ P_UNUSED(Sender);
pScientificGraph->fnAutoScale(); //autoscale graph
pScientificGraph->fnPaint(); //paint
Image1->Picture->Assign(pScientificGraph->pBitmap); //copy bitmap
zoomed=false;
}
//------------------------------------------------------------------------------
// defines for line drawn on right mouse click ("measure"). Used 3 times and each must be identicel for code to work.
#define RT_CLICK_Width 3 /* width of line in pixels */
#define RT_CLICK_Style psSolid /* other options don't appear to work [ even with width=1] */
#define RT_CLICK_Mode pmXor /* has to be XOR as we want to be able to erase line be redrawing it */
#define RT_CLICK_Color clWhite /* white also seems to be the best choice for visibility */
#define RT_CLICK_A_size 6 /* length of arrow, 0 means no arrow drawn on end of line */
static void Mouse_line(TImage * I1,int a,int b,int d,int e)
{// draw line for right mouse key from x=a,y=b to x=d,y=e
I1->Canvas->Pen->Width=RT_CLICK_Width;
I1->Canvas->Pen->Style=RT_CLICK_Style;
I1->Canvas->Pen->Mode=RT_CLICK_Mode;
I1->Canvas->Pen->Color=RT_CLICK_Color;
I1->Canvas->MoveTo(a,b);
I1->Canvas->LineTo(d,e);
#if RT_CLICK_A_size>0
#if 1
/* draw arrow on line has to use a slightly different approach for vertical lines, >45 deg lines and < 45 deg "horizontal lines" */
/* Algorithm below believed to be novel, created by Peter Miller 10/2020 */
/* this version is better in that it avoids "jmp" at 45 deg */
double m,c; // line is y=mx+c
if(a!=d)
{m=(b-e)/(double)(a-d); // a==d is trapped in if above
c=b-m*a;
}
else
{m=c=0.0; // these values should not ever be used...
}
if(a==d )
{// "vertical line" (only exactly vertical line processed here [traps m=infinity])
if(b<e)
{int t=b; // swap ends
b=e;e=t;
t=d; d=a; a=t;
}
// now b>=e
I1->Canvas->MoveTo(a,b);
I1->Canvas->LineTo(a-RT_CLICK_A_size,b-RT_CLICK_A_size);
I1->Canvas->MoveTo(a,b);
I1->Canvas->LineTo(a+RT_CLICK_A_size,b-RT_CLICK_A_size);
I1->Canvas->MoveTo(d,e);
I1->Canvas->LineTo(d-RT_CLICK_A_size,e+RT_CLICK_A_size);
I1->Canvas->MoveTo(d,e);
I1->Canvas->LineTo(d+RT_CLICK_A_size,e+RT_CLICK_A_size);
}
else if(fabs(m)>=1) // was >= 1.0
{ // vertical > 45 deg (not completely vertical thats done above) y=m*x+c so x=(y-c)/m
int miny,maxy,x1,x2;
if(b<e) {miny=b;maxy=e;x1=a;x2=d;} // line from minx to maxx
else {miny=e;maxy=b;x1=d;x2=a;}
double dy=(RT_CLICK_A_size/m)+0.5; // arrow shape correction, keeps arrow ~ the same size as it rotates
I1->Canvas->MoveTo(x1,miny); // top
I1->Canvas->LineTo((int)((miny+RT_CLICK_A_size-c)/m+0.5+RT_CLICK_A_size),(int)(miny+RT_CLICK_A_size-dy)); // 0.5 for rounding float to int
I1->Canvas->MoveTo(x1,miny); // top
I1->Canvas->LineTo((int)((miny+RT_CLICK_A_size-c)/m-0.5-RT_CLICK_A_size),(int)(miny+RT_CLICK_A_size+dy));
I1->Canvas->MoveTo(x2,maxy); // bottom
I1->Canvas->LineTo((int)((maxy-RT_CLICK_A_size-c)/m+0.5+RT_CLICK_A_size),(int)(maxy-RT_CLICK_A_size-dy));
I1->Canvas->MoveTo(x2,maxy); // bottom
I1->Canvas->LineTo((int)((maxy-RT_CLICK_A_size-c)/m-0.5-RT_CLICK_A_size),(int)(maxy-RT_CLICK_A_size+dy));
}
else
{ // "horizontal line (< 45 deg)" y=m*x+c
int minx,maxx,y1,y2;
if(a<d) {minx=a;maxx=d;y1=b;y2=e;} // line from minx to maxx
else {minx=d;maxx=a;y1=e;y2=b;}
double dx=RT_CLICK_A_size*m+0.5; // arrow shape correction, keeps arrow ~ the same size as it rotates
I1->Canvas->MoveTo(minx,y1); // left end
I1->Canvas->LineTo((int)(minx+RT_CLICK_A_size+dx),(int)(m*(minx+RT_CLICK_A_size)+c-RT_CLICK_A_size-0.5)); // 0.5 for rounding float to int
I1->Canvas->MoveTo(minx,y1); // left end
I1->Canvas->LineTo((int)(minx+RT_CLICK_A_size-dx),(int)(m*(minx+RT_CLICK_A_size)+c+RT_CLICK_A_size+0.5));
I1->Canvas->MoveTo(maxx,y2); // right end
I1->Canvas->LineTo((int)(maxx-RT_CLICK_A_size+dx),(int)(m*(maxx-RT_CLICK_A_size)+c-RT_CLICK_A_size-0.5));
I1->Canvas->MoveTo(maxx,y2); // right end
I1->Canvas->LineTo((int)(maxx-RT_CLICK_A_size-dx),(int)(m*(maxx-RT_CLICK_A_size)+c+RT_CLICK_A_size+0.5));
}
#else /* use v12.2 algorithm (which is not bad) */
/* draw arrow on line has to use a slightly different approach for vertical lines, >45 deg lines and < 45 deg "horizontal lines" */
/* Algorithm below believed to be novel, created by Peter Miller 10/2020 */
double m,c; // line is y=mx+c
if(a!=d)
{m=(b-e)/(double)(a-d); // a==d is trapped in if above
c=b-m*a;
}
else
{m=c=0.0; // these values should not ever be used...
}
if(a==d )
{// "vertical line" (only exactly vertical line processed here [traps m=infinity])
if(b<e)
{int t=b; // swap ends
b=e;e=t;
t=d; d=a; a=t;
}
// now b>=e
I1->Canvas->MoveTo(a,b);
I1->Canvas->LineTo(a-RT_CLICK_A_size,b-RT_CLICK_A_size);
I1->Canvas->MoveTo(a,b);
I1->Canvas->LineTo(a+RT_CLICK_A_size,b-RT_CLICK_A_size);
I1->Canvas->MoveTo(d,e);
I1->Canvas->LineTo(d-RT_CLICK_A_size,e+RT_CLICK_A_size);
I1->Canvas->MoveTo(d,e);
I1->Canvas->LineTo(d+RT_CLICK_A_size,e+RT_CLICK_A_size);
}
else if(fabs(m)>=1.0) // was >= 1.0
{ // vertical > 45 deg (not completely vertical thats done above) y=m*x+c so x=(y-c)/m
int miny,maxy,x1,x2;
if(b<e) {miny=b;maxy=e;x1=a;x2=d;} // line from minx to maxx
else {miny=e;maxy=b;x1=d;x2=a;}
double dx=0.2*(RT_CLICK_A_size/m); // arrow shape correction, keeps arrow ~ the same size as it rotates
I1->Canvas->MoveTo(x1,miny); // top
I1->Canvas->LineTo((miny+RT_CLICK_A_size-c)/m+0.5+RT_CLICK_A_size+fabs(dx),miny+RT_CLICK_A_size-dx-0.5); // 0.5 for rounding float to int
I1->Canvas->MoveTo(x1,miny); // top
I1->Canvas->LineTo((miny+RT_CLICK_A_size-c)/m-0.5-RT_CLICK_A_size-fabs(dx),miny+RT_CLICK_A_size+dx+0.5);
I1->Canvas->MoveTo(x2,maxy); // bottom
I1->Canvas->LineTo((maxy-RT_CLICK_A_size-c)/m+0.5+RT_CLICK_A_size+fabs(dx),maxy-RT_CLICK_A_size-dx-0.5);
I1->Canvas->MoveTo(x2,maxy); // bottom
I1->Canvas->LineTo((maxy-RT_CLICK_A_size-c)/m-0.5-RT_CLICK_A_size-fabs(dx),maxy-RT_CLICK_A_size+dx+0.5);
}
else
{ // "horizontal line (< 45 deg)" y=m*x+c
int minx,maxx,y1,y2;
if(a<d) {minx=a;maxx=d;y1=b;y2=e;} // line from minx to maxx
else {minx=d;maxx=a;y1=e;y2=b;}
double dy=0.2*RT_CLICK_A_size*m; // arrow shape correction, keeps arrow ~ the same size as it rotates
I1->Canvas->MoveTo(minx,y1); // left end
I1->Canvas->LineTo(minx+RT_CLICK_A_size+dy+0.5,m*(minx+RT_CLICK_A_size)+c-RT_CLICK_A_size-0.5-fabs(dy)); // 0.5 for rounding float to int
I1->Canvas->MoveTo(minx,y1); // left end
I1->Canvas->LineTo(minx+RT_CLICK_A_size-dy-0.5,m*(minx+RT_CLICK_A_size)+c+RT_CLICK_A_size+0.5+fabs(dy));
I1->Canvas->MoveTo(maxx,y2); // right end
I1->Canvas->LineTo(maxx-RT_CLICK_A_size+dy+0.5,m*(maxx-RT_CLICK_A_size)+c-RT_CLICK_A_size-0.5-fabs(dy));
I1->Canvas->MoveTo(maxx,y2); // right end