-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsheet.c
More file actions
2564 lines (2214 loc) · 84.8 KB
/
sheet.c
File metadata and controls
2564 lines (2214 loc) · 84.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// sheet.c - Spreadsheet implementation
#include "sheet.h"
#include "console.h"
#include "constants.h"
// Global variables for IF function string results
char g_if_result_string[MAX_CELL_DISPLAY_LENGTH] = {0};
int g_if_result_is_string = 0;
static Cell* g_current_evaluating_cell = NULL;
// Forward declarations for expression parsing
double parse_arithmetic_expression(Sheet* sheet, const char** expr, ErrorType* error);
double parse_term(Sheet* sheet, const char** expr, ErrorType* error);
double parse_factor(Sheet* sheet, const char** expr, ErrorType* error);
double parse_function(Sheet* sheet, const char** expr, ErrorType* error);
// Range parsing structures
typedef struct {
int start_row, start_col;
int end_row, end_col;
} CellRange;
typedef struct {
int min_row, max_row, min_col, max_col;
} NormalizedRange;
NormalizedRange normalize_range(const RangeSelection* sel) {
NormalizedRange r;
r.min_row = sel->start_row < sel->end_row ? sel->start_row : sel->end_row;
r.max_row = sel->start_row > sel->end_row ? sel->start_row : sel->end_row;
r.min_col = sel->start_col < sel->end_col ? sel->start_col : sel->end_col;
r.max_col = sel->start_col > sel->end_col ? sel->start_col : sel->end_col;
return r;
}
int parse_range(const char* range_str, CellRange* range);
int get_range_values(Sheet* sheet, const CellRange* range, double* values, int max_values);
// Function implementations
double func_sum(const double* values, int count);
double func_avg(const double* values, int count);
double func_max(const double* values, int count);
double func_min(const double* values, int count);
double func_median(double* values, int count);
double func_mode(const double* values, int count);
double func_if(double condition, double true_val, double false_val);
double func_if_enhanced(double condition, double true_val, double false_val,
const char* true_str, const char* false_str);
double func_power(double base, double exponent);
double func_xlookup(Sheet* sheet, double lookup_value, const char* lookup_str,
const char* lookup_array, const char* return_array, int exact_match, ErrorType* error);
int compare_double(const void* a, const void* b);
char* escape_csv_string(const char* str);
char* parse_csv_field(const char** csv_line, int* is_end);
char* get_cell_string_value(Sheet* sheet, const char* ref);
// Implementation
Sheet* sheet_new(int rows, int cols) {
Sheet* sheet = (Sheet*)calloc(1, sizeof(Sheet));
if (!sheet) return NULL;
sheet->rows = rows;
sheet->cols = cols;
sheet->name = _strdup("Sheet1");
if (!sheet->name) {
free(sheet);
return NULL;
}
// Allocate cell array
sheet->cells = (Cell***)calloc(rows, sizeof(Cell**));
if (!sheet->cells) {
free(sheet);
return NULL;
}
for (int i = 0; i < rows; i++) {
sheet->cells[i] = (Cell**)calloc(cols, sizeof(Cell*));
if (!sheet->cells[i]) {
// Cleanup on failure
for (int j = 0; j < i; j++) {
free(sheet->cells[j]);
}
free(sheet->cells);
free(sheet);
return NULL;
}
} // Initialize column widths
sheet->col_widths = (int*)calloc(cols, sizeof(int));
for (int i = 0; i < cols; i++) {
sheet->col_widths[i] = DEFAULT_COLUMN_WIDTH;
}
// Initialize row heights
sheet->row_heights = (int*)calloc(rows, sizeof(int));
for (int i = 0; i < rows; i++) {
sheet->row_heights[i] = 1; // Default height
}
// Initialize range selection and clipboard
sheet->selection.is_active = 0;
sheet->range_clipboard.is_active = 0;
sheet->range_clipboard.cells = NULL;
return sheet;
}
void sheet_free(Sheet* sheet) {
if (!sheet) return;
// Free all cells
for (int i = 0; i < sheet->rows; i++) {
for (int j = 0; j < sheet->cols; j++) {
if (sheet->cells[i][j]) {
cell_free(sheet->cells[i][j]);
}
}
free(sheet->cells[i]); }
free(sheet->cells);
// Free range clipboard
if (sheet->range_clipboard.cells) {
for (int i = 0; i < sheet->range_clipboard.rows; i++) {
for (int j = 0; j < sheet->range_clipboard.cols; j++) {
if (sheet->range_clipboard.cells[i][j]) {
cell_free(sheet->range_clipboard.cells[i][j]);
}
}
free(sheet->range_clipboard.cells[i]);
}
free(sheet->range_clipboard.cells);
}
free(sheet->col_widths);
free(sheet->row_heights); // Free row heights
free(sheet->name);
free(sheet->calc_order);
free(sheet);
}
Cell* sheet_get_cell(Sheet* sheet, int row, int col) {
if (row < 0 || row >= sheet->rows || col < 0 || col >= sheet->cols) {
return NULL;
}
return sheet->cells[row][col];
}
Cell* sheet_get_or_create_cell(Sheet* sheet, int row, int col) {
if (row < 0 || row >= sheet->rows || col < 0 || col >= sheet->cols) {
return NULL;
}
if (!sheet->cells[row][col]) {
sheet->cells[row][col] = cell_new(row, col);
}
return sheet->cells[row][col];
}
Cell* cell_new(int row, int col) {
Cell* cell = (Cell*)calloc(1, sizeof(Cell));
if (!cell) return NULL; cell->type = CELL_EMPTY;
cell->row = row;
cell->col = col;
cell->width = 10;
cell->precision = 2;
cell->align = 2; // Right align for numbers by default
// Initialize formatting
cell->format = FORMAT_GENERAL;
cell->format_style = 0;
// Initialize color formatting
cell->text_color = -1; // Default text color
cell->background_color = -1; // Default background color
cell->row_height = -1; // Default row height
return cell;
}
void cell_free(Cell* cell) {
if (!cell) return;
// Free string data
if (cell->type == CELL_STRING && cell->data.string) {
free(cell->data.string);
} else if (cell->type == CELL_FORMULA) {
if (cell->data.formula.expression) {
free(cell->data.formula.expression);
}
if (cell->data.formula.cached_string) {
free(cell->data.formula.cached_string);
}
}
// Free dependency arrays
free(cell->depends_on);
free(cell->dependents);
free(cell);
}
void cell_clear(Cell* cell) {
if (!cell) return;
// Save the type and set to CELL_EMPTY first to prevent double-free on re-entry
CellType old_type = cell->type;
cell->type = CELL_EMPTY;
// Free existing data
if (old_type == CELL_STRING && cell->data.string) {
free(cell->data.string);
cell->data.string = NULL;
} else if (old_type == CELL_FORMULA) {
if (cell->data.formula.expression) {
free(cell->data.formula.expression);
cell->data.formula.expression = NULL;
}
if (cell->data.formula.cached_string) {
free(cell->data.formula.cached_string);
cell->data.formula.cached_string = NULL;
} }
// Keep formatting when clearing
}
void cell_set_number(Cell* cell, double value) {
if (!cell) return;
cell_clear(cell);
cell->type = CELL_NUMBER;
cell->data.number = value;
}
void cell_set_string(Cell* cell, const char* str) {
if (!cell) return;
cell_clear(cell);
cell->type = CELL_STRING;
cell->data.string = _strdup(str);
if (!cell->data.string) {
cell->type = CELL_EMPTY; // Revert on allocation failure
return;
}
cell->align = 0; // Left align for strings
}
void cell_set_formula(Cell* cell, const char* formula) {
if (!cell) return;
cell_clear(cell);
cell->type = CELL_FORMULA;
cell->data.formula.expression = _strdup(formula);
if (!cell->data.formula.expression) {
cell->type = CELL_EMPTY; // Revert on allocation failure
return;
}
cell->data.formula.cached_value = 0.0;
cell->data.formula.cached_string = NULL;
cell->data.formula.is_string_result = 0;
cell->data.formula.error = ERROR_NONE;
}
void sheet_set_number(Sheet* sheet, int row, int col, double value) {
Cell* cell = sheet_get_or_create_cell(sheet, row, col);
if (cell) {
cell_set_number(cell, value);
sheet->needs_recalc = 1;
}
}
void sheet_set_string(Sheet* sheet, int row, int col, const char* str) {
Cell* cell = sheet_get_or_create_cell(sheet, row, col);
if (cell) {
cell_set_string(cell, str);
}
}
void sheet_set_formula(Sheet* sheet, int row, int col, const char* formula) {
Cell* cell = sheet_get_or_create_cell(sheet, row, col);
if (cell) {
cell_set_formula(cell, formula);
sheet->needs_recalc = 1;
}
}
void sheet_clear_cell(Sheet* sheet, int row, int col) {
Cell* cell = sheet_get_cell(sheet, row, col);
if (cell) {
cell_clear(cell);
sheet->needs_recalc = 1;
}
}
char* cell_get_display_value(Cell* cell) {
// Use the formatting function
return format_cell_value(cell);
}
char* sheet_get_display_value(Sheet* sheet, int row, int col) {
Cell* cell = sheet_get_cell(sheet, row, col);
return cell_get_display_value(cell);
}
// Convert column number to letter(s) (0 -> A, 25 -> Z, 26 -> AA, etc.)
// Caller provides buffer to avoid memory management issues
void cell_reference_to_string(int row, int col, char* buffer, size_t size) {
if (!buffer || size == 0) return;
char colStr[8];
int idx = 0;
// Convert column number to letters
col++; // Make it 1-based for conversion
while (col > 0) {
col--;
colStr[idx++] = 'A' + (col % 26);
col /= 26;
}
// Reverse the string
for (int i = 0; i < idx / 2; i++) {
char temp = colStr[i];
colStr[i] = colStr[idx - 1 - i];
colStr[idx - 1 - i] = temp;
}
colStr[idx] = '\0';
snprintf(buffer, size, "%s%d", colStr, row + 1);
}
// Parse cell reference like "A1" or "AB23"
int parse_cell_reference(const char* ref, int* row, int* col) {
if (!ref || !row || !col) return 0;
const char* p = ref;
*col = 0;
// Skip whitespace
while (*p && isspace(*p)) p++;
// Parse column letters
if (!isalpha(*p)) return 0;
while (*p && isalpha(*p)) {
*col = *col * 26 + (toupper(*p) - 'A' + 1);
p++;
}
(*col)--; // Convert to 0-based
// Parse row number
if (!isdigit(*p)) return 0;
*row = 0;
while (*p && isdigit(*p)) {
*row = *row * 10 + (*p - '0');
p++;
}
(*row)--; // Convert to 0-based
// Check for trailing garbage
while (*p && isspace(*p)) p++;
if (*p) return 0;
return 1;
}
// Forward declarations for expression parsing
double parse_arithmetic_expression(Sheet* sheet, const char** expr, ErrorType* error);
double parse_arithmetic_expression_old(Sheet* sheet, const char* expr, ErrorType* error);
double parse_term(Sheet* sheet, const char** expr, ErrorType* error);
double parse_factor(Sheet* sheet, const char** expr, ErrorType* error);
double parse_function(Sheet* sheet, const char** expr, ErrorType* error);
void skip_whitespace(const char** expr);
// Parse range notation like "A1:A3" or "B2:D5"
int parse_range(const char* range_str, CellRange* range) {
if (!range_str || !range) return 0;
const char* colon = strchr(range_str, ':');
if (!colon) return 0;
// Parse start cell
char start_ref[16];
int start_len = (int)(colon - range_str);
if (start_len >= sizeof(start_ref)) return 0;
strncpy_s(start_ref, sizeof(start_ref), range_str, start_len);
start_ref[start_len] = '\0';
if (!parse_cell_reference(start_ref, &range->start_row, &range->start_col)) {
return 0;
}
// Parse end cell
const char* end_ref = colon + 1;
if (!parse_cell_reference(end_ref, &range->end_row, &range->end_col)) {
return 0;
}
// Ensure start <= end
if (range->start_row > range->end_row) {
int temp = range->start_row;
range->start_row = range->end_row;
range->end_row = temp;
}
if (range->start_col > range->end_col) {
int temp = range->start_col;
range->start_col = range->end_col;
range->end_col = temp;
}
return 1;
}
// Get values from a range of cells
int get_range_values(Sheet* sheet, const CellRange* range, double* values, int max_values) {
// Optimized: Pass pre-allocated buffer or use iterator pattern
// Avoid creating temporary array every time
int count = 0;
// Early exit if invalid range
if (!range || max_values <= 0) return 0;
for (int row = range->start_row; row <= range->end_row; row++) {
if (count >= max_values) break;
for (int col = range->start_col; col <= range->end_col; col++) {
if (count >= max_values) break;
Cell* cell = sheet_get_cell(sheet, row, col);
if (cell) {
switch (cell->type) {
case CELL_NUMBER:
values[count++] = cell->data.number;
break;
case CELL_FORMULA:
if (cell->data.formula.error == ERROR_NONE) {
values[count++] = cell->data.formula.cached_value;
}
break;
case CELL_EMPTY:
values[count++] = 0.0;
break;
default:
// Skip strings and errors
break;
}
} else {
values[count++] = 0.0;
}
}
}
return count;
}
// Function implementations
double func_sum(const double* values, int count) {
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += values[i];
}
return sum;
}
double func_avg(const double* values, int count) {
if (count == 0) return 0.0;
return func_sum(values, count) / count;
}
double func_max(const double* values, int count) {
if (count == 0) return 0.0;
double max = values[0];
for (int i = 1; i < count; i++) {
if (values[i] > max) max = values[i];
}
return max;
}
double func_min(const double* values, int count) {
if (count == 0) return 0.0;
double min = values[0];
for (int i = 1; i < count; i++) {
if (values[i] < min) min = values[i];
}
return min;
}
// Helper function for median calculation
int compare_double(const void* a, const void* b) {
double da = *(const double*)a;
double db = *(const double*)b;
if (da < db) return -1;
if (da > db) return 1;
return 0;
}
double func_median(double* values, int count) {
if (count == 0) return 0.0;
// Sort the values
qsort(values, count, sizeof(double), compare_double);
if (count % 2 == 0) {
// Even number of values - return average of middle two
return (values[count/2 - 1] + values[count/2]) / 2.0;
} else {
// Odd number of values - return middle value
return values[count/2];
}
}
double func_mode(const double* values, int count) {
if (count == 0) return 0.0;
// Simple mode calculation - find most frequent value
double mode = values[0];
int max_count = 1;
for (int i = 0; i < count; i++) {
int current_count = 1;
for (int j = i + 1; j < count; j++) {
if (fabs(values[i] - values[j]) < FLOAT_COMPARISON_EPSILON) {
current_count++;
}
}
if (current_count > max_count) {
max_count = current_count;
mode = values[i];
}
}
return mode;
}
double func_if(double condition, double true_val, double false_val) {
return (condition != 0.0) ? true_val : false_val;
}
double func_if_enhanced(double condition, double true_val, double false_val,
const char* true_str, const char* false_str) {
// Reset global string result flag
g_if_result_is_string = 0;
g_if_result_string[0] = '\0';
// Also reset the current cell's string result
if (g_current_evaluating_cell) {
if (g_current_evaluating_cell->data.formula.cached_string) {
free(g_current_evaluating_cell->data.formula.cached_string);
g_current_evaluating_cell->data.formula.cached_string = NULL;
}
g_current_evaluating_cell->data.formula.is_string_result = 0;
}
if (condition != 0.0) {
// True condition
if (true_str) {
strcpy_s(g_if_result_string, sizeof(g_if_result_string), true_str);
g_if_result_is_string = 1;
// Store in current cell if available
if (g_current_evaluating_cell) {
char* cached = _strdup(true_str);
if (cached) {
g_current_evaluating_cell->data.formula.cached_string = cached;
g_current_evaluating_cell->data.formula.is_string_result = 1;
}
}
return 1.0; // Return non-zero to indicate string result available
} else {
return true_val;
}
} else {
// False condition
if (false_str) {
strcpy_s(g_if_result_string, sizeof(g_if_result_string), false_str);
g_if_result_is_string = 1;
// Store in current cell if available
if (g_current_evaluating_cell) {
char* cached = _strdup(false_str);
if (cached) {
g_current_evaluating_cell->data.formula.cached_string = cached;
g_current_evaluating_cell->data.formula.is_string_result = 1;
}
}
return 0.0; // Return zero to indicate string result available
} else {
return false_val;
}
}
}
double func_power(double base, double exponent) {
return pow(base, exponent);
}
// Skip whitespace in expression
void skip_whitespace(const char** expr) {
while (**expr && isspace(**expr)) {
(*expr)++;
}
}
// Clipboard functionality
static Cell* clipboard_cell = NULL;
Cell* sheet_get_clipboard_cell(void) {
return clipboard_cell;
}
void sheet_set_clipboard_cell(Cell* cell) {
// Free existing clipboard cell
if (clipboard_cell) {
cell_free(clipboard_cell);
}
// Create a copy of the cell
if (cell) {
clipboard_cell = cell_new(cell->row, cell->col);
switch (cell->type) {
case CELL_NUMBER:
cell_set_number(clipboard_cell, cell->data.number);
break;
case CELL_STRING:
cell_set_string(clipboard_cell, cell->data.string);
break;
case CELL_FORMULA:
cell_set_formula(clipboard_cell, cell->data.formula.expression);
clipboard_cell->data.formula.cached_value = cell->data.formula.cached_value;
clipboard_cell->data.formula.error = cell->data.formula.error;
break;
default:
clipboard_cell->type = CELL_EMPTY;
break;
}
// Copy display properties
clipboard_cell->width = cell->width;
clipboard_cell->precision = cell->precision;
clipboard_cell->align = cell->align;
// Copy color formatting
clipboard_cell->text_color = cell->text_color;
clipboard_cell->background_color = cell->background_color;
clipboard_cell->row_height = cell->row_height;
} else {
clipboard_cell = NULL;
}
}
void sheet_copy_cell(Sheet* sheet, int src_row, int src_col, int dest_row, int dest_col) {
Cell* src_cell = sheet_get_cell(sheet, src_row, src_col);
if (!src_cell) {
// Clear destination cell if source is empty
sheet_clear_cell(sheet, dest_row, dest_col);
return;
}
switch (src_cell->type) {
case CELL_NUMBER:
sheet_set_number(sheet, dest_row, dest_col, src_cell->data.number);
break;
case CELL_STRING:
sheet_set_string(sheet, dest_row, dest_col, src_cell->data.string);
break;
case CELL_FORMULA:
sheet_set_formula(sheet, dest_row, dest_col, src_cell->data.formula.expression);
break;
default:
sheet_clear_cell(sheet, dest_row, dest_col);
break;
}
// Copy display properties
Cell* dest_cell = sheet_get_cell(sheet, dest_row, dest_col);
if (dest_cell) {
dest_cell->width = src_cell->width;
dest_cell->precision = src_cell->precision;
dest_cell->align = src_cell->align;
// Copy color formatting
dest_cell->text_color = src_cell->text_color;
dest_cell->background_color = src_cell->background_color;
dest_cell->row_height = src_cell->row_height;
}
sheet_recalculate(sheet);
}
// Range selection functions
void sheet_start_range_selection(Sheet* sheet, int row, int col) {
sheet->selection.start_row = row;
sheet->selection.start_col = col;
sheet->selection.end_row = row;
sheet->selection.end_col = col;
sheet->selection.is_active = 1;
}
void sheet_extend_range_selection(Sheet* sheet, int row, int col) {
if (sheet->selection.is_active) {
sheet->selection.end_row = row;
sheet->selection.end_col = col;
}
}
void sheet_clear_range_selection(Sheet* sheet) {
sheet->selection.is_active = 0;
}
int sheet_is_in_selection(Sheet* sheet, int row, int col) {
if (!sheet->selection.is_active) return 0;
NormalizedRange r = normalize_range(&sheet->selection);
return (row >= r.min_row && row <= r.max_row && col >= r.min_col && col <= r.max_col);
}
// Copy range to clipboard
void sheet_copy_range(Sheet* sheet) {
if (!sheet->selection.is_active) return;
// Free existing clipboard
if (sheet->range_clipboard.cells) {
for (int i = 0; i < sheet->range_clipboard.rows; i++) {
for (int j = 0; j < sheet->range_clipboard.cols; j++) {
if (sheet->range_clipboard.cells[i][j]) {
cell_free(sheet->range_clipboard.cells[i][j]);
}
}
free(sheet->range_clipboard.cells[i]);
}
free(sheet->range_clipboard.cells);
}
// Calculate range dimensions
NormalizedRange r = normalize_range(&sheet->selection);
int rows = r.max_row - r.min_row + 1;
int cols = r.max_col - r.min_col + 1;
// Allocate clipboard
sheet->range_clipboard.rows = rows;
sheet->range_clipboard.cols = cols;
sheet->range_clipboard.cells = (Cell***)calloc(rows, sizeof(Cell**));
if (!sheet->range_clipboard.cells) {
// Handle allocation failure
return;
}
for (int i = 0; i < rows; i++) {
sheet->range_clipboard.cells[i] = (Cell**)calloc(cols, sizeof(Cell*));
if (!sheet->range_clipboard.cells[i]) {
// Handle allocation failure
return;
}
}
// Copy cells
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
Cell* src_cell = sheet_get_cell(sheet, r.min_row + i, r.min_col + j);
if (src_cell) {
Cell* copied_cell = cell_new(r.min_row + i, r.min_col + j);
switch (src_cell->type) {
case CELL_NUMBER:
cell_set_number(copied_cell, src_cell->data.number);
break;
case CELL_STRING:
cell_set_string(copied_cell, src_cell->data.string);
break;
case CELL_FORMULA:
cell_set_formula(copied_cell, src_cell->data.formula.expression);
copied_cell->data.formula.cached_value = src_cell->data.formula.cached_value;
copied_cell->data.formula.error = src_cell->data.formula.error;
break;
default:
break;
}
// Copy display and formatting properties
copied_cell->width = src_cell->width;
copied_cell->precision = src_cell->precision;
copied_cell->align = src_cell->align;
copied_cell->format = src_cell->format;
copied_cell->format_style = src_cell->format_style;
sheet->range_clipboard.cells[i][j] = copied_cell;
}
}
}
sheet->range_clipboard.is_active = 1;
}
// Paste range from clipboard
void sheet_paste_range(Sheet* sheet, int start_row, int start_col) {
if (!sheet->range_clipboard.is_active) return;
for (int i = 0; i < sheet->range_clipboard.rows; i++) {
for (int j = 0; j < sheet->range_clipboard.cols; j++) {
int dest_row = start_row + i;
int dest_col = start_col + j;
if (dest_row >= sheet->rows || dest_col >= sheet->cols) continue;
Cell* src_cell = sheet->range_clipboard.cells[i][j];
if (src_cell) {
Cell* dest_cell = sheet_get_or_create_cell(sheet, dest_row, dest_col);
if (dest_cell) {
switch (src_cell->type) {
case CELL_NUMBER:
cell_set_number(dest_cell, src_cell->data.number);
break;
case CELL_STRING:
cell_set_string(dest_cell, src_cell->data.string);
break;
case CELL_FORMULA:
cell_set_formula(dest_cell, src_cell->data.formula.expression);
sheet->needs_recalc = 1; // Mark sheet for recalculation
break;
default:
cell_clear(dest_cell);
break;
}
// Copy display and formatting properties
dest_cell->width = src_cell->width;
dest_cell->precision = src_cell->precision;
dest_cell->align = src_cell->align;
dest_cell->format = src_cell->format;
dest_cell->format_style = src_cell->format_style;
}
} else {
sheet_clear_cell(sheet, dest_row, dest_col);
}
}
}
sheet_recalculate(sheet);
}
// Cell formatting functions
void cell_set_format(Cell* cell, DataFormat format, FormatStyle style) {
if (!cell) return;
cell->format = format;
cell->format_style = style;
}
char* format_cell_value(Cell* cell) {
static char buffer[256];
if (!cell || cell->type == CELL_EMPTY) {
return "";
}
double value = 0.0;
char* string_value = NULL;
// Get the value to format
switch (cell->type) {
case CELL_NUMBER:
value = cell->data.number;
break;
case CELL_FORMULA:
if (cell->data.formula.error != ERROR_NONE) {
switch (cell->data.formula.error) {
case ERROR_DIV_ZERO: return "#DIV/0!";
case ERROR_REF: return "#REF!";
case ERROR_VALUE: return "#VALUE!";
case ERROR_PARSE: return "#PARSE!";
case ERROR_NA: return "#N/A!";
default: return "#ERROR!";
}
}
if (cell->data.formula.is_string_result && cell->data.formula.cached_string) {
return cell->data.formula.cached_string;
}
value = cell->data.formula.cached_value;
break;
case CELL_STRING:
return cell->data.string;
default:
return "";
}
// Apply formatting based on format type
switch (cell->format) {
case FORMAT_PERCENTAGE:
return format_number_as_percentage(value, cell->precision);
case FORMAT_CURRENCY:
return format_number_as_currency(value);
case FORMAT_DATE:
return format_number_as_date(value, cell->format_style);
case FORMAT_TIME:
return format_number_as_time(value, cell->format_style);
case FORMAT_DATETIME:
// Check if it's one of the enhanced datetime styles
if (cell->format_style == DATETIME_STYLE_SHORT ||
cell->format_style == DATETIME_STYLE_LONG ||
cell->format_style == DATETIME_STYLE_ISO) {
return format_number_as_enhanced_datetime(value, cell->format_style);
} else {
return format_number_as_datetime(value, DATE_STYLE_MM_DD_YYYY, TIME_STYLE_12HR);
}
case FORMAT_NUMBER:
case FORMAT_GENERAL:
default:
// Standard number formatting
snprintf(buffer, sizeof(buffer), "%.*f", cell->precision, value);
// Remove trailing zeros
char* dot = strchr(buffer, '.');
if (dot) {
char* end = buffer + strlen(buffer) - 1;
while (end > dot && *end == '0') *end-- = '\0';
if (*end == '.') *end = '\0';
}
return buffer;
}
}
char* format_number_as_percentage(double value, int precision) {
static char buffer[64];
snprintf(buffer, sizeof(buffer), "%.*f%%", precision, value * 100.0);
return buffer;
}
char* format_number_as_currency(double value) {
static char buffer[64];
if (value < 0) {
snprintf(buffer, sizeof(buffer), "-$%.2f", -value);
} else {
snprintf(buffer, sizeof(buffer), "$%.2f", value);
}
return buffer;
}
char* format_number_as_date(double value, FormatStyle style) {
static char buffer[64];
// Convert Excel serial date to time_t (days since 1900-01-01)
// Excel incorrectly treats 1900 as a leap year, so we need adjustment
time_t base_time = (time_t)EXCEL_BASE_TIME; // 1900-01-01 00:00:00 UTC (adjusted)
time_t date_time = base_time + (time_t)(value * SECONDS_PER_DAY); // seconds per day
struct tm date_struct;
if (gmtime_s(&date_struct, &date_time) != 0) {
strcpy_s(buffer, sizeof(buffer), "#DATE!");
return buffer;
}
switch (style) {
case DATE_STYLE_MM_DD_YYYY:
strftime(buffer, sizeof(buffer), "%m/%d/%Y", &date_struct);
break;
case DATE_STYLE_DD_MM_YYYY:
strftime(buffer, sizeof(buffer), "%d/%m/%Y", &date_struct);
break;
case DATE_STYLE_YYYY_MM_DD:
strftime(buffer, sizeof(buffer), "%Y-%m-%d", &date_struct);
break;
case DATE_STYLE_MON_DD_YYYY:
strftime(buffer, sizeof(buffer), "%b %d, %Y", &date_struct);
break;
case DATE_STYLE_DD_MON_YYYY:
strftime(buffer, sizeof(buffer), "%d %b %Y", &date_struct);
break;
case DATE_STYLE_YYYY_MON_DD:
strftime(buffer, sizeof(buffer), "%Y %b %d", &date_struct);
break;
case DATE_STYLE_SHORT_DATE:
strftime(buffer, sizeof(buffer), "%m/%d/%y", &date_struct);
break;
default:
strftime(buffer, sizeof(buffer), "%Y-%m-%d", &date_struct);
break;
}
return buffer;
}
char* format_number_as_time(double value, FormatStyle style) {
static char buffer[64];
// Extract time portion (fractional part of the day)
double time_fraction = value - floor(value);
if (time_fraction < 0) time_fraction += 1.0;
int total_seconds = (int)(time_fraction * SECONDS_PER_DAY);
int hours = total_seconds / SECONDS_PER_HOUR;
int minutes = (total_seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
int seconds = total_seconds % SECONDS_PER_MINUTE;
switch (style) {
case TIME_STYLE_12HR:
{
int display_hours = hours;
const char* am_pm = "AM";