1 // [DEAR IMGUI]
2 // This is a slightly modified version of stb_textedit.h 1.13.
3 // Those changes would need to be pushed into nothings/stb:
4 // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)
5 // Grep for [DEAR IMGUI] to find the changes.
6 
7 // stb_textedit.h - v1.13  - public domain - Sean Barrett
8 // Development of this library was sponsored by RAD Game Tools
9 //
10 // This C header file implements the guts of a multi-line text-editing
11 // widget; you implement display, word-wrapping, and low-level string
12 // insertion/deletion, and stb_textedit will map user inputs into
13 // insertions & deletions, plus updates to the cursor position,
14 // selection state, and undo state.
15 //
16 // It is intended for use in games and other systems that need to build
17 // their own custom widgets and which do not have heavy text-editing
18 // requirements (this library is not recommended for use for editing large
19 // texts, as its performance does not scale and it has limited undo).
20 //
21 // Non-trivial behaviors are modelled after Windows text controls.
22 //
23 //
24 // LICENSE
25 //
26 // See end of file for license information.
27 //
28 //
29 // DEPENDENCIES
30 //
31 // Uses the C runtime function 'memmove', which you can override
32 // by defining STB_TEXTEDIT_memmove before the implementation.
33 // Uses no other functions. Performs no runtime allocations.
34 //
35 //
36 // VERSION HISTORY
37 //
38 //   1.13 (2019-02-07) fix bug in undo size management
39 //   1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash
40 //   1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield
41 //   1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual
42 //   1.9  (2016-08-27) customizable move-by-word
43 //   1.8  (2016-04-02) better keyboard handling when mouse button is down
44 //   1.7  (2015-09-13) change y range handling in case baseline is non-0
45 //   1.6  (2015-04-15) allow STB_TEXTEDIT_memmove
46 //   1.5  (2014-09-10) add support for secondary keys for OS X
47 //   1.4  (2014-08-17) fix signed/unsigned warnings
48 //   1.3  (2014-06-19) fix mouse clicking to round to nearest char boundary
49 //   1.2  (2014-05-27) fix some RAD types that had crept into the new code
50 //   1.1  (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )
51 //   1.0  (2012-07-26) improve documentation, initial public release
52 //   0.3  (2012-02-24) bugfixes, single-line mode; insert mode
53 //   0.2  (2011-11-28) fixes to undo/redo
54 //   0.1  (2010-07-08) initial version
55 //
56 // ADDITIONAL CONTRIBUTORS
57 //
58 //   Ulf Winklemann: move-by-word in 1.1
59 //   Fabian Giesen: secondary key inputs in 1.5
60 //   Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6
61 //
62 //   Bugfixes:
63 //      Scott Graham
64 //      Daniel Keller
65 //      Omar Cornut
66 //      Dan Thompson
67 //
68 // USAGE
69 //
70 // This file behaves differently depending on what symbols you define
71 // before including it.
72 //
73 //
74 // Header-file mode:
75 //
76 //   If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this,
77 //   it will operate in "header file" mode. In this mode, it declares a
78 //   single public symbol, STB_TexteditState, which encapsulates the current
79 //   state of a text widget (except for the string, which you will store
80 //   separately).
81 //
82 //   To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a
83 //   primitive type that defines a single character (e.g. char, wchar_t, etc).
84 //
85 //   To save space or increase undo-ability, you can optionally define the
86 //   following things that are used by the undo system:
87 //
88 //      STB_TEXTEDIT_POSITIONTYPE         small int type encoding a valid cursor position
89 //      STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow
90 //      STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer
91 //
92 //   If you don't define these, they are set to permissive types and
93 //   moderate sizes. The undo system does no memory allocations, so
94 //   it grows STB_TexteditState by the worst-case storage which is (in bytes):
95 //
96 //        [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT
97 //      +          sizeof(STB_TEXTEDIT_CHARTYPE)      * STB_TEXTEDIT_UNDOCHAR_COUNT
98 //
99 //
100 // Implementation mode:
101 //
102 //   If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it
103 //   will compile the implementation of the text edit widget, depending
104 //   on a large number of symbols which must be defined before the include.
105 //
106 //   The implementation is defined only as static functions. You will then
107 //   need to provide your own APIs in the same file which will access the
108 //   static functions.
109 //
110 //   The basic concept is that you provide a "string" object which
111 //   behaves like an array of characters. stb_textedit uses indices to
112 //   refer to positions in the string, implicitly representing positions
113 //   in the displayed textedit. This is true for both plain text and
114 //   rich text; even with rich text stb_truetype interacts with your
115 //   code as if there was an array of all the displayed characters.
116 //
117 // Symbols that must be the same in header-file and implementation mode:
118 //
119 //     STB_TEXTEDIT_CHARTYPE             the character type
120 //     STB_TEXTEDIT_POSITIONTYPE         small type that is a valid cursor position
121 //     STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow
122 //     STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer
123 //
124 // Symbols you must define for implementation mode:
125 //
126 //    STB_TEXTEDIT_STRING               the type of object representing a string being edited,
127 //                                      typically this is a wrapper object with other data you need
128 //
129 //    STB_TEXTEDIT_STRINGLEN(obj)       the length of the string (ideally O(1))
130 //    STB_TEXTEDIT_LAYOUTROW(&r,obj,n)  returns the results of laying out a line of characters
131 //                                        starting from character #n (see discussion below)
132 //    STB_TEXTEDIT_GETWIDTH(obj,n,i)    returns the pixel delta from the xpos of the i'th character
133 //                                        to the xpos of the i+1'th char for a line of characters
134 //                                        starting at character #n (i.e. accounts for kerning
135 //                                        with previous char)
136 //    STB_TEXTEDIT_KEYTOTEXT(k)         maps a keyboard input to an insertable character
137 //                                        (return type is int, -1 means not valid to insert)
138 //    STB_TEXTEDIT_GETCHAR(obj,i)       returns the i'th character of obj, 0-based
139 //    STB_TEXTEDIT_NEWLINE              the character returned by _GETCHAR() we recognize
140 //                                        as manually wordwrapping for end-of-line positioning
141 //
142 //    STB_TEXTEDIT_DELETECHARS(obj,i,n)      delete n characters starting at i
143 //    STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n)   insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*)
144 //
145 //    STB_TEXTEDIT_K_SHIFT       a power of two that is or'd in to a keyboard input to represent the shift key
146 //
147 //    STB_TEXTEDIT_K_LEFT        keyboard input to move cursor left
148 //    STB_TEXTEDIT_K_RIGHT       keyboard input to move cursor right
149 //    STB_TEXTEDIT_K_UP          keyboard input to move cursor up
150 //    STB_TEXTEDIT_K_DOWN        keyboard input to move cursor down
151 //    STB_TEXTEDIT_K_PGUP        keyboard input to move cursor up a page
152 //    STB_TEXTEDIT_K_PGDOWN      keyboard input to move cursor down a page
153 //    STB_TEXTEDIT_K_LINESTART   keyboard input to move cursor to start of line  // e.g. HOME
154 //    STB_TEXTEDIT_K_LINEEND     keyboard input to move cursor to end of line    // e.g. END
155 //    STB_TEXTEDIT_K_TEXTSTART   keyboard input to move cursor to start of text  // e.g. ctrl-HOME
156 //    STB_TEXTEDIT_K_TEXTEND     keyboard input to move cursor to end of text    // e.g. ctrl-END
157 //    STB_TEXTEDIT_K_DELETE      keyboard input to delete selection or character under cursor
158 //    STB_TEXTEDIT_K_BACKSPACE   keyboard input to delete selection or character left of cursor
159 //    STB_TEXTEDIT_K_UNDO        keyboard input to perform undo
160 //    STB_TEXTEDIT_K_REDO        keyboard input to perform redo
161 //
162 // Optional:
163 //    STB_TEXTEDIT_K_INSERT              keyboard input to toggle insert mode
164 //    STB_TEXTEDIT_IS_SPACE(ch)          true if character is whitespace (e.g. 'isspace'),
165 //                                          required for default WORDLEFT/WORDRIGHT handlers
166 //    STB_TEXTEDIT_MOVEWORDLEFT(obj,i)   custom handler for WORDLEFT, returns index to move cursor to
167 //    STB_TEXTEDIT_MOVEWORDRIGHT(obj,i)  custom handler for WORDRIGHT, returns index to move cursor to
168 //    STB_TEXTEDIT_K_WORDLEFT            keyboard input to move cursor left one word // e.g. ctrl-LEFT
169 //    STB_TEXTEDIT_K_WORDRIGHT           keyboard input to move cursor right one word // e.g. ctrl-RIGHT
170 //    STB_TEXTEDIT_K_LINESTART2          secondary keyboard input to move cursor to start of line
171 //    STB_TEXTEDIT_K_LINEEND2            secondary keyboard input to move cursor to end of line
172 //    STB_TEXTEDIT_K_TEXTSTART2          secondary keyboard input to move cursor to start of text
173 //    STB_TEXTEDIT_K_TEXTEND2            secondary keyboard input to move cursor to end of text
174 //
175 // Keyboard input must be encoded as a single integer value; e.g. a character code
176 // and some bitflags that represent shift states. to simplify the interface, SHIFT must
177 // be a bitflag, so we can test the shifted state of cursor movements to allow selection,
178 // i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.
179 //
180 // You can encode other things, such as CONTROL or ALT, in additional bits, and
181 // then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,
182 // my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN
183 // bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit,
184 // and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the
185 // API below. The control keys will only match WM_KEYDOWN events because of the
186 // keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN
187 // bit so it only decodes WM_CHAR events.
188 //
189 // STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed
190 // row of characters assuming they start on the i'th character--the width and
191 // the height and the number of characters consumed. This allows this library
192 // to traverse the entire layout incrementally. You need to compute word-wrapping
193 // here.
194 //
195 // Each textfield keeps its own insert mode state, which is not how normal
196 // applications work. To keep an app-wide insert mode, update/copy the
197 // "insert_mode" field of STB_TexteditState before/after calling API functions.
198 //
199 // API
200 //
201 //    void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)
202 //
203 //    void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
204 //    void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
205 //    int  stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
206 //    int  stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)
207 //    void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key)
208 //
209 //    Each of these functions potentially updates the string and updates the
210 //    state.
211 //
212 //      initialize_state:
213 //          set the textedit state to a known good default state when initially
214 //          constructing the textedit.
215 //
216 //      click:
217 //          call this with the mouse x,y on a mouse down; it will update the cursor
218 //          and reset the selection start/end to the cursor point. the x,y must
219 //          be relative to the text widget, with (0,0) being the top left.
220 //
221 //      drag:
222 //          call this with the mouse x,y on a mouse drag/up; it will update the
223 //          cursor and the selection end point
224 //
225 //      cut:
226 //          call this to delete the current selection; returns true if there was
227 //          one. you should FIRST copy the current selection to the system paste buffer.
228 //          (To copy, just copy the current selection out of the string yourself.)
229 //
230 //      paste:
231 //          call this to paste text at the current cursor point or over the current
232 //          selection if there is one.
233 //
234 //      key:
235 //          call this for keyboard inputs sent to the textfield. you can use it
236 //          for "key down" events or for "translated" key events. if you need to
237 //          do both (as in Win32), or distinguish Unicode characters from control
238 //          inputs, set a high bit to distinguish the two; then you can define the
239 //          various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit
240 //          set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is
241 //          clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to
242 //          anything other type you wante before including.
243 //
244 //
245 //   When rendering, you can read the cursor position and selection state from
246 //   the STB_TexteditState.
247 //
248 //
249 // Notes:
250 //
251 // This is designed to be usable in IMGUI, so it allows for the possibility of
252 // running in an IMGUI that has NOT cached the multi-line layout. For this
253 // reason, it provides an interface that is compatible with computing the
254 // layout incrementally--we try to make sure we make as few passes through
255 // as possible. (For example, to locate the mouse pointer in the text, we
256 // could define functions that return the X and Y positions of characters
257 // and binary search Y and then X, but if we're doing dynamic layout this
258 // will run the layout algorithm many times, so instead we manually search
259 // forward in one pass. Similar logic applies to e.g. up-arrow and
260 // down-arrow movement.)
261 //
262 // If it's run in a widget that *has* cached the layout, then this is less
263 // efficient, but it's not horrible on modern computers. But you wouldn't
264 // want to edit million-line files with it.
265 
266 
267 ////////////////////////////////////////////////////////////////////////////
268 ////////////////////////////////////////////////////////////////////////////
269 ////
270 ////   Header-file mode
271 ////
272 ////
273 
274 #ifndef INCLUDE_STB_TEXTEDIT_H
275 #define INCLUDE_STB_TEXTEDIT_H
276 
277 ////////////////////////////////////////////////////////////////////////
278 //
279 //     STB_TexteditState
280 //
281 // Definition of STB_TexteditState which you should store
282 // per-textfield; it includes cursor position, selection state,
283 // and undo state.
284 //
285 
286 #ifndef STB_TEXTEDIT_UNDOSTATECOUNT
287 #define STB_TEXTEDIT_UNDOSTATECOUNT   99
288 #endif
289 #ifndef STB_TEXTEDIT_UNDOCHARCOUNT
290 #define STB_TEXTEDIT_UNDOCHARCOUNT   999
291 #endif
292 #ifndef STB_TEXTEDIT_CHARTYPE
293 #define STB_TEXTEDIT_CHARTYPE        int
294 #endif
295 #ifndef STB_TEXTEDIT_POSITIONTYPE
296 #define STB_TEXTEDIT_POSITIONTYPE    int
297 #endif
298 
299 typedef struct
300 {
301    // private data
302    STB_TEXTEDIT_POSITIONTYPE  where;
303    STB_TEXTEDIT_POSITIONTYPE  insert_length;
304    STB_TEXTEDIT_POSITIONTYPE  delete_length;
305    int                        char_storage;
306 } StbUndoRecord;
307 
308 typedef struct
309 {
310    // private data
311    StbUndoRecord          undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT];
312    STB_TEXTEDIT_CHARTYPE  undo_char[STB_TEXTEDIT_UNDOCHARCOUNT];
313    short undo_point, redo_point;
314    int undo_char_point, redo_char_point;
315 } StbUndoState;
316 
317 typedef struct
318 {
319    /////////////////////
320    //
321    // public data
322    //
323 
324    int cursor;
325    // position of the text cursor within the string
326 
327    int select_start;          // selection start point
328    int select_end;
329    // selection start and end point in characters; if equal, no selection.
330    // note that start may be less than or greater than end (e.g. when
331    // dragging the mouse, start is where the initial click was, and you
332    // can drag in either direction)
333 
334    unsigned char insert_mode;
335    // each textfield keeps its own insert mode state. to keep an app-wide
336    // insert mode, copy this value in/out of the app state
337 
338    int row_count_per_page;
339    // page size in number of row.
340    // this value MUST be set to >0 for pageup or pagedown in multilines documents.
341 
342    /////////////////////
343    //
344    // private data
345    //
346    unsigned char cursor_at_end_of_line; // not implemented yet
347    unsigned char initialized;
348    unsigned char has_preferred_x;
349    unsigned char single_line;
350    unsigned char padding1, padding2, padding3;
351    float preferred_x; // this determines where the cursor up/down tries to seek to along x
352    StbUndoState undostate;
353 } STB_TexteditState;
354 
355 
356 ////////////////////////////////////////////////////////////////////////
357 //
358 //     StbTexteditRow
359 //
360 // Result of layout query, used by stb_textedit to determine where
361 // the text in each row is.
362 
363 // result of layout query
364 typedef struct
365 {
366    float x0,x1;             // starting x location, end x location (allows for align=right, etc)
367    float baseline_y_delta;  // position of baseline relative to previous row's baseline
368    float ymin,ymax;         // height of row above and below baseline
369    int num_chars;
370 } StbTexteditRow;
371 #endif //INCLUDE_STB_TEXTEDIT_H
372 
373 
374 ////////////////////////////////////////////////////////////////////////////
375 ////////////////////////////////////////////////////////////////////////////
376 ////
377 ////   Implementation mode
378 ////
379 ////
380 
381 
382 // implementation isn't include-guarded, since it might have indirectly
383 // included just the "header" portion
384 #ifdef STB_TEXTEDIT_IMPLEMENTATION
385 
386 #ifndef STB_TEXTEDIT_memmove
387 #include <string.h>
388 #define STB_TEXTEDIT_memmove memmove
389 #endif
390 
391 
392 /////////////////////////////////////////////////////////////////////////////
393 //
394 //      Mouse input handling
395 //
396 
397 // traverse the layout to locate the nearest character to a display position
stb_text_locate_coord(STB_TEXTEDIT_STRING * str,float x,float y)398 static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y)
399 {
400    StbTexteditRow r;
401    int n = STB_TEXTEDIT_STRINGLEN(str);
402    float base_y = 0, prev_x;
403    int i=0, k;
404 
405    r.x0 = r.x1 = 0;
406    r.ymin = r.ymax = 0;
407    r.num_chars = 0;
408 
409    // search rows to find one that straddles 'y'
410    while (i < n) {
411       STB_TEXTEDIT_LAYOUTROW(&r, str, i);
412       if (r.num_chars <= 0)
413          return n;
414 
415       if (i==0 && y < base_y + r.ymin)
416          return 0;
417 
418       if (y < base_y + r.ymax)
419          break;
420 
421       i += r.num_chars;
422       base_y += r.baseline_y_delta;
423    }
424 
425    // below all text, return 'after' last character
426    if (i >= n)
427       return n;
428 
429    // check if it's before the beginning of the line
430    if (x < r.x0)
431       return i;
432 
433    // check if it's before the end of the line
434    if (x < r.x1) {
435       // search characters in row for one that straddles 'x'
436       prev_x = r.x0;
437       for (k=0; k < r.num_chars; ++k) {
438          float w = STB_TEXTEDIT_GETWIDTH(str, i, k);
439          if (x < prev_x+w) {
440             if (x < prev_x+w/2)
441                return k+i;
442             else
443                return k+i+1;
444          }
445          prev_x += w;
446       }
447       // shouldn't happen, but if it does, fall through to end-of-line case
448    }
449 
450    // if the last character is a newline, return that. otherwise return 'after' the last character
451    if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)
452       return i+r.num_chars-1;
453    else
454       return i+r.num_chars;
455 }
456 
457 // API click: on mouse down, move the cursor to the clicked location, and reset the selection
stb_textedit_click(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,float x,float y)458 static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
459 {
460    // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
461    // goes off the top or bottom of the text
462    if( state->single_line )
463    {
464       StbTexteditRow r;
465       STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
466       y = r.ymin;
467    }
468 
469    state->cursor = stb_text_locate_coord(str, x, y);
470    state->select_start = state->cursor;
471    state->select_end = state->cursor;
472    state->has_preferred_x = 0;
473 }
474 
475 // API drag: on mouse drag, move the cursor and selection endpoint to the clicked location
stb_textedit_drag(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,float x,float y)476 static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
477 {
478    int p = 0;
479 
480    // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
481    // goes off the top or bottom of the text
482    if( state->single_line )
483    {
484       StbTexteditRow r;
485       STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
486       y = r.ymin;
487    }
488 
489    if (state->select_start == state->select_end)
490       state->select_start = state->cursor;
491 
492    p = stb_text_locate_coord(str, x, y);
493    state->cursor = state->select_end = p;
494 }
495 
496 /////////////////////////////////////////////////////////////////////////////
497 //
498 //      Keyboard input handling
499 //
500 
501 // forward declarations
502 static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
503 static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);
504 static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);
505 static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);
506 static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);
507 
508 typedef struct
509 {
510    float x,y;    // position of n'th character
511    float height; // height of line
512    int first_char, length; // first char of row, and length
513    int prev_first;  // first char of previous row
514 } StbFindState;
515 
516 // find the x/y location of a character, and remember info about the previous row in
517 // case we get a move-up event (for page up, we'll have to rescan)
stb_textedit_find_charpos(StbFindState * find,STB_TEXTEDIT_STRING * str,int n,int single_line)518 static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line)
519 {
520    StbTexteditRow r;
521    int prev_start = 0;
522    int z = STB_TEXTEDIT_STRINGLEN(str);
523    int i=0, first;
524 
525    if (n == z) {
526       // if it's at the end, then find the last line -- simpler than trying to
527       // explicitly handle this case in the regular code
528       if (single_line) {
529          STB_TEXTEDIT_LAYOUTROW(&r, str, 0);
530          find->y = 0;
531          find->first_char = 0;
532          find->length = z;
533          find->height = r.ymax - r.ymin;
534          find->x = r.x1;
535       } else {
536          find->y = 0;
537          find->x = 0;
538          find->height = 1;
539          while (i < z) {
540             STB_TEXTEDIT_LAYOUTROW(&r, str, i);
541             prev_start = i;
542             i += r.num_chars;
543          }
544          find->first_char = i;
545          find->length = 0;
546          find->prev_first = prev_start;
547       }
548       return;
549    }
550 
551    // search rows to find the one that straddles character n
552    find->y = 0;
553 
554    for(;;) {
555       STB_TEXTEDIT_LAYOUTROW(&r, str, i);
556       if (n < i + r.num_chars)
557          break;
558       prev_start = i;
559       i += r.num_chars;
560       find->y += r.baseline_y_delta;
561    }
562 
563    find->first_char = first = i;
564    find->length = r.num_chars;
565    find->height = r.ymax - r.ymin;
566    find->prev_first = prev_start;
567 
568    // now scan to find xpos
569    find->x = r.x0;
570    for (i=0; first+i < n; ++i)
571       find->x += STB_TEXTEDIT_GETWIDTH(str, first, i);
572 }
573 
574 #define STB_TEXT_HAS_SELECTION(s)   ((s)->select_start != (s)->select_end)
575 
576 // make the selection/cursor state valid if client altered the string
stb_textedit_clamp(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)577 static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
578 {
579    int n = STB_TEXTEDIT_STRINGLEN(str);
580    if (STB_TEXT_HAS_SELECTION(state)) {
581       if (state->select_start > n) state->select_start = n;
582       if (state->select_end   > n) state->select_end = n;
583       // if clamping forced them to be equal, move the cursor to match
584       if (state->select_start == state->select_end)
585          state->cursor = state->select_start;
586    }
587    if (state->cursor > n) state->cursor = n;
588 }
589 
590 // delete characters while updating undo
stb_textedit_delete(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,int where,int len)591 static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len)
592 {
593    stb_text_makeundo_delete(str, state, where, len);
594    STB_TEXTEDIT_DELETECHARS(str, where, len);
595    state->has_preferred_x = 0;
596 }
597 
598 // delete the section
stb_textedit_delete_selection(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)599 static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
600 {
601    stb_textedit_clamp(str, state);
602    if (STB_TEXT_HAS_SELECTION(state)) {
603       if (state->select_start < state->select_end) {
604          stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start);
605          state->select_end = state->cursor = state->select_start;
606       } else {
607          stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end);
608          state->select_start = state->cursor = state->select_end;
609       }
610       state->has_preferred_x = 0;
611    }
612 }
613 
614 // canoncialize the selection so start <= end
stb_textedit_sortselection(STB_TexteditState * state)615 static void stb_textedit_sortselection(STB_TexteditState *state)
616 {
617    if (state->select_end < state->select_start) {
618       int temp = state->select_end;
619       state->select_end = state->select_start;
620       state->select_start = temp;
621    }
622 }
623 
624 // move cursor to first character of selection
stb_textedit_move_to_first(STB_TexteditState * state)625 static void stb_textedit_move_to_first(STB_TexteditState *state)
626 {
627    if (STB_TEXT_HAS_SELECTION(state)) {
628       stb_textedit_sortselection(state);
629       state->cursor = state->select_start;
630       state->select_end = state->select_start;
631       state->has_preferred_x = 0;
632    }
633 }
634 
635 // move cursor to last character of selection
stb_textedit_move_to_last(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)636 static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
637 {
638    if (STB_TEXT_HAS_SELECTION(state)) {
639       stb_textedit_sortselection(state);
640       stb_textedit_clamp(str, state);
641       state->cursor = state->select_end;
642       state->select_start = state->select_end;
643       state->has_preferred_x = 0;
644    }
645 }
646 
647 #ifdef STB_TEXTEDIT_IS_SPACE
is_word_boundary(STB_TEXTEDIT_STRING * str,int idx)648 static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx )
649 {
650    return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1;
651 }
652 
653 #ifndef STB_TEXTEDIT_MOVEWORDLEFT
stb_textedit_move_to_word_previous(STB_TEXTEDIT_STRING * str,int c)654 static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c )
655 {
656    --c; // always move at least one character
657    while( c >= 0 && !is_word_boundary( str, c ) )
658       --c;
659 
660    if( c < 0 )
661       c = 0;
662 
663    return c;
664 }
665 #define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous
666 #endif
667 
668 #ifndef STB_TEXTEDIT_MOVEWORDRIGHT
stb_textedit_move_to_word_next(STB_TEXTEDIT_STRING * str,int c)669 static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c )
670 {
671    const int len = STB_TEXTEDIT_STRINGLEN(str);
672    ++c; // always move at least one character
673    while( c < len && !is_word_boundary( str, c ) )
674       ++c;
675 
676    if( c > len )
677       c = len;
678 
679    return c;
680 }
681 #define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next
682 #endif
683 
684 #endif
685 
686 // update selection and cursor to match each other
stb_textedit_prep_selection_at_cursor(STB_TexteditState * state)687 static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state)
688 {
689    if (!STB_TEXT_HAS_SELECTION(state))
690       state->select_start = state->select_end = state->cursor;
691    else
692       state->cursor = state->select_end;
693 }
694 
695 // API cut: delete selection
stb_textedit_cut(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)696 static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
697 {
698    if (STB_TEXT_HAS_SELECTION(state)) {
699       stb_textedit_delete_selection(str,state); // implicitly clamps
700       state->has_preferred_x = 0;
701       return 1;
702    }
703    return 0;
704 }
705 
706 // API paste: replace existing selection with passed-in text
stb_textedit_paste_internal(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,STB_TEXTEDIT_CHARTYPE * text,int len)707 static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)
708 {
709    // if there's a selection, the paste should delete it
710    stb_textedit_clamp(str, state);
711    stb_textedit_delete_selection(str,state);
712    // try to insert the characters
713    if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) {
714       stb_text_makeundo_insert(state, state->cursor, len);
715       state->cursor += len;
716       state->has_preferred_x = 0;
717       return 1;
718    }
719    // [DEAR IMGUI]
720    //// remove the undo since we didn't actually insert the characters
721    //if (state->undostate.undo_point)
722    //   --state->undostate.undo_point;
723    // note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details)
724    return 0;
725 }
726 
727 #ifndef STB_TEXTEDIT_KEYTYPE
728 #define STB_TEXTEDIT_KEYTYPE int
729 #endif
730 
731 // API key: process a keyboard input
stb_textedit_key(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,STB_TEXTEDIT_KEYTYPE key)732 static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)
733 {
734 retry:
735    switch (key) {
736       default: {
737          int c = STB_TEXTEDIT_KEYTOTEXT(key);
738          if (c > 0) {
739             STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c;
740 
741             // can't add newline in single-line mode
742             if (c == '\n' && state->single_line)
743                break;
744 
745             if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {
746                stb_text_makeundo_replace(str, state, state->cursor, 1, 1);
747                STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);
748                if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
749                   ++state->cursor;
750                   state->has_preferred_x = 0;
751                }
752             } else {
753                stb_textedit_delete_selection(str,state); // implicitly clamps
754                if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {
755                   stb_text_makeundo_insert(state, state->cursor, 1);
756                   ++state->cursor;
757                   state->has_preferred_x = 0;
758                }
759             }
760          }
761          break;
762       }
763 
764 #ifdef STB_TEXTEDIT_K_INSERT
765       case STB_TEXTEDIT_K_INSERT:
766          state->insert_mode = !state->insert_mode;
767          break;
768 #endif
769 
770       case STB_TEXTEDIT_K_UNDO:
771          stb_text_undo(str, state);
772          state->has_preferred_x = 0;
773          break;
774 
775       case STB_TEXTEDIT_K_REDO:
776          stb_text_redo(str, state);
777          state->has_preferred_x = 0;
778          break;
779 
780       case STB_TEXTEDIT_K_LEFT:
781          // if currently there's a selection, move cursor to start of selection
782          if (STB_TEXT_HAS_SELECTION(state))
783             stb_textedit_move_to_first(state);
784          else
785             if (state->cursor > 0)
786                --state->cursor;
787          state->has_preferred_x = 0;
788          break;
789 
790       case STB_TEXTEDIT_K_RIGHT:
791          // if currently there's a selection, move cursor to end of selection
792          if (STB_TEXT_HAS_SELECTION(state))
793             stb_textedit_move_to_last(str, state);
794          else
795             ++state->cursor;
796          stb_textedit_clamp(str, state);
797          state->has_preferred_x = 0;
798          break;
799 
800       case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT:
801          stb_textedit_clamp(str, state);
802          stb_textedit_prep_selection_at_cursor(state);
803          // move selection left
804          if (state->select_end > 0)
805             --state->select_end;
806          state->cursor = state->select_end;
807          state->has_preferred_x = 0;
808          break;
809 
810 #ifdef STB_TEXTEDIT_MOVEWORDLEFT
811       case STB_TEXTEDIT_K_WORDLEFT:
812          if (STB_TEXT_HAS_SELECTION(state))
813             stb_textedit_move_to_first(state);
814          else {
815             state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);
816             stb_textedit_clamp( str, state );
817          }
818          break;
819 
820       case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT:
821          if( !STB_TEXT_HAS_SELECTION( state ) )
822             stb_textedit_prep_selection_at_cursor(state);
823 
824          state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);
825          state->select_end = state->cursor;
826 
827          stb_textedit_clamp( str, state );
828          break;
829 #endif
830 
831 #ifdef STB_TEXTEDIT_MOVEWORDRIGHT
832       case STB_TEXTEDIT_K_WORDRIGHT:
833          if (STB_TEXT_HAS_SELECTION(state))
834             stb_textedit_move_to_last(str, state);
835          else {
836             state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);
837             stb_textedit_clamp( str, state );
838          }
839          break;
840 
841       case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT:
842          if( !STB_TEXT_HAS_SELECTION( state ) )
843             stb_textedit_prep_selection_at_cursor(state);
844 
845          state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);
846          state->select_end = state->cursor;
847 
848          stb_textedit_clamp( str, state );
849          break;
850 #endif
851 
852       case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT:
853          stb_textedit_prep_selection_at_cursor(state);
854          // move selection right
855          ++state->select_end;
856          stb_textedit_clamp(str, state);
857          state->cursor = state->select_end;
858          state->has_preferred_x = 0;
859          break;
860 
861       case STB_TEXTEDIT_K_DOWN:
862       case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT:
863       case STB_TEXTEDIT_K_PGDOWN:
864       case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: {
865          StbFindState find;
866          StbTexteditRow row;
867          int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
868          int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN;
869          int row_count = is_page ? state->row_count_per_page : 1;
870 
871          if (!is_page && state->single_line) {
872             // on windows, up&down in single-line behave like left&right
873             key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT);
874             goto retry;
875          }
876 
877          if (sel)
878             stb_textedit_prep_selection_at_cursor(state);
879          else if (STB_TEXT_HAS_SELECTION(state))
880             stb_textedit_move_to_last(str, state);
881 
882          // compute current position of cursor point
883          stb_textedit_clamp(str, state);
884          stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
885 
886          for (j = 0; j < row_count; ++j) {
887             float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;
888             int start = find.first_char + find.length;
889 
890             if (find.length == 0)
891                break;
892 
893             // [DEAR IMGUI]
894             // going down while being on the last line shouldn't bring us to that line end
895             if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE)
896                break;
897 
898             // now find character position down a row
899             state->cursor = start;
900             STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
901             x = row.x0;
902             for (i=0; i < row.num_chars; ++i) {
903                float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);
904                #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE
905                if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)
906                   break;
907                #endif
908                x += dx;
909                if (x > goal_x)
910                   break;
911                ++state->cursor;
912             }
913             stb_textedit_clamp(str, state);
914 
915             state->has_preferred_x = 1;
916             state->preferred_x = goal_x;
917 
918             if (sel)
919                state->select_end = state->cursor;
920 
921             // go to next line
922             find.first_char = find.first_char + find.length;
923             find.length = row.num_chars;
924          }
925          break;
926       }
927 
928       case STB_TEXTEDIT_K_UP:
929       case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT:
930       case STB_TEXTEDIT_K_PGUP:
931       case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: {
932          StbFindState find;
933          StbTexteditRow row;
934          int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;
935          int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP;
936          int row_count = is_page ? state->row_count_per_page : 1;
937 
938          if (!is_page && state->single_line) {
939             // on windows, up&down become left&right
940             key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT);
941             goto retry;
942          }
943 
944          if (sel)
945             stb_textedit_prep_selection_at_cursor(state);
946          else if (STB_TEXT_HAS_SELECTION(state))
947             stb_textedit_move_to_first(state);
948 
949          // compute current position of cursor point
950          stb_textedit_clamp(str, state);
951          stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
952 
953          for (j = 0; j < row_count; ++j) {
954             float  x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;
955 
956             // can only go up if there's a previous row
957             if (find.prev_first == find.first_char)
958                break;
959 
960             // now find character position up a row
961             state->cursor = find.prev_first;
962             STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);
963             x = row.x0;
964             for (i=0; i < row.num_chars; ++i) {
965                float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);
966                #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE
967                if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)
968                   break;
969                #endif
970                x += dx;
971                if (x > goal_x)
972                   break;
973                ++state->cursor;
974             }
975             stb_textedit_clamp(str, state);
976 
977             state->has_preferred_x = 1;
978             state->preferred_x = goal_x;
979 
980             if (sel)
981                state->select_end = state->cursor;
982 
983             // go to previous line
984             // (we need to scan previous line the hard way. maybe we could expose this as a new API function?)
985             prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0;
986             while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE)
987                --prev_scan;
988             find.first_char = find.prev_first;
989             find.prev_first = prev_scan;
990          }
991          break;
992       }
993 
994       case STB_TEXTEDIT_K_DELETE:
995       case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT:
996          if (STB_TEXT_HAS_SELECTION(state))
997             stb_textedit_delete_selection(str, state);
998          else {
999             int n = STB_TEXTEDIT_STRINGLEN(str);
1000             if (state->cursor < n)
1001                stb_textedit_delete(str, state, state->cursor, 1);
1002          }
1003          state->has_preferred_x = 0;
1004          break;
1005 
1006       case STB_TEXTEDIT_K_BACKSPACE:
1007       case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT:
1008          if (STB_TEXT_HAS_SELECTION(state))
1009             stb_textedit_delete_selection(str, state);
1010          else {
1011             stb_textedit_clamp(str, state);
1012             if (state->cursor > 0) {
1013                stb_textedit_delete(str, state, state->cursor-1, 1);
1014                --state->cursor;
1015             }
1016          }
1017          state->has_preferred_x = 0;
1018          break;
1019 
1020 #ifdef STB_TEXTEDIT_K_TEXTSTART2
1021       case STB_TEXTEDIT_K_TEXTSTART2:
1022 #endif
1023       case STB_TEXTEDIT_K_TEXTSTART:
1024          state->cursor = state->select_start = state->select_end = 0;
1025          state->has_preferred_x = 0;
1026          break;
1027 
1028 #ifdef STB_TEXTEDIT_K_TEXTEND2
1029       case STB_TEXTEDIT_K_TEXTEND2:
1030 #endif
1031       case STB_TEXTEDIT_K_TEXTEND:
1032          state->cursor = STB_TEXTEDIT_STRINGLEN(str);
1033          state->select_start = state->select_end = 0;
1034          state->has_preferred_x = 0;
1035          break;
1036 
1037 #ifdef STB_TEXTEDIT_K_TEXTSTART2
1038       case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT:
1039 #endif
1040       case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT:
1041          stb_textedit_prep_selection_at_cursor(state);
1042          state->cursor = state->select_end = 0;
1043          state->has_preferred_x = 0;
1044          break;
1045 
1046 #ifdef STB_TEXTEDIT_K_TEXTEND2
1047       case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT:
1048 #endif
1049       case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT:
1050          stb_textedit_prep_selection_at_cursor(state);
1051          state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str);
1052          state->has_preferred_x = 0;
1053          break;
1054 
1055 
1056 #ifdef STB_TEXTEDIT_K_LINESTART2
1057       case STB_TEXTEDIT_K_LINESTART2:
1058 #endif
1059       case STB_TEXTEDIT_K_LINESTART:
1060          stb_textedit_clamp(str, state);
1061          stb_textedit_move_to_first(state);
1062          if (state->single_line)
1063             state->cursor = 0;
1064          else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
1065             --state->cursor;
1066          state->has_preferred_x = 0;
1067          break;
1068 
1069 #ifdef STB_TEXTEDIT_K_LINEEND2
1070       case STB_TEXTEDIT_K_LINEEND2:
1071 #endif
1072       case STB_TEXTEDIT_K_LINEEND: {
1073          int n = STB_TEXTEDIT_STRINGLEN(str);
1074          stb_textedit_clamp(str, state);
1075          stb_textedit_move_to_first(state);
1076          if (state->single_line)
1077              state->cursor = n;
1078          else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
1079              ++state->cursor;
1080          state->has_preferred_x = 0;
1081          break;
1082       }
1083 
1084 #ifdef STB_TEXTEDIT_K_LINESTART2
1085       case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT:
1086 #endif
1087       case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT:
1088          stb_textedit_clamp(str, state);
1089          stb_textedit_prep_selection_at_cursor(state);
1090          if (state->single_line)
1091             state->cursor = 0;
1092          else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)
1093             --state->cursor;
1094          state->select_end = state->cursor;
1095          state->has_preferred_x = 0;
1096          break;
1097 
1098 #ifdef STB_TEXTEDIT_K_LINEEND2
1099       case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT:
1100 #endif
1101       case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: {
1102          int n = STB_TEXTEDIT_STRINGLEN(str);
1103          stb_textedit_clamp(str, state);
1104          stb_textedit_prep_selection_at_cursor(state);
1105          if (state->single_line)
1106              state->cursor = n;
1107          else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)
1108             ++state->cursor;
1109          state->select_end = state->cursor;
1110          state->has_preferred_x = 0;
1111          break;
1112       }
1113    }
1114 }
1115 
1116 /////////////////////////////////////////////////////////////////////////////
1117 //
1118 //      Undo processing
1119 //
1120 // @OPTIMIZE: the undo/redo buffer should be circular
1121 
stb_textedit_flush_redo(StbUndoState * state)1122 static void stb_textedit_flush_redo(StbUndoState *state)
1123 {
1124    state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;
1125    state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;
1126 }
1127 
1128 // discard the oldest entry in the undo list
stb_textedit_discard_undo(StbUndoState * state)1129 static void stb_textedit_discard_undo(StbUndoState *state)
1130 {
1131    if (state->undo_point > 0) {
1132       // if the 0th undo state has characters, clean those up
1133       if (state->undo_rec[0].char_storage >= 0) {
1134          int n = state->undo_rec[0].insert_length, i;
1135          // delete n characters from all other records
1136          state->undo_char_point -= n;
1137          STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE)));
1138          for (i=0; i < state->undo_point; ++i)
1139             if (state->undo_rec[i].char_storage >= 0)
1140                state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it
1141       }
1142       --state->undo_point;
1143       STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));
1144    }
1145 }
1146 
1147 // discard the oldest entry in the redo list--it's bad if this
1148 // ever happens, but because undo & redo have to store the actual
1149 // characters in different cases, the redo character buffer can
1150 // fill up even though the undo buffer didn't
stb_textedit_discard_redo(StbUndoState * state)1151 static void stb_textedit_discard_redo(StbUndoState *state)
1152 {
1153    int k = STB_TEXTEDIT_UNDOSTATECOUNT-1;
1154 
1155    if (state->redo_point <= k) {
1156       // if the k'th undo state has characters, clean those up
1157       if (state->undo_rec[k].char_storage >= 0) {
1158          int n = state->undo_rec[k].insert_length, i;
1159          // move the remaining redo character data to the end of the buffer
1160          state->redo_char_point += n;
1161          STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));
1162          // adjust the position of all the other records to account for above memmove
1163          for (i=state->redo_point; i < k; ++i)
1164             if (state->undo_rec[i].char_storage >= 0)
1165                state->undo_rec[i].char_storage += n;
1166       }
1167       // now move all the redo records towards the end of the buffer; the first one is at 'redo_point'
1168       // [DEAR IMGUI]
1169       size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0]));
1170       const char* buf_begin = (char*)state->undo_rec; (void)buf_begin;
1171       const char* buf_end   = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end;
1172       IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin);
1173       IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end);
1174       STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size);
1175 
1176       // now move redo_point to point to the new one
1177       ++state->redo_point;
1178    }
1179 }
1180 
stb_text_create_undo_record(StbUndoState * state,int numchars)1181 static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars)
1182 {
1183    // any time we create a new undo record, we discard redo
1184    stb_textedit_flush_redo(state);
1185 
1186    // if we have no free records, we have to make room, by sliding the
1187    // existing records down
1188    if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
1189       stb_textedit_discard_undo(state);
1190 
1191    // if the characters to store won't possibly fit in the buffer, we can't undo
1192    if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) {
1193       state->undo_point = 0;
1194       state->undo_char_point = 0;
1195       return NULL;
1196    }
1197 
1198    // if we don't have enough free characters in the buffer, we have to make room
1199    while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT)
1200       stb_textedit_discard_undo(state);
1201 
1202    return &state->undo_rec[state->undo_point++];
1203 }
1204 
stb_text_createundo(StbUndoState * state,int pos,int insert_len,int delete_len)1205 static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len)
1206 {
1207    StbUndoRecord *r = stb_text_create_undo_record(state, insert_len);
1208    if (r == NULL)
1209       return NULL;
1210 
1211    r->where = pos;
1212    r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len;
1213    r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len;
1214 
1215    if (insert_len == 0) {
1216       r->char_storage = -1;
1217       return NULL;
1218    } else {
1219       r->char_storage = state->undo_char_point;
1220       state->undo_char_point += insert_len;
1221       return &state->undo_char[r->char_storage];
1222    }
1223 }
1224 
stb_text_undo(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)1225 static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
1226 {
1227    StbUndoState *s = &state->undostate;
1228    StbUndoRecord u, *r;
1229    if (s->undo_point == 0)
1230       return;
1231 
1232    // we need to do two things: apply the undo record, and create a redo record
1233    u = s->undo_rec[s->undo_point-1];
1234    r = &s->undo_rec[s->redo_point-1];
1235    r->char_storage = -1;
1236 
1237    r->insert_length = u.delete_length;
1238    r->delete_length = u.insert_length;
1239    r->where = u.where;
1240 
1241    if (u.delete_length) {
1242       // if the undo record says to delete characters, then the redo record will
1243       // need to re-insert the characters that get deleted, so we need to store
1244       // them.
1245 
1246       // there are three cases:
1247       //    there's enough room to store the characters
1248       //    characters stored for *redoing* don't leave room for redo
1249       //    characters stored for *undoing* don't leave room for redo
1250       // if the last is true, we have to bail
1251 
1252       if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) {
1253          // the undo records take up too much character space; there's no space to store the redo characters
1254          r->insert_length = 0;
1255       } else {
1256          int i;
1257 
1258          // there's definitely room to store the characters eventually
1259          while (s->undo_char_point + u.delete_length > s->redo_char_point) {
1260             // should never happen:
1261             if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
1262                return;
1263             // there's currently not enough room, so discard a redo record
1264             stb_textedit_discard_redo(s);
1265          }
1266          r = &s->undo_rec[s->redo_point-1];
1267 
1268          r->char_storage = s->redo_char_point - u.delete_length;
1269          s->redo_char_point = s->redo_char_point - u.delete_length;
1270 
1271          // now save the characters
1272          for (i=0; i < u.delete_length; ++i)
1273             s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i);
1274       }
1275 
1276       // now we can carry out the deletion
1277       STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length);
1278    }
1279 
1280    // check type of recorded action:
1281    if (u.insert_length) {
1282       // easy case: was a deletion, so we need to insert n characters
1283       STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length);
1284       s->undo_char_point -= u.insert_length;
1285    }
1286 
1287    state->cursor = u.where + u.insert_length;
1288 
1289    s->undo_point--;
1290    s->redo_point--;
1291 }
1292 
stb_text_redo(STB_TEXTEDIT_STRING * str,STB_TexteditState * state)1293 static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
1294 {
1295    StbUndoState *s = &state->undostate;
1296    StbUndoRecord *u, r;
1297    if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
1298       return;
1299 
1300    // we need to do two things: apply the redo record, and create an undo record
1301    u = &s->undo_rec[s->undo_point];
1302    r = s->undo_rec[s->redo_point];
1303 
1304    // we KNOW there must be room for the undo record, because the redo record
1305    // was derived from an undo record
1306 
1307    u->delete_length = r.insert_length;
1308    u->insert_length = r.delete_length;
1309    u->where = r.where;
1310    u->char_storage = -1;
1311 
1312    if (r.delete_length) {
1313       // the redo record requires us to delete characters, so the undo record
1314       // needs to store the characters
1315 
1316       if (s->undo_char_point + u->insert_length > s->redo_char_point) {
1317          u->insert_length = 0;
1318          u->delete_length = 0;
1319       } else {
1320          int i;
1321          u->char_storage = s->undo_char_point;
1322          s->undo_char_point = s->undo_char_point + u->insert_length;
1323 
1324          // now save the characters
1325          for (i=0; i < u->insert_length; ++i)
1326             s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i);
1327       }
1328 
1329       STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length);
1330    }
1331 
1332    if (r.insert_length) {
1333       // easy case: need to insert n characters
1334       STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length);
1335       s->redo_char_point += r.insert_length;
1336    }
1337 
1338    state->cursor = r.where + r.insert_length;
1339 
1340    s->undo_point++;
1341    s->redo_point++;
1342 }
1343 
stb_text_makeundo_insert(STB_TexteditState * state,int where,int length)1344 static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length)
1345 {
1346    stb_text_createundo(&state->undostate, where, 0, length);
1347 }
1348 
stb_text_makeundo_delete(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,int where,int length)1349 static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length)
1350 {
1351    int i;
1352    STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0);
1353    if (p) {
1354       for (i=0; i < length; ++i)
1355          p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
1356    }
1357 }
1358 
stb_text_makeundo_replace(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,int where,int old_length,int new_length)1359 static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length)
1360 {
1361    int i;
1362    STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length);
1363    if (p) {
1364       for (i=0; i < old_length; ++i)
1365          p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
1366    }
1367 }
1368 
1369 // reset the state to default
stb_textedit_clear_state(STB_TexteditState * state,int is_single_line)1370 static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line)
1371 {
1372    state->undostate.undo_point = 0;
1373    state->undostate.undo_char_point = 0;
1374    state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;
1375    state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;
1376    state->select_end = state->select_start = 0;
1377    state->cursor = 0;
1378    state->has_preferred_x = 0;
1379    state->preferred_x = 0;
1380    state->cursor_at_end_of_line = 0;
1381    state->initialized = 1;
1382    state->single_line = (unsigned char) is_single_line;
1383    state->insert_mode = 0;
1384    state->row_count_per_page = 0;
1385 }
1386 
1387 // API initialize
stb_textedit_initialize_state(STB_TexteditState * state,int is_single_line)1388 static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)
1389 {
1390    stb_textedit_clear_state(state, is_single_line);
1391 }
1392 
1393 #if defined(__GNUC__) || defined(__clang__)
1394 #pragma GCC diagnostic push
1395 #pragma GCC diagnostic ignored "-Wcast-qual"
1396 #endif
1397 
stb_textedit_paste(STB_TEXTEDIT_STRING * str,STB_TexteditState * state,STB_TEXTEDIT_CHARTYPE const * ctext,int len)1398 static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len)
1399 {
1400    return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len);
1401 }
1402 
1403 #if defined(__GNUC__) || defined(__clang__)
1404 #pragma GCC diagnostic pop
1405 #endif
1406 
1407 #endif//STB_TEXTEDIT_IMPLEMENTATION
1408 
1409 /*
1410 ------------------------------------------------------------------------------
1411 This software is available under 2 licenses -- choose whichever you prefer.
1412 ------------------------------------------------------------------------------
1413 ALTERNATIVE A - MIT License
1414 Copyright (c) 2017 Sean Barrett
1415 Permission is hereby granted, free of charge, to any person obtaining a copy of
1416 this software and associated documentation files (the "Software"), to deal in
1417 the Software without restriction, including without limitation the rights to
1418 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
1419 of the Software, and to permit persons to whom the Software is furnished to do
1420 so, subject to the following conditions:
1421 The above copyright notice and this permission notice shall be included in all
1422 copies or substantial portions of the Software.
1423 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1424 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1425 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1426 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1427 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1428 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1429 SOFTWARE.
1430 ------------------------------------------------------------------------------
1431 ALTERNATIVE B - Public Domain (www.unlicense.org)
1432 This is free and unencumbered software released into the public domain.
1433 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
1434 software, either in source code form or as a compiled binary, for any purpose,
1435 commercial or non-commercial, and by any means.
1436 In jurisdictions that recognize copyright laws, the author or authors of this
1437 software dedicate any and all copyright interest in the software to the public
1438 domain. We make this dedication for the benefit of the public at large and to
1439 the detriment of our heirs and successors. We intend this dedication to be an
1440 overt act of relinquishment in perpetuity of all present and future rights to
1441 this software under copyright law.
1442 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1443 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1444 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1445 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1446 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
1447 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1448 ------------------------------------------------------------------------------
1449 */
1450