Calculator created by MATLAB

This is a MATLAB GUI code for an advanced calculator with multiple functions.

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
function calculatorAdvanced
% Create a figure for the calculator
h.fig = figure('Name', 'Simple Calculator', ...
'NumberTitle', 'off', ...
'MenuBar', 'none', ...
'Resize', 'off', ...
...'Resize', 'on', ...
'Position', [800, 500, 300, 330]... Adjust the position and size as needed
,'Alphamap',0.2 ...
,'Color',[0.95 0.95 0.95]...[87 86 84]/255 ...
...,'Visible','off'...
,'WindowKeyPressFcn',@keyPressCallback); % Listen for key presses

lastOperator = ''; % To store the last operator used
lastOperand = ''; % To store the last operand used
h.figOriginPosition = h.fig.Position;

% Create the main panel
h.panel = uipanel('Parent', h.fig, ...
'Position', [0, 0, 1, 1]);

% Add a logo to the main panel
logoImage = imread('logo.jpg'); % Replace 'logo.png' with the path to your logo image
logoAxes = axes('Parent', h.panel, ...
'Units','Pixels',...
'Position', [100, 150, 100, 100], ...
'Visible', 'off');
image(logoImage, 'Parent', logoAxes);
% axis(logoAxes, 'image');
axis equal
axis off



%% Calculator
% Create the button to open the calculator interface
h.openButton = uicontrol('Parent', h.panel, ...
'Style', 'pushbutton', ...
'Position', [50, 260, 200, 40], ...
'String', 'Open Calculator', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @openCalculator);


% Callback function for opening the calculator interface
function openCalculator(~, ~)
% Hide the main panel and show the calculator interface
set(h.panel, 'Visible', 'off');
set(h.fig, 'Color', 'white');
% set(h.fig, 'WindowKeyPressFcn', @calculatorKeyPressCallback);
% Create the calculator interface
createCalculatorInterface();
end


% Create the calculator interface
function createCalculatorInterface()
% Create a panel for the calculator interface
h.calculatorPanel = uipanel('Parent', h.fig, ...
'Position', [0, 0, 1, 1]);
% Display for the calculator
h.display = uicontrol('Parent',h.calculatorPanel,'Style', 'edit', ...
'Position', [60+30, 245, 280-80, 30], ...
'FontSize', 18, ...
'BackgroundColor', [1 1 1], ...[46 45 36]/255, ...
'HorizontalAlignment', 'right', ...
'ForegroundColor',[0.1 0.1 0.1],...
'FontWeight','Bold',...
'String', '');

h.display2 = uicontrol('Parent',h.calculatorPanel,'Style', 'edit', ...
'Position', [60+30, 278, 280-80, 40], ...
'FontSize', 12, ...
'BackgroundColor', [1 1 1], ...[46 45 36]/255, ...
'HorizontalAlignment', 'right', ...
'ForegroundColor',[0.3 0.3 0.3],...
'String', '');

% Button size and padding
btnSize = [50, 40]; % Width, height
padding = [7, 7]; % Padding between buttons
startPos = [10, 200]; % Starting position of the first button

% Button labels
% btns = {'7', '8', '9', '+', 'C'; ...
% '4', '5', '6', '-', 'CE'; ...
% '1', '2', '3', '*', '='; ...
% '0', '', '.', '/', ''};
btns = {char(9003), 'CE', 'C', char(177), char(8730); ...
'7', '8', '9', '/', '%'; ...
'4', '5', '6', '*', '1/x'; ...
'1', '2', '3', '-', '=';...
'0','','.','+',''};

% Create the buttons in a grid
numRows = size(btns, 1);
numCols = size(btns, 2);
h.btn = zeros(numRows, numCols);
for row = 1:numRows
for col = 1:numCols
btnVal = btns{row, col};
if ~isempty(btnVal)
btnWidth = btnSize(1);
btnHeight = btnSize(2);
% Adjust '=' button to span two rows
if strcmp(btnVal, '=')
btnHeight = btnHeight * 2 + padding(2);
btnPosition = [startPos(1) + (col - 1) * (btnSize(1) + padding(1)), ...
startPos(2) - (row - 1) * (btnSize(2) + padding(2)) - padding(2) - btnSize(2), ...
btnWidth, btnHeight];
elseif strcmp(btnVal, '0')
btnWidth = btnWidth * 2 + padding(1);
btnPosition = [startPos(1) + (col - 1) * (btnSize(1) + padding(1)), ...
startPos(2) - (row - 1) * (btnSize(2) + padding(2)) ...
btnWidth, btnHeight];
else
btnPosition = [startPos(1) + (col - 1) * (btnSize(1) + padding(1)), ...
startPos(2) - (row - 1) * (btnSize(2) + padding(2)), ...
btnWidth, btnHeight];
end

h.btn(row, col) = uicontrol('Parent',h.calculatorPanel,'Style', 'pushbutton', ...
'Position', btnPosition, ...
'String', btnVal, ...
'FontSize', 16, ...
'BackgroundColor',[0.94 0.94 0.94], ...
'ForegroundColor',[50 50 50]/255,...
'Callback', {@btnCallback, btnVal});

end
end
end


% Create the button to return to the main panel
h.returnButton = uicontrol('Parent', h.calculatorPanel, ...
'Style', 'pushbutton', ...
'Position', [10 245 80 60], ...
'String', 'Return', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @returnToMainPanel);

end

% Callback function for button clicks
function btnCallback(src, ~, btnVal)
current = get(h.display2, 'String');

