-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
2064 lines (1829 loc) · 67.8 KB
/
Copy pathmain.c
File metadata and controls
2064 lines (1829 loc) · 67.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
/*
* typewriter - a lightweight typewriter-style text editor
*
* Dependencies: SDL2, SDL2_ttf
* Build: make (or) gcc -O2 main.c -o typewriter $(pkg-config --cflags --libs sdl2 SDL2_ttf) -lm
*/
#define TYPEWRITER_VERSION "0.2.0"
#include <SDL.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Embedded sound data (PCM float32, 44100Hz, mono) */
#include "snd_keypress.h"
#include "snd_clack.h"
#include "snd_space.h"
#include "snd_backspace.h"
#include "snd_bell.h"
/* ── Configuration ─────────────────────────────────────────────── */
#define WINDOW_W 900
#define WINDOW_H 640
#define FONT_SIZE 18
#define TAB_STOP 4
#define SCROLL_SPEED 3
#define MARGIN_LEFT_MIN 20
#define MARGIN_TOP 50
#define GUTTER_PAD 14 /* pixels between line numbers and text */
#define CURSOR_BLINK_MS 530
#define BELL_COLUMN 80
#define MAX_PATH_LEN 4096
#define UNDO_MAX 512
/* ── Colors ────────────────────────────────────────────────────── */
typedef struct {
SDL_Color paper;
SDL_Color text;
SDL_Color cursor;
SDL_Color lnum;
SDL_Color status_bg;
SDL_Color status_fg;
SDL_Color sel_bg;
SDL_Color notebook_line;
SDL_Color notebook_margin;
} Theme;
static const Theme g_themes[] = {
{ /* 0: Cream / Classic */
{ 245, 240, 230, 255 }, { 44, 44, 44, 255 }, { 180, 40, 40, 200 },
{ 180, 175, 165, 255 }, { 60, 58, 54, 255 }, { 210, 205, 195, 255 },
{ 180, 210, 230, 255 }, { 195, 215, 230, 255 }, { 220, 140, 140, 180 }
},
{ /* 1: Dark Mode */
{ 30, 30, 30, 255 }, { 220, 220, 220, 255 }, { 200, 80, 80, 200 },
{ 100, 100, 100, 255 }, { 45, 45, 45, 255 }, { 180, 180, 180, 255 },
{ 60, 90, 120, 255 }, { 50, 50, 50, 255 }, { 100, 60, 60, 180 }
},
{ /* 2: Terminal Green */
{ 10, 10, 10, 255 }, { 50, 200, 50, 255 }, { 50, 200, 50, 200 },
{ 30, 120, 30, 255 }, { 20, 20, 20, 255 }, { 40, 160, 40, 255 },
{ 30, 80, 30, 255 }, { 20, 40, 20, 255 }, { 20, 40, 20, 180 }
}
};
#define THEME_COUNT 3
/* ── Line buffer ───────────────────────────────────────────────── */
typedef struct {
char *text;
int len;
int cap;
} Line;
typedef struct {
Line *lines;
int count;
int cap;
int cx, cy; /* cursor col, row */
int scroll_y; /* first visible line */
int scroll_x; /* first visible column */
int sel_active;
int sel_ax, sel_ay; /* selection anchor */
int dirty;
char filepath[MAX_PATH_LEN];
} Doc;
/* ── Undo system ───────────────────────────────────────────────── */
typedef enum {
UNDO_INSERT_CHAR,
UNDO_DELETE_CHAR,
UNDO_INSERT_LINE,
UNDO_DELETE_LINE,
UNDO_JOIN_LINES,
UNDO_SPLIT_LINE,
} UndoType;
typedef struct {
UndoType type;
int line, col;
char ch;
char *text; /* for line ops; owned, must free */
} UndoEntry;
static UndoEntry g_undo[UNDO_MAX];
static int g_undo_count = 0;
static int g_undo_pos = 0; /* next slot to write */
/* ── Sound ─────────────────────────────────────────────────────── */
#define SAMPLE_RATE 44100
typedef struct {
float *samples;
int len;
} SoundBuf;
static SoundBuf snd_click;
static SoundBuf snd_clack; /* enter */
static SoundBuf snd_space;
static SoundBuf snd_bell;
static SoundBuf snd_backspace;
static SDL_AudioDeviceID audio_dev;
/* ── Options ───────────────────────────────────────────────────── */
typedef struct {
int sound_enabled;
int show_line_numbers;
int show_notebook_lines;
int theme_idx;
int font_size;
} Options;
#define MENU_ITEM_COUNT 5
static const char *menu_labels[MENU_ITEM_COUNT] = {
"Sound effects",
"Line numbers",
"Notebook lines",
"Theme",
"Font size",
};
/* ── Globals ───────────────────────────────────────────────────── */
static SDL_Window *g_win;
static SDL_Renderer *g_ren;
static TTF_Font *g_font; /* Editor font (dynamic) */
static TTF_Font *g_ui_font; /* UI font (fixed size) */
static int g_char_w;
static int g_char_h;
static int g_ui_char_w;
static int g_ui_char_h;
static int g_running = 1;
static int g_need_redraw = 1;
static Doc g_doc;
static Options g_opts = { 1, 1, 0, 0, 18 }; /* sound=on, lnums=on, lines=off, theme=cream, font=18 */
static int g_menu_open = 0;
static int g_menu_sel = 0;
static int g_quit_dialog = 0; /* save-before-quit dialog */
static int g_quit_sel = 0; /* 0=Save, 1=Don't Save, 2=Cancel */
/* Find/Replace state */
static int g_find_dialog = 0;
static char g_find_text[256] = {0};
static char g_replace_text[256] = {0};
static int g_find_focus = 0; /* 0 = Find input, 1 = Replace input */
/* ── Forward declarations ──────────────────────────────────────── */
static void doc_grow(Doc *d);
static void doc_init(Doc *d);
static void doc_free(Doc *d);
static void doc_insert_char(Doc *d, char c);
static void doc_delete_back(Doc *d);
static void doc_delete_forward(Doc *d);
static void doc_insert_newline(Doc *d);
static void doc_ensure_line(Doc *d, int idx);
static int doc_load(Doc *d, const char *path);
static int doc_save(Doc *d);
static int doc_visible_lines(void);
/* ── Utility ───────────────────────────────────────────────────── */
static void *xmalloc(size_t n) {
void *p = malloc(n);
if (!p) { fprintf(stderr, "out of memory\n"); exit(1); }
return p;
}
static void *xrealloc(void *p, size_t n) {
void *q = realloc(p, n);
if (!q) { fprintf(stderr, "out of memory\n"); exit(1); }
return q;
}
static int clamp(int v, int lo, int hi) {
return v < lo ? lo : v > hi ? hi : v;
}
static int min_i(int a, int b) { return a < b ? a : b; }
/* How many decimal digits in n (at least 1) */
static int digit_count(int n) {
if (n < 0) n = -n;
int d = 1;
while (n >= 10) { n /= 10; d++; }
return d;
}
/* Helper to get pixel width of a text segment */
static int text_segment_width(TTF_Font *font, const char *text, int len) {
if (len <= 0) return 0;
int w = 0;
if (len < 1024) {
char buf[1024];
memcpy(buf, text, len);
buf[len] = '\0';
TTF_SizeUTF8(font, buf, &w, NULL);
} else {
char *buf = (char *)xmalloc(len + 1);
memcpy(buf, text, len);
buf[len] = '\0';
TTF_SizeUTF8(font, buf, &w, NULL);
free(buf);
}
return w;
}
/* Compute the left margin (gutter width) based on line count */
static int compute_text_x(int line_count) {
if (!g_opts.show_line_numbers) return MARGIN_LEFT_MIN;
int digits = digit_count(line_count);
if (digits < 3) digits = 3; /* minimum 3 digits wide */
return (digits + 1) * g_ui_char_w + GUTTER_PAD;
}
/* ── Sound (embedded PCM data) ─────────────────────────────────── */
static SoundBuf soundbuf_from_embed(const float *data, int len) {
SoundBuf sb;
sb.len = len;
sb.samples = (float *)xmalloc(len * sizeof(float));
memcpy(sb.samples, data, len * sizeof(float));
return sb;
}
#define MAX_CONCURRENT_SOUNDS 32
typedef struct {
float *samples;
int len;
int pos;
int active;
} ActiveSound;
static ActiveSound g_active_sounds[MAX_CONCURRENT_SOUNDS];
static void audio_callback(void *userdata, Uint8 *stream, int len) {
float *fstream = (float *)stream;
int samples_count = len / sizeof(float);
memset(fstream, 0, len);
for (int i = 0; i < MAX_CONCURRENT_SOUNDS; i++) {
if (g_active_sounds[i].active) {
int remain = g_active_sounds[i].len - g_active_sounds[i].pos;
int to_mix = samples_count < remain ? samples_count : remain;
float *src = g_active_sounds[i].samples + g_active_sounds[i].pos;
for (int j = 0; j < to_mix; j++) {
fstream[j] += src[j];
}
g_active_sounds[i].pos += to_mix;
if (g_active_sounds[i].pos >= g_active_sounds[i].len) {
g_active_sounds[i].active = 0;
}
}
}
}
static void sound_init(void) {
SDL_AudioSpec want = {0}, have;
want.freq = SAMPLE_RATE;
want.format = AUDIO_F32SYS;
want.channels = 1;
want.samples = 512;
want.callback = audio_callback;
want.userdata = NULL;
memset(g_active_sounds, 0, sizeof(g_active_sounds));
audio_dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0);
if (audio_dev == 0) {
fprintf(stderr, "warning: no audio: %s\n", SDL_GetError());
} else {
SDL_PauseAudioDevice(audio_dev, 0);
}
snd_click = soundbuf_from_embed(snd_embed_keypress_data, snd_embed_keypress_LEN);
snd_clack = soundbuf_from_embed(snd_embed_clack_data, snd_embed_clack_LEN);
snd_space = soundbuf_from_embed(snd_embed_space_data, snd_embed_space_LEN);
snd_backspace = soundbuf_from_embed(snd_embed_backspace_data, snd_embed_backspace_LEN);
snd_bell = soundbuf_from_embed(snd_embed_bell_data, snd_embed_bell_LEN);
}
static void play_sound(SoundBuf *sb) {
if (!g_opts.sound_enabled) return;
if (audio_dev && sb->samples) {
SDL_LockAudioDevice(audio_dev);
for (int i = 0; i < MAX_CONCURRENT_SOUNDS; i++) {
if (!g_active_sounds[i].active) {
g_active_sounds[i].samples = sb->samples;
g_active_sounds[i].len = sb->len;
g_active_sounds[i].pos = 0;
g_active_sounds[i].active = 1;
break;
}
}
SDL_UnlockAudioDevice(audio_dev);
}
}
static void sound_cleanup(void) {
if (audio_dev) SDL_CloseAudioDevice(audio_dev);
free(snd_click.samples);
free(snd_clack.samples);
free(snd_space.samples);
free(snd_backspace.samples);
free(snd_bell.samples);
}
/* ── Undo ──────────────────────────────────────────────────────── */
static void undo_push(UndoType type, int line, int col, char ch, const char *text) {
UndoEntry *e = &g_undo[g_undo_pos % UNDO_MAX];
/* Free previous text if overwriting */
if (e->text) { free(e->text); e->text = NULL; }
e->type = type;
e->line = line;
e->col = col;
e->ch = ch;
e->text = text ? SDL_strdup(text) : NULL;
g_undo_pos++;
if (g_undo_count < UNDO_MAX) g_undo_count++;
/* After pushing, we can't redo anything */
}
static void undo_pop(Doc *d) {
if (g_undo_count == 0) return;
g_undo_count--;
g_undo_pos--;
UndoEntry *e = &g_undo[g_undo_pos % UNDO_MAX];
switch (e->type) {
case UNDO_INSERT_CHAR: {
/* An insert was done, so we delete it */
Line *ln = &d->lines[e->line];
if (e->col < ln->len) {
memmove(&ln->text[e->col], &ln->text[e->col + 1], ln->len - e->col - 1);
ln->len--;
}
d->cy = e->line; d->cx = e->col;
} break;
case UNDO_DELETE_CHAR: {
/* A char was deleted, re-insert it */
Line *ln = &d->lines[e->line];
if (ln->len + 1 >= ln->cap) {
ln->cap = (ln->len + 1) * 2;
ln->text = (char *)xrealloc(ln->text, ln->cap);
}
memmove(&ln->text[e->col + 1], &ln->text[e->col], ln->len - e->col);
ln->text[e->col] = e->ch;
ln->len++;
d->cy = e->line; d->cx = e->col + 1;
} break;
case UNDO_SPLIT_LINE: {
/* A newline was inserted, join lines back */
if (e->line + 1 < d->count) {
Line *cur = &d->lines[e->line];
Line *next = &d->lines[e->line + 1];
int need = cur->len + next->len + 1;
if (need >= cur->cap) { cur->cap = need * 2; cur->text = (char *)xrealloc(cur->text, cur->cap); }
memcpy(&cur->text[cur->len], next->text, next->len);
int old_len = cur->len;
cur->len += next->len;
free(next->text);
memmove(&d->lines[e->line + 1], &d->lines[e->line + 2],
(d->count - e->line - 2) * sizeof(Line));
d->count--;
d->cy = e->line; d->cx = old_len;
}
} break;
case UNDO_JOIN_LINES: {
/* Lines were joined, split them back */
int split_at = e->col;
/* Insert new line */
if (d->count + 1 >= d->cap)
doc_grow(d);
memmove(&d->lines[e->line + 2], &d->lines[e->line + 1],
(d->count - e->line - 1) * sizeof(Line));
d->count++;
Line *ln = &d->lines[e->line];
Line *newln = &d->lines[e->line + 1];
int tail = ln->len - split_at;
newln->cap = tail > 16 ? tail * 2 : 16;
newln->text = (char *)xmalloc(newln->cap);
memcpy(newln->text, &ln->text[split_at], tail);
newln->len = tail;
ln->len = split_at;
d->cy = e->line + 1; d->cx = 0;
} break;
case UNDO_INSERT_LINE:
/* A line was inserted, remove it */
if (e->line < d->count) {
free(d->lines[e->line].text);
memmove(&d->lines[e->line], &d->lines[e->line + 1],
(d->count - e->line - 1) * sizeof(Line));
d->count--;
d->cy = e->line > 0 ? e->line - 1 : 0;
d->cx = d->lines[d->cy].len;
}
break;
case UNDO_DELETE_LINE:
/* A line was deleted, re-insert it */
if (d->count + 1 >= d->cap)
doc_grow(d);
memmove(&d->lines[e->line + 1], &d->lines[e->line],
(d->count - e->line) * sizeof(Line));
d->count++;
d->lines[e->line].len = e->text ? (int)strlen(e->text) : 0;
d->lines[e->line].cap = d->lines[e->line].len + 16;
d->lines[e->line].text = (char *)xmalloc(d->lines[e->line].cap);
if (e->text) memcpy(d->lines[e->line].text, e->text, d->lines[e->line].len);
d->cy = e->line; d->cx = 0;
break;
}
if (e->text) { free(e->text); e->text = NULL; }
g_need_redraw = 1;
}
/* ── Document operations ───────────────────────────────────────── */
static void line_init(Line *ln) {
ln->cap = 64;
ln->len = 0;
ln->text = (char *)xmalloc(ln->cap);
}
static void doc_init(Doc *d) {
memset(d, 0, sizeof(*d));
d->cap = 64;
d->lines = (Line *)xmalloc(d->cap * sizeof(Line));
d->count = 1;
line_init(&d->lines[0]);
}
static void doc_free(Doc *d) {
for (int i = 0; i < d->count; i++) free(d->lines[i].text);
free(d->lines);
}
static void doc_grow(Doc *d) {
int new_cap = d->cap < 1024 ? d->cap * 2 : d->cap + d->cap / 2;
if (new_cap <= d->cap) new_cap = d->cap + 1024; /* overflow guard */
d->lines = (Line *)xrealloc(d->lines, (size_t)new_cap * sizeof(Line));
d->cap = new_cap;
}
static void doc_ensure_line(Doc *d, int idx) {
while (d->count <= idx) {
if (d->count >= d->cap)
doc_grow(d);
line_init(&d->lines[d->count]);
d->count++;
}
}
static void line_insert_char(Line *ln, int pos, char c) {
if (ln->len + 1 >= ln->cap) {
ln->cap *= 2;
ln->text = (char *)xrealloc(ln->text, ln->cap);
}
memmove(&ln->text[pos + 1], &ln->text[pos], ln->len - pos);
ln->text[pos] = c;
ln->len++;
}
static void doc_insert_char(Doc *d, char c) {
doc_ensure_line(d, d->cy);
Line *ln = &d->lines[d->cy];
int pos = clamp(d->cx, 0, ln->len);
undo_push(UNDO_INSERT_CHAR, d->cy, pos, c, NULL);
line_insert_char(ln, pos, c);
d->cx = pos + 1;
d->dirty = 1;
/* Bell at margin */
if (d->cx == BELL_COLUMN)
play_sound(&snd_bell);
}
static void doc_delete_back(Doc *d) {
if (d->cx > 0) {
Line *ln = &d->lines[d->cy];
d->cx = clamp(d->cx, 0, ln->len);
if (d->cx > 0) {
d->cx--;
undo_push(UNDO_DELETE_CHAR, d->cy, d->cx, ln->text[d->cx], NULL);
memmove(&ln->text[d->cx], &ln->text[d->cx + 1], ln->len - d->cx - 1);
ln->len--;
d->dirty = 1;
}
} else if (d->cy > 0) {
/* Join with previous line */
Line *prev = &d->lines[d->cy - 1];
Line *cur = &d->lines[d->cy];
int old_len = prev->len;
undo_push(UNDO_JOIN_LINES, d->cy - 1, old_len, 0, NULL);
if (prev->len + cur->len + 1 >= prev->cap) {
prev->cap = (prev->len + cur->len + 1) * 2;
prev->text = (char *)xrealloc(prev->text, prev->cap);
}
memcpy(&prev->text[prev->len], cur->text, cur->len);
prev->len += cur->len;
free(cur->text);
memmove(&d->lines[d->cy], &d->lines[d->cy + 1],
(d->count - d->cy - 1) * sizeof(Line));
d->count--;
d->cy--;
d->cx = old_len;
d->dirty = 1;
}
}
static void doc_delete_forward(Doc *d) {
Line *ln = &d->lines[d->cy];
if (d->cx < ln->len) {
undo_push(UNDO_DELETE_CHAR, d->cy, d->cx, ln->text[d->cx], NULL);
memmove(&ln->text[d->cx], &ln->text[d->cx + 1], ln->len - d->cx - 1);
ln->len--;
d->dirty = 1;
} else if (d->cy + 1 < d->count) {
/* Join with next line */
Line *next = &d->lines[d->cy + 1];
undo_push(UNDO_JOIN_LINES, d->cy, ln->len, 0, NULL);
if (ln->len + next->len + 1 >= ln->cap) {
ln->cap = (ln->len + next->len + 1) * 2;
ln->text = (char *)xrealloc(ln->text, ln->cap);
}
memcpy(&ln->text[ln->len], next->text, next->len);
ln->len += next->len;
free(next->text);
memmove(&d->lines[d->cy + 1], &d->lines[d->cy + 2],
(d->count - d->cy - 2) * sizeof(Line));
d->count--;
d->dirty = 1;
}
}
static void doc_insert_newline(Doc *d) {
doc_ensure_line(d, d->cy);
d->cx = clamp(d->cx, 0, d->lines[d->cy].len);
undo_push(UNDO_SPLIT_LINE, d->cy, d->cx, 0, NULL);
/* Make room for new line */
if (d->count + 1 >= d->cap) {
doc_grow(d);
}
memmove(&d->lines[d->cy + 2], &d->lines[d->cy + 1],
(d->count - d->cy - 1) * sizeof(Line));
d->count++;
/* Split text */
Line *ln = &d->lines[d->cy];
Line *newln = &d->lines[d->cy + 1];
int tail = ln->len - d->cx;
newln->cap = tail > 16 ? tail * 2 : 16;
newln->text = (char *)xmalloc(newln->cap);
memcpy(newln->text, &ln->text[d->cx], tail);
newln->len = tail;
ln->len = d->cx;
d->cy++;
d->cx = 0;
d->dirty = 1;
}
static int doc_visible_lines(void) {
int ww, wh;
SDL_GetWindowSize(g_win, &ww, &wh);
return (wh - MARGIN_TOP - 30) / g_char_h; /* 30px for status bar */
}
static void doc_scroll_to_cursor(Doc *d) {
int ww, wh;
SDL_GetWindowSize(g_win, &ww, &wh);
int vis_y = doc_visible_lines();
int text_x = compute_text_x(d->count);
int vis_x = (ww - text_x - MARGIN_LEFT_MIN) / g_char_w;
if (vis_x < 1) vis_x = 1;
/* Vertical scroll */
if (d->cy < d->scroll_y)
d->scroll_y = d->cy;
else if (d->cy >= d->scroll_y + vis_y)
d->scroll_y = d->cy - vis_y + 1;
/* Horizontal scroll */
if (d->cx < d->scroll_x)
d->scroll_x = d->cx;
else if (d->cx >= d->scroll_x + vis_x)
d->scroll_x = d->cx - vis_x + 1;
}
static int doc_load(Doc *d, const char *path) {
FILE *f = fopen(path, "rb");
if (!f) return -1;
/* Clear existing doc */
for (int i = 0; i < d->count; i++) free(d->lines[i].text);
d->count = 0;
d->cx = d->cy = d->scroll_y = 0;
d->dirty = 0;
snprintf(d->filepath, MAX_PATH_LEN, "%s", path);
char buf[8192];
int line_idx = 0;
doc_ensure_line(d, 0);
while (fgets(buf, sizeof(buf), f)) {
int len = (int)strlen(buf);
/* Strip \r\n or \n */
while (len > 0 && (buf[len-1] == '\n' || buf[len-1] == '\r')) len--;
doc_ensure_line(d, line_idx);
Line *ln = &d->lines[line_idx];
if (len >= ln->cap) {
ln->cap = len * 2;
ln->text = (char *)xrealloc(ln->text, ln->cap);
}
memcpy(ln->text, buf, len);
ln->len = len;
line_idx++;
}
if (d->count == 0) doc_ensure_line(d, 0);
fclose(f);
/* Reset undo on load */
g_undo_count = g_undo_pos = 0;
return 0;
}
static int doc_save(Doc *d) {
if (d->filepath[0] == '\0') return -1;
FILE *f = fopen(d->filepath, "wb");
if (!f) return -1;
for (int i = 0; i < d->count; i++) {
fwrite(d->lines[i].text, 1, d->lines[i].len, f);
fputc('\n', f);
}
fclose(f);
d->dirty = 0;
return 0;
}
/* ── Selection helpers ─────────────────────────────────────────── */
static void sel_start(Doc *d) {
if (!d->sel_active) {
d->sel_active = 1;
d->sel_ax = d->cx;
d->sel_ay = d->cy;
}
}
static void sel_clear(Doc *d) {
d->sel_active = 0;
}
static void sel_get_range(Doc *d, int *r1, int *c1, int *r2, int *c2) {
if (d->sel_ay < d->cy || (d->sel_ay == d->cy && d->sel_ax <= d->cx)) {
*r1 = d->sel_ay; *c1 = d->sel_ax;
*r2 = d->cy; *c2 = d->cx;
} else {
*r1 = d->cy; *c1 = d->cx;
*r2 = d->sel_ay; *c2 = d->sel_ax;
}
}
static void sel_delete(Doc *d) {
if (!d->sel_active) return;
int r1, c1, r2, c2;
sel_get_range(d, &r1, &c1, &r2, &c2);
d->cy = r1; d->cx = c1;
if (r1 == r2) {
Line *ln = &d->lines[r1];
memmove(&ln->text[c1], &ln->text[c2], ln->len - c2);
ln->len -= (c2 - c1);
} else {
/* Keep start of first line + end of last line */
Line *first = &d->lines[r1];
Line *last = &d->lines[r2];
int tail = last->len - c2;
if (c1 + tail >= first->cap) {
first->cap = (c1 + tail) * 2;
first->text = (char *)xrealloc(first->text, first->cap);
}
memcpy(&first->text[c1], &last->text[c2], tail);
first->len = c1 + tail;
/* Remove intermediate lines */
for (int i = r1 + 1; i <= r2; i++) free(d->lines[i].text);
int removed = r2 - r1;
memmove(&d->lines[r1 + 1], &d->lines[r2 + 1],
(d->count - r2 - 1) * sizeof(Line));
d->count -= removed;
}
sel_clear(d);
d->dirty = 1;
}
static char *sel_get_text(Doc *d) {
if (!d->sel_active) return NULL;
int r1, c1, r2, c2;
sel_get_range(d, &r1, &c1, &r2, &c2);
/* Calculate total size */
int total = 0;
for (int i = r1; i <= r2; i++) {
int start = (i == r1) ? c1 : 0;
int end = (i == r2) ? c2 : d->lines[i].len;
total += (end - start);
if (i < r2) total++; /* newline */
}
char *text = (char *)xmalloc(total + 1);
int pos = 0;
for (int i = r1; i <= r2; i++) {
int start = (i == r1) ? c1 : 0;
int end = (i == r2) ? c2 : d->lines[i].len;
memcpy(&text[pos], &d->lines[i].text[start], end - start);
pos += (end - start);
if (i < r2) text[pos++] = '\n';
}
text[pos] = '\0';
return text;
}
/* ── Font loading ──────────────────────────────────────────────── */
/* Try multiple typewriter/monospace fonts in order of preference */
static const char *font_candidates[] = {
/* Typewriter-style fonts */
"C:/Windows/Fonts/cour.ttf", /* Courier New (Windows) */
"C:/Windows/Fonts/courbd.ttf", /* Courier New Bold (Windows) */
"C:/Windows/Fonts/lucon.ttf", /* Lucida Console (Windows) */
"/Library/Fonts/Courier New.ttf", /* macOS */
"/System/Library/Fonts/Courier.dfont", /* macOS system */
"/Library/Fonts/American Typewriter.ttf", /* macOS typewriter */
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", /* Linux */
"/usr/share/fonts/TTF/DejaVuSansMono.ttf",
"/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",
"/usr/share/fonts/truetype/ubuntu/UbuntuMono-R.ttf",
"/usr/share/fonts/gnu-free/FreeMono.ttf",
"/usr/share/fonts/truetype/freefont/FreeMono.ttf",
"/usr/share/fonts/noto/NotoSansMono-Regular.ttf",
NULL
};
static TTF_Font *load_font(int size) {
/* First try bundled font next to executable */
char exe_path[MAX_PATH_LEN];
/* Try "typewriter.ttf" next to the binary */
const char *base = SDL_GetBasePath();
if (base) {
snprintf(exe_path, sizeof(exe_path), "%stypewriter.ttf", base);
TTF_Font *f = TTF_OpenFont(exe_path, size);
if (f) return f;
}
/* Try font path from environment */
const char *env_font = SDL_getenv("TYPEWRITER_FONT");
if (env_font) {
TTF_Font *f = TTF_OpenFont(env_font, size);
if (f) return f;
}
/* Try system fonts */
for (int i = 0; font_candidates[i]; i++) {
TTF_Font *f = TTF_OpenFont(font_candidates[i], size);
if (f) return f;
}
return NULL;
}
/* ── Rendering ─────────────────────────────────────────────────── */
static void render_text(TTF_Font *font, const char *text, int len, int x, int y,
SDL_Color col) {
if (len <= 0) return;
/* Build null-terminated substring */
char *buf = (char *)xmalloc(len + 1);
memcpy(buf, text, len);
buf[len] = '\0';
SDL_Surface *surf = TTF_RenderUTF8_Blended(font, buf, col);
free(buf);
if (!surf) return;
SDL_Texture *tex = SDL_CreateTextureFromSurface(g_ren, surf);
SDL_Rect dst = { x, y, surf->w, surf->h };
SDL_RenderCopy(g_ren, tex, NULL, &dst);
SDL_DestroyTexture(tex);
SDL_FreeSurface(surf);
}
static int *menu_opt_ptr(int idx) {
switch (idx) {
case 0: return &g_opts.sound_enabled;
case 1: return &g_opts.show_line_numbers;
case 2: return &g_opts.show_notebook_lines;
case 3: return &g_opts.theme_idx;
default: return NULL;
}
}
static void render(Doc *d) {
int ww, wh;
SDL_GetWindowSize(g_win, &ww, &wh);
int t_idx = clamp(g_opts.theme_idx, 0, THEME_COUNT - 1);
const Theme *t = &g_themes[t_idx];
/* Paper background */
SDL_SetRenderDrawColor(g_ren, t->paper.r, t->paper.g, t->paper.b, 255);
SDL_RenderClear(g_ren);
int text_x = compute_text_x(d->count);
/* Subtle left margin line */
if (g_opts.show_line_numbers) {
SDL_SetRenderDrawColor(g_ren, t->lnum.r, t->lnum.g, t->lnum.b, 100);
SDL_RenderDrawLine(g_ren, text_x - 10, 0, text_x - 10, wh - 28);
}
int vis = doc_visible_lines();
int sel_r1 = 0, sel_c1 = 0, sel_r2 = 0, sel_c2 = 0;
if (d->sel_active)
sel_get_range(d, &sel_r1, &sel_c1, &sel_r2, &sel_c2);
/* Notebook lines — draw across the full visible area */
if (g_opts.show_notebook_lines) {
SDL_SetRenderDrawColor(g_ren, t->notebook_line.r, t->notebook_line.g, t->notebook_line.b, 255);
for (int i = 0; i < vis + 1; i++) {
int ly = MARGIN_TOP + i * g_char_h + g_char_h - 1;
if (ly < wh - 28)
SDL_RenderDrawLine(g_ren, 0, ly, ww, ly);
}
/* Red margin line for notebook look */
SDL_SetRenderDrawColor(g_ren, t->notebook_margin.r, t->notebook_margin.g, t->notebook_margin.b, t->notebook_margin.a);
int margin_x = text_x - 6;
SDL_RenderDrawLine(g_ren, margin_x, 0, margin_x, wh - 28);
}
for (int i = 0; i < vis && d->scroll_y + i < d->count; i++) {
int li = d->scroll_y + i;
int y = MARGIN_TOP + i * g_char_h;
Line *ln = &d->lines[li];
/* Line number — right-aligned in the gutter */
if (g_opts.show_line_numbers) {
char lnum[32];
int digits = digit_count(d->count);
if (digits < 3) digits = 3;
snprintf(lnum, sizeof(lnum), "%*d", digits, li + 1);
int lnum_w = text_segment_width(g_ui_font, lnum, (int)strlen(lnum));
render_text(g_ui_font, lnum, (int)strlen(lnum), text_x - GUTTER_PAD - lnum_w, y + (g_char_h - g_ui_char_h)/2, t->lnum);
}
/* Selection highlight */
if (d->sel_active && li >= sel_r1 && li <= sel_r2) {
int sc = (li == sel_r1) ? sel_c1 : 0;
int ec = (li == sel_r2) ? sel_c2 : ln->len;
int sc_rel = sc > d->scroll_x ? sc - d->scroll_x : 0;
int ec_rel = ec > d->scroll_x ? ec - d->scroll_x : 0;
if (sc_rel < ec_rel && ln->len > d->scroll_x) {
int x1 = text_x + text_segment_width(g_font, &ln->text[d->scroll_x], sc_rel);
int x2 = text_x + text_segment_width(g_font, &ln->text[d->scroll_x], ec_rel);
SDL_Rect hr = { x1, y, x2 - x1, g_char_h };
SDL_SetRenderDrawColor(g_ren, t->sel_bg.r, t->sel_bg.g, t->sel_bg.b, 255);
SDL_RenderFillRect(g_ren, &hr);
}
}
/* Line text with horizontal scroll and clipping */
if (ln->len > d->scroll_x) {
int start_col = d->scroll_x;
int len = ln->len - start_col;
/* Conservative estimate: assume at least 4px per character */
int max_vis_chars = (ww - text_x) / 4 + 40;
if (len > max_vis_chars) len = max_vis_chars;
if (len > 0)
render_text(g_font, &ln->text[start_col], len, text_x, y, t->text);
}
}
/* Cursor */
Uint32 now = SDL_GetTicks();
if ((now / CURSOR_BLINK_MS) % 2 == 0) {
int cx_rel = d->cx - d->scroll_x;
int cy_screen = MARGIN_TOP + (d->cy - d->scroll_y) * g_char_h;
if (d->cy >= d->scroll_y && d->cy < d->scroll_y + vis && cx_rel >= 0) {
Line *ln = &d->lines[d->cy];
int cx_screen = text_x + text_segment_width(g_font, &ln->text[d->scroll_x], cx_rel);
if (cx_screen < ww) {
SDL_SetRenderDrawColor(g_ren, t->cursor.r, t->cursor.g, t->cursor.b, t->cursor.a);
SDL_Rect cr = { cx_screen, cy_screen, 2, g_char_h };
SDL_RenderFillRect(g_ren, &cr);
/* Underscore style second cursor indicator */
int next_w = g_char_w;
if (d->cx < ln->len) {
next_w = text_segment_width(g_font, &ln->text[d->cx], 1);
if (next_w <= 0) next_w = g_char_w;
}
if (cx_screen + next_w <= ww) {
SDL_Rect ul = { cx_screen, cy_screen + g_char_h - 2, next_w, 2 };
SDL_RenderFillRect(g_ren, &ul);
}
}
}
}
/* Status bar */
SDL_Rect sb = { 0, wh - 28, ww, 28 };
SDL_SetRenderDrawColor(g_ren, t->status_bg.r, t->status_bg.g, t->status_bg.b, 255);
SDL_RenderFillRect(g_ren, &sb);
char status[512];
char fname_short[128];
const char *fname = d->filepath[0] ? d->filepath : "[untitled]";
/* Truncate displayed filename to fit status bar */
snprintf(fname_short, sizeof(fname_short), "%.120s", fname);
snprintf(status, sizeof(status), " %s%s | Ln %d, Col %d | %d lines | Ctrl+K options",
fname_short, d->dirty ? " *" : "", d->cy + 1, d->cx + 1, d->count);
render_text(g_ui_font, status, (int)strlen(status), 8, wh - 24, t->status_fg);
/* ── Options menu overlay ── */
if (g_menu_open) {
/* Semi-transparent backdrop */
SDL_SetRenderDrawBlendMode(g_ren, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(g_ren, 0, 0, 0, 140);
SDL_Rect overlay = { 0, 0, ww, wh };
SDL_RenderFillRect(g_ren, &overlay);
/* Shortcuts reference */
static const char *shortcut_keys[] = {
"Ctrl+S", "Ctrl+O", "Ctrl+Q", "Ctrl+Z",
"Ctrl+C", "Ctrl+X", "Ctrl+V", "Ctrl+A",
"Ctrl+F",
};
static const char *shortcut_desc[] = {
"Save", "Open", "Quit", "Undo",
"Copy", "Cut", "Paste", "Select all",
"Find & Replace",
};
#define SHORTCUT_COUNT 9
/* Menu panel — sized to fit options + shortcuts */
int opts_h = MENU_ITEM_COUNT * 32;
int shorts_h = SHORTCUT_COUNT * 22;
int panel_w = 400;
int panel_h = 48 + opts_h + 20 + shorts_h + 44;
int panel_x = (ww - panel_w) / 2;
int panel_y = (wh - panel_h) / 2;
/* Panel background */
SDL_SetRenderDrawColor(g_ren, 50, 48, 44, 240);
SDL_Rect panel = { panel_x, panel_y, panel_w, panel_h };
SDL_RenderFillRect(g_ren, &panel);
/* Panel border */
SDL_SetRenderDrawColor(g_ren, 90, 85, 78, 255);
SDL_RenderDrawRect(g_ren, &panel);