forked from P33a/SimTwo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSheets.pas
1299 lines (1097 loc) · 37.5 KB
/
Sheets.pas
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
unit Sheets;
{$MODE Delphi}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, ComCtrls, StdCtrls, ExtCtrls, Menus, Buttons, OmniXML,
OmniXMLUtils, SimpleParser, math, dynmatrix, clipbrd, IniPropStorage;
type
TSheet = class;
TSheetCellList = class;
TCellType = (ctText, ctFormula, ctButton);
TCellButtonState = (cstButtonUp, cstButtonDown);
TSheetCell = class
sheet: TSheet;
row, col: integer;
text, name, expression: string; // Text: the raw edit text
CompiledExpr: TStringList;
value: double;
NumberFormat: string;
CellType: TCellType;
CellButtonState: TCellButtonState;
SourceCellsList: TStringList;
level: integer;
backColor: TColor;
Font: TFont;
constructor Create;
destructor Destroy; override;
function DisplayText_: string;
procedure ParseText(txt: string);
function CalcSourceLevel: integer;
end;
TSheetCellList = class(TList)
private
protected
function GetItems(Index: Integer): TSheetCell;
procedure SetItems(Index: Integer; ASheetCell: TSheetCell);
public
function Add(ASheetCell: TSheetCell): Integer;
function Extract(Item: TSheetCell): TSheetCell;
function Remove(ASheetCell: TSheetCell): Integer;
function IndexOf(ASheetCell: TSheetCell): Integer;
function First: TSheetCell;
function Last: TSheetCell;
procedure Insert(Index: Integer; ASheetCell: TSheetCell);
property Items[Index: Integer]: TSheetCell read GetItems write SetItems; default;
procedure ClearAll;
function IndexFromName(aName: string): integer;
function IndexFromRC(aRow, aCol: integer): integer;
end;
TSheet = class
name: string;
CellList: TSheetCellList; // List of all, non empty, cells (owns each TSheetCell)
SGrid: TSTringGrid;
DefaultSheetCell: TSheetCell; // Empty TSheetCell
Parser: TSimpleParser;
TmpSourceCells: TStringList; // "Global" that holds the SourceList that is being filled by the parser activity
TmpSourceCellsIdx: integer; // "Global" position in the SourceList for the dependency checks
MustRebuildSourceCells: boolean; // "Global" that signals a change in the source cells list
CalcSequence: TSheetCellList; // Recalc sequence that only evaluates each cell once (does not owns each TSheetCell)
constructor Create;
destructor Destroy; override;
function Cell(r, c: integer): TSheetCell;
function EditCell(r, c: integer): TSheetCell;
procedure BuildCalcSequence;
procedure ShowCalcSequence(SL: TStrings);
function ReCalc: integer;
end;
TClearFlag = (cfFormat, cfFormulas);
TClearFlagsSet = Set of TClearFlag;
type
{ TFSheets }
TFSheets = class(TForm)
IniPropStorage: TIniPropStorage;
PanelFormula: TPanel;
CBNames: TComboBox;
EditFormula: TEdit;
StatusBar: TStatusBar;
PageControl: TPageControl;
TabGlobal: TTabSheet;
SGGlobal: TStringGrid;
MainMenu: TMainMenu;
PopupMenu: TPopupMenu;
SpeedButtonOK: TSpeedButton;
MenuFile: TMenuItem;
MenuSave: TMenuItem;
MenuReLoad: TMenuItem;
Edit1: TMenuItem;
GoTo1: TMenuItem;
Replace1: TMenuItem;
Find1: TMenuItem;
N2: TMenuItem;
PasteSpecial1: TMenuItem;
MenuPaste: TMenuItem;
MenuCopy: TMenuItem;
MenuCut: TMenuItem;
N3: TMenuItem;
Repeatcommand1: TMenuItem;
Undo1: TMenuItem;
N1: TMenuItem;
MenuDelete: TMenuItem;
ColorDialog: TColorDialog;
SpeedButtonBackColor: TSpeedButton;
MenuDeleteAll: TMenuItem;
FontDialog: TFontDialog;
SpeedButtonFont: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SGGlobalMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SGGlobalDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure SGGlobalMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SGGlobalPrepareCanvas(sender: TObject; aCol, aRow: Integer;
aState: TGridDrawState);
procedure SpeedButtonOKClick(Sender: TObject);
procedure MenuSaveClick(Sender: TObject);
procedure MenuReLoadClick(Sender: TObject);
procedure SGGlobalKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EditFormulaKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SGGlobalKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SGGlobalKeyPress(Sender: TObject; var Key: Char);
procedure EditFormulaExit(Sender: TObject);
procedure PanelFormulaClick(Sender: TObject);
procedure EditFormulaKeyPress(Sender: TObject; var Key: Char);
procedure MenuDeleteClick(Sender: TObject);
procedure MenuCopyClick(Sender: TObject);
procedure MenuPasteClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure SpeedButtonBackColorClick(Sender: TObject);
procedure MenuDeleteAllClick(Sender: TObject);
procedure SpeedButtonFontClick(Sender: TObject);
private
procedure FillHeaders(SGrid: TStringGrid);
procedure CellsRectToStringList(CellsRect: TGridRect; SL: TStringList);
procedure StringListToCellsRect(SL: TStringList; CellsRect: TGridRect);
public
ActSheet: TSheet;
Last_x, Last_y: integer;
Last_r, Last_c: integer;
MouseDown: boolean;
Escaping: boolean;
procedure SaveSheet(XMLFile: string; Sheet: TSheet);
procedure LoadSheet(Sheet: TSheet; XMLFile: string);
procedure EnterFormula(r, c: integer; newText: string);
end;
var
FSheets: TFSheets;
procedure SetRCValue(r, c: integer; s: string);
function GetRCValue(r, c: integer): double;
function GetRCText(r, c: integer): string;
function RCButtonPressed(r, c: integer): boolean;
procedure SetRCBackColor(r, c: integer; newColor: TColor);
procedure ClearButtons;
function RangeToMatrix(r, c, rows, cols: integer): Matrix;
procedure MatrixToRange(r, c: integer; const M: Matrix);
procedure MatrixToRangeF(r, c: integer; const M: Matrix; FormatString: string);
procedure RefreshSheets;
function ColFromPack(v: TObject): integer;
function RowFromPack(v: TObject): integer;
function RCValue(const v: array of double): double;
implementation
{$R *.lfm}
uses Viewer, ProjConfig;
procedure SetRCBackColor(r, c: integer; newColor: TColor);
var SheetCell: TSheetCell;
begin
if not assigned(FSheets.ActSheet) then exit;
SheetCell := FSheets.ActSheet.EditCell(r, c);
SheetCell.backColor := newColor;
end;
// This function is regietered on the simpleparser to evaluate the RC(r,c) function
// EVIL: a global (SourceCells) is being used to create a side effect where when
// there is an evaluation, the evaluated cell is added to the SourceCells list
// EVEN MORE EVIL: Another global (TmpSourceCellsIdx) is used to signal that the evaluation
// should check if the the source cells are the same or there was a change:
// In that case the calc sequence may be invalid and should be recalculated
function RCValue(const v: array of double): double;
var SheetCell: TSheetCell;
r, c: integer;
o: TObject;
begin
r := round(v[0]);
c := round(v[1]);
SheetCell := FSheets.ActSheet.Cell(r, c);
if FSheets.ActSheet.TmpSourceCells <> nil then begin
if FSheets.ActSheet.TmpSourceCellsIdx = -1 then begin // Building the dependency list;
FSheets.ActSheet.TmpSourceCells.AddObject(format('%4d,%4d',[r, c]), TObject(((r and $FFFF) shl 16) or (c and $FFFF)));
end else begin
with FSheets.ActSheet do begin // Checking the dependency list;
o := TmpSourceCells.Objects[TmpSourceCellsIdx];
if (rowfromPack(o) <> r) or (colfromPack(o) <> c) then begin
MustRebuildSourceCells := true;
TmpSourceCells.Objects[TmpSourceCellsIdx] := TObject(((r and $FFFF) shl 16) or (c and $FFFF));
end;
inc(TmpSourceCellsIdx);
end;
end;
end;
// TCellType = (ctText, ctFormula, ctButton);
case SheetCell.CellType of
ctText:
result := SheetCell.value;
ctFormula:
result := SheetCell.value;
ctButton: begin
result := SheetCell.value;
SheetCell.value := 0; // Assuming that if is a button, it is not the defaultCell
end;
else
result := 0;
end;
end;
{ TSheetCellList }
function TSheetCellList.Add(ASheetCell: TSheetCell): Integer;
begin
Result := inherited Add(ASheetCell);
end;
procedure TSheetCellList.ClearAll;
var i: integer;
begin
For i := 0 to count-1 do begin
GetItems(i).Free;
end;
clear;
end;
function TSheetCellList.Extract(Item: TSheetCell): TSheetCell;
begin
Result := TSheetCell(inherited Extract(Item));
end;
function TSheetCellList.First: TSheetCell;
begin
Result := TSheetCell(inherited First);
end;
function TSheetCellList.GetItems(Index: Integer): TSheetCell;
begin
Result := TSheetCell(inherited Items[Index]);
end;
function TSheetCellList.IndexFromName(aName: string): integer;
var i: integer;
begin
result := -1;
for i := 0 to Count - 1 do begin
if Items[i].Name = aName then begin
result := i;
exit;
end;
end;
end;
function TSheetCellList.IndexFromRC(aRow, aCol: integer): integer;
var i: integer;
begin
result := -1;
for i := 0 to Count - 1 do begin
if (Items[i].row = aRow) and (Items[i].col = aCol) then begin
result := i;
exit;
end;
end;
end;
function TSheetCellList.IndexOf(ASheetCell: TSheetCell): Integer;
begin
Result := inherited IndexOf(ASheetCell);
end;
procedure TSheetCellList.Insert(Index: Integer; ASheetCell: TSheetCell);
begin
inherited Insert(Index, ASheetCell);
end;
function TSheetCellList.Last: TSheetCell;
begin
Result := TSheetCell(inherited Last);
end;
function TSheetCellList.Remove(ASheetCell: TSheetCell): Integer;
begin
Result := inherited Remove(ASheetCell);
end;
procedure TSheetCellList.SetItems(Index: Integer; ASheetCell: TSheetCell);
begin
inherited Items[Index] := ASheetCell;
end;
procedure SetRCValue(r, c: integer; s: string);
begin
if (r > 0) and (c > 0) then
FSheets.ActSheet.EditCell(r, c).ParseText(s);
end;
procedure TFSheets.FormCreate(Sender: TObject);
var Sel: TGridRect;
begin
ActSheet := TSheet.Create;
ActSheet.SGrid := SGGlobal;
FillHeaders(SGGlobal);
Sel.Left := 1;
Sel.Top := 1;
Sel.Right := 1;
Sel.Bottom := 1;
SGGlobal.Selection := sel;
IniPropStorage.IniFileName := GetIniFineName(copy(name, 2, MaxInt));
Last_r := 1;
Last_c := 1;
end;
procedure TFSheets.FormDestroy(Sender: TObject);
begin
ActSheet.Free;
end;
procedure TFSheets.FormShow(Sender: TObject);
begin
if FileExists('Global.S2Sheet') then
LoadSheet(ActSheet, 'Global.S2Sheet');
StatusBar.Panels[0].Text := format('%3d: %3d',[1, 1]);
end;
procedure TFSheets.FormClose(Sender: TObject; var Action: TCloseAction);
begin
SaveSheet('Global.S2Sheet', ActSheet);
end;
procedure TFSheets.FillHeaders(SGrid: TStringGrid);
var i: integer;
begin
for i := 0 to Sgrid.ColCount -1 do begin
SGrid.Cells[i, 0] := inttostr(i);
end;
for i := 0 to Sgrid.RowCount -1 do begin
SGrid.Cells[0, i] := inttostr(i);
end;
end;
procedure TFSheets.SGGlobalMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var i, r, c: integer;
Grid: TStringGrid;
SheetCell: TSheetCell;
o: Tobject;
// RClkPoint: TPoint;
begin
MouseDown := true;
Last_x := x;
Last_y := y;
Grid:= TStringGrid(Sender);
Grid.MouseToCell(x, y, c, r);
StatusBar.Panels[0].Text := format('%3d: %3d',[r, c]);
if (c < 0) or (r < 0) then exit; // The user's right-click was not within a cell.
Last_r := r;
Last_c := c;
SheetCell := ActSheet.Cell(r, c);
{if (Button = mbRight) then begin
if (c < Grid.FixedCols) or (r < Grid.FixedRows) then exit; // The user clicked on a fixed cell
RClkPoint := Grid.ClientToScreen(Point(x, y));
MenuButton.Checked := (SheetCell.CellType = ctButton);
PopupMenu.Popup(RClkPoint.X, RClkPoint.Y);
end;}
if SheetCell.CellType = ctButton then begin
SheetCell.CellButtonState := cstButtonDown;
SheetCell.value := SheetCell.value + 1;
grid.Invalidate;
end;
EditFormula.Text := SheetCell.Text;
CBNames.Items.Clear;
CBNames.Items.add(inttostr(SheetCell.SourceCellsList.Count));
//CBNames.Items.AddStrings(SheetCell.SourceCellsList);
for i := 0 to SheetCell.SourceCellsList.Count -1 do begin
o := SheetCell.SourceCellsList.Objects[i];
CBNames.Items.add(format('(%d,%d)', [ rowFRomPack(o), colFromPack(o)]));
end;
end;
procedure TFSheets.SGGlobalMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var //r, c: integer;
Grid: TStringGrid;
SheetCell: TSheetCell;
begin
MouseDown := false;
Grid:= TStringGrid(Sender);
//Grid.MouseToCell(x, y, c, r);
//SGGlobal.MouseToCell(last_x, last_y, c, r);
//Grid.Cells[Last_c, Last_r] := '';
SheetCell := ActSheet.Cell(Last_r, Last_c);
if SheetCell.CellType = ctButton then begin
SheetCell.CellButtonState := cstButtonUp;
grid.Invalidate;
end;
end;
procedure MyDrawCellText(const Canvas: TCanvas; const Rect: TRect;
const Text: String; const textFont: TFont; const BackColor, TextColor: TColor;
const Alignment: TAlignment);
const
X_BORDER_WIDTH = 2;
Y_BORDER_WIDTH = 1;
var
iLeftBorder: Integer;
newTextStyle: TTextStyle;
begin
Canvas.Font := textFont;
// calculate the left border
iLeftBorder := 0;
case Alignment of
taLeftJustify : iLeftBorder := Rect.Left + X_BORDER_WIDTH;
taRightJustify: iLeftBorder := Rect.Right - X_BORDER_WIDTH - Canvas.TextWidth(Text) -1;
taCenter : iLeftBorder := Rect.Left + (Rect.Right - Rect.Left - Canvas.TextWidth(Text)) div 2;
end;
// set colors
Canvas.Font.Color := TextColor;
Canvas.Brush.Color := BackColor;
// paint the text
//ExtTextOut(Canvas.Handle, iLeftBorder, Rect.Top + Y_BORDER_WIDTH, ETO_CLIPPED or ETO_OPAQUE,
// @Rect, PChar(Text), Length(Text), nil);
Canvas.Brush.Style := bsSolid;
//Canvas.Brush.Style := bsClear;
//newTextStyle := Canvas.TextStyle;
//newTextStyle.Opaque := true;
//Canvas.TextStyle := newTextStyle;
//Canvas.FrameRect(Rect);
//Canvas.TextRect(Rect, iLeftBorder, Rect.Top + Y_BORDER_WIDTH, Text);
end;
procedure DrawButtonText(const Canvas: TCanvas; const Rect: TRect;
const Text: String; const textFont: TFont; const BackColor, TextColor: TColor; Pushed: boolean);
const
X_BORDER_WIDTH = 2;
Y_BORDER_WIDTH = 1;
var
iLeftBorder: Integer;
begin
Canvas.Font := textFont;
// calculate the left border
iLeftBorder := Rect.Left + (Rect.Right - Rect.Left - Canvas.TextWidth(Text)) div 2;
// set colors
Canvas.Font.Color := TextColor;
Canvas.Brush.Color := BackColor;
Canvas.Brush.Style := bsclear;
// paint the text
Canvas.TextRect(Rect, iLeftBorder + ord(Pushed), Rect.Top + Y_BORDER_WIDTH + ord(Pushed), Text);
end;
procedure TFSheets.SGGlobalPrepareCanvas(sender: TObject; aCol, aRow: Integer; aState: TGridDrawState);
var Grid: TStringGrid;
SheetCell: TSheetCell;
begin
Grid := TStringGrid(Sender);
SheetCell := ActSheet.Cell(Arow, Acol);
if (not (gdFocused in aState)) and (not (gdSelected in aState)) then begin
Grid.Canvas.Brush.Color := SheetCell.backColor;
end;
end;
procedure TFSheets.SGGlobalDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
Grid: TStringGrid;
sText: String;
myBackColor: TColor;
myTextColor: TColor;
myAlignment: TAlignment;
SheetCell: TSheetCell;
begin
Grid := TStringGrid(Sender);
SheetCell := ActSheet.Cell(Arow, Acol);
// set default values for the parameters,
// get the values depending on the grid settings.
sText := Grid.Cells[ACol, ARow];
//myAlignment := taLeftJustify;
//if (ARow < Grid.FixedRows) or (ACol < Grid.FixedCols) then begin
// myBackColor := Grid.FixedColor;
// myAlignment := taCenter;
// myTextColor := Grid.Font.Color;
//end else begin
// if (acol >= Grid.Selection.Left) and (acol <= Grid.Selection.Right) and
// (arow >= Grid.Selection.top) and (arow <= Grid.Selection.bottom) then begin
// myBackColor := clHighlight;
// myTextColor := clHighlightText;
// end else begin
// myBackColor := SheetCell.backColor;
// myTextColor := clWindowText;
// end;
//end;
// draw the text in the cell
//if (SheetCell.CellType = ctText) or (SheetCell.CellType = ctFormula) then begin
// MyDrawCellText(Grid.Canvas, Rect, sText, SheetCell.Font, myBackColor, myTextColor, myAlignment);
//end else
if SheetCell.CellType = ctButton then begin
myTextColor := clBtnText;
if SheetCell.CellButtonState = cstButtonDown then begin
DrawFrameControl(Grid.Canvas.Handle, Rect, DFC_BUTTON, DFCS_BUTTONPUSH or DFCS_PUSHED);
DrawButtonText(Grid.Canvas, Rect, sText, SheetCell.Font, myBackColor, myTextColor, true);
end else begin
DrawFrameControl(Grid.Canvas.Handle, Rect, DFC_BUTTON, DFCS_BUTTONPUSH);
DrawButtonText(Grid.Canvas, Rect, sText, SheetCell.Font, myBackColor, myTextColor, false);
end;
end;
//end;
end;
procedure TFSheets.SpeedButtonOKClick(Sender: TObject);
begin
EnterFormula(Last_r, Last_c, EditFormula.Text); // 1st way on accepting an edited formula
end;
//TFontStyle = (fsBold, fsItalic, fsUnderline, fsStrikeOut);
function FontStylesToStr(FontStyles: TFontStyles): string;
begin
result := '[ ]';
if fsBold in FontStyles then result[2] := 'B';
if fsItalic in FontStyles then result[3] := 'I';
if fsUnderline in FontStyles then result[4] := 'U';
if fsStrikeOut in FontStyles then result[5] := 'S';
end;
function StrToFontStyles(s: string; default: TFontStyles): TFontStyles;
begin
result := default;
if length(s) <> 6 then exit;
result := [];
if s[2] = 'B' then result := result + [fsBold];
if s[3] = 'I' then result := result + [fsItalic];
if s[4] = 'I' then result := result + [fsUnderline];
if s[5] = 'S' then result := result + [fsStrikeOut];
end;
procedure TFSheets.SaveSheet(XMLFile: string; Sheet: TSheet);
var XML: IXMLDocument;
node, prop: IXMLElement;
PI: IXMLProcessingInstruction;
i: integer;
s, def_s: string;
begin
XML := CreateXMLDoc;
PI := XML.CreateProcessingInstruction('xml', 'version="1.0"');
XML.InsertBefore(PI, XML.DocumentElement);
XML.DocumentElement := XML.CreateElement('sheet');
// Save columns width if they are different from the default value
node := XML.CreateElement('columns');
XML.DocumentElement.AppendChild(node);
prop := XML.CreateElement('defaultcol');
prop.SetAttribute('width', format('%d',[Sheet.SGrid.DefaultColWidth]));
node.AppendChild(prop);
for i := 1 to Sheet.SGrid.ColCount - 1 do begin
if Sheet.SGrid.ColWidths[i] = Sheet.SGrid.DefaultColWidth then continue;
prop := XML.CreateElement('col');
prop.SetAttribute('num', format('%d',[i]));
prop.SetAttribute('width', format('%d',[Sheet.SGrid.ColWidths[i]]));
node.AppendChild(prop);
end;
node := XML.CreateElement('cells');
XML.DocumentElement.AppendChild(node);
def_s := FontStylesToStr(Sheet.DefaultSheetCell.Font.Style);
for i := 0 to Sheet.CellList.Count - 1 do begin
if Sheet.CellList[i].text = '' then continue;
prop := XML.CreateElement('cell');
prop.SetAttribute('r', format('%d',[Sheet.CellList[i].row]));
prop.SetAttribute('c', format('%d',[Sheet.CellList[i].col]));
prop.SetAttribute('text', format('%s',[Sheet.CellList[i].text]));
if Sheet.CellList[i].backcolor <> clWindow then
prop.SetAttribute('backcolor', format('$%.6x',[integer(Sheet.CellList[i].backcolor)]));
if Sheet.CellList[i].Font.Name <> Sheet.DefaultSheetCell.Font.Name then
prop.SetAttribute('font', format('%s',[Sheet.CellList[i].Font.Name]));
if Sheet.CellList[i].Font.Size <> Sheet.DefaultSheetCell.Font.Size then
prop.SetAttribute('fsize', format('%d',[Sheet.CellList[i].Font.Size]));
s := FontStylesToStr(Sheet.CellList[i].Font.Style);
if s <> def_s then
prop.SetAttribute('style', s);
node.AppendChild(prop);
end;
XML.Save(XMLFile, ofIndent);
end;
procedure TFSheets.LoadSheet(Sheet: TSheet; XMLFile: string);
var XML: IXMLDocument;
root, node, prop: IXMLNode;
w, num: integer;
r, c: integer;
s, def_s: string;
bcolor: integer;
begin
XML := LoadXML(XMLFile, nil);
if XML = nil then exit;
root:=XML.SelectSingleNode('/sheet');
if root = nil then exit;
def_s := FontStylesToStr(Sheet.DefaultSheetCell.Font.Style);
node := root.FirstChild;
while node <> nil do begin
if node.NodeName = 'columns' then begin
prop := node.FirstChild;
while prop <> nil do begin
// default values
if prop.NodeName = 'defaultcol' then begin
w := Sheet.Sgrid.ColWidths[0]; //Preserve fixed column width
Sheet.SGrid.DefaultColWidth := GetNodeAttrInt(prop, 'width', Sheet.SGrid.DefaultColWidth);
Sheet.Sgrid.ColWidths[0] := w;
end else if prop.NodeName = 'col' then begin
num := GetNodeAttrInt(prop, 'num', -1);
w := GetNodeAttrInt(prop, 'width', Sheet.SGrid.DefaultColWidth);
if num > 0 then begin
Sheet.SGrid.ColWidths[num] := w;
end;
end;
prop := prop.NextSibling;
end;
end else if node.NodeName = 'cells' then begin
prop := node.FirstChild;
while prop <> nil do begin
// default values
if prop.NodeName = 'cell' then begin
r := GetNodeAttrInt(prop, 'r', -1);
c := GetNodeAttrInt(prop, 'c', -1);
s := GetNodeAttrStr(prop, 'backcolor','');
bcolor := strtointdef(s, clWindow);
s := GetNodeAttrStr(prop, 'text', '');
//bcolor := GetNodeAttr(prop, 'backcolor', clWindow);
if (r >= 0) and (c >= 0) then begin
Sheet.EditCell(r, c).backColor := TColor(bcolor);
Sheet.EditCell(r, c).ParseText(s);
Sheet.EditCell(r, c).Font.Name := GetNodeAttrStr(prop, 'font', Sheet.DefaultSheetCell.Font.Name);
Sheet.EditCell(r, c).Font.Size := GetNodeAttrInt(prop, 'fsize', Sheet.DefaultSheetCell.Font.Size);
Sheet.EditCell(r, c).Font.Style := StrToFontStyles(GetNodeAttrStr(prop, 'style', def_s), Sheet.DefaultSheetCell.Font.Style);
end;
end;
prop := prop.NextSibling;
end;
end;
node := node.NextSibling;
end;
Sheet.BuildCalcSequence;
while Sheet.ReCalc <> Sheet.CalcSequence.Count do begin
Sheet.BuildCalcSequence;
end;
end;
procedure TFSheets.MenuSaveClick(Sender: TObject);
begin
SaveSheet('Global.S2Sheet', ActSheet);
end;
procedure TFSheets.MenuReLoadClick(Sender: TObject);
begin
LoadSheet(ActSheet, 'Global.S2Sheet');
end;
{ TSheet }
procedure TSheet.BuildCalcSequence;
var i, lvl, FormulaCount, added: integer;
SheetCell: TSheetCell;
begin
CalcSequence.Clear; // New start
FormulaCount := 0;
for i := 0 to CellList.Count -1 do begin
CellList[i].level := 0;
if CellList[i].CellType = ctFormula then begin // We only need to recalc formulas,
if CellList[i].SourceCellsList.Count > 0 then begin // that are dependent on other cells
inc(FormulaCount);
CellList[i].level := maxint; // These are the cells that must be in the CalcSequence
end;
end;
end;
while CalcSequence.Count < FormulaCount do begin // We must add FormulaCount cells to the CalcSequence list
added := 0;
for i := 0 to CellList.Count -1 do begin
SheetCell := CellList[i];
if SheetCell.level <> maxint then continue; // These cells already have been processed
lvl := SheetCell.CalcSourceLevel;
if lvl < maxint then begin // If all the parents have level (that means they are on the list)
CalcSequence.Add(SheetCell); // then it can be on the list
SheetCell.level := lvl + 1; // And have level
inc(added);
end;
end;
if added = 0 then
raise Exception.Create('Circular Reference');
end;
end;
function TSheet.Cell(r, c: integer): TSheetCell;
begin
result := DefaultSheetCell;
if SGrid.Objects[c, r] = nil then exit;
result := TSheetCell(SGrid.Objects[c, r]);
end;
constructor TSheet.Create;
begin
DefaultSheetCell := TSheetCell.Create;
CellList := TSheetCellList.Create;
Parser := TSimpleParser.Create;
Parser.RegisterFunction('RC', @RCValue, 2);
CalcSequence := TSheetCellList.Create;
TmpSourceCellsIdx := -1;
end;
destructor TSheet.Destroy;
begin
CalcSequence.Free;
Parser.free;
CellList.ClearAll;
CellList.Free;
DefaultSheetCell.Free;
inherited;
end;
function TSheet.EditCell(r, c: integer): TSheetCell;
begin
if SGrid.Objects[c, r] <> nil then begin
// if it was already alocated use it
Result := TSheetCell(SGrid.Objects[c, r]);
end else begin
// Must create a new one and add it to the list
Result := TSheetCell.Create;
CellList.Add(result);
SGrid.Objects[c, r] := Result;
Result.sheet := self;
Result.row := r;
Result.col := c;
end;
end;
function TSheet.ReCalc: integer;
var i: integer;
SheetCell: TSheetCell;
begin
result := CalcSequence.Count;
for i := 0 to CalcSequence.Count - 1 do begin
SheetCell := CalcSequence[i];
with SheetCell do begin
//value := Sheet.Parser.Calc(expression);
//value := Sheet.Parser.Run(CompiledExpr);
try
Sheet.TmpSourceCells := SourceCellsList;
Sheet.TmpSourceCellsIdx := 0;
MustRebuildSourceCells := false;
value := Sheet.Parser.Calc(expression);
finally
Sheet.TmpSourceCells := nil;
Sheet.TmpSourceCellsIdx := -1;
end;
Sheet.SGrid.Cells[col, row] := format(NumberFormat, [value]);
if MustRebuildSourceCells then begin
result := i;
exit;
end;
end;
end;
end;
procedure TSheet.ShowCalcSequence(SL: TStrings);
var i: integer;
//SheetCell: TSheetCell;
begin
with Fsheets do begin
SL.Clear;
SL.add(inttostr(CalcSequence.Count));
for i := 0 to CalcSequence.Count -1 do begin
SL.add(format('(%d,%d)', [ CalcSequence[i].row, CalcSequence[i].col]));
end;
end;
end;
{
procedure TSheet.ShowCalcSequence(SL: TStringList);
var i: integer;
//SheetCell: TSheetCell;
begin
with Fsheets do begin
CBNames.Items.Clear;
CBNames.Items.add(inttostr(CalcSequence.Count));
for i := 0 to CalcSequence.Count -1 do begin
CBNames.Items.add(format('(%d,%d)', [ CalcSequence[i].row, CalcSequence[i].col]));
end;
end;
end;
}
{ TSheetCell }
function RowFromPack(v: TObject): integer;
begin
result := (PtrUInt(v) shr 16) and $FFFF;
end;
function ColFromPack(v: TObject): integer;
begin
result := PtrUInt(v) and $FFFF;
end;
function TSheetCell.CalcSourceLevel: integer;
var i, row, col, idx: integer;
o: TObject;
SheetCell: TSheetCell;
begin
result := 0;
for i := 0 to SourceCellsList.Count -1 do begin
o := SourceCellsList.Objects[i];
row := RowFromPack(o);
col := ColFromPack(o);
idx := Sheet.CellList.IndexFromRC(row, col);
if idx >= 0 then begin
SheetCell := Sheet.CellList[idx];
end else begin
SheetCell := Sheet.DefaultSheetCell;
end;
result := max(result, SheetCell.level);
end;
end;
constructor TSheetCell.Create;
begin
row := -1;
col := -1;
NumberFormat := '%g';
SourceCellsList := TStringList.Create;
CompiledExpr := TStringList.Create;
//SourceCellsList := TSheetCellList.Create;
//DependentCellsList := TSheetCellList.Create;
backColor := clWindow;
font := TFont.Create;
end;
destructor TSheetCell.Destroy;
begin
font.Free;
CompiledExpr.Free;
SourceCellsList.Free;
//DependentCellsList.Free;
inherited;
end;
function TSheetCell.DisplayText_: string;
begin
if CellType = ctFormula then begin
result := '=' + expression;
end else if CellType = ctButton then begin
result := '[' + expression + ']';
end else begin
result := text;
end;
end;
procedure TFSheets.SGGlobalKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = VK_RETURN then
EditFormula.SetFocus;
end;
procedure TFSheets.EditFormulaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var SelRect: TGridRect;
begin
if key in [VK_RETURN, VK_DOWN, VK_UP] then begin // 2nd way of accepting an edited formula
//ActSheet.EditCell(Last_r, Last_c).ParseText(EditFormula.Text);
key := 0;
EnterFormula(Last_r, Last_c, EditFormula.Text);
ActSheet.SGrid.SetFocus;
if (key = VK_DOWN) then begin
SelRect := ActSheet.SGrid.Selection;
if SelRect.Top < ActSheet.SGrid.RowCount then begin
SelRect.Top := SelRect.Top + 1;
SelRect.Bottom := SelRect.Bottom + 1;
ActSheet.SGrid.Selection := SelRect;
end;
end;
end else if key = VK_ESCAPE then begin
Escaping := true;
ActSheet.SGrid.SetFocus;
end;
end;
procedure TFSheets.SGGlobalKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Last_c := ActSheet.SGrid.Selection.Left;
Last_r := ActSheet.SGrid.Selection.Top;
StatusBar.Panels[0].Text := format('%3d: %3d',[Last_r, Last_c]);
EditFormula.Text := ActSheet.Cell(Last_r, Last_c).Text;
end;
procedure TFSheets.SGGlobalKeyPress(Sender: TObject; var Key: Char);
begin
if ord(key) < ord(' ') then exit; // Filter non printable codes
EditFormula.SetFocus;
EditFormula.Text := key;
EditFormula.SelStart := maxint;
end;