switch btnVal
case {'+', '-', '*', '/'}
% Do not add an operator if the string is empty or already ends with an operator
if ~isempty(current)% && ~any(current(end) == '+-*/')
set(h.display2, 'String', [current btnVal]);
% result = eval(current);
% set(h.display, 'String', num2str(result));
% set(h.display2, 'String', result);
if any(current(end) == '+-*/')
set(h.display2, 'String', [current(1:end-1) btnVal]);
end
end
case 'CE'
% Clear the last entry
if ~isempty(current)
set(h.display2, 'String', current(1:end-1));
end
case '='
% Calculate the result or repeat the last operation
if isempty(lastOperator) || isempty(lastOperand)
% If there's no last operation, perform the current calculation
try
result = eval(current);
set(h.display, 'String', num2str(result));
% Store the last operand and operator for repeated "=" presses
tokens = regexp(current, '(.*?)([\+\-\*\/])(\d+\.?\d*)$', 'tokens');
if ~isempty(tokens)
lastOperator = tokens{1}{2};
lastOperand = tokens{1}{3};
end
catch
% If there's an error in evaluation, display an error message
set(h.display, 'String', 'Error');
end
else
% If there's a last operation, repeat it with the current result
try
% Get the current result to use as the first operand
currentResult = get(h.display, 'String');
% Repeat the operation using the last operand and operator
newExpression = [currentResult lastOperator lastOperand];
result = eval(newExpression);
set(h.display, 'String', num2str(result));
set(h.display2,'String',[get(h.display2, 'String') lastOperator lastOperand])
catch
% If there's an error, clear last operation and display an error message
lastOperator = '';
lastOperand = '';
set(h.display, 'String', 'Error');
end
end
% Clear the last operation if 'C' is pressed
case 'C'
lastOperator = '';
lastOperand = '';
set(h.display, 'String', '');
set(h.display2, 'String', '');
case char(9003)
% Delete the last character
if ~isempty(current)
set(h.display2, 'String', current(1:end-1));
end
case char(177)
% Plus-minus (change sign)
tokens = regexp(current, '(.*?)([\+\-\*\/]|^)(\d+\.?\d*)$', 'tokens');
if ~isempty(tokens)
% tokens{1} should be a cell with the parts: {before, operator, number}
before = tokens{1}{1};
operator = tokens{1}{2};
lastNum = tokens{1}{3};

if isempty(operator)
operator = '-';
elseif strcmp(operator(end),'-')
operator(end) = '+';
elseif strcmp(operator(end),'+')
operator(end) = '-';

end

% Reconstruct the display string
newDisplay = [before, operator, lastNum];
set(h.display2, 'String', newDisplay);
end

case char(8730)
tokens = regexp(current, '(.*?)([\+\-\*\/]|^)(\d+\.?\d*)$', 'tokens');
if ~isempty(tokens)
% tokens{1} should be a cell with the parts: {before, operator, number}
before = tokens{1}{1};operator = tokens{1}{2};lastNum = tokens{1}{3};
% Take the square root of the last number
sqrtLastNum = num2str(sqrt(str2double(lastNum)));

% Reconstruct the display string
newDisplay = [before, operator, sqrtLastNum];
set(h.display2, 'String', newDisplay);
end

case '%'
tokens = regexp(current, '(.*?)([\+\-\*\/]|^)(\d+\.?\d*)$', 'tokens');
if ~isempty(tokens)
% tokens{1} should be a cell with the parts: {before, operator, number}
before = tokens{1}{1};operator = tokens{1}{2};lastNum = tokens{1}{3};

% Take the square root of the last number
sqrtLastNum = num2str(str2double(lastNum)*0.01);

% Reconstruct the display string
newDisplay = [before, operator, sqrtLastNum];
set(h.display2, 'String', newDisplay);
end
otherwise
% For numbers and decimal point, append to the display
set(h.display2, 'String', [current btnVal]);
end

set(src, 'enable', 'off');
drawnow;
set(src, 'enable', 'on');
end


% Key press callback function
function keyPressCallback(~, event)
% Mapping from key names to button labels
keyToButtonMap = containers.Map(...
{'numpad0', 'numpad1', 'numpad2', 'numpad3', 'numpad4', ...
'numpad5', 'numpad6', 'numpad7', 'numpad8', 'numpad9', ...
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ...
'add', 'plus', 'subtract', 'minus', 'multiply', 'divide', ...
'decimal', 'period', 'return', 'equal','enter' ,'escape', 'c', ...
'backspace', 'ce'}, ...
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ...
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ...
'+', '+', '-', '-', '*', '/', '.', '.', '=', '=', '=', ...
'C', 'C', 'CE', 'CE'});
% Get the button label from the map if it exists
if keyToButtonMap.isKey(event.Key)
btnVal = keyToButtonMap(event.Key);
btnCallback([], [], btnVal); % Call the button callback directly
end

end


%% Word Lookup
% Create the button to open the English word lookup interface
h.wordButton = uicontrol('Parent', h.panel, ...
'Style', 'pushbutton', ...
'Position', [50, 100, 200, 40], ...
'String', 'English Word Lookup', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @openWordLookupInterface);
% Callback function for opening the English word lookup interface
function openWordLookupInterface(~, ~)
% Hide the main panel and show the word lookup interface
set(h.panel, 'Visible', 'off');
set(h.fig, 'Color', 'white');
set(h.fig, 'WindowKeyPressFcn', @wordLookupKeyPressCallback);

% Create the word lookup interface
createWordLookupInterface();
end

% Create the word lookup interface
function createWordLookupInterface()
% Create a panel for the word lookup interface
h.wordLookupPanel = uipanel('Parent', h.fig, ...
'Position', [0, 0, 1, 1]);

% Create a button to return to the main panel
h.returnButton = uicontrol('Parent', h.wordLookupPanel, ...
'Style', 'pushbutton', ...
'Position', [50, 50, 200, 40], ...
'String', 'Return to Main Panel', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @returnToMainPanel);

% Create a button to select an Excel file and load the data
h.selectButton = uicontrol('Parent', h.wordLookupPanel, ...
'Style', 'pushbutton', ...
'Position', [50, 100, 200, 40], ...
'String', 'Select Excel File', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @selectExcelFile);

