-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfltk-mini-edit.cc
1894 lines (1762 loc) · 63.3 KB
/
fltk-mini-edit.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
// // file fltk-mini-edit.cc
// SPDX-License-Identifier: GPL-3.0-or-later
// A simple text editor program for the Fast Light Tool Kit (FLTK). It
// should interact with another Linux process using some protocol to
// be defined...
//
// This program is inspired by Chapter 4 of the FLTK Programmer's Guide.
/****
© Copyright 1998-2024 by Bill Spitzak and Basile Starynkevitch and CEA
program released under GNU general public license
this is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
this is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
****/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <gnu/libc-version.h>
/// GNU libunistring https://www.gnu.org/software/libunistring/
#include <unistd.h>
#include <unicase.h>
#include <unictype.h>
#include <uniconv.h>
#include <unistr.h>
#include <poll.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cassert>
#include <atomic>
/// https://github.com/ianlancetaylor/libbacktrace/
#include <backtrace.h>
/// JSONCPP from https://github.com/open-source-parsers/jsoncpp
#include <json/json.h>
#include <json/version.h>
#include <FL/Fl.H>
#include <FL/platform.H> // for fl_open_callback
#include <FL/Fl_Group.H>
#include <FL/Fl_Double_Window.H>
#include <FL/fl_ask.H>
#include <FL/Fl_Native_File_Chooser.H>
#include <FL/Fl_Menu_Bar.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Return_Button.H>
#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Text_Editor.H>
#include <FL/filename.H>
extern "C" [[noreturn]] void my_abort(void) __attribute__((noreturn));
extern "C" struct backtrace_state *my_backtrace_state;
extern "C" const char*my_prog_name;
extern "C" void*my_prog_dlhandle; // the dlopen of the whole program
extern "C" char my_host_name[];
extern "C" bool my_help_flag;
extern "C" bool my_version_flag;
extern "C" bool my_debug_flag;
extern "C" bool my_styledemo_flag;
extern "C" Fl_Window *my_top_window;
extern "C" Fl_Menu_Bar*my_menubar;
extern "C" const int my_font_delta;
extern "C" const char* my_fifo_name;
extern "C" const char my_source_dir[];
extern "C" const char my_source_file[];
extern "C" const char my_compile_script[];
#define MY_TEMPDIR_LEN 256
extern "C" char my_tempdir[MY_TEMPDIR_LEN];
class MyAbstractCommandProcessor;
typedef void my_jsoncmd_handling_sigt(const Json::Value*pcmdjson, long cmdcount, MyAbstractCommandProcessor*cmdproc);
struct my_jsoncmd_handler_st
{
my_jsoncmd_handling_sigt*cmd_fun;
intptr_t cmd_data1;
intptr_t cmd_data2;
};
extern "C" std::map<std::string,my_jsoncmd_handler_st> my_cmd_handling_dict;
extern "C" void my_command_register(const std::string&name, struct my_jsoncmd_handler_st cmdh);
extern "C" void my_command_register_plain(const std::string&name, my_jsoncmd_handling_sigt*cmdrout);
extern "C" void my_command_register_data1(const std::string&name, my_jsoncmd_handling_sigt*cmdrout, intptr_t data1);
extern "C" void my_command_register_data2(const std::string&name, my_jsoncmd_handling_sigt*cmdrout, intptr_t data1, intptr_t data2);
/// by convention, handling of JSONRPC method FOO is named my_rpc_FOO_handler
extern "C" void my_rpc_compileplugin_handler(const Json::Value*pcmdjson, long cmdcount, MyAbstractCommandProcessor*cmdproc);
/// a small integer to increase font size at compile time, e.g. compiling with -DMY_FONT_DELTA=2
#ifndef MY_FONT_DELTA
#define MY_FONT_DELTA 0
#endif
#define MY_FIFO_NAME_MAXLEN 250
#define MY_FONT_SIZE(Fsiz) ((int)(MY_FONT_DELTA)+(Fsiz))
/// from www.december.com/html/spec/colorsvghex.html
#ifndef FL_ORANGE
#define FL_ORANGE 0xffA500
#endif
#ifndef FL_PURPLE
#define FL_PURPLE 0x800080
#endif
#ifndef FL_GOLDENROD
#define FL_GOLDENROD 0xDAA520
#endif
#ifndef FL_LIGHTCYAN
#define FL_LIGHTCYAN 0xE0FFFF
#endif
#ifndef FL_SLATEBLUE
#define FL_SLATEBLUE 0x6A5ACD
#endif
const Fl_Font MYFL_FREEMONO_FONT = FL_FREE_FONT;
const Fl_Font MYFL_FREEMONO_BOLD_FONT = FL_FREE_FONT+1;
const Fl_Font MYFL_GOMONO_FONT = FL_FREE_FONT+2;
const Fl_Font MYFL_DEJAVUSANSMONO_FONT = FL_FREE_FONT+2;
const Fl_Font MYFL_XTRAFONT = FL_FREE_FONT+3;
const Fl_Font MYFL_OTHERFONT = FL_FREE_FONT+4;
#define MY_BACKTRACE_PRINT(Skip) do {if (my_debug_flag) \
my_backtrace_print_at(__FILE__,__LINE__, (Skip)); } while (0)
extern "C" void my_backtrace_print_at(const char*fil, int line, int skip);
extern "C" int miniedit_prog_arg_handler(int argc, char **argv, int &i);
/// fatal error macro, printf-like
#define FATALPRINTF_AT(Fil,Lin,Fmt,...) do { \
printf("\n@@°@@FATAL ERROR (%s pid %d) %s:%d:\n", \
my_prog_name, (int)getpid(), \
Fil,Lin); \
printf((Fmt), ##__VA_ARGS__); \
putchar('\n'); \
my_backtrace_print_at(Fil,Lin, (1)); \
fflush(nullptr); \
my_postponed_remove_tempdir(); \
my_abort(); } while(0)
//// example is FATALPRINTF ("x=%d",x)
#define FATALPRINTF(Fmt,...) FATALPRINTF_AT(__FILE__,__LINE__,\
Fmt,##__VA_ARGS__)
#define FATALOUT_AT(Fil,Lin,Out) do { \
std::ostringstream outs##Lin; \
outs##Lin << Out << std::fflush; \
FATALPRINTF_AT(Fil,Lin,"%s", \
outs##Lin.str().c_str()); \
} while(0)
#define FATALOUT(Out) FATALOUT_AT(__FILE__,__LINE__,Out)
/// debug printing macro à la printf
#define DBGPRINTF_AT(Fil,Lin,Fmt,...) do { \
if (my_debug_flag) { \
printf("@@%s:%d:",Fil,Lin); \
printf((Fmt), ##__VA_ARGS__); \
putchar('\n'); fflush(stdout); \
}} while(0)
#define DBGPRINTF(Fmt,...) DBGPRINTF_AT(__FILE__,__LINE__,Fmt,\
##__VA_ARGS__)
/// debug printing macro à la C++
#define DBGOUT_AT(Fil,Lin,Out) do { \
if (my_debug_flag) { \
std::cout << "@@" Fil << ":" << Lin << ':' \
<< Out << std::endl; \
}} while(0)
#define DBGOUT(Out) DBGOUT_AT(__FILE__,__LINE__,Out)
class MyEditor;
class MyAbstractCommandProcessor;
extern "C" void my_postponed_remove_tempdir(void);
extern "C" void do_style_demo(MyEditor*);
extern "C" void my_initialize_fifo(void);
extern "C" void my_cmd_fd_handler(FL_SOCKET, void*);
extern "C" void my_out_fd_handler(FL_SOCKET, void*);
extern "C" void my_cmd_processor(int cmdlen, FL_SOCKET outsock);
extern "C" void my_cmd_handle_buffer(const char*cmdbuf, int cmdlen, FL_SOCKET outsock);
extern "C" void my_cmd_process_json(const Json::Value*pjson, long cmdcount, FL_SOCKET outsock= -1);
class MyAbstractCommandProcessor
{
int cmdproc_magic;
static int constexpr CMDPROC_NUM_MAGIC = 0x65bdf317 ;//=1706947351
static std::atomic<MyAbstractCommandProcessor*> the_cmdproc;
FL_SOCKET cmdproc_in_sock;
FL_SOCKET cmdproc_out_sock;
static std::map<int, MyAbstractCommandProcessor*> cmdproc_map_in_fd;
static std::map<int, MyAbstractCommandProcessor*> cmdproc_map_out_fd;
static constexpr int cmdproc_poll_delay_milliseconds = 10;
protected:
char* cmdproc_data1;
char* cmdproc_data2;
intptr_t cmdproc_num1;
intptr_t cmdproc_num2;
std::istringstream cmdproc_instr;
std::ostringstream cmdproc_outstr;
long cmdproc_event_counter;
static std::atomic_ulong cmdproc_unique_counter;
protected:
MyAbstractCommandProcessor(FL_SOCKET insock, FL_SOCKET outsock, char*data1 = nullptr, char*data2 = nullptr, intptr_t num1= 0, intptr_t num2= 0);
MyAbstractCommandProcessor(const MyAbstractCommandProcessor& oth) = default;
MyAbstractCommandProcessor(MyAbstractCommandProcessor&& oth) = default;
public:
inline bool is_valid_cmdproc(void) const
{
return cmdproc_magic == CMDPROC_NUM_MAGIC;
}
static inline MyAbstractCommandProcessor*instance(void)
{
return the_cmdproc.load();
};
FL_SOCKET cmd_socket() const
{
return cmdproc_in_sock;
};
FL_SOCKET out_socket() const
{
return cmdproc_out_sock;
};
std::ostringstream& out_stream(void)
{
return cmdproc_outstr;
};
bool flush_output_stream(void);// return true if no pending bytes....
static void cmd_fd_handler(FL_SOCKET*, void*);
static void out_fd_handler(FL_SOCKET*, void*);
virtual ~MyAbstractCommandProcessor();
virtual void process_jsonrpc_command(const Json::Value*pjson, long cmdcount);
virtual std::string command_processor_name(void) const =0;
void send_asynchronous_json_event (const std::string& evname, const Json::Value evjson = Json::nullValue);
}; // end MyAbstractCommandProcessor
class MyFifoCommandProcessor : public MyAbstractCommandProcessor
{
std::string fifocmd_prefix;
static int open_fifo_cmd(const std::string& prefix);
static int open_fifo_out(const std::string& prefix);
public:
MyFifoCommandProcessor(const std::string& prefix);
~MyFifoCommandProcessor();
const std::string & fifo_prefix(void) const
{
return fifocmd_prefix;
};
virtual std::string command_processor_name(void) const
{
return std::string("FIFOcmdproc:")+fifocmd_prefix;
};
}; // end MyFifoCommandProcessor
////////////////////////////////////////////////////////////////
// Custom class to demonstrate a specialized text editor
class MyEditor : public Fl_Text_Editor
{
friend void do_style_demo(MyEditor*);
Fl_Text_Buffer *myed_txtbuff; // text buffer
Fl_Text_Buffer *stybuff; // style buffer
static int tab_key_binding(int key, Fl_Text_Editor*editor);
static int escape_key_binding(int key, Fl_Text_Editor*editor);
public:
void initialize(void);
void ModifyCallback(int pos, // position of update
int nInserted, // number of inserted chars
int nDeleted, // number of deleted chars
int, // number of restyled chars (unused here)
const char*deltxt // deleted text
);
static void static_modify_callback(int pos, // position of update
int nInserted, // number of inserted chars
int nDeleted, // number of deleted chars
int nRestyled, // number of restyled chars
const char *deletedText, // text deleted
void *cbarg); // callback data
MyEditor(int X,int Y,int W,int H);
~MyEditor();
inline void text(const char* val)
{
myed_txtbuff->text(val);
};
enum my_style_en
{
Style_Plain,
Style_Literal,
Style_Number,
Style_Name,
Style_Word,
Style_Keyword,
Style_Oid,
Style_Comment,
Style_Bold,
Style_Italic,
Style_CodeChunk,
Style_Unicode,
Style_Errored,
Style__LAST
};
/****
* Important notice
*
* Debian trixie is (in Feb. 2024) packaging libfltk1.3-dev
*
* in FLTK 1.3 a Fl_Text_Editor::Style_Table_Entry is a:
*
* struct Style_Table_Entry {
* Fl_Color color; ///< text color
* Fl_Font font; ///< text font
* Fl_Fontsize size; ///< text font size
* unsigned attr; ///< currently unused (this may be change in the future)
* };
*
* but in FLTK 1.4 obtained from https://www.fltk.org/software.php?VERSION=1.4.x it is a:
*
* struct Style_Table_Entry {
* Fl_Color color; ///< text color
* Fl_Font font; ///< text font
* Fl_Fontsize size; ///< text font size
* unsigned attr; ///< further attributes for the text style (see `ATTR_BGCOLOR`, etc.)
* Fl_Color bgcolor; ///< text background color if `ATTR_BGCOLOR` or `ATTR_BGCOLOR_EXT` is set
* };
*
*
****/
static inline constexpr Fl_Text_Editor::Style_Table_Entry style_table[(unsigned)Style__LAST] =
{
// FONT COLOR FONT FACE SIZE
// ......... ATTRIBUTE [BACKGROUND COLOR]
[Style_Plain] = //
{
FL_BLACK, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Plain,
[Style_Literal] = //
{
FL_DARK_GREEN, FL_COURIER_BOLD, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Literal,
[Style_Number] = //
{
FL_DARK_BLUE, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Number,
[Style_Name] = //
{
FL_CYAN, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Name,
[Style_Word] = //
{
FL_BLUE, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Word,
[Style_Keyword] = //
{
FL_DARK_MAGENTA, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Keyword,
[Style_Oid] = //
{
FL_ORANGE, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Oid,
[Style_Comment] = //
{
FL_PURPLE, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Comment,
[Style_Bold] = //
{
FL_BLACK, FL_COURIER_BOLD, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Bold,
[Style_Italic] = //
{
FL_BLACK, FL_COURIER_ITALIC, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_Italic,
[Style_CodeChunk] = //
{
FL_SLATEBLUE, FL_COURIER, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_WHITE
#endif
}, //:Style_CodeChunk,
[Style_Unicode] = //
{
FL_DARK_RED, MYFL_FREEMONO_BOLD_FONT, MY_FONT_SIZE(17), ///
0, //
#if FLTK_ABI_VERSION >= 10400
FL_GRAY0
#endif
}, //:Style_Unicode,
[Style_Errored] = //
{
FL_RED, FL_COURIER_BOLD, MY_FONT_SIZE(17), ///
#if FLTK_ABI_VERSION >= 10400
ATTR_BGCOLOR, //
FL_GRAY0
#else /*FLTK 1.3*/
0
#endif
}, //:Style_Errored,
};
static inline constexpr const char*stylename_table[(unsigned)Style__LAST+1] =
{
#define NAME_STYLE(N) [(int)N] = #N
NAME_STYLE(Style_Plain),
NAME_STYLE(Style_Literal),
NAME_STYLE(Style_Number),
NAME_STYLE(Style_Name),
NAME_STYLE(Style_Word),
NAME_STYLE(Style_Keyword),
NAME_STYLE(Style_Oid),
NAME_STYLE(Style_Comment),
NAME_STYLE(Style_Bold),
NAME_STYLE(Style_Italic),
NAME_STYLE(Style_CodeChunk),
NAME_STYLE(Style_Unicode),
NAME_STYLE(Style_Errored),
nullptr
};
void decorate(void);
}; // end MyEditor
// we could compile and dlopen extra C++ plugins, sharing all the code above up to the last_shared_line
extern "C" const int last_shared_line = __LINE__; ///°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
#if FLTK_ABI_VERSION >= 10300 && FLTK_ABI_VERSION < 10400
#pragma message "FLTK 1.3.x"
#elif FLTK_ABI_VERSION > 10400
#pragma message "FLTK 1.4.x"
#else
#error unsupported FLTK ABI version not 1.3 or 1.4
#endif
std::map<int, MyAbstractCommandProcessor*> MyAbstractCommandProcessor::cmdproc_map_in_fd;
std::map<int, MyAbstractCommandProcessor*> MyAbstractCommandProcessor::cmdproc_map_out_fd;
std::atomic_ulong MyAbstractCommandProcessor::cmdproc_unique_counter;
std::atomic<MyAbstractCommandProcessor*>MyAbstractCommandProcessor::the_cmdproc;
MyAbstractCommandProcessor::MyAbstractCommandProcessor(FL_SOCKET insock, FL_SOCKET outsock,
char*data1, char*data2,
intptr_t num1, intptr_t num2)
: cmdproc_magic(CMDPROC_NUM_MAGIC),
cmdproc_in_sock(insock), cmdproc_out_sock(outsock),
cmdproc_data1(data1), cmdproc_data2(data2),
cmdproc_num1(num1), cmdproc_num2(num2), cmdproc_event_counter(0)
{
MyAbstractCommandProcessor* oldproc = the_cmdproc.exchange(this);
assert (oldproc == nullptr);
assert (insock>=0);
assert (outsock>=0);
cmdproc_map_in_fd.insert({insock,this});
cmdproc_map_out_fd.insert({outsock,this});
}; // end MyAbstractCommandProcessor::MyAbstractCommandProcessor
MyAbstractCommandProcessor::~MyAbstractCommandProcessor()
{
assert (is_valid_cmdproc());
cmdproc_magic = 0;
assert(cmdproc_in_sock>=0 && cmdproc_map_in_fd.find(cmdproc_in_sock) != cmdproc_map_in_fd.end());
assert(cmdproc_out_sock>=0 && cmdproc_map_out_fd.find(cmdproc_out_sock) != cmdproc_map_out_fd.end());
cmdproc_map_in_fd.erase(cmdproc_in_sock);
close(cmdproc_in_sock);
cmdproc_in_sock= -1;
cmdproc_map_out_fd.erase(cmdproc_out_sock);
close(cmdproc_out_sock);
cmdproc_out_sock= -1;
the_cmdproc.store(nullptr);
} // end MyAbstractCommandProcessor::~MyAbstractCommandProcessor
void
MyAbstractCommandProcessor::process_jsonrpc_command(Json::Value const*pjson, long cmdcount)
{
assert (pjson != nullptr);
DBGOUT("process_jsonrpc_command start cmdcount:" << cmdcount);
if (!pjson->isMember("method"))
FATALPRINTF("MyAbstractCommandProcessor::process_jsonrpc_command missing method cmdcount:%ld json:%s",
cmdcount, pjson->asCString());
std::string methstr = (*pjson)["method"].asString();
my_jsoncmd_handler_st jh = my_cmd_handling_dict.at(methstr);
assert (jh.cmd_fun);
DBGOUT("process_jsonrpc_command method " << methstr << " cmdcount:" << cmdcount
<< " processor:" << command_processor_name()
<< " pjson:" << (*pjson));
(*jh.cmd_fun)(pjson, cmdcount, this);
DBGOUT("process_jsonrpc_command DONE method " << methstr << " cmdcount:" << cmdcount
<< " processor:" << command_processor_name() << std::endl);
} // end MyAbstractCommandProcessor::process_jsonrpc_command
void
MyAbstractCommandProcessor::send_asynchronous_json_event (const std::string& evname, const Json::Value evjson)
{
Json::Value jmsg(Json::objectValue);
jmsg["json_event"] = Json::Value("1.0");
jmsg["event_number"] = ++cmdproc_event_counter;
jmsg["event_unique_rank"] = 1+cmdproc_unique_counter.fetch_add(1);
jmsg["event_name"] = evname;
jmsg["event_data"] = evjson;
struct timespec ts = {0,0};
clock_gettime(CLOCK_REALTIME, &ts);
double nowt = ts.tv_sec + 1.0e-9*ts.tv_nsec;
jmsg["event_time"] = nowt;
cmdproc_outstr << jmsg << "\n\n" << std::flush;
bool flushed = flush_output_stream();
DBGOUT("command processor " << command_processor_name() << " async JSON event " << jmsg
<< (flushed?" flushed ":" pending output"));
} // end MyAbstractCommandProcessor::send_asynchronous_json_event
bool
MyAbstractCommandProcessor::flush_output_stream(void)
{
cmdproc_outstr << std::flush;
if (cmdproc_out_sock < 0)
return false;
std::string ostr = cmdproc_outstr.str();
if (ostr.empty())
return true;
struct pollfd pfarr[2];
memset (pfarr, 0, sizeof(pfarr));
pfarr[0].fd = cmdproc_out_sock;
pfarr[0].events = POLLOUT;
if (poll(pfarr, 1, cmdproc_poll_delay_milliseconds) >0 && pfarr[0].revents == POLLOUT)
{
int slen = ostr.size();
const char*buf = ostr.c_str();
DBGPRINTF("flush_output_stream wants to write %d bytes to outsockfd#%d:\n%s\n### end %d bytes\n",
slen, cmdproc_out_sock, buf, slen);
int nbw = write(cmdproc_out_sock, buf, slen);
if (nbw < 0)
{
DBGPRINTF("flush_output_stream FAILED write %d bytes to outsockfd#%d: %m\n",slen, cmdproc_out_sock);
return false;
}
if (nbw == slen)
{
cmdproc_outstr.str("");
cmdproc_outstr.clear();
DBGPRINTF("flush_output_stream COMPLETED write %d bytes to outsockfd#%d: %m\n",slen, cmdproc_out_sock);
return true;
}
else
{
std::string rest {buf+nbw, (std::size_t)(slen-nbw)};
cmdproc_outstr.clear();
DBGPRINTF("flush_output_stream PARTIAL write %d bytes to outsockfd#%d: remaining %d bytes\n%s\n",
slen, cmdproc_out_sock, slen-nbw, rest.c_str());
cmdproc_outstr.str(rest);
return false;
}
}
else
return false;
} // end MyAbstractCommandProcessor::flush_output_stream
MyFifoCommandProcessor::MyFifoCommandProcessor(const std::string& fifoprefix)
: MyAbstractCommandProcessor(open_fifo_cmd(fifoprefix), open_fifo_out(fifoprefix)),
fifocmd_prefix(fifoprefix)
{
} // end MyFifoCommandProcessor::MyFifoCommandProcessor
MyFifoCommandProcessor::~MyFifoCommandProcessor()
{
fifocmd_prefix.erase();
} // end MyFifoCommandProcessor::~MyFifoCommandProcessor
int
MyFifoCommandProcessor::open_fifo_cmd (const std::string&fifoprefix)
{
std::string fifo_cmd_str = fifoprefix + ".cmd";
struct stat fifo_cmd_stat = {};
/// code copied from old my_initialize_fifo below
DBGPRINTF("MyFifoCommandProcessor::open_fifo_cmd fifo_cmd_str:%s", fifo_cmd_str.c_str());
if (!stat(fifo_cmd_str.c_str(), &fifo_cmd_stat))
{
// should check that it is a FIFO
mode_t cmd_mod = fifo_cmd_stat.st_mode;
if ((cmd_mod&S_IFMT) != S_IFIFO)
FATALPRINTF("%s is not a FIFO but should be the command FIFO - %m",
fifo_cmd_str.c_str());
}
else
{
// should create the cmd FIFO
if (!mkfifo(fifo_cmd_str.c_str(), S_IRUSR|S_IWUSR))
FATALPRINTF("failed to make command FIFO %s - %m", fifo_cmd_str.c_str());
printf("%s: (pid %d on %s) created command FIFO %s\n",
my_prog_name, (int)getpid(), my_host_name, fifo_cmd_str.c_str());
fflush(stdout);
};
int fifo_cmd_fd = open(fifo_cmd_str.c_str(), O_RDONLY|O_NONBLOCK);
if (fifo_cmd_fd < 0)
FATALPRINTF("failed to open command FIFO %s - %m", fifo_cmd_str.c_str());
DBGPRINTF("MyFifoCommandProcessor::open_fifo_cmd fifo_cmd_str:%s fifo_cmd_fd:%d", fifo_cmd_str.c_str(), fifo_cmd_fd);
return fifo_cmd_fd;
} // end MyFifoCommandProcessor::open_fifo_cmd
int
MyFifoCommandProcessor::open_fifo_out (const std::string&fifoprefix)
{
std::string fifo_out_str = fifoprefix + ".out";
struct stat fifo_out_stat = {};
/// code copied from old my_initialize_fifo below
DBGPRINTF("MyFifoCommandProcessor::open_fifo_out fifo_out_str:%s", fifo_out_str.c_str());
if (!stat(fifo_out_str.c_str(), &fifo_out_stat))
{
// should check that it is a FIFO
mode_t cmd_mod = fifo_out_stat.st_mode;
if ((cmd_mod&S_IFMT) != S_IFIFO)
FATALPRINTF("%s is not a FIFO but should be the output FIFO - %m",
fifo_out_str.c_str());
}
else
{
// should create the out FIFO
if (!mkfifo(fifo_out_str.c_str(), S_IRUSR|S_IWUSR))
FATALPRINTF("failed to make output FIFO %s - %m", fifo_out_str.c_str());
printf("%s: (pid %d on %s) created output FIFO %s\n",
my_prog_name, (int)getpid(), my_host_name, fifo_out_str.c_str());
fflush(stdout);
};
int fifo_out_fd = open(fifo_out_str.c_str(), O_WRONLY|O_NONBLOCK);
if (fifo_out_fd < 0)
FATALPRINTF("failed to open output FIFO %s - %m", fifo_out_str.c_str());
DBGPRINTF("MyFifoCommandProcessor::open_fifo_out fifo_out_str:%s fd#%d", fifo_out_str.c_str(), fifo_out_fd);
return fifo_out_fd;
} // end MyFifoCommandProcessor::open_fifo_out
Json::CharReaderBuilder my_json_cmd_builder;
Json::StreamWriterBuilder my_json_out_builder;
char* my_shell_command;
char* my_xtrafont_name;
char* my_otherfont_name;
MyEditor::MyEditor(int X,int Y,int W,int H)
: Fl_Text_Editor(X,Y,W,H), myed_txtbuff(nullptr), stybuff(nullptr)
{
myed_txtbuff = new Fl_Text_Buffer(); // text buffer
stybuff = new Fl_Text_Buffer(); // style buffer
buffer(myed_txtbuff);
initialize();
} // end MyEditor::MyEditor
MyEditor::~MyEditor()
{
delete myed_txtbuff;
delete stybuff;
myed_txtbuff = nullptr;
stybuff = nullptr;
} // end MyEditor::~MyEditor
void
MyEditor::static_modify_callback(int pos, // position of update
int nInserted, // number of inserted chars
int nDeleted, // number of deleted chars
int nRestyled, // number of restyled chars
const char *deletedText, // text deleted
void *cbarg)
{
assert (cbarg != nullptr);
MyEditor* med = reinterpret_cast<MyEditor*>(cbarg);
MY_BACKTRACE_PRINT(1);
med->ModifyCallback(pos, nInserted, nDeleted, nRestyled, deletedText);
};
int
MyEditor::tab_key_binding(int key, Fl_Text_Editor*editor)
{
MyEditor* myed = dynamic_cast<MyEditor*>(editor);
assert (key == FL_Tab);
MY_BACKTRACE_PRINT(1);
assert (myed != nullptr);
int inspos = myed->insert_position();
int lin= -1, col= -1;
if (myed->position_to_linecol(inspos, &lin, &col))
{
Fl_Text_Buffer* mybuf = myed->buffer();
assert (mybuf != nullptr);
unsigned int curutf = mybuf->char_at(inspos);
int wstart = mybuf->word_start(inspos);
int wend = mybuf->word_end(inspos);
int linend = mybuf->line_end(inspos);
int insmode = myed->insert_mode();
DBGPRINTF("MyEditor TAB key=%d inspos=%d L%dC%d curutf#%d wstart=%d"
" wend=%d linend=%d insmode=%d",
key,
inspos, lin, col, curutf, wstart, wend, linend, insmode);
if (wend > linend)
wend = linend;
const char*startchr = mybuf->address(wstart);
const char*endchr = mybuf->address(wend);
assert(startchr != nullptr);
assert(endchr != nullptr);
DBGPRINTF("MyEditor TAB inspos=%d startchr:%p endchr:%p",
inspos, startchr, endchr);
if (startchr > endchr)
{
// this happens when TAB is pressed with the cursor at end
// of line...
DBGPRINTF("MyEditor TAB inspos=%d endofline#%d",
inspos, lin);
return 0; // don't handle
}
assert (endchr >= startchr);
char*curword = mybuf->text_range(wstart, wend);
char*prefix = mybuf->text_range(wstart, inspos);
DBGPRINTF("MyEditor TAB inspos=%d word '%s' prefix='%s'",
inspos, curword, prefix);
bool prefixdigits = true;
bool prefixletters = true;
for (const char*pc = prefix; *pc; pc++)
{
if (!isalpha(*pc)) prefixletters = false;
if (!isdigit(*pc)) prefixdigits = false;
};
char* prefixrepl = nullptr; // possible replacement of prefix
/// If the prefix is only made of digits replace it (as a
/// number) by its numerical successor.
if (prefixdigits)
{
int ok = asprintf(&prefixrepl, "%d", atoi(prefix)+1);
assert (ok > 0);
}
/// If the prefix is only letters replace it by a x2 duplicate
else if (prefixletters)
{
int ok = asprintf(&prefixrepl, "%s/%s", prefix, prefix);
assert (ok > 0);
}
if (prefixrepl)
{
DBGPRINTF("MyEditor TAB inspos=%d prefixrepl:%s",
inspos, prefixrepl);
mybuf->remove(wstart, inspos);
mybuf->insert(wstart, prefixrepl);
#warning missing style insertion
free (prefixrepl), prefixrepl = nullptr;
}
free (curword), curword = nullptr;
free (prefix), prefix = nullptr;
}
else
DBGPRINTF("MyEditor TAB inspos=%d not shown", inspos);
fflush(stdout);
return 0; /// this means don't handle
} // end MyEditor::tab_key_binding
int
MyEditor::escape_key_binding(int key, Fl_Text_Editor*editor)
{
MyEditor* myed = dynamic_cast<MyEditor*>(editor);
MY_BACKTRACE_PRINT(1);
assert (myed != nullptr);
assert (key == FL_Escape);
DBGPRINTF("MyEditor::escape_key_binding myed@%p", myed);
return 1; // this means do handle the binding
} // end MyEditor::escape_key_binding
void
MyEditor::initialize()
{
DBGOUT("MyEditor::initialize this@" << (void*)this);
assert (myed_txtbuff);
assert (stybuff);
highlight_data(stybuff, style_table,
(unsigned)Style__LAST,
'A', 0, 0);
myed_txtbuff->add_modify_callback(MyEditor::static_modify_callback, (void*)this);
// the 0 is a state, could be FL_SHIFT etc... See Fl/Enumerations.h
add_key_binding(FL_Tab, 0, tab_key_binding);
add_key_binding(FL_Escape, 0, escape_key_binding);
MY_BACKTRACE_PRINT(1);
} // end MyEditor::initialize
void
MyEditor::ModifyCallback(int pos, // position of update
int nInserted, // number of inserted chars
int nDeleted, // number of deleted chars
int nRestyled, // number of restyled chars (unused here)
const char*deltxt // deleted text
)
{
DBGPRINTF("MyEditor::ModifyCallback pos=%d ninserted=%d ndeleted=%d"
" nrestyled=%d deltxt=%s",
pos, nInserted, nDeleted, nRestyled, deltxt);
MY_BACKTRACE_PRINT(1);
decorate();
} // end MyEditor::ModifyCallback
void
MyEditor::decorate(void)
{
if (my_styledemo_flag)
return;
Fl_Text_Buffer*buf = buffer();
assert (buf != nullptr);
#if FLTK_ABI_VERSION >= 10400
Fl_Text_Buffer*stybuf = style_buffer();
assert (stybuf != nullptr);
#endif
int curix= -1, previx= -1;
int buflen = buf->length();
for (curix=0;
curix>=0 && curix<buflen;
curix=buf->next_char(curix))
{
if (previx == curix)
break;
unsigned int curch = buf->char_at(curix);
assert (curch>0);
char utfbuf[8];
memset (utfbuf, 0, sizeof(utfbuf));
u8_uctomb((uint8_t*)utfbuf, (ucs4_t)curch, sizeof(utfbuf));
enum my_style_en cursty = Style_Plain;
if (curch < 0x7F)
{
if (strchr("aeiouyAEIOUY", (int)curch))
cursty = Style_Name;
else if (isalpha(curch))
cursty = Style_Literal;
else if (isdigit(curch))
cursty = Style_Number;
}
else
cursty = Style_Unicode;
//Fl_Text_Editor::Style_Table_Entry curstyent = style_table[cursty];
if (cursty != Style_Plain)
{
char stychar[4];
memset (stychar, 0, sizeof(stychar));
stychar[0] = 'A' + cursty;
#if FLTK_ABI_VERSION >= 10400
stybuf->replace(curix, curix+1, stychar);
#endif
DBGPRINTF("MyEditor::decorate Unicode %s at %d=%#x style#%d/%s",
utfbuf, curix, curix, (int)cursty,
stylename_table[(int)cursty]);
}
else
{
if (curch < ' ')
{
const char*escstr = "";
switch (curch)
{
case '\t':
escstr = "=\\t";
break;
case '\r':
escstr = "=\\r";
break;
case '\n':
escstr = "=\\n";
break;
case '\v':
escstr = "=\\v";
break;
case '\b':
escstr = "=\\b";
break;
case '\f':
escstr = "=\\f";
break;
case '\e':
escstr = "=\\e";
break;
default:
break;
};
DBGPRINTF("MyEditor::decorate Ctrlchar \\x%02x%s "
"at %d=%#x plain_style",
(int)curch, escstr, curix, curix);
}
else
DBGPRINTF("MyEditor::decorate Unicode %s at %d=%#x plain_style",
utfbuf, curix, curix);
}
previx= curix;
};
#warning incomplete MyEditor::decorate
} // end MyEditor::decorate
void
do_style_demo(MyEditor*med)
{
assert (med != nullptr);
DBGOUT("do_style_demo start med@" << (void*)med);
assert (med->myed_txtbuff != nullptr);
assert (med ->stybuff != nullptr);
#define DEMO_STYLE(S) do { \
int sl = strlen(#S); \
char sbuf[sizeof(#S)+1]; \
memset(sbuf, 0, sizeof(sbuf)); \
med->myed_txtbuff->append(#S); \
for (int i=0; i<sl; i++) \
sbuf[i] = 'A'+(int)MyEditor::S; \
med->myed_txtbuff->append("\n"); \
med->stybuff->append(sbuf); \
med->stybuff->append("A"); \
DBGPRINTF("DEMO_STYLE " # S \
" myed_txtbuff.len %d stybuff.len %d", \
med->myed_txtbuff->length(), \
med->stybuff->length()); \
} while(0);
/* starting demo styles */
DEMO_STYLE(Style_Plain);
DEMO_STYLE(Style_Literal);
DEMO_STYLE(Style_Number);
DBGPRINTF("after Style_Number myed_txtbuff.len %d stybuff.len %d", med->myed_txtbuff->length(), med->stybuff->length());
DEMO_STYLE(Style_Name);
DEMO_STYLE(Style_Word);
DBGPRINTF("after Style_Word myed_txtbuff.len %d stybuff.len %d", med->myed_txtbuff->length(), med->stybuff->length());