-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.cc
2229 lines (2072 loc) · 80.2 KB
/
main.cc
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
/* Ad-hoc programming editor for DOSBox -- (C) 2011-03-08 Joel Yliluoma */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include "langdefs.hh"
#include "kbhit.hh"
#include "vga.hh"
#include "chartype.hh"
#include "jsf.hh"
#include "cpu.h"
#ifdef __BORLANDC__
# include <process.h> // For Cycles adjust on DOSBOX
# include <dos.h> // MK_FP, getpsp, inportb
#endif
#ifdef __DJGPP__
# include <dos.h>
# include <dpmi.h>
# include <go32.h>
# include <sys/farptr.h>
#endif
#define CTRL(c) ((c) & 0x1F)
static const bool ENABLE_DRAG = false;
static unsigned long chars_file = 0;
static unsigned long chars_typed = 0;
static bool use9bit=false, dblw=false, dblh=false;
static inline int isalnum_(unsigned char c)
{
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57)/*isalnum(c)*/ || c == '_';
}
static inline int ispunct_(unsigned char c)
{
return !isspace(c) && !isalnum_(c);
}
static inline int isspace_or_punct(unsigned char c)
{
return !isalnum_(c);
}
// Return just the filename part of pathfilename
const char* fnpart(const char* fn)
{
if(!fn) return "[untitled]";
for(;;)
{
const char* p = strchr(fn, '/');
if(!p) break;
fn = p+1;
}
return fn;
}
char StatusLine[256] = // WARNING: Not range-checked
"Ad-hoc programming editor - (C) 2011-03-08 Joel Yliluoma";
EditorLineVecType EditLines;
struct Anchor
{
size_t x, y;
Anchor() : x(0), y(0) { }
};
enum { MaxSavedCursors = 4, NumCursors = MaxSavedCursors + 2 };
Anchor Win, SavedCursors[NumCursors];
bool InsertMode =true;
char WaitingCtrl =0;
unsigned char CurrentCursor=0;
unsigned char TabSize =4;
#define Cur SavedCursors[CurrentCursor]
#define BlockBegin SavedCursors[MaxSavedCursors ]
#define BlockEnd SavedCursors[MaxSavedCursors+1]
bool UnsavedChanges = false;
char* CurrentFileName = nullptr;
static void FileLoad(const char* fn)
{
fprintf(stderr, "Loading '%s'...\n", fn);
FILE* fp = fopen(fn, "rb");
if(!fp) { perror(fn); return; }
fseek(fp, 0, SEEK_END);
rewind(fp);
if(CurrentFileName) free(CurrentFileName);
CurrentFileName = strdup(fn);
EditLines.clear();
int hadnl = 1;
EditorCharVecType editline;
int got_cr = 0;
for(;;)
{
unsigned char Buf[512];
size_t r = fread(Buf, 1, sizeof(Buf), fp);
if(r == 0) break;
for(size_t a=0; a<r; ++a)
{
if(Buf[a] == '\r' && !got_cr) { got_cr = 1; continue; }
int maxrepeat = (got_cr && Buf[a] != '\n') ? 2 : 1;
for(int repeat=0; repeat<maxrepeat; ++repeat)
{
unsigned char c = Buf[a];
if(repeat == 0 && got_cr) c = '\n';
if(c == '\t')
{
size_t nextstop = editline.size() + TabSize;
nextstop -= nextstop % TabSize;
editline.resize(nextstop, MakeUnknownColor(' '));
/*while(editline.size() < nextstop)
editline.push_back( MakeUnknownColor(' ') );*/
}
else
editline.push_back( MakeUnknownColor(c) );
hadnl = 0;
if(c == '\n')
{
EditLines.push_back(editline);
editline.clear();
hadnl = 1;
}
}
got_cr = Buf[a] == '\r';
}
}
if(hadnl)
{
EditLines.push_back(editline);
editline.clear();
}
fclose(fp);
Win = Cur = Anchor();
UnsavedChanges = false;
chars_file = 0;
for(size_t a=0; a<EditLines.size(); ++a)
chars_file += EditLines[a].size();
}
static void FileNew()
{
Win = Cur = Anchor();
EditLines.clear();
EditorCharVecType emptyline;
emptyline.push_back(MakeUnknownColor('\n'));
EditLines.push_back(emptyline);
EditLines.push_back(emptyline);
EditLines.push_back(emptyline);
if(CurrentFileName) free(CurrentFileName);
CurrentFileName = 0;
chars_file = 3; // Three newlines
}
struct ApplyEngine
#if !(defined(__cplusplus) && __cplusplus >= 199700L)
: public JSF::Applier
#endif
{
bool finished;
unsigned nlinestotal, nlines;
size_t x,y, begin_line;
unsigned pending_recolor_distance, pending_recolor;
EditorCharType pending_attr;
ApplyEngine()
{ Reset(0); }
void Reset(size_t line)
{ x=0; y=begin_line=line; finished=false; nlinestotal=nlines=0;
pending_recolor=0;
pending_attr =0;
}
#if !(defined(__cplusplus) && __cplusplus >= 199700L)
virtual cdecl
#endif
int Get(void)
{
if(y >= EditLines.size() || EditLines[y].empty())
{
finished = true;
FlushColor();
return -1;
}
int ret = ExtractCharCode(EditLines[y][x]);
if(ret == '\n')
{
if(kbhit()) { return -1; }
++nlines;
if((nlines >= VidH)
|| (nlinestotal > Win.y + VidH && nlines >= 4))
{ nlines=0; FlushColor(); return -1; }
++nlinestotal;
}
pending_recolor_distance += 1;
++x;
if(x == EditLines[y].size()) { x=0; ++y; }
//fprintf(stdout, "Gets '%c'\n", ret);
return ret;
}
/* attr = Attribute to set
* n = Number of last characters to apply that attribute for
* distance = Extra number of characters to count and skip
*/
#if !(defined(__cplusplus) && __cplusplus >= 199700L)
virtual cdecl
#endif
void Recolor(register unsigned distance, register unsigned n, register EditorCharType attr)
{
/* Flush the previous req, unless this new req is a super-set of the previous request */
if(pending_recolor > 0)
{
register unsigned old_apply_begin = pending_recolor + pending_recolor_distance;
register unsigned old_apply_end = pending_recolor_distance;
register unsigned new_apply_begin = distance + n;
register unsigned new_apply_end = distance;
if(new_apply_begin < old_apply_begin || new_apply_end > old_apply_end)
{
FlushColor();
}
}
pending_recolor_distance = distance;
pending_recolor = n;
pending_attr = attr;
}
private:
void FlushColor()
{
register unsigned dist = pending_recolor_distance;
register unsigned n = pending_recolor;
register EditorCharType attr = pending_attr;
if(n > 0)
{
//fprintf(stdout, "Recolors %u as %02X\n", n, attr);
size_t px=x, py=y;
EditorCharVecType* line = &EditLines[py];
for(n += dist; n > 0; --n)
{
if(px == 0) { if(!py) break; line = &EditLines[--py]; px = line->size()-1; }
else --px;
if(dist > 0)
--dist;
else
{
EditorCharType& w = (*line)[px];
w = ::Recolor(w, attr);
}
}
}
pending_recolor = 0;
pending_recolor_distance = 0;
}
};
#include "mario.hh"
unsigned CursorCounter = 0;
/* SoftCursor is only used in the C64 simulation mode. */
static void VisSoftCursor(int mode)
{
if(!C64palette) return; // Don't do anything if C64palette is not activated.
/* Modes:
* 0 = blink ticker (100 Hz)
* 1 = screen contents have changed
* -1 = request undo the cursor at current location
*/
static unsigned short* cursor_location = nullptr;
static unsigned evacuation = 0;
// *READ* hardware cursor position from screen */
unsigned char cux=0, cuy=0;
#ifdef __BORLANDC__
_asm { mov ah, 3; mov bh, 0; int 0x10; mov cux, dl; mov cuy, dh; xchg cx,cx }
#elif defined(__DJGPP__)
{ REGS r{}; r.h.ah = 3; r.h.bh = 0; int86(0x10, &r, &r); cux = r.h.dl; cuy = r.h.dh; }
#endif
// Get the corresponding location in the video memory
unsigned short* now_location = GetVidMem(cux,cuy); //VidMem + cux + cuy * unsigned(VidW + C64palette*4);
if(mode == 1) // screen redrawn
{
cursor_location = now_location;
evacuation = *now_location;
CursorCounter = 0;
}
if(mode == -1 || now_location != cursor_location) // undo
{
if(cursor_location) *cursor_location = evacuation;
if(mode == -1) { cursor_location = 0; return; }
cursor_location = now_location;
evacuation = *now_location;
CursorCounter = 0;
}
switch(CursorCounter++)
{
case 60:
CursorCounter=0;
#ifdef __GNUC__
[[fallthrough]];
#endif
case 0:
*cursor_location = ((evacuation&0xF00) << 4) | evacuation;
break;
case 30:
*cursor_location = evacuation;
}
}
void VisPutCursorAt(unsigned cx,unsigned cy)
{
#ifdef __BORLANDC__
unsigned size = InsertMode ? (VidCellHeight-2) : (VidCellHeight*2/8);
size = (size << 8) | (VidCellHeight-1);
if(C64palette) size = 0x3F3F;
#else
unsigned top = VidCellHeight>8 ? VidCellHeight-4 : 6;
unsigned bottom = VidCellHeight>8 ? VidCellHeight-3 : 7;
if(!InsertMode) top = VidCellHeight*2/8;
unsigned size = (top<<8) | bottom;
#endif
VgaPutCursorAt(cx,cy, size);
CursorCounter=0;
}
void VisSetCursor()
{
unsigned cx = Win.x > Cur.x ? 0 : Cur.x-Win.x; if(cx >= VidW) cx = VidW-1;
unsigned cy = Win.y > Cur.y ? 1 : Cur.y-Win.y; ++cy; if(cy >= VidH) cy = VidH-1;
VisPutCursorAt(cx,cy);
}
static long CYCLES_Current = 80000l;
static long CYCLES_Goal = 80000l;
static int Cycles_Trend = 0;
static void Cycles_Adjust(int direction)
{
Cycles_Trend = direction;
}
static void Cycles_Check()
{
// For Cycles adjust on DOSBOX
if(Cycles_Trend > 0 && CYCLES_Goal < 1000000l)
{
CYCLES_Goal = CYCLES_Goal * 125l / 100l;
}
if(Cycles_Trend < 0 && CYCLES_Goal > 12000l)
{
if(CYCLES_Goal > 150000l)
CYCLES_Goal = CYCLES_Goal * 5l / 10l;
else
CYCLES_Goal = CYCLES_Goal * 7l / 10l;
}
if(CYCLES_Goal/3000l != CYCLES_Current/3000l)
{
//static unsigned counter=0;
//if(counter != 1) return;//if(++counter < 5) return;
//counter=0;
CYCLES_Current = CYCLES_Goal;
#ifdef __BORLANDC__
char Buf[64];
sprintf(Buf, " CYCLES=%ld", CYCLES_Current);
unsigned psp = getpsp();
strcpy( (char*) MK_FP(psp, 0x80), Buf);
// FIXME: THIS METHOD OF INVOKING CONFIG.COM DEPENDS ON EXACT DOSBOX VERSION.
// ALSO, IT WILL NOT WORK IF RUNNING E.G. UNDER FREEDOS OR DPMI...
_asm { db 0xFE,0x38,0x06,0x00 }
#elif defined(__DJGPP__)
/* HUGE WARNING: THIS *REQUIRES* A PATCHED DOSBOX,
* UNPATCHED DOSBOXES WILL TRIGGER AN EXCEPTION HERE */
__asm__ volatile("movl %0, %%tr2" : : "a"(CYCLES_Current));
#else
#warning "No CPU speed control"
#endif
}
Cycles_Trend = 0;
}
struct ColorSlideCache
{
enum { MaxWidth = 192 };
const unsigned char* const colors;
const unsigned short* const color_positions;
const unsigned color_length;
unsigned cached_width;
unsigned short cache_color[MaxWidth];
unsigned char cache_char[MaxWidth];
public:
ColorSlideCache(const unsigned char* c, const unsigned short* p, unsigned l)
: colors(c), color_positions(p), color_length(l), cached_width(0) {}
void SetWidth(unsigned w)
{
if(w == cached_width) return;
cached_width = w;
unsigned char first=0;
{ memset(cache_char, 0, sizeof(cache_char)); memset(cache_color, 0, sizeof(cache_color)); }
for(unsigned x=0; x<w && x<MaxWidth; ++x)
{
unsigned short cur_position = (((unsigned long)x) << 16u) / w;
while(first < color_length && color_positions[first] <= cur_position) ++first;
unsigned long next_position=0;
unsigned char next_value=0;
if(first < color_length)
{ next_position = color_positions[first]; next_value = colors[first]; }
else
{ next_position = 10000ul; next_value = colors[color_length-1]; }
unsigned short prev_position=0;
unsigned char prev_value =next_value;
if(first > 0)
{ prev_position = color_positions[first-1]; prev_value = colors[first-1]; }
float position = (cur_position - prev_position) / float(next_position - prev_position );
//static const unsigned char chars[4] = { 0x20, 0xB0, 0xB1, 0xB2 };
//register unsigned char ch = chars[unsigned(position*4)];
static const unsigned char chars[2] = { 0x20, 0xDC };
register unsigned char ch = chars[unsigned(position*2)];
//unsigned char ch = 'A';
if(prev_value == next_value || ch == 0x20) { ch = 0x20; next_value = 0; }
cache_char[x] = ch;
cache_color[x] = prev_value | (next_value << 8u);
//cache[x] = 0x80008741ul;
}
}
inline void Get(unsigned x, unsigned char& ch, unsigned char& c1, unsigned char& c2) const
{
register unsigned short tmp = cache_color[x];
ch = cache_char[x];
c1 = tmp;
c2 = tmp >> 8u;
}
};
/*
float xscale = x * (sizeof(slide)-1) / float(StatusWidth-1);
unsigned c1 = slide[(unsigned)( xscale + Bayer[0*8 + (x&7)] )];
unsigned c2 = slide[(unsigned)( xscale + Bayer[1*8 + (x&7)] )];
unsigned char ch = 0xDC;
*/
#ifdef ATTRIBUTE_CODES_IN_ANSI_ORDER
static const unsigned char slide1_colors[21] = {6,73,109,248,7,7,7,7,7,248,109,73,6,6,6,36,35,2,2,28,22};
static const unsigned short slide1_positions[21] = {0u,1401u,3711u,6302u,7072u,8192u,16384u,24576u,32768u,33889u,34659u,37250u,39560u,40960u,49152u,50903u,53634u,55944u,57344u,59937u,63981u};
static const unsigned char slide2_colors[35] = {248,7,249,250,251,252,188,253,254,255,15,230,229,228,227,11,227,185,186,185,179,143,142,136,100,94,58,239,238,8,236,235,234,233,0};
static const unsigned short slide2_positions[35] = {0u,440u,1247u,2126u,3006u,3886u,4839u,5938u,6965u,8064u,9750u,12590u,15573u,18029u,19784u,21100u,24890u,27163u,30262u,35051u,35694u,38054u,40431u,41156u,46212u,46523u,50413u,52303u,53249u,54194u,56294u,58815u,61335u,63856u,64696u};
#endif
#ifdef ATTRIBUTE_CODES_IN_VGA_ORDER
static const unsigned char slide1_colors[12] = {3,7,7,7,7,7,3,3,3,2,2,2};
static const unsigned short slide1_positions[12] = {0u,4132u,8192u,16384u,24576u,32768u,36829u,40960u,49152u,52583u,53876u,57344u};
static const unsigned char slide2_colors[11] = {7,15,15,14,14,14,6,6,8,8,0};
static const unsigned short slide2_positions[11] = {0u,5541u,10923u,16363u,21846u,32768u,38151u,43691u,49153u,54614u,59655u};
#endif
static ColorSlideCache slide1(slide1_colors, slide1_positions, sizeof(slide1_colors));
static ColorSlideCache slide2(slide2_colors, slide2_positions, sizeof(slide2_colors));
/* Renders status-bar on screen, if non-empty. */
static void VisRenderStatusLine()
{
// Only render Statusline if non-empty
if(!StatusLine[0]) return;
unsigned short* Stat = GetVidMem(0, (VidH-1) / columns, 1);
const unsigned StatusWidth = VidW*columns;
slide2.SetWidth(StatusWidth);
for(unsigned p=0,x=0; x<StatusWidth; ++x)
{
unsigned char ch, c1, c2; slide2.Get(x, ch,c1,c2);
if(C64palette) { c1=7; c2=0; ch = 0x20; }
unsigned char c = StatusLine[p]; if(!c) c = 0x20;
if(c != 0x20)
{
ch = c; c2 = 0;
//if(c1 == c2) c2 = 7;
}
/*if(!C64palette && c != 0x20)
switch(c2)
{
case 8: c1 = 7; break;
case 0: c1 = 8; break;
}*/
VidmemPutEditorChar(ComposeEditorChar(ch, c2, c1), Stat);
if(StatusLine[p]) ++p;
}
}
static const char* StatusGetCPUspeed()
{
// Because running CPUinfo() interferes with our PIT clock,
// only run the CPU speed check maybe twice in a second.
static double cpuspeed = 12345678.90123;
static unsigned long last_check_when = 0;
#ifdef __BORLANDC__
unsigned long now_when = (*(unsigned long*)MK_FP(0x40,0x6C)) & ~7ul;
#elif defined(__DJGPP__)
unsigned long now_when = _farpeekl(_dos_ds, 0x46C) & ~7ul;
#else
unsigned long now_when = (MarioTimer&31)==0;
#endif
static char Part6[18]; // 11+2+4+nul
if(last_check_when != now_when)
{
cpuspeed = CPUinfo();
FixMarioTimer();
last_check_when = now_when;
Cycles_Check();
if(cpuspeed >= 1e9)
sprintf(Part6, "%1d.%1d GHz",
(int)(cpuspeed * 1e-9),
(int)(cpuspeed * 1e-8) % 10
);
else
sprintf(Part6, "%3d MHz", (int)(cpuspeed * 1e-6));
}
return Part6;
}
static const char* StatusGetClock()
{
static time_t last_t = 0;
time_t t = time(0);
static char Part3[12]; // 5+1+2+1+2+nul
if(!last_t || t != last_t)
{
last_t = t;
struct tm* tm = localtime(&t);
/*
static unsigned long begintime = *(unsigned long*)MK_FP(0x40,0x6C);
unsigned long nowtime = *(unsigned long*)MK_FP(0x40,0x6C);
unsigned long time = (47*60+11) - 759 + (nowtime-begintime)*(65536.0/0x1234DC);
tm->tm_hour = 18;
tm->tm_min = time/60;
tm->tm_sec = time%60;
*/
sprintf(Part3, "%02d:%02d:%02d", tm->tm_hour,tm->tm_min,tm->tm_sec);
}
return Part3;
}
/* VisRenderTitleAndStatus: Renders the title bar and the status bar.
* Status bar is only rendered if non-empty.
*/
static void VisRenderTitleAndStatus(int force=0)
{
// Only re-render status once per frame
static unsigned long LastMarioTimer = 0xFFFFFFFFul;
static unsigned long last_check_when = 0;
if(MarioTimer == LastMarioTimer && !force) return;
LastMarioTimer = MarioTimer;
unsigned StatusWidth = VidW*columns;
static EditorCharVecType Hdr;
//fprintf(stderr, "Hdr size: %u\n", (FatMode ? StatusWidth*2 : StatusWidth));
Hdr.resize(FatMode ? StatusWidth*2 : StatusWidth);
// We do the Mario update every frame, but this buffer is updated
// less frequently, only ~18 times a second, because it's rather heavy.
/*#ifdef __BORLANDC__
unsigned long now_when = (*(unsigned long*)MK_FP(0x40,0x6C));
#elif defined(__DJGPP__)
unsigned long now_when = _farpeekl(_dos_ds, 0x46C);
#else*/
unsigned long now_when = MarioTimer & ~7;
//#endif
if(now_when != last_check_when)
{
last_check_when = now_when;
// LEFT-size parts
const char* Part1 = fnpart(CurrentFileName);
static char Part2[44]; sprintf(Part2, "Row %-5u/%u Col %u", // 4+11+1+11+5+11+nul
(unsigned) (Cur.y+1),
(unsigned) EditLines.size(), // (unsigned) EditLines.capacity(),
(unsigned) (Cur.x+1));
// RIGHT-side parts
const char* Part3 = StatusGetClock();
static char Part4[26]; sprintf(Part4, "%lu/%lu C", chars_file, chars_typed); //11+1+11+2+nul
static const char Part5[] = "-6.4øC"; // temperature degC degrees celsius
const char* Part6 = StatusGetCPUspeed();
const unsigned NumParts = 6;
const char* const Parts[6] = {Part1,Part2,Part3,Part4,Part5,Part6};
static const char Prio[6] = {10, 13, 7, 4, 0, 2 };
unsigned Lengths[NumParts];
{for(unsigned n=0; n<NumParts; ++n) Lengths[n] = strlen(Parts[n]);}
// Create a plan which parts are rendered on the left side of the title bar,
// and which parts are rendered on the right side. Cache this plan.
// The plan is only updated whenever the screen width changes.
static unsigned left_parts = 0, right_parts = 0, last_check_width = 0;
if(last_check_width != StatusWidth)
{
// When video width changes, determine which parts we can fit on the screen
unsigned columns_remaining = StatusWidth - 8;
last_check_width = StatusWidth;
// Check which combination of columns produces the best fit.
// Try all 2^6 = 64 combinations.
unsigned allowed_parts = 1, best_length = 0, best_prio = 0;
for(unsigned combination = 0; combination < (1 << NumParts); ++combination)
{
unsigned length = 0, prio = 0;
for(unsigned n=0; n<NumParts; ++n)
if(combination & (1 << n))
{
if(length) ++length;
length += Lengths[n];
prio += Prio[n];
}
if(length > columns_remaining) continue;
if((length+prio) > (best_length+best_prio))
{
best_length = length;
best_prio = prio;
allowed_parts = combination;
}
}
// Only the first two parts go to the left, anything else goes on right
left_parts = allowed_parts & 3;
right_parts = allowed_parts & ~3;
}
unsigned xbegin[NumParts], xend[NumParts];
memset(xbegin,0,sizeof(xbegin)); memset(xend,0,sizeof(xend));
unsigned leftn=6; // Calculate starting positions for left-side parts
unsigned rightn=0; // Calculate relative starting positions for right-side parts
{for(unsigned n=0; n<NumParts; ++n)
{
unsigned bit = 1 << n;
if(left_parts & bit) { if(leftn) { ++leftn; } xbegin[n] = leftn; xend[n] = (leftn += Lengths[n]); }
if(right_parts & bit) { if(rightn) { ++rightn; } xbegin[n] = rightn; xend[n] = (rightn += Lengths[n]); }
}}
// Adjust the right-side starting positions
int right_start = StatusWidth - 1 - rightn;
int left_end = leftn+1;
if(right_start < left_end) right_start = left_end;
{for(unsigned n=0; n<NumParts; ++n)
if(right_parts & (1u << n)) { xbegin[n] += right_start; xend[n] += right_start; }
}
// Now render the actual status line into Hdr[] with colors.
slide1.SetWidth(StatusWidth);
for(unsigned x=0; x<StatusWidth; ++x)
{
unsigned char ch, c1, c2; slide1.Get(x, ch,c1,c2);
if(C64palette) { c1=7; c2=0; ch = 0x20; }
// Identify the character at this position
unsigned char c = 0x20;
if(x == 0 && WaitingCtrl) c = '^';
else if(x == 1 && WaitingCtrl) c = WaitingCtrl;
else if(x == 3 && InsertMode) c = 'I';
else if(x == 4 && UnsavedChanges) c = '*';
else for(unsigned n=0; n<NumParts; ++n)
if(x < xend[n] && x >= xbegin[n])
{
c = (unsigned char) Parts[n][x - xbegin[n]];
break;
}
// Convert the character into rendered symbol
if(c != 0x20)
{
ch = c; c2 = 0;
//if(c1 == c2) c2 = 7;
}
/*if(!C64palette && c != 0x20)
switch(c2)
{
case 8: c1 = 7; break;
case 0: c1 = 8; break;
}*/
Hdr[x] = ComposeEditorChar(ch, c2, c1);
}
}
// Then translate the Hdr[] buffer on screen using MarioTranslate.
MarioTranslate(&Hdr[0], GetVidMem(0,0,1), StatusWidth);
VisRenderStatusLine();
}
/* VisRender: Render whole screen except the status line */
static void VisRender()
{
static EditorCharVecType EmptyLine; // Dummy vector representing an empty line
// Hide soft-cursor
VisSoftCursor(-1);
unsigned winh = VidH - 1;
if(StatusLine[0]) --winh;
for(unsigned y=0; y<winh; ++y)
{
unsigned short* Tgt = GetVidMem(0, y+1);
unsigned ly = Win.y + y;
EditorCharVecType* line = &EmptyLine;
if(ly < EditLines.size()) line = &EditLines[ly];
unsigned lw = line->size(), lx=0, x=Win.x, xl=x + VidW;
EditorCharType trail = MakeDefaultColor(' ');
for(unsigned l=0; l<lw; ++l)
{
EditorCharType attr = (*line)[l];
if(ExtractCharCode(attr) == '\n') break;
++lx;
if(lx > x)
{
if( ((ly == BlockBegin.y && lx-1 >= BlockBegin.x)
|| ly > BlockBegin.y)
&& ((ly == BlockEnd.y && lx-1 < BlockEnd.x)
|| ly < BlockEnd.y) )
{
attr = InvertColor(attr);
}
if(DispUcase && islower(ExtractCharCode(attr)))
attr &= ~0x20ul;
do VidmemPutEditorChar(attr, Tgt); while(lx > ++x);
if(x >= xl) break;
}
}
while(x++ < xl) VidmemPutEditorChar(trail, Tgt);
}
// Redraw soft-cursor
VisSoftCursor(1);
}
unsigned wx = ~0u, wy = ~0u, cx = ~0u, cy = ~0u;
enum SyntaxCheckingType
{
SyntaxChecking_IsPerfect = 0,
SyntaxChecking_DidEdits = 1,
SyntaxChecking_Interrupted = 2,
SyntaxChecking_DoingFull = 3
} SyntaxCheckingNeeded = SyntaxChecking_DoingFull;
#if defined(__cplusplus) && __cplusplus >= 199700L
JSF<ApplyEngine> Syntax;
ApplyEngine& SyntaxCheckingApplier = Syntax;
JSF<ApplyEngine>::ApplyState SyntaxCheckingState;
#else
JSF Syntax;
ApplyEngine SyntaxCheckingApplier;
JSF::ApplyState SyntaxCheckingState;
#endif
/* TODO: In syntax checking: If the syntax checker ever reaches the current editing line,
* make a save in the beginning of the line and use that for resuming
* instead of backtracking to the context
*/
// How many lines to backtrack
#define SyntaxChecking_ContextOffset 50
static void WaitInput(bool may_redraw = true)
{
if(may_redraw)
{
// If the cursor position has changed from last update,
// hide the software cursor and replace the hardware cursor
if(cx != Cur.x || cy != Cur.y) { cx=Cur.x; cy=Cur.y; VisSoftCursor(-1); VisSetCursor(); }
// If statusline is visible and cursor coincides with statusline, scroll screen down
if(StatusLine[0] && Cur.y >= Win.y+VidH-2) Win.y += 2;
}
// There is work to do, so request more CPU speed
Cycles_Adjust(1);
// Quickly skip doing anything if a key has been presed
if(kbhit()) return;
// Adjust window position horizontally making sure cursor is on screen
while(Cur.x < Win.x) Win.x -= 8;
while(Cur.x >= Win.x + VidW) Win.x += 8;
bool needs_redraw = false;
// If the window position has changed from last update,
// hide the software cursor and replace the hardware cursor
if(may_redraw && (wx != Win.x || wy != Win.y))
{
VisSoftCursor(-1);
VisSetCursor();
// Delay the screen refreshing though,
// so we only do it once
needs_redraw = true;
}
while(!kbhit())
{
if(may_redraw)
{
if(SyntaxCheckingNeeded != SyntaxChecking_IsPerfect)
{
bool horrible_sight =
ExtractColor(VidmemReadEditorChar(VidMem+VidW*2)) == MakeUnknownColor('\0')
|| ExtractColor(VidmemReadEditorChar(VidMem+VidW*(VidH*3/4))) == MakeUnknownColor('\0');
/* If the sight on the very screen currently
* is "horrible", do, as a quick fix, a scan
* of the current screen to at least make it
* look different.
*/
if(SyntaxCheckingNeeded != SyntaxChecking_Interrupted
|| horrible_sight)
{
unsigned line = 0;
if( horrible_sight)
line = Win.y;
else if(SyntaxCheckingNeeded != SyntaxChecking_DoingFull)
line = Win.y>SyntaxChecking_ContextOffset ? Win.y-SyntaxChecking_ContextOffset : 0;
Syntax.ApplyInit(SyntaxCheckingState);
SyntaxCheckingApplier.Reset(line);
}
// Apply syntax coloring. Will continue applying colors until
// either a key is pressed, or the checking finishes.
#if defined(__cplusplus) && __cplusplus >= 199700L
Syntax.Apply(SyntaxCheckingState);
#else
Syntax.Apply(SyntaxCheckingState, SyntaxCheckingApplier);
#endif
// Update the need-syntax-checking state
SyntaxCheckingNeeded =
!SyntaxCheckingApplier.finished
? SyntaxChecking_Interrupted
: (SyntaxCheckingApplier.begin_line == 0)
? SyntaxChecking_IsPerfect
: SyntaxChecking_DoingFull;
// Something was changed, so refresh screen now
needs_redraw = true;
}
// In any case, refresh screen if _something_ changed
if(needs_redraw)
{ wx=Win.x; wy=Win.y; VisRender(); needs_redraw = false; }
}
VisRenderTitleAndStatus();
VisSoftCursor(0);
if(SyntaxCheckingNeeded == SyntaxChecking_IsPerfect
#if defined(__BORLANDC__) || defined(__DJGPP__)
|| SyntaxCheckingNeeded != SyntaxChecking_DoingFull
#endif
|| !may_redraw
)
{
if(SyntaxCheckingNeeded == SyntaxChecking_IsPerfect)
Cycles_Adjust(-1);
KbIdle();
}
}
}
struct UndoEvent
{
unsigned x, y;
unsigned n_delete;
EditorCharVecType insert_chars;
};
const unsigned MaxUndo = 256;
UndoEvent UndoQueue[MaxUndo];
UndoEvent RedoQueue[MaxUndo];
unsigned UndoHead = 0, RedoHead = 0;
unsigned UndoTail = 0, RedoTail = 0;
bool UndoAppendOk = false;
static void AddUndo(const UndoEvent& event)
{
unsigned UndoBufSize = (UndoHead + MaxUndo - UndoTail) % MaxUndo;
if(UndoAppendOk && UndoBufSize > 0)
{
UndoEvent& prev = UndoQueue[ (UndoHead + MaxUndo-1) % MaxUndo ];
/*if(event.n_delete == 0 && prev.n_delete == 0
&& event.x == prev.x && event.y == prev.y
)
{
prev.insert_chars.insert(
prev.insert_chars.end(),
event.insert_chars.begin(),
event.insert_chars.end());
return;
}*/
if(event.insert_chars.empty() && prev.insert_chars.empty())
{
prev.n_delete += event.n_delete;
return;
}
}
if( UndoBufSize >= MaxUndo - 1) UndoTail = (UndoTail + 1) % MaxUndo;
UndoQueue[UndoHead] = event;
UndoHead = (UndoHead + 1) % MaxUndo;
}
static void AddRedo(const UndoEvent& event)
{
unsigned RedoBufSize = (RedoHead + MaxUndo - RedoTail) % MaxUndo;
if( RedoBufSize >= MaxUndo - 1) RedoTail = (RedoTail + 1) % MaxUndo;
RedoQueue[RedoHead] = event;
RedoHead = (RedoHead + 1) % MaxUndo;
}
#define AllCursors() \
do { int cn; \
for(cn=0; cn<NumCursors; ++cn) \
{ Anchor& c = SavedCursors[cn]; o(); } \
} while(0)
#define AlmostAllCursors() \
do { int cn; \
for(cn=0; cn<MaxSavedCursors; ++cn) \
{ Anchor& c = SavedCursors[cn]; o(); } \
} while(0)
#define TheOtherCursors() \
do { int cn; \
for(cn=MaxSavedCursors; cn<NumCursors; ++cn) \
{ Anchor& c = SavedCursors[cn]; o(); } \
} while(0)
enum UndoType
{
DoingUndo_Not,
DoingUndo_Undo,
DoingUndo_Redo
};
static void PerformEdit(
unsigned x, unsigned y,
unsigned n_delete,
const EditorCharVecType& insert_chars,
UndoType DoingUndo = DoingUndo_Not)
{
unsigned eol_x = EditLines[y].size();
if(eol_x > 0 && ExtractCharCode(EditLines[y].back()) == '\n') --eol_x;
if(x > eol_x) x = eol_x;
UndoEvent event;
event.x = x;
event.y = y;
event.n_delete = 0;
chars_file += insert_chars.size();
if(DoingUndo)
{
int s = sprintf(StatusLine,"Edit%u @%u,%u: Delete %u, insert '",
int(UndoAppendOk), x,y,n_delete);
for(unsigned b=insert_chars.size(), a=0; a<b && s<252; ++a)
{
char c = ExtractCharCode(insert_chars[a]);
if(c == '\n') { StatusLine[s++] = '\\'; StatusLine[s++] = 'n'; }
else StatusLine[s++] = c;
}
sprintf(StatusLine+s, "'");
}
// Is there something to delete?
if(n_delete > 0)
{
unsigned n_lines_deleted = 0;
// If the deletion spans across newlines, concatenate those lines first
while(n_delete >= EditLines[y].size() - x
&& y+1+n_lines_deleted < EditLines.size())
{