% Create an edit box for typing English words
h.editEnglish = uicontrol('Parent', h.wordLookupPanel, ...
'Style', 'edit', ...
'Position', [50, 180, 200, 30], ...
'FontSize', 14, ...
'BackgroundColor', [1 1 1], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', @lookupTranslation);

% h.displayEnglish = uicontrol('Parent', h.wordLookupPanel, ...
% 'Style', 'text', ...
% 'Position', [50, 180, 60, 30], ...
% 'FontSize', 14, ...
% 'BackgroundColor','none', ...
% 'HorizontalAlignment', 'left', ...
% 'String', 'English', ...
% 'Callback', @lookupTranslation);

% Set the key press callback function for the edit box
set(h.editEnglish, 'KeyPressFcn', @wordLookupKeyPressCallback);

% Create a text box for displaying corresponding Chinese translations
h.textChinese = uicontrol('Parent', h.wordLookupPanel, ...
'Style', 'text', ...
'Position', [50, 220, 200, 30], ...
'FontSize', 14, ...
'BackgroundColor', [1 1 1], ...
'HorizontalAlignment', 'left', ...
'String', '');

% Create a button to trigger the lookup operation
h.lookupButton = uicontrol('Parent', h.wordLookupPanel, ...
'Style', 'pushbutton', ...
'Position', [50, 260, 60, 40], ...
'String', 'Lookup', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @lookupButtonCallback);
end

% Callback function for selecting an Excel file and loading the data
function selectExcelFile(~, ~)
% Prompt the user to select an Excel file
[fileName, pathName] = uigetfile('*.xlsx', 'Select Excel File');

% Check if the user clicked Cancel
if fileName == 0
return;
end

% Construct the full file path
filePath = fullfile(pathName, fileName);

% Read the Excel file
try
dataTable = readcell(filePath);
h.data = dataTable(:,1:2);
catch ME
errordlg('Error reading Excel file.', 'Error', 'modal');
return;
end

end
% Callback function for looking up the translation
function lookupTranslation(src, ~)
englishWord = string(get(src, 'String'));

% Check if the loaded data is empty or not
if ~isfield(h,'data')
set(h.textChinese, 'String', 'No Dictionary Loaded');
return;
end

% Find the corresponding translation in the loaded data
% (Assuming the first column contains English words and the second column contains Chinese translations)
englishColumn = string(h.data(:, 1));
[~, idx] = ismember(englishWord, englishColumn);

if idx > 0
chineseTranslation = h.data(idx, 2);
set(h.textChinese, 'String', chineseTranslation{1});
else
set(h.textChinese, 'String', 'Translation not found');
end
end

% Callback function for the lookup button
function lookupButtonCallback(~, ~)
lookupTranslation(h.editEnglish);
end


% Key press callback function for the word lookup interface
function wordLookupKeyPressCallback(~, event)
% Get the key value from the event
keyValue = event.Key;

% Check if the key value is 'return' or 'enter'
if strcmpi(keyValue, 'return') || strcmpi(keyValue, 'enter')
lookupTranslation(h.editEnglish);
end
end


%% Stock Market
%%% Stock Market Interface %%%

% Create the button to open the Stock Market interface
h.StockButton = uicontrol('Parent', h.panel, ...
'Style', 'pushbutton', ...
'Position', [50, 40, 200, 40], ...
'String', 'Stock Market', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @openStockMarketInterface);

function openStockMarketInterface(~, ~)
set(h.panel, 'Visible', 'off');
set(h.fig, 'Color', 'white');
% set(h.fig, 'WindowKeyPressFcn', @wordLookupKeyPressCallback);
createStockMarketInterface();
end

% Create the word lookup interface
function createStockMarketInterface()
% Create a panel for the interface

h.fig.Position = [300 400 500 600];
h.StockMarketPanel = uipanel('Parent', h.fig, ...
'Position', [0, 0, 1, 1]);

% Create a button to return to the main panel
h.returnButton = uicontrol('Parent', h.StockMarketPanel, ...
'Style', 'pushbutton', ...
'Position', [50, 10, 180, 30], ...
'String', 'Return to Main Panel', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @returnToMainPanel);


h.webSite = uicontrol('Parent', h.StockMarketPanel, ...
'Style', 'text', ...
'Position', [105, 545, 300, 40], ...
'String', '搜狐证券上证指数历史数据爬取', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255 ..., ...
... 'Callback', @selectExcelFile
);

h.webButton = uicontrol('Parent', h.StockMarketPanel, ...
'Style', 'pushbutton', ...
'Position', [50, 50, 180, 30], ...
'String', 'Crawl a website', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @getWebData);

% Create a table within the figure
columnNames = {'日期', '开盘价', '收盘价', '最低价', '最高价'};
h.webTable = uitable('Parent',h.StockMarketPanel, 'Position', [50, 100, 420, 450], 'ColumnName', columnNames);
% Store the table handle in the button's UserData for later access in the callback
h.webButton.UserData = h.webTable;



% Button to export table data to Excel
h.exportExcelButton = uicontrol('Parent', h.StockMarketPanel, ...
'Style', 'pushbutton', ...
'Position', [300, 50, 180, 30], ...
'String', 'Export to Excel', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @exportToExcel);

% Button to export table data to TXT
h.exportTxtButton = uicontrol('Parent', h.StockMarketPanel, ...
'Style', 'pushbutton', ...
'Position', [300, 10, 180, 30], ...
'String', 'Export to TXT', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @exportToTxt);

h.webPlottingPanel = uipanel('Parent',h.StockMarketPanel,'Units',h.webTable.Units,'Position', h.webTable.Position);

h.webPlottingPanel.Visible = 'off';

% Button to plot table data
h.plotToggleButton = uicontrol('Parent', h.StockMarketPanel, ...
'Style', 'pushbutton', ...
'Position', [10, 558, 60, 30], ...
'String', 'Plot', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
'Callback', @createToggleButton);

end



function historicalStructArray = getWebData(src, ~)
h.webTable = src.UserData;
url = 'https://q.stock.sohu.com/hisHq?code=zs_000001&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp&0.41374664091573843';
jsonpStr = webread(url);
% Use regexprep to remove the padding around the JSON object
jsonStr = regexprep(jsonpStr, '^[^(]*\((.*)\)[^)]*$', '$1');
% Parse the JSON string into a MATLAB structure
data1 = jsondecode(jsonStr);
% Access the 'hq' data which contains historical stock data
historicalData = data1.hq;

% Now process `historicalData` as needed.
% Initialize an empty struct array with the fields you mentioned
historicalStructArray = struct('date', {}, 'openPrice', {}, 'closePrice', {}, ...
'priceChange', {}, 'percentChange', {}, 'lowPrice', {}, ...
'highPrice', {}, 'volume', {}, 'anotherFinancialFigure', {}, 'placeholder', {});

for i = 1:length(historicalData)
% Assign each field from the cell array to the corresponding field in the struct
historicalStructArray(i).date = historicalData{i}{1};
historicalStructArray(i).openPrice = historicalData{i}{2};
historicalStructArray(i).closePrice = historicalData{i}{3};
historicalStructArray(i).priceChange = historicalData{i}{4};
historicalStructArray(i).percentChange = historicalData{i}{5};
historicalStructArray(i).lowPrice = historicalData{i}{6};
historicalStructArray(i).highPrice = historicalData{i}{7};
historicalStructArray(i).volume = historicalData{i}{8};
% historicalStructArray(i).anotherFinancialFigure = historicalData{i}{9};
% historicalStructArray(i).placeholder = historicalData{i}{10}; % Assuming there is a 10th field for placeholder
end

tableData = {historicalStructArray.date; historicalStructArray.openPrice; ...
historicalStructArray.closePrice; historicalStructArray.lowPrice; ...
historicalStructArray.highPrice}';
% Update the table with the new data
set(h.webTable, 'Data', tableData);
% Adjust column width based on the data
set(h.webTable, 'ColumnWidth', {100, 80, 80, 80, 80});


end


% create a toggle for plotting
function createToggleButton(~,~)
if isempty(h.webTable.Data)
return
end

if isfield(h,'ax') && isfield(h,'webPlottingPanel')
if strcmp(h.webPlottingPanel.Visible, 'on')
h.webPlottingPanel.Visible = 'off';
else
h.webPlottingPanel.Visible = 'on';
end
return
else

% h.figwebData = figure('NumberTitle','off', 'MenuBar', 'none', ...
% 'Resize', 'off', ...
% ...'Resize', 'on', ...
% 'Position', h.webTable.Position... Adjust the position and size as needed
% ,'Alphamap',0.2 ...
% ,'Color',[0.95 0.95 0.95],'Parent');
h.webPlottingPanel.Visible = 'on';
h.ax = axes('Parent',h.webPlottingPanel,'box','on','Units','Normalized','Position',[0.13 0.16 0.76 0.76]);
h.zoomButton = uicontrol('Parent', h.webPlottingPanel, ...
'Style', 'togglebutton', ...
'Units','Normalized',...
'Position', [0.1+0.02, 0.92, 0.18, 0.08], ...
'String', 'Zoom', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
...'Value',0, ...
'Callback', @zoomToggle);

h.dataCursorButton = uicontrol('Parent', h.webPlottingPanel, ...
'Style', 'togglebutton', ...
'Units','Normalized',...
'Position', [0.32, 0.92, 0.22, 0.08], ...
'String', 'Data Cursor', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
...'Value',0, ...
'Callback', @dataCursorToggle);

h.panButton = uicontrol('Parent', h.webPlottingPanel, ...
'Style', 'togglebutton', ...
'Units','Normalized',...
'Position', [0.54+0.02, 0.92, 0.18, 0.08], ...
'String', 'Pan', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
...'Value',0, ...
'Callback', @panToggle);


% You would call this function typically from a 'Restore' button callback like this:
uicontrol('Parent', h.webPlottingPanel, ...
'Style', 'pushbutton', ...
'Units','Normalized',...
'Position', [0.76, 0.92, 0.22, 0.08], ...
'String', 'Restore', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
...'Value',0, ...
'Callback', @restorePlot);

h.exportWebPlot = uicontrol('Parent', h.webPlottingPanel, ...
'Style', 'pushbutton', ...
'Units','Normalized',...
'Position', [0.02, 0.02, 0.30, 0.08], ...
'String', 'Export PNG', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
...'Value',0, ...
'Callback', @exportPlot);

h.exportWebPlot = uicontrol('Parent', h.webPlottingPanel, ...
'Style', 'pushbutton', ...
'Units','Normalized',...
'Position', [0.70, 0.02, 0.30, 0.08], ...
'String', 'Export Word', ...
'FontSize', 14, ...
'BackgroundColor', [0.94 0.94 0.94], ...
'ForegroundColor', [50 50 50]/255, ...
...'Value',0, ...
'Callback', @exportWord);

% Convert webData.data to a numeric matrix if they are stored as strings

% Get the data from the webTable
data = get(h.webTable, 'Data');
% Convert cell array to table
numericData = str2double(data);

% Extract the Open, High, Low, Close data
ohlcData = numericData(:, 2:5);

% Now, convert the date strings to a datetime array
dates = datetime(data(:,1), 'InputFormat', 'yyyy-MM-dd');

tableTMW = timetable(dates,ohlcData(:,1),ohlcData(:,4),ohlcData(:,3),ohlcData(:,2));

tableTMW.Properties.VariableNames = {'open';'high';'low';'close'};

% Use the Financial Toolbox candle function to create the plot
hCandle = candle(h.ax,tableTMW, 'blue');
h.ax.XTickLabelRotation = 0;
grid on
set(h.ax,'ylim',[2500 3200],'FontSize',13,'FontName','Times New Roman','TickLength',[0.022 0.022]);
% Label the axes and title
xlabel('Date','FontSize',14,'FontName','Times New Roman');
ylabel('Price','FontSize',14,'FontName','Times New Roman');


modifyCandleStick();


end
end


% Callback function to export table data to Excel
function exportToExcel(~, ~)
% Get the data from the webTable
data = get(h.webTable, 'Data');
% Convert cell array to table
T = cell2table(data, 'VariableNames', h.webTable.ColumnName);
% Define Excel file name
excelFileName = 'stock_data.xlsx';
% Write table data to Excel file
writetable(T, excelFileName);
disp(['Data exported to ', excelFileName]);
end

% Callback function to export table data to TXT
function exportToTxt(~, ~)
% Get the data from the webTable
data = get(h.webTable, 'Data');
% Define TXT file name
txtFileName = 'stock_data.txt';
% Open the TXT file for writing
fileID = fopen(txtFileName, 'wt');
% Write the headers
fprintf(fileID, '%s\t%s\t%s\t%s\t%s\n', h.webTable.ColumnName{:});
% Write the data
for i = 1:size(data, 1)
fprintf(fileID, '%s\t%s\t%s\t%s\t%s\n', data{i, :});
end
% Close the file
fclose(fileID);
disp(['Data exported to ', txtFileName]);
end

function exportToExcelWithColor(~,~)
% Get the data from the webTable
data = get(h.webTable, 'Data');

% Convert cell array to table
T = cell2table(data, 'VariableNames', h.webTable.ColumnName);

% Define Excel file name
excelFileName = 'stock_data.xlsx';
% Write table data to Excel file
writetable(T, excelFileName);

% Start an ActiveX server to Excel
Excel = actxserver('Excel.Application');
Excel.Visible = true; % if you want to see this happen
Workbook = Excel.Workbooks.Open(fullfile(pwd, excelFileName));
Sheets = Excel.ActiveWorkbook.Sheets;
Sheet = Sheets.Item(1); % assumes data is in the first sheet

% Get range of cells where data is written
Range = Sheet.Range('B2:E2'); % Adjust range for your data
Range.Resize(size(data,1), size(data,2)).Interior.ColorIndex = 0; % Clear any existing colors

% Loop over each row and set color based on condition
for i = 1:size(data,1)
cellOpenPrice = Sheet.Range(['B' num2str(i+1)]);
cellClosePrice = Sheet.Range(['C' num2str(i+1)]);

if cellClosePrice.Value > cellOpenPrice.Value
cellClosePrice.Interior.Color = 255; % Red
elseif cellClosePrice.Value < cellOpenPrice.Value
cellClosePrice.Interior.Color = 5287936; % Green
end
end

% Save and close
Workbook.Save;
Workbook.Close;
Excel.Quit;
end


function zoomToggle(src,~)
% Toggle the zoom state based on the button's value
if get(src, 'Value')
zoom(h.ax, 'on');
set(src, 'BackgroundColor', [0.5, 0.5, 0.5]); % Change color to indicate 'on' state
else
zoom(h.ax, 'off');
set(src, 'BackgroundColor', [0.94, 0.94, 0.94]); % Reset color to default
end
end


function dataCursorToggle(src,~)
% Toggle the data cursor mode based on the button's value
if get(src, 'Value')
datacursormode(h.fig, 'on');
set(src, 'BackgroundColor', [0.5, 0.5, 0.5]); % Change color to indicate 'on' state
else
datacursormode(h.fig, 'off');
set(src, 'BackgroundColor', [0.94, 0.94, 0.94]); % Reset color to default
end
end

function panToggle(src,~)
% Toggle the rotate 3D state based on the button's value
if get(src, 'Value')
pan(h.ax, 'on');
set(src, 'BackgroundColor', [0.5, 0.5, 0.5]); % Change color to indicate 'on' state
else
pan(h.ax, 'off');
set(src, 'BackgroundColor', [0.94, 0.94, 0.94]); % Reset color to default
end
end

function restorePlot(src, ~)
% Disable all interactive modes
updateUIControls();
zoom(h.ax, 'off');
datacursormode(h.fig, 'off');
pan(h.ax, 'off');
% Reset the view to the default 2D view
view(h.ax, 2);
% Reset zoom level to the default (showing all data)
axis(h.ax, 'auto');
% Update any UI controls if they exist (e.g., toggle buttons)


end

function updateUIControls()
% Assuming you have stored the UI control handles in 'h.zoomBtn', etc.
% Reset the state of the toggle buttons to 'off'
if isfield(h, 'zoomButton')
% disp(['Zoom Button Handle: ', num2str(h.zoomButton)]); % Debugging line
set(h.zoomButton, 'Value', 0,'BackgroundColor',[0.94 0.94 0.94]);
end
if isfield(h, 'dataCursorButton')
set(h.dataCursorButton, 'Value', 0,'BackgroundColor',[0.94 0.94 0.94]);
end

if isfield(h, 'panButton')
set(h.panButton, 'Value', 0,'BackgroundColor',[0.94 0.94 0.94]);
end

set(h.fig, 'HandleVisibility', 'on');

end


function exportPlot(src, ~)
% Ask user for file name and location to save the PNG
[file, path] = uiputfile('export.png', 'Save image as');
if isequal(file, 0) || isequal(path, 0)
disp('User clicked cancel.');
return;
else
filename = fullfile(path, file);
end

figTemp = figure;
figTemp.Visible = 'off';
axTemp = h.ax;
axTemp1 = copyobj(axTemp,figTemp);
set(axTemp1,'Parent',figTemp);
% You might need to make sure 'h.ax' is the handle to your axes

print(figTemp,filename, '-dpng','-r300');

disp(['Plot saved as ', filename]); % Optional message to indicate success
end



function exportWord(src, ~)
% Ask user for file name and location to save the PNG
[file, path] = uiputfile('export.doc', 'Save file as');
if isequal(file, 0) || isequal(path, 0)
disp('User clicked cancel.');
return;
else
filename = fullfile(path, file);
end

% Create a Word application object
wordApp = actxserver('Word.Application');

% Make Word application visible (optional)
wordApp.Visible = 1;

% Create a new document
wordDoc = wordApp.Documents.Add;

% Add content to the Word document
wordDoc.Paragraphs.Add; % Add a new paragraph
wordDoc.Paragraphs.Item(1).Range.Text = 'This is a sample paragraph.';
% Insert the PNG figure into the Word document
imagePath = 'export.png';
shape = wordDoc.Shapes.AddPicture(imagePath, false, true);

% Save the Word document
wordDoc.SaveAs2(filename);

% Close the Word document
wordDoc.Close;

% Quit the Word application
wordApp.Quit;

% Release the COM objects
wordDoc.release;
wordApp.release;


end


function modifyCandleStick()


data = get(h.webTable, 'Data');
dates = datetime(data(:,1), 'InputFormat', 'yyyy-MM-dd');

customRed = [0.6350 0.0780 0.1840];
customGreen = [0.4660 0.6740 0.1880];

% Find all objects of type 'patch' (the candlestick bodies)
hold(h.ax,'on');
patches = findobj(h.ax, 'Type', 'patch');
lines = findobj(gca, 'Type', 'line');
lineXData = fliplr(get(lines, 'XData'));
lineYData = fliplr(get(lines, 'YData'));
delete(lines);
% Loop through the patches to adjust their colors
for i = 1:length(patches)

patchXData = get(patches(i), 'XData');
% Determine the corresponding date index based on XData
% dateIndex = find(dates == patchXData(1));

yData = get(patches(i),'YData');
openPrices = yData(1);
closePrices = yData(2);

% Compare open and close prices for the current date
if closePrices > openPrices
% If close is greater than open, set the body to customRed
set(patches(i), 'FaceColor', 'None' ,'EdgeColor',customRed);
plot(h.ax,[lineXData(3*i-1) lineXData(3*i)], [lineYData(3*i-1) lineYData(3*i)],...
'Color',customRed,'LineWidth',1.1)
else
% If close is less than or equal to open, set the body to customGreen
set(patches(i), 'FaceColor','none','EdgeColor', customGreen);
plot(h.ax,[lineXData(3*i-1) lineXData(3*i)], [lineYData(3*i-1) lineYData(3*i)],...
'Color',customGreen,'LineWidth',1.1)
end
end

end

% Callback function for returning to the main panel
function returnToMainPanel(~, ~)
% Delete the calculator interface or word lookup interface and show the main panel
panelFields = {'calculatorPanel', 'wordLookupPanel', 'StockMarketPanel','webPlottingPanel','ax'};
% Loop over each field name and delete the field if it exists
for k = 1:numel(panelFields)
fieldName = panelFields{k};
if isfield(h, fieldName)
% delete(h.(fieldName).Children)
delete(h.(fieldName));
h = rmfield(h, fieldName); % Optionally remove the field from the structure
end
end
set(h.panel, 'Visible', 'on');
set(h.fig, 'Color', [0.95 0.95 0.95]);
set(h.fig, 'WindowKeyPressFcn', @keyPressCallback);
set(h.fig,'Position',h.figOriginPosition);
end
end


This is another GUI tool used for a file filter with some fancy stuff.

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


function file_explorer()
if exist('myTempDataBase.txt', 'file')
database = readcell('myTempDataBase.txt','Delimiter','Tab','LineEnding',"\n");
else
database = []; % Initialize an empty database or however you wish
end
% Create the main figure window
main_fig = figure('Name', 'File Explorer', 'Position', [100, 100, 800, 600]...
, 'Units', 'pixels', 'Resize', 'on', 'NumberTitle', 'off' ...
, 'MenuBar', 'none','CloseRequestFcn',{@saveDatabaseOnClose,database});

% Create a panel for the controls
controls_panel = uipanel('Parent', main_fig, 'Title', 'Controls', 'Position', [0.01, 0.88, 0.98, 0.11]);

% Create the file retrieval button
btn_retrieve = uicontrol('Parent', controls_panel, 'Style', 'pushbutton', 'String', 'Retrieve Files', ...
'Units', 'normalized', 'Position', [0.01, 0.1, 0.10, 0.5], 'Callback', @retrieve_files);

% Create the sorting button
btn_sort = uicontrol('Parent', controls_panel, 'Style', 'pushbutton', 'String', 'Sort by Date', ...
'Units', 'normalized', 'Position', [0.11, 0.1, 0.10, 0.5], 'Callback', @sort_files);


% Create the open button
btn_open = uicontrol('Parent', controls_panel, 'Style', 'pushbutton', 'String', 'Open', ...
'Units', 'normalized', 'Position', [0.21, 0.1, 0.06, 0.5], 'Callback', @open_file);

panel_filter = uipanel('Parent', controls_panel, 'Title', 'Filter'...
,'Units','normalized' ,'Position', [0.27, 0.05, 0.36, .92]...
,'TitlePosition','centertop');
btn_filter = uicontrol('Parent', controls_panel, 'Style', 'pushbutton', 'String', 'Filter File', ...
'Units', 'normalized', 'Position', [0.28, 0.1, 0.08, 0.5], 'Callback', @loadFileFilter);
btn_filterSearch = uicontrol('Parent', controls_panel, 'Style', 'edit', 'String', '', ...
'Units', 'normalized', 'Position', [0.36, 0.1, 0.1, 0.5], 'Callback', @searchKeyWordsCallBack);

btn_saveData = uicontrol('Parent', controls_panel, 'Style', 'pushbutton', 'String', 'Save', ...
'Units', 'normalized', 'Position', [0.46, 0.1, 0.08, 0.5], 'Callback', @SaveFilterData);
btn_loadData = uicontrol('Parent', controls_panel, 'Style', 'pushbutton', 'String', 'Load', ...
'Units', 'normalized', 'Position', [0.54, 0.1, 0.08, 0.5], 'Callback', @loadFileFilterData);


btn_searchBar = uipanel('Parent', controls_panel, 'Title','Search', 'Units', 'normalized', ...
'Position', [0.64, 0.05, 0.15, 0.92],'TitlePosition','centertop');
edit_search = uicontrol('Parent', controls_panel, 'Style', 'edit', 'Units', 'normalized', ...
'Position', [0.65, 0.10, 0.13, 0.5], 'Callback', @search_files,'ButtonDownFcn',@clear_search);
edit_clicked = false;



table_dataFilter = uitable('Parent', main_fig, 'Units', 'normalized', 'Position', [0.01, 0.01, 0.98, 0.86], ...
'ColumnName', {'Search Result'}, ...
'ColumnWidth', {830}, 'RowName', []...
,'CellSelectionCallback',@table_selection_callback...
,'ButtonDownFcn',@tableClickHandle...
,'Visible','on','FontSize',15);


table_dataFilter.Visible = 'off';

% Create the table to display the file information
table_data = uitable('Parent', main_fig, 'Units', 'normalized', 'Position', [0.01, 0.01, 0.98, 0.86], ...
'ColumnName', {'Name', 'Type', 'Size (MB)', 'Date', 'Path'}, ...
'ColumnWidth', {200, 80, 100, 150, 300}, 'RowName', []...
,'CellSelectionCallback',@table_selection_callback...
,'ButtonDownFcn',@tableClickHandle);

% Wait for uitable to be ready
drawnow;
% Access Java component of uitable
jScroll = findjobj(table_data);
jTable = jScroll.getViewport.getView;
% Set up a MouseListener for double-click detection
set(jTable, 'MouseClickedCallback', @(src, event)onTableClick(src, event));


jScroll2 = findjobj(table_dataFilter);
jTable2 = jScroll2.getViewport.getView;
% Set up a MouseListener for double-click detection
set(jTable2, 'MouseClickedCallback', @(src, event)onTableClick(src, event));


% Define a MATLAB context menu
cMenu = uicontextmenu;
uimenu(cMenu, 'Label', 'Copy', 'Callback', @(src, event)copyFileOrFolderAction(jTable));
uimenu(cMenu, 'Label', 'Open Folder Path', 'Callback', @(src, event)openFolderPathAction());
% uimenu(cMenu, 'Label', 'Properties', 'Callback', @(src, event)showPropertiesAction(jTable));

set(jTable, 'MousePressedCallback', @(src, event)onTableRightClick(src, event, cMenu,table_data));

% Set the maximum number of rows
% table_data.Data = cell(1000, 5); % Initialize with 1000 rows

% Initialize variables
files = []; file_info = [];
sort_order = 1; % 1 for descending, -1 for ascending

path = [];
pathIndex = [];
line_number = [];
% Create the text label for the edit component
label_folder = uipanel('Parent', controls_panel, 'Title', 'Folder Path', 'Units', 'normalized', ...
'Position', [0.80, 0.05, 0.185, 0.92],'TitlePosition','centertop');
% Create the text input field
edit_folder = uicontrol('Parent', controls_panel, 'Style', 'edit', 'Units', 'normalized', ...
'Position', [0.81, 0.1, 0.165, 0.5], 'Callback', @set_folder,'String',path);

initialiseDatabase(database)

function retrieve_files(~, ~)
% Specify the file path
% Prompt the user to select a folder
% if isempty(path)
path = uigetdir('/Applications/MATLAB_R2021a.app/toolbox/matlab/iofun/');
if path == 0
return;
end
% end

% Initialize the file_info cell array
file_info = {};

% Recursively retrieve files and update file_info
file_info = retrieveFilesRecursively(path, file_info);

table_data.Visible = 'on';
table_dataFilter.Visible = 'off';

% Update the table data
set(table_data, 'Data', file_info);


edit_folder.String = path;
end

function loadFileFilter(~,~)
if isempty(file_info)
return;
end
% Filter files by format

filtered_data = file_info(contains(file_info(:,1), '.m') | contains(file_info(:,1), '.txt'), :);
% Update the table data
set(table_data, 'Data', filtered_data);

end

function file_info = retrieveFilesRecursively(folderPath, file_info)
% Get the list of files and folders
items = dir(folderPath);
items = items(~ismember({items.name}, {'.', '..'})); % Filter out '.' and '..' entries

for i = 1:length(items)
currentItemPath = fullfile(folderPath, items(i).name);

% Common details to store
itemSizeMB = bytes2mb(items(i).bytes); % Convert bytes to MB for files, will be 0 for folders
itemDate = datestr(items(i).datenum, 'yyyy-mm-dd HH:MM:SS');

if items(i).isdir
% Add directory info to file_info before recursing into it
% Note: Size for directories can be complex to calculate and might not be meaningful;
dirInfo = {items(i).name, 'Directory', ' ', itemDate, currentItemPath};
file_info{end+1, 1} = dirInfo{1}; % Directory name
file_info{end, 2} = dirInfo{2}; % Placeholder for size (0 for directories)
file_info{end, 3} = dirInfo{3}; % Last modified date
file_info{end, 4} = dirInfo{4}; % Full directory path
file_info{end, 5} = dirInfo{5}; % Type (File/Directory)

% Recurse into subdirectories
file_info = retrieveFilesRecursively(currentItemPath, file_info);
else
% File processing
fileInfo = {items(i).name, 'File', itemSizeMB, itemDate, currentItemPath};
file_info{end+1, 1} = fileInfo{1}; % Full file name with extension
file_info{end, 2} = fileInfo{2}; % Store file size in MB
file_info{end, 3} = fileInfo{3}; % Store last modified date
file_info{end, 4} = fileInfo{4}; % Store the full file path
file_info{end, 5} = fileInfo{5}; % Type (File/Directory)
end
end
end

function set_folder(~, ~)
% Get the selected folder path from the edit component
folder_path = get(edit_folder, 'String');

% Check if the folder path exists
if exist(folder_path, 'dir')
% Retrieve files and update file_info
file_info = retrieveFilesRecursively(folder_path, {});

% Update the table data
set(table_data, 'Data', file_info);
else
errordlg('Invalid folder path!', 'Error');
end
end

function sort_files(~, ~)
% Get the current table data
file_info = get(table_data, 'Data');

% Check if the table data is not empty
if isempty(file_info) || all(cellfun(@isempty, file_info(:,1)))
return;
end

% Convert date strings to numbers for sorting
date_values = datenum(file_info(:,4), 'yyyy-mm-dd HH:MM:SS');

if sort_order
% Sort in descending order
[~, idx] = sort(date_values, 'descend');
else
% Sort in ascending order
[~, idx] = sort(date_values, 'ascend');
end

% Apply sorted index to table data
table_data.Data = file_info(idx,:);

% Toggle the sort order for the next sort operation
sort_order = ~sort_order;
end

function clear_search(src,~)
edit_clicked = true;
set(src,'String','');
end

function search_files(~, ~)
if edit_clicked
edit_clicked = false;
return;
end

% Get the search term
search_term = get(edit_search, 'String');
search_term = lower(search_term); % Convert search term to lowercase for case-insensitive comparison

% Always display all files if search term is empty
if isempty(search_term)
set_folder()
else
% Refresh the table with files that match the search term (case-insensitive)
matching_files = cellfun(@(name) contains(lower(name), search_term), file_info(:,1));
filtered_data = file_info(matching_files, :);
table_data.Data = filtered_data;
end
table_data.Visible = 'on';
table_dataFilter.Visible = 'off';
end

function searchKeyWordsCallBack(~, ~)
if edit_clicked
edit_clicked = false;
return;
end

% Get the search term
search_term = get(btn_filterSearch, 'String');

fileList = dir(fullfile(path, '**/*.m'));
fileList = [fileList; dir(fullfile(path, '**/*.txt'))];
allMatches = {}; % Initialize an empty cell array to store all matches
allMatchesPure = {}; % Initialize an empty cell array to store all matches
mm = 1;
for i = 1:length(fileList)
filePath = fullfile(fileList(i).folder, fileList(i).name);
fileContent = fileread(filePath);
expr = ['[^\n]*' search_term '[^\n]*'];
[matches, starts] = regexp(fileContent,expr, 'match','start' ,'ignorecase');
matchesHighlighted = cellfun(@(x) [ '<html>' strrep(x, search_term, ['<span style="color: blue;"><b>', search_term, '</b></span>']) '</html>'], matches, 'UniformOutput', false);
% matchesHighlighted = cellfun(@(x) ['<html><span style="color: blue;">', strrep(x, search_term, ['<b>', search_term, '</b>']), '</span></html>'], matches, 'UniformOutput', false);
allMatches = [allMatches; matchesHighlighted']; % Append to allMatches
allMatchesPure = [allMatchesPure; matches'];
% Create a logical array where newlines are 1, others are 0
newlines = (fileContent == char(10));
lineNumbersAtIndices = cumsum([1, newlines]); % Start from 1 to count lines correctly
lineNumbersForMatches = lineNumbersAtIndices(starts);
if ~isempty(matchesHighlighted)
for j = 1:length(matchesHighlighted)
pathIndex{mm + j -1} = filePath;
line_number(mm+j-1) = lineNumbersForMatches(j);
end
mm = mm + 1;
end
end
table_data.Visible = 'off';
table_dataFilter.Visible = 'on';
table_dataFilter.Data = allMatches;

jtableFilter = findjobj(table_dataFilter);
height = jtableFilter.getViewport.getView.getRowHeight;
if height < 30
jtableFilter.getViewport.getView.setRowHeight(2*height)
end

setappdata(btn_saveData,'allMatchesPure',allMatchesPure);
end

function SaveFilterData(~,~)

[fileName1, folder_path] = uiputfile({'example*.txt','Text Files (*.txt)';...
'example*.mat','Mat Files (*.mat)';...
'example*.*','All Files (*.*)'},...
'Save as');
if isequal(fileName1,0) || isequal(folder_path,0)
% User pressed cancel or closed the dialog
disp('User cancelled the save operation.');
return;
else
fullFilePath = fullfile(folder_path, fileName1);
% allMatchesPure = regexprep(getappdata(btn_saveData, 'allMatchesPure'),'\"',' ');
allMatchesPure = getappdata(btn_saveData, 'allMatchesPure');
writecell(allMatchesPure,fullFilePath,'Delimiter','tab','QuoteStrings',false);

end
end

function loadFileFilterData(~,~)
[fileName1,folder_path,indx] = uigetfile( ...
{'*.txt;*.csv','Text File (*.txt,*csv)'; ...
... '*.m;*.mlx;*.fig;*.mat;*.slx;*.mdl',...
... 'MATLAB Files (*.m,*.mlx,*.fig,*.mat,*.slx,*.mdl)';
... '*.m;*.mlx','Code files (*.m,*.mlx)'; ...
... '*.fig','Figures (*.fig)'; ...
'*.mat','MAT-files (*.mat)'; ...
...'*.mdl;*.slx','Models (*.slx, *.mdl)'; ...
'*.*', 'All Files (*.*)'}, ...
'Select a File');
if isequal(fileName1,0) || isequal(folder_path,0)
% User pressed cancel or closed the dialog
disp('User cancelled the loading operation.');
return;
else
fullFilePath = fullfile(folder_path, fileName1);
allMatchesPure = readcell(fullFilePath,'Delimiter','tab','LineEnding',"\n");

table_data.Visible = 'off';
table_dataFilter.Visible = 'on';
table_dataFilter.Data = allMatchesPure;

jtableFilter = findjobj(table_dataFilter);
height = jtableFilter.getViewport.getView.getRowHeight;
if height < 30
jtableFilter.getViewport.getView.setRowHeight(2*height)
end
setappdata(btn_saveData,'allMatchesPure',allMatchesPure);
end
end

function initialiseDatabase(database)
if ~isempty(database)
allMatchesPure = database;
table_data.Visible = 'off';
table_dataFilter.Visible = 'on';
table_dataFilter.Data = allMatchesPure;
jtableFilter = findjobj(table_dataFilter);
height = jtableFilter.getViewport.getView.getRowHeight;
if height < 30
jtableFilter.getViewport.getView.setRowHeight(2*height)
end
setappdata(btn_saveData,'allMatchesPure',allMatchesPure);
else
return;
end
end

function saveDatabaseOnClose(src, ~, database)
if ~isempty(table_dataFilter.Data)
allMatchesPure = getappdata(btn_saveData, 'allMatchesPure');
fullFilePath = pwd;
writecell(allMatchesPure,[fullFilePath '/myTempDatabase.txt'],'Delimiter','tab','QuoteStrings',false);
delete(src);
end
end

function table_selection_callback(src, event)
if ~isempty(event.Indices)
src.UserData = event.Indices(1); % Store the row index in UserData
else
src.UserData = []; % Clear selection if no cell is selected
end
pause(0.4); % to allow the user time to add a second click
if strcmpi(main_fig.SelectionType, 'open')
% fprintf(1, 'Double click on cell');
open_file();
end
end

function onTableClick(~, event)
% Check if the event is a double-click
if event.getClickCount() == 2
open_file();
end
end

function onTableRightClick(src, event, cMenu, table_data)
% Check if the event is a right-click (button 3 is the right mouse button)
if event.getButton() == 3
% Get the current pointer location (in pixels)
fig = table_data.Parent;
currentPoint = fig.CurrentPoint;
% Show the context menu at the current pointer location
set(cMenu, 'Position', currentPoint, 'Visible', 'on');
end
end

function copyFileOrFolderAction(jTable)
% Get selected cell value
row = jTable.getSelectedRow() + 1; % Java indices are 0-based
col = jTable.getSelectedColumn() + 1;
if row > 0 && col > 0
dataModel = jTable.getModel();
path1 = char(dataModel.getValueAt(row - 1, col - 1)); % Assuming the cell contains a file/folder path
if exist(path1, 'file') || exist(path1, 'dir') % Check if it's a valid file/folder path
% Ask the user to select a destination folder
destinationFolder = uigetdir('Select a destination folder');
if destinationFolder ~= 0 % Ensure the user didn't cancel the dialog
[~, name, ext] = fileparts(path1);
destinationPath = fullfile(destinationFolder, '/'); % Construct the destination path
try
% Attempt to copy the file or folder
copyfile([path path1], destinationPath);
% msgbox('Copy successful!', 'Success');
catch
errordlg('Failed to copy the selected file/folder.', 'Error');
end
end
else
errordlg('The selected cell does not contain a valid file/folder path.', 'Error');
end
end
end

function openFolderPathAction()
% Open user's home directory for demonstration. Replace this path with
% the one you'd like to open based on your application's logic.
if ispc
folderPath = getenv('USERPROFILE'); % Works on Windows;
else
folderPath = getenv('HOME');% on Linux/Mac
end
if isfolder(folderPath)
% Open the folder
web(['file:///', path], '-browser');
end
end

% function showPropertiesAction(jTable)
% % Get selected cell info
% row = jTable.getSelectedRow() + 1;
% col = jTable.getSelectedColumn() + 1;
% if row > 0 && col > 0
% dataModel = jTable.getModel();
% value = dataModel.getValueAt(row - 1, col - 1); % Java is 0-based
% % Display properties
% msgbox(sprintf('Row: %d\nColumn: %d\nValue: %s', row, col, num2str(value)), 'Cell Properties');
% end
% end

function open_file(~, ~)
selected_index = get(table_data, 'UserData');
selected_index2 = get(table_dataFilter, 'UserData');
if ~isempty(selected_index)
% Get the file path of the selected row
file_path = table_data.Data{selected_index, 5};
if ispc
winopen(file_path);
else
system(['open ', file_path]); % For macOS and Linux
end
elseif ~isempty(selected_index2)
file_path = pathIndex{selected_index2};
[~, ~, ext] = fileparts(file_path);
lineNumber = line_number(selected_index2);
if strcmp(ext, '.m')
edit(file_path);
pause(0.1); % Wait for the file to open
matlab.desktop.editor.getActive().goToLine(lineNumber);
elseif strcmp(ext, '.txt')
open(file_path);
pause(0.1); % Wait for the file to open
com.mathworks.mde.editor.EditorUtils.scrollToLine(lineNumber);
end
end
return; % No file selected
end

end


function mb = bytes2mb(bytes)
% Convert bytes to megabytes
mb = bytes / (1024 ^ 2);
end
打赏
  • © 2020-2025 Yu Xia
  • Powered by Hexo Theme Ayer
    • PV:
    • UV:

Buy me a cup of coffee~

支付宝
微信