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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
|
/**
\page editor Designing a Simple Text Editor
This chapter guides you through the design of a simple FLTK-based text editor.
The complete source code for our text editor can be found in
the test/editor.cxx file.
The tutorial comprises multiple chapters, and you can activate the relevant
code by adjusting the TUTORIAL_CHAPTER macro at the top of the source file
to match the chapter number.
Each chapter builds on the previous one. The documentation, as well as the
source code, can be read sequentially, maintaining a consistent program
structure while introducing additional features step by step.
\note The tutorial uses several global variables for brevity. Additionally,
the order of code blocks is rather uncommon but helps to keep related
features within a chapter.
<!-- ----------------------------------------------------- -->
\section editor_goals Determining the Goals of the Text Editor
As our first step, we define what we want our text editor to do:
-# Edit a single text document.
-# Provide a menubar/menus for all functions.
-# Load from a file.
-# Save to a file.
-# Keep track of when the file has been changed.
-# Cut/copy/delete/paste menus.
-# Search and replace functionality.
-# Multiple views of the same text.
-# "C" language syntax highlighting.
<!-- NEED 4in -->
<!-- ----------------------------------------------------- -->
\section editor_main_window Chapter 1: A Minimal App
Let's ensure that we can set up our build process to compile and verify our
code as we add features. We begin by writing a minimal program with no
other purpose than opening a window.
The code for that is barely longer than a "Hello, world" program and is
marked in the source code as `TUTORIAL_CHAPTER = 1`.
\code
#include <FL/Fl_Double_Window.H>
#include <FL/Fl.H>
Fl_Double_Window *app_window = NULL;
void tut1_build_app_window() {
app_window = new Fl_Double_Window(640, 480, "FLTK Editor");
}
int main (int argc, char **argv) {
tut1_build_app_window();
app_window->show(argc, argv);
return Fl::run();
}
\endcode
Passing `argc` and `argv` to `Fl_Double_Window::show()` allows FLTK to parse
command line options, providing the user with the ability to change the
color or graphical scheme of the editor at launch time.
`Fl::run()` will return when no more windows in the app are visible.
In other words, if all windows in an app are closed, hidden, or deleted.
Pressing "Escape" or clicking the "Close" button in the window frame will
close our only window, prompting `Fl::run()` to return, effectively
ending the app.
When building FLTK from source, the `CMake` environment includes the
necessary rules to build the editor. You can find more information on
how to write your own `CMake` files in the `README.CMake.txt` text in the
top FLTK directory.
For Linux and macOS, FLTK comes with the `fltk-config` script that generates
the compiler commands for you:
\code
fltk-config --compile editor.cxx
\endcode
If the code compiles and links correctly, running the app will pop up an
empty application window on the desktop screen. You can close the window
and quit the app by pressing the 'Escape' key or by clicking the "Close"
button in the window frame.
Congratulations, you've just built a minimal FLTK app.
<!-- ----------------------------------------------------- -->
\section editor_main_menu Chapter 2: Adding a Menu Bar
In this chapter, we will handle the window title and add the main menu
bar with a File menu and a Quit button.
We need to declare a variable to track track changes in the text, and
a buffer for the current filename.
\code
// remove `main()` from chapter 1, but keep the rest of the code, then add...
#include <FL/Fl_Menu_Bar.H>
#include <FL/fl_ask.H>
#include <FL/filename.H>
#include <FL/fl_string_functions.h>
Fl_Menu_Bar *app_menu_bar = NULL;
bool text_changed = false;
char app_filename[FL_PATH_MAX] = "";
\endcode
The window title is either "FLTK Editor" if the text is not saved in any
file, or the filename, followed by an `*` if the text changed. Note that
we have two ways to set the label of a widget. `label()` will link a static
text, and `copy_label()` which will copy and manage the label text.
\code
void update_title() {
const char *fname = NULL;
if (app_filename[0])
fname = fl_filename_name(app_filename);
if (fname) {
char buf[FL_PATH_MAX + 3];
buf[FL_PATH_MAX + 2] = '\0'; // ensure that the buffer is always terminated
if (text_changed) {
snprintf(buf, FL_PATH_MAX+2, "%s *", fname);
} else {
snprintf(buf, FL_PATH_MAX+2, "%s", fname);
}
app_window->copy_label(buf);
} else {
app_window->label("FLTK Editor");
}
}
\endcode
Now instead of writing directly to `text_changed`, we write a function that
can set and clear the flag, and update the title accordingly.
\code
void set_changed(bool v) {
if (v != text_changed) {
text_changed = v;
update_title();
}
}
\endcode
Let's do the same for changing the filename. If the new filename is
NULL, the window title will revert to "FLTK Editor".
\code
void set_filename(const char *new_filename) {
if (new_filename) {
fl_strlcpy(app_filename, new_filename, FL_PATH_MAX);
} else {
app_filename[0] = 0;
}
update_title();
}
\endcode
But enough of managing window titles. The following code will add the first
widget to our window. A menubar is created at the top and all across the
main window.
\code
void menu_quit_callback(Fl_Widget *, void *) { /* TODO */ }
void tut2_build_app_menu_bar() {
app_window->begin();
app_menu_bar = new Fl_Menu_Bar(0, 0, app_window->w(), 25);
app_menu_bar->add("File/Quit Editor", FL_COMMAND+'q', menu_quit_callback);
app_window->callback(menu_quit_callback);
app_window->end();
}
int main (int argc, char **argv) {
tut1_build_app_window();
tut2_build_app_menu_bar();
app_window->show(argc, argv);
return Fl::run();
}
\endcode
`begin()` tells FLTK to add all widgets created hereafter to our
`app_window`. In this particular case, it is redundant because creating
the window in the previous chapter already called `begin()` for us.
In the next line, we create the menu bar and add our first menu item
to it. Menus can be constructed like file paths, with forward slashes
'/' separating submenus from menu items.
Our basic callback is simple:
\code
void menu_quit_callback(Fl_Widget *, void *) {
Fl::hide_all_windows();
}
\endcode
`Fl::hide_all_windows()` will make all windows invisible, causing `Fl::run()`
to return and `main` to exit.
The next line, `app_window->callback(menu_quit_callback)` links the same
`menu_quit_callback` to the `app_window` as well. Assigning the window
callback removes the default "Escape" key handling and allows the
`menu_quit_callback` to handle that keypress with a friendly dialog box
instead of just quitting the app.
The `Fl_Widget*` parameter in the callback will either be `app_window` if
called through the window callback, or `app_menu_bar` if called by one of
the menu items.
One of our goals was to keep track of text changes. If we know the
text changed and is unsaved, we should notify the user that she is
about to lose her work. We achieve this by adding a dialog box in
the Quit callback that queries if the user really wants to quit,
even if text was changed:
\code
void menu_quit_callback(Fl_Widget *, void *) {
if (text_changed) {
int c = fl_choice("Changes in your text have not been saved.\n"
"Do you want to quit the editor anyway?",
"Quit", "Cancel", NULL);
if (c == 1) return;
}
Fl::hide_all_windows();
}
\endcode
<!-- ----------------------------------------------------- -->
\section editor_text_widget Chapter 3: Adding a Text Editor widget
FLTK comes with a pretty capable builtin text editing widget. We will use
this `Fl_Text_Editor` widget here to allow users to edit their documents.
`Fl_Text_Editor` needs an `Fl_Text_Buffer` to do anything useful. What
might seem like an unnecessary extra step is a great feature: we can
assign one text buffer to multiple text editors. In a later chapter,
we will use this feature to implement a split editor window.
\code
#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Text_Editor.H>
Fl_Text_Editor *app_editor = NULL;
Fl_Text_Editor *app_split_editor = NULL; // for later
Fl_Text_Buffer *app_text_buffer = NULL;
// ... callbacks go here
void tut3_build_main_editor() {
app_window->begin();
app_text_buffer = new Fl_Text_Buffer();
app_text_buffer->add_modify_callback(text_changed_callback, NULL);
app_editor = new Fl_Text_Editor(0, app_menu_bar->h(),
app_window->w(), app_window->h() - app_menu_bar->h());
app_editor->buffer(app_text_buffer);
app_editor->textfont(FL_COURIER);
app_window->resizable(app_editor);
app_window->end();
}
\endcode
By setting the `app_editor` to be the `resizable()` property of
`app_window`, we make our application window resizable on the desktop,
and we ensure that resizing the window will only resize the text editor
vertically, but not our menu bar.
To keep track of changes to the document, we add a callback to the text
editor that will be called whenever text is added or deleted. The text modify
callback sets our `text_changed` flag if text was changed:
\code
// insert before tut3_build_main_editor()
void text_changed_callback(int, int n_inserted, int n_deleted, int, const char*, void*) {
if (n_inserted || n_deleted)
set_changed(true);
}
\endcode
To wrap this chapter up, we add a "File/New" menu and link it to a callback
that clears the text buffer, clears the current filename, and marks the buffer
as unchanged.
\code
// insert before tut3_build_main_editor()
void menu_new_callback(Fl_Widget*, void*) {
app_text_buffer->text("");
set_changed(false);
}
// insert at the end of tut3_build_main_editor()
...
// find the Quit menu and insert the New menu there
int ix = app_menu_bar->find_index(menu_quit_callback);
app_menu_bar->insert(ix, "New", FL_COMMAND+'n', menu_new_callback);
...
\endcode
<!-- ----------------------------------------------------- -->
\section editor_file_support Chapter 4: Reading and Writing Files
In this chapter, we will add support for loading and saving text files,
so we need three more menu items in the File menu: Open, Save, and Save As.
\code
#include <FL/Fl_Native_File_Chooser.H>
#include <FL/platform.H>
#include <errno.h>
// ... add callbacks here
void tut4_add_file_support() {
int ix = app_menu_bar->find_index(menu_quit_callback);
app_menu_bar->insert(ix, "Open", FL_COMMAND+'o', menu_open_callback, NULL, FL_MENU_DIVIDER);
app_menu_bar->insert(ix+1, "Save", FL_COMMAND+'s', menu_save_callback);
app_menu_bar->insert(ix+2, "Save as...", FL_COMMAND+'S', menu_save_as_callback, NULL, FL_MENU_DIVIDER);
}
\endcode
\note The menu shortcuts <TT>FL_COMMAND+'s'</TT> and <TT>FL_COMMAND+'S'</TT>
look the same at a first glance, but the second shortcut is actually
<TT>Ctrl-Shift-S</TT> due to the capital letter 'S'. Also, we use
<TT>FL_COMMAND</TT> as our menu shortcut modifier key. <TT>FL_COMMAND</TT>
translates to `FL_CTRL` on Windows and Linux, and to `FL_META` on macOS,
better known as the cloverleaf, or simply "the Apple key".
We implement the Save As callback first, because we will want to call it from
the Open callback later. The basic callback is only a few lines of code.
\code
void menu_save_as_callback(Fl_Widget*, void*) {
Fl_Native_File_Chooser file_chooser;
file_chooser.title("Save File As...");
file_chooser.type(Fl_Native_File_Chooser::BROWSE_SAVE_FILE);
if (file_chooser.show() == 0) {
app_text_buffer->savefile(file_chooser.filename());
set_filename(file_chooser.filename());
set_changed(false);
}
}
\endcode
However if the user has already set a file name including path information,
it is the polite thing to preload the file chooser with that information. This
little chunk of code will separate the file name from the path before we call
`file_chooser.show()`:
\code
// insert before `if (file_chooser.show()...`
if (app_filename[0]) {
char temp_filename[FL_PATH_MAX];
fl_strlcpy(temp_filename, app_filename, FL_PATH_MAX);
const char *name = fl_filename_name(temp_filename);
if (name) {
file_chooser.preset_file(name);
temp_filename[name - temp_filename] = 0;
file_chooser.directory(temp_filename);
}
}
\endcode
Great. Now let's add code for our File/Save menu. If no filename was set yet,
it falls back to our Save As callback. `Fl_Text_Editor::savefile()` writes
the contents of our text widget into a UTF-8 encoded text file.
\code
void menu_save_callback(Fl_Widget*, void*) {
if (!app_filename[0]) {
menu_save_as_callback(NULL, NULL);
} else {
app_text_buffer->savefile(file_chooser.filename());
set_changed(false);
}
}
\endcode
Now that we have a save method available, we can improve the
`menu_quit_callback` and offer the option to save the current
modified text before quitting the app. Here is the new quit callback
code that replaces the old callback:
\code
void menu_quit_callback(Fl_Widget *, void *) {
if (text_changed) {
int r = fl_choice("The current file has not been saved.\n"
"Would you like to save it now?",
"Cancel", "Save", "Don't Save");
if (r == 0) // cancel
return;
if (r == 1) { // save
menu_save_callback(NULL, NULL);
return;
}
}
Fl::hide_all_windows();
}
\endcode
On to loading a new file. Let's write the function to load a file
from a given file name:
\code
void load(const char *filename) {
if (app_text_buffer->loadfile(filename) == 0) {
set_filename(filename);
set_changed(false);
}
}
\endcode
A friendly app should warn the user if file operations fail. This can be
done in three lines of code, so let's add an alert dialog after every `loadfile`
and `savefile` call. This is exemplary for `load()`, and the
code is very similar for the two other locations.
\code
void load(const char *filename) {
if (app_text_buffer->loadfile(filename) == 0) {
set_filename(filename);
set_changed(false);
} else {
fl_alert("Failed to load file\n%s\n%s",
filename,
strerror(errno));
}
}
\endcode
If the user selects our pulldown "Load" menu, we first check if the current
text was modified and provide a dialog box that offers to save the changes
before loading a new text file:
\code
void menu_open_callback(Fl_Widget*, void*) {
if (text_changed) {
int r = fl_choice("The current file has not been saved.\n"
"Would you like to save it now?",
"Cancel", "Save", "Don't Save");
if (r == 2)
return;
if (r == 1)
menu_save_callback();
}
...
\endcode
If the user did not cancel the operation, we pop up a file chooser for
loading the file, using similar code as in Save As.
\code
...
Fl_Native_File_Chooser file_chooser;
file_chooser.title("Open File...");
file_chooser.type(Fl_Native_File_Chooser::BROWSE_FILE);
...
\endcode
Again, we preload the file chooser with the last used path and file
name:
\code
...
if (app_filename[0]) {
char temp_filename[FL_PATH_MAX];
fl_strlcpy(temp_filename, app_filename, FL_PATH_MAX);
const char *name = fl_filename_name(temp_filename);
if (name) {
file_chooser.preset_file(name);
temp_filename[name - temp_filename] = 0;
file_chooser.directory(temp_filename);
}
}
...
\endcode
And finally, we pop up the file chooser. If the user cancels the file
dialog, we do nothing and keep the current file. Otherwise, we call
the `load()` function that we already wrote:
\code
if (file_chooser.show() == 0)
load(file_chooser.filename());
}
\endcode
We really should support two more ways to load documents from a file.
Let's modify the "show and run" part of `main()` to handle command
line parameters and desktop drag'n'drop operations. For that, we refactor
the last two lines of `main()` into a new function:
\code
// ... new function here
int main (int argc, char **argv) {
tut1_build_app_window();
tut2_build_app_menu_bar();
tut3_build_main_editor();
tut4_add_file_support();
// ... refactor those into the new function
// app_window->show(argc, argv);
// return Fl::run();
return tut4_handle_commandline_and_run(argc, argv);
}
\endcode
Our function to show the window and run the app has a few lines of boilerplate
code. `Fl::args_to_utf8()` converts the command line argument from whatever
the host system provides into Unicode. `Fl::args()` goes through the
list of arguments and gives `args_handler()` a chance to handle each argument.
It also makes sure that FLTK specific args are still forwarded to FLTK,
so `"-scheme plastic"` and `"-background #aaccff"` will draw beautiful blue
buttons in a plastic look.
`fl_open_callback()` lets FLTK know what to do if a user drops a text
file onto our editor icon (Apple macOS). Here, we ask it to call the `load()`
function that we wrote earlier.
\code
// ... args_handler here
int tut4_handle_commandline_and_run(int &argc, char **argv) {
int i = 0;
Fl::args_to_utf8(argc, argv);
Fl::args(argc, argv, i, args_handler);
fl_open_callback(load);
app_window->show(argc, argv);
return Fl::run();
}
\endcode
Last work item for this long chapter: what should our `args_handler`
do? We could handle additional command line options here, but for now,
all we want to handle is file names and paths. Let's make this easy: if the
current arg does not start with a '-', we assume it is a file name, and
we call `load()`:
\code
int args_handler(int argc, char **argv, int &i) {
if (argv && argv[i] && argv[i][0]!='-') {
load(argv[i]);
i++;
return 1;
}
return 0;
}
\endcode
So this is our basic but quite functional text editor app in about
100 lines of code. The following chapters add some user convenience
functions and show off some FLTK features including split editors and
syntax highlighting.
<!-- ----------------------------------------------------- -->
\section editor_cut_copy_paste Chapter 5: Cut, Copy, and Paste
The FLTK Text Editor widget comes with builtin cut, copy, and
paste functionality, but as a courtesy, we should also offer these
as menu items in the main menu.
In our feature list, we noted that we want to implement a split
text editor. This requires that the callbacks know which text editor
has the keyboard focus. Calling `Fl::focus()` may return `NULL` or
other unknown widgets, so we add a little test in our callbacks:
\code
void menu_cut_callback(Fl_Widget*, void* v) {
Fl_Widget *e = Fl::focus();
if (e && (e == app_editor || e == app_split_editor))
Fl_Text_Editor::kf_cut(0, (Fl_Text_Editor*)e);
}
\endcode
We can write very similar callbacks for undo, redo, copy, paste, and delete.
Adding a new menu and the six menu items follows the same pattern as
before. Using the Menu/Item notation will create an Edit menu for us:
\code
void tut5_cut_copy_paste() {
app_menu_bar->add("Edit/Undo", FL_COMMAND+'z', menu_undo_callback);
app_menu_bar->add("Edit/Redo", FL_COMMAND+'Z', menu_redo_callback, NULL, FL_MENU_DIVIDER);
app_menu_bar->add("Edit/Cut", FL_COMMAND+'x', menu_cut_callback);
app_menu_bar->add("Edit/Copy", FL_COMMAND+'c', menu_copy_callback);
app_menu_bar->add("Edit/Paste", FL_COMMAND+'v', menu_paste_callback);
app_menu_bar->add("Edit/Delete", 0, menu_delete_callback);
}
\endcode
<!-- ----------------------------------------------------- -->
\section editor_find Chapter 6: Find and Find Next
Corporate called. They want a dialog box for their users that can search
for some word in the text file. We can add this functionality using
a callback and a standard FLTK dialog box.
Here is some code to find a string in a text editor. The first four lines
make sure that we start our search at the cursor position of the current
editor window. The rest of the code searches the string and marks it
if found.
\code
void find_next(const char *needle) {
Fl_Text_Editor *editor = app_editor;
Fl_Widget *e = Fl::focus();
if (e && e == app_split_editor)
editor = app_split_editor;
int pos = editor->insert_position();
int found = app_text_buffer->search_forward(pos, needle, &pos);
if (found) {
app_text_buffer->select(pos, pos + (int)strlen(needle));
editor->insert_position(pos + (int)strlen(needle));
editor->show_insert_position();
} else {
fl_alert("No further occurrences of '%s' found!", needle);
}
}
\endcode
The callbacks are short, using the FLTK text field dialog box and the
`find_next` function that we already implemented. The last searched text
is saved in `last_find_text` to be reused by `menu_find_next_callback`.
If no search text was set yet, or it was set to an empty text, "Find Next"
will forward to `menu_find_callback` and pop up our "Find Text" dialog.
\code
char last_find_text[1024] = "";
void menu_find_callback(Fl_Widget*, void* v) {
const char *find_text = fl_input("Find in text:", last_find_text);
if (find_text) {
fl_strlcpy(last_find_text, find_text, sizeof(last_find_text));
find_next(find_text);
}
}
void menu_find_next_callback(Fl_Widget*, void* v) {
if (last_find_text[0]) {
find_next(last_find_text);
} else {
menu_find_callback(NULL, NULL);
}
}
\endcode
And of course we need to add two menu items to our main application menu.
\code
...
app_menu_bar->add("Find/Find...", FL_COMMAND+'f', menu_find_callback);
app_menu_bar->add("Find/Find Next", FL_COMMAND+'g', menu_find_next_callback, NULL, FL_MENU_DIVIDER);
...
\endcode
<!-- ----------------------------------------------------- -->
\section editor_replace Chapter 7: Replace and Replace Next
To implement the next feature, we will need to implement our own "Find
and Replace" dialog box. To make this dialog box useful, it needs the
following elements:
- a text input field for the text that we want to find
- a text input field for the replacement text
- a button to find the next occurrence
- a button to replace the current text and find the next occurrence
- a button to close the dialog
This is rather complex functionality, so instead of adding more global
variables, we will pack this dialog into a class, derived from `Fl_Window`.
\note The tutorial uses `Fl_Double_Window` instead of `Fl_Window` throughout.
Historically, on some platforms, `Fl_Window` renders faster, but has a
tendency to flicker. In today's world, this has very little relevance and
FLTK optimizes both window types. `Fl_Double_Window` is recommended unless
there is a specific reason to use `Fl_Window`.
Let's implement the text replacement code first:
\code
char last_replace_text[1024] = "";
void replace_selection(const char *new_text) {
Fl_Text_Editor *editor = app_editor;
Fl_Widget *e = Fl::focus();
if (e && e == app_split_editor)
editor = app_split_editor;
int start, end;
if (app_text_buffer->selection_position(&start, &end)) {
app_text_buffer->remove_selection();
app_text_buffer->insert(start, new_text);
app_text_buffer->select(start, start + (int)strlen(new_text));
editor->insert_position(start + (int)strlen(new_text));
editor->show_insert_position();
}
}
\endcode
As before, the first four lines anticipate a split editor and find the
editor that has focus. The code then deletes the currently selected
text, replaces it with the new text, selects the new text, and finally
sets the text cursor to the end of the new text.
<H3>The Replace_Dialog class</H3>
The Replace_Dialog class holds pointers to our active UI elements as
well as all the callbacks for the dialog buttons.
\code
class Replace_Dialog : public Fl_Double_Window {
Fl_Input *find_text_input;
Fl_Input *replace_text_input;
Fl_Button *find_next_button;
Fl_Button *replace_and_find_button;
Fl_Button *close_button;
public:
Replace_Dialog(const char *label);
void show() FL_OVERRIDE;
private:
static void find_next_callback(Fl_Widget*, void*);
static void replace_and_find_callback(Fl_Widget*, void*);
static void close_callback(Fl_Widget*, void*);
};
Replace_Dialog *replace_dialog = NULL;
\endcode
The constructor creates the dialog and marks it as "non modal". This will
make the dialog hover over the application window like a toolbox window until
the user closes it, allowing multiple "find and replace" operations. So here
is our constructor:
\code
Replace_Dialog::Replace_Dialog(const char *label)
: Fl_Double_Window(430, 110, label)
{
find_text_input = new Fl_Input(100, 10, 320, 25, "Find:");
replace_text_input = new Fl_Input(100, 40, 320, 25, "Replace:");
Fl_Flex* button_field = new Fl_Flex(100, 70, w()-100, 40);
button_field->type(Fl_Flex::HORIZONTAL);
button_field->margin(0, 5, 10, 10);
button_field->gap(10);
find_next_button = new Fl_Button(0, 0, 0, 0, "Next");
find_next_button->callback(find_next_callback, this);
replace_and_find_button = new Fl_Button(0, 0, 0, 0, "Replace");
replace_and_find_button->callback(replace_and_find_callback, this);
close_button = new Fl_Button(0, 0, 0, 0, "Close");
close_button->callback(close_callback, this);
button_field->end();
set_non_modal();
}
\endcode
All buttons are created inside an `Fl_Flex` group. They will be arranged
automatically by `Fl_Flex`, so there is no need to set x and y coordinates
or a width or height. `button_field` will lay out the buttons for us.
\note There is no need to write a destructor or delete individual widgets.
When we delete an instance of `Replace_Dialog`, all children are deleted
for us.
The `show()` method overrides the window's show method. It adds some code to
preload the values of the text fields for added convenience. It then pops up
the dialog box by calling the original `Fl_Double_Window::show()`.
\code
void Replace_Dialog::show() {
find_text_input->value(last_find_text);
replace_text_input->value(last_replace_text);
Fl_Double_Window::show();
}
\endcode
The buttons in the dialog need callbacks to be useful. If callbacks are
defined within a class, they must be defined `static`, but a pointer to the
class can be provided through the `user_data` field. We have done that in
the constructor by adding `this` as the last argument when setting the
callback, for example in `close_button->callback(close_callback, this);`.
The callback itself can then extract the `this` pointer with a static cast:
\code
void Replace_Dialog::close_callback(Fl_Widget*, void* my_dialog) {
Replace_Dialog *dlg = static_cast<Replace_Dialog*>(my_dialog);
dlg->hide();
}
\endcode
The callback for the Find button uses our already implemented `find_next`
function:
\code
void Replace_Dialog::find_next_callback(Fl_Widget*, void* my_dialog) {
Replace_Dialog *dlg = static_cast<Replace_Dialog*>(my_dialog);
fl_strlcpy(last_find_text, dlg->find_text_input->value(), sizeof(last_find_text));
fl_strlcpy(last_replace_text, dlg->replace_text_input->value(), sizeof(last_replace_text));
if (last_find_text[0])
find_next(last_find_text);
}
\endcode
The Replace button callback calls our newly implemented `replace_selection`
function and then continues on to the `find_next_callback`:
\code
void Replace_Dialog::replace_and_find_callback(Fl_Widget*, void* my_dialog) {
Replace_Dialog *dlg = static_cast<Replace_Dialog*>(my_dialog);
replace_selection(dlg->replace_text_input->value());
find_next_callback(NULL, my_dialog);
}
\endcode
This long chapter comes close to its end. We are missing menu items that pop
up our dialog and that allow a quick "Replace and Find Next" functionality
without popping up the dialog. The code is quite similar to the "Find" and
"Find Next" code in the previous chapter:
\code
void menu_replace_callback(Fl_Widget*, void*) {
if (!replace_dialog)
replace_dialog = new Replace_Dialog("Find and Replace");
replace_dialog->show();
}
void menu_replace_next_callback(Fl_Widget*, void*) {
if (!last_find_text[0]) {
menu_replace_callback(NULL, NULL);
} else {
replace_selection(last_replace_text);
find_next(last_find_text);
}
}
void tut7_implement_replace() {
app_menu_bar->add("Find/Replace...", FL_COMMAND+'r', menu_replace_callback);
app_menu_bar->add("Find/Replace Next", FL_COMMAND+'t', menu_replace_next_callback);
}
\endcode
<!-- ----------------------------------------------------- -->
\section editor_editor_features Chapter 8: Editor Features
Chapter 7 was long an intense. Let's relax and implement something simple here.
We want menus with check boxes that can toggle some text editor features on
and off:
\code
void tut8_editor_features() {
app_menu_bar->add("Window/Line Numbers", FL_COMMAND+'l', menu_linenumbers_callback, NULL, FL_MENU_TOGGLE);
app_menu_bar->add("Window/Word Wrap", 0, menu_wordwrap_callback, NULL, FL_MENU_TOGGLE);
}
\endcode
The `Fl_Widget` parameter in callbacks always points to the widget that causes
the callback. Menu items are not derived from widgets, so to find out which
menu item caused a callback, we can do this:
\code
void menu_linenumbers_callback(Fl_Widget* w, void*) {
Fl_Menu_Bar* menu = static_cast<Fl_Menu_Bar*>(w);
const Fl_Menu_Item* linenumber_item = menu->mvalue();
if (linenumber_item->value()) {
app_editor->linenumber_width(40);
} else {
app_editor->linenumber_width(0);
}
app_editor->redraw();
}
\endcode
Setting the width enables the line numbers, setting it to 0 disables the
line number display. When changing the value of a widget, FLTK will make sure
that the widget is redrawn to reflect the new value. When changing other
attributes such as colors or fonts, FLTK assumes that many attributes are
changed at the same time and leaves it to the user to call
`Fl_Widget::redraw()` when done. Here we call `app_editor->redraw()` to make
sure that the change in the line number setting is also drawn on screen.
Let's not forget to update the line number display
for a potential split editor widget es well:
\code
// add before the end of menu_linenumbers_callback
if (app_split_editor) {
if (linenumber_item->value()) {
app_split_editor->linenumber_width(40);
} else {
app_split_editor->linenumber_width(0);
}
app_split_editor->redraw();
}
\endcode
The word wrap feature is activated by calling `Fl_Text_Editor::wrap_mode()`
with the parameters `Fl_Text_Display::WRAP_AT_BOUNDS` and `0`. It's
deactivated with `Fl_Text_Display::WRAP_NONE`. The implementation of
the callback is the same as `menu_linenumbers_callback`.
<!-- ----------------------------------------------------- -->
\section editor_split_editor Chapter 9: Split Editor
When editing long source code files, it can be really helpful to split
the editor to view statements at the top of the text while
adding features at the bottom of the text in a split text view.
FLTK can link multiple text editors to a single text buffer. Let's implement
this now. This chapter will show you how to rearrange widgets in an existing
widget tree.
Our initializer removes the main text editor from the widget tree and
replaces it with an `Fl_Tile`. A tile can hold multiple widgets that can
then be resized interactively by the user by clicking and dragging the divider
between those widgets.
We start by replacing the editor widget with a tile group of the same size.
\code
#include <FL/Fl_Tile.H>
Fl_Tile *app_tile = NULL;
void tut9_split_editor() {
app_window->begin();
app_tile = new Fl_Tile(app_editor->x(), app_editor->y(),
app_editor->w(), app_editor->h());
app_window->remove(app_editor);
\endcode
Next we add our existing editor as the first child of the tile and create
another text editor `app_split_editor` as the second child of the tile, but
it's hidden for now with a height of zero pixels.
\note Creating the new `Fl_Tile` also calls `Fl_Tile::begin()`.
<BR><BR>Adding `app_editor` to the tile would have also removed it from
`app_window`, so `app_window->remove(app_editor)` in the code above is not
really needed, but illustrates what we are doing.
\code
app_tile->add(app_editor);
app_split_editor = new Fl_Text_Editor(app_tile->x(), app_tile->y()+app_tile->h(),
app_tile->w(), 0);
app_split_editor->buffer(app_text_buffer);
app_split_editor->textfont(FL_COURIER);
app_split_editor->hide();
\endcode
Now we clean up after ourselves and make sure that the resizables are all
set correctly. Lastly, we add a menu item with a callback.
\code
app_tile->end();
app_tile->size_range(0, 25, 25);
app_tile->size_range(1, 25, 25);
app_window->end();
app_window->resizable(app_tile);
app_tile->resizable(app_editor);
app_menu_bar->add("Window/Split", FL_COMMAND+'i', menu_split_callback, NULL, FL_MENU_TOGGLE);
}
\endcode
Now with all widgets in place, the callback's job is to show and resize, or
hide and resize the split editor. We can implement that like here:
\code
void menu_split_callback(Fl_Widget* w, void*) {
Fl_Menu_Bar* menu = static_cast<Fl_Menu_Bar*>(w);
const Fl_Menu_Item* splitview_item = menu->mvalue();
if (splitview_item->value()) {
int h_split = app_tile->h()/2;
app_editor->size(app_tile->w(), h_split);
app_split_editor->resize(app_tile->x(), app_tile->y() + h_split,
app_tile->w(), app_tile->h() - h_split);
app_split_editor->show();
} else {
app_editor->size(app_tile->w(), app_tile->h());
app_split_editor->resize(app_tile->x(), app_tile->y()+app_tile->h(),
app_tile->w(), 0);
app_split_editor->hide();
}
app_tile->resizable(app_editor);
app_tile->init_sizes();
app_tile->redraw();
}
\endcode
<!-- ----------------------------------------------------- -->
\section editor_syntax_highlighting Chapter 10: Syntax Highlighting
Chapter 10 adds a lot of code to implement "C" language syntax highlighting.
Not all code is duplicated here in the documentation. Please check out
`test/editor.cxx` for all the details.
The Fl_Text_Editor widget supports highlighting
of text with different fonts, colors, and sizes. The
implementation is based on the excellent
<A HREF="https://sourceforge.net/projects/nedit/">NEdit</A>
text editor core, from https://sourceforge.net/projects/nedit/, which
uses a parallel "style" buffer which tracks the font, color, and
size of the text that is drawn.
Styles are defined using the
Fl_Text_Display::Style_Table_Entry structure
defined in <tt><FL/Fl_Text_Display.H></tt>:
\code
struct Style_Table_Entry {
Fl_Color color;
Fl_Font font;
int size;
unsigned attr;
};
\endcode
The \p color member sets the color for the text,
the \p font member sets the FLTK font index to use,
and the \p size member sets the pixel size of the
text. The \p attr member is currently not used.
For our text editor we'll define 7 styles for plain code,
comments, keywords, and preprocessor directives:
\code
Fl_Text_Display::Style_Table_Entry styletable[] = { // Style table
{ FL_BLACK, FL_COURIER, FL_NORMAL_SIZE }, // A - Plain
{ FL_DARK_GREEN, FL_COURIER_ITALIC, FL_NORMAL_SIZE }, // B - Line comments
{ FL_DARK_GREEN, FL_COURIER_ITALIC, FL_NORMAL_SIZE }, // C - Block comments
{ FL_BLUE, FL_COURIER, FL_NORMAL_SIZE }, // D - Strings
{ FL_DARK_RED, FL_COURIER, FL_NORMAL_SIZE }, // E - Directives
{ FL_DARK_RED, FL_COURIER_BOLD, FL_NORMAL_SIZE }, // F - Types
{ FL_BLUE, FL_COURIER_BOLD, FL_NORMAL_SIZE } // G - Keywords
};
\endcode
You'll notice that the comments show a letter next to each
style - each style in the style buffer is referenced using a
character starting with the letter 'A'.
You call the \p highlight_data() method to associate the
style data and buffer with the text editor widget:
\code
Fl_Text_Buffer *app_style_buffer;
app_editor->highlight_data(app_style_buffer, styletable,
sizeof(styletable) / sizeof(styletable[0]),
'A', style_unfinished_cb, 0);
\endcode
Finally, you need to add a callback to the main text buffer so
that changes to the text buffer are mirrored in the style buffer:
\code
app_text_buffer->add_modify_callback(style_update, app_editor);
\endcode
The \p style_update() function, like the \p change_cb()
function described earlier, is called whenever text is added or removed from
the text buffer. It mirrors the changes in the style buffer and then updates
the style data as necessary:
\code
//
// 'style_update()' - Update the style buffer...
//
void
style_update(int pos, // I - Position of update
int nInserted, // I - Number of inserted chars
int nDeleted, // I - Number of deleted chars
int nRestyled, // I - Number of restyled chars
const char *deletedText, // I - Text that was deleted
void *cbArg) { // I - Callback data
int start, // Start of text
end; // End of text
char last, // Last style on line
*style, // Style data
*text; // Text data
// If this is just a selection change, just unselect the style buffer...
if (nInserted == 0 && nDeleted == 0) {
app_style_buffer->unselect();
return;
}
// Track changes in the text buffer...
if (nInserted > 0) {
// Insert characters into the style buffer...
style = new char[nInserted + 1];
memset(style, 'A', nInserted);
style[nInserted] = '\0';
app_style_buffer->replace(pos, pos + nDeleted, style);
delete[] style;
} else {
// Just delete characters in the style buffer...
app_style_buffer->remove(pos, pos + nDeleted);
}
// Select the area that was just updated to avoid unnecessary
// callbacks...
app_style_buffer->select(pos, pos + nInserted - nDeleted);
// Re-parse the changed region; we do this by parsing from the
// beginning of the line of the changed region to the end of
// the line of the changed region... Then we check the last
// style character and keep updating if we have a multi-line
// comment character...
start = app_text_buffer->line_start(pos);
end = app_text_buffer->line_end(pos + nInserted - nDeleted);
text = app_text_buffer->text_range(start, end);
style = app_style_buffer->text_range(start, end);
last = style[end - start - 1];
style_parse(text, style, end - start);
app_style_buffer->replace(start, end, style);
((Fl_Text_Editor *)cbArg)->redisplay_range(start, end);
if (last != style[end - start - 1]) {
// The last character on the line changed styles, so reparse the
// remainder of the buffer...
free(text);
free(style);
end = app_text_buffer->length();
text = app_text_buffer->text_range(start, end);
style = app_style_buffer->text_range(start, end);
style_parse(text, style, end - start);
app_style_buffer->replace(start, end, style);
((Fl_Text_Editor *)cbArg)->redisplay_range(start, end);
}
free(text);
free(style);
}
\endcode
The \p style_parse() function scans a copy of the
text in the buffer and generates the necessary style characters
for display. It assumes that parsing begins at the start of a line:
\code
//
// 'style_parse()' - Parse text and produce style data.
//
void
style_parse(const char *text,
char *style,
int length) {
char current;
int col;
int last;
char buf[255],
*bufptr;
const char *temp;
for (current = *style, col = 0, last = 0; length > 0; length --, text ++) {
if (current == 'A') {
// Check for directives, comments, strings, and keywords...
if (col == 0 && *text == '#') {
// Set style to directive
current = 'E';
} else if (strncmp(text, "//", 2) == 0) {
current = 'B';
} else if (strncmp(text, "/*", 2) == 0) {
current = 'C';
} else if (strncmp(text, "\\\"", 2) == 0) {
// Quoted quote...
*style++ = current;
*style++ = current;
text ++;
length --;
col += 2;
continue;
} else if (*text == '\"') {
current = 'D';
} else if (!last && islower(*text)) {
// Might be a keyword...
for (temp = text, bufptr = buf;
islower(*temp) && bufptr < (buf + sizeof(buf) - 1);
*bufptr++ = *temp++);
if (!islower(*temp)) {
*bufptr = '\0';
bufptr = buf;
if (bsearch(&bufptr, code_types,
sizeof(code_types) / sizeof(code_types[0]),
sizeof(code_types[0]), compare_keywords)) {
while (text < temp) {
*style++ = 'F';
text ++;
length --;
col ++;
}
text --;
length ++;
last = 1;
continue;
} else if (bsearch(&bufptr, code_keywords,
sizeof(code_keywords) / sizeof(code_keywords[0]),
sizeof(code_keywords[0]), compare_keywords)) {
while (text < temp) {
*style++ = 'G';
text ++;
length --;
col ++;
}
text --;
length ++;
last = 1;
continue;
}
}
}
} else if (current == 'C' && strncmp(text, "*/", 2) == 0) {
// Close a C comment...
*style++ = current;
*style++ = current;
text ++;
length --;
current = 'A';
col += 2;
continue;
} else if (current == 'D') {
// Continuing in string...
if (strncmp(text, "\\\"", 2) == 0) {
// Quoted end quote...
*style++ = current;
*style++ = current;
text ++;
length --;
col += 2;
continue;
} else if (*text == '\"') {
// End quote...
*style++ = current;
col ++;
current = 'A';
continue;
}
}
// Copy style info...
if (current == 'A' && (*text == '{' || *text == '}')) *style++ = 'G';
else *style++ = current;
col ++;
last = isalnum(*text) || *text == '.';
if (*text == '\n') {
// Reset column and possibly reset the style
col = 0;
if (current == 'B' || current == 'E') current = 'A';
}
}
}
\endcode
\htmlonly
<hr>
<table summary="navigation bar" width="100%" border="0">
<tr>
<td width="45%" align="LEFT">
<a class="el" href="resize.html">
[Prev]
How Does Resizing Work?
</a>
</td>
<td width="10%" align="CENTER">
<a class="el" href="index.html">[Index]</a>
</td>
<td width="45%" align="RIGHT">
<a class="el" href="drawing.html">
Drawing Things in FLTK
[Next]
</a>
</td>
</tr>
</table>
\endhtmlonly
*/
|