]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/move_field.c
ncurses 6.3 - patch 20220521
[ncurses.git] / test / move_field.c
1 /****************************************************************************
2  * Copyright 2020-2021,2022 Thomas E. Dickey                                *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28 /*
29  * $Id: move_field.c,v 1.13 2022/05/21 20:59:46 tom Exp $
30  *
31  * Demonstrate move_field().
32  */
33
34 #include <test.priv.h>
35
36 #if USE_LIBFORM
37
38 #include <edit_field.h>
39 #include <popup_msg.h>
40
41 #define DO_DEMO CTRL('F')       /* actual key for toggling demo-mode */
42 #define MY_DEMO EDIT_FIELD('f') /* internal request-code */
43
44 static char empty[] = "";
45 static FIELD *all_fields[100];
46 /* *INDENT-OFF* */
47 static struct {
48     int code;
49     int result;
50     const char *help;
51 } commands[] = {
52     { CTRL('A'),     REQ_BEG_FIELD,   "go to beginning of field" },
53     { CTRL('D'),     REQ_DOWN_FIELD,  "move downward to field" },
54     { CTRL('E'),     REQ_END_FIELD,   "go to end of field" },
55     { CTRL('H'),     REQ_DEL_PREV,    "delete previous character" },
56     { CTRL('I'),     REQ_NEXT_FIELD,  "go to next field" },
57     { CTRL('K'),     REQ_CLR_EOF,     "clear to end of field" },
58     { CTRL('N'),     REQ_NEXT_FIELD,  "go to next field" },
59     { CTRL('P'),     REQ_PREV_FIELD,  "go to previous field" },
60     { CTRL('Q'),     MY_QUIT,         "exit form" },
61     { CTRL('U'),     REQ_UP_FIELD,    "move upward to field" },
62     { CTRL('W'),     REQ_NEXT_WORD,   "go to next word" },
63     { CTRL('X'),     REQ_CLR_FIELD,   "clear field" },
64     { CTRL('['),     MY_QUIT,         "exit form" },
65     { KEY_F(1),      MY_HELP,         "show this screen", },
66     { KEY_BACKSPACE, REQ_DEL_PREV,    "delete previous character" },
67     { KEY_BTAB,      REQ_PREV_FIELD,  "go to previous field" },
68     { KEY_DOWN,      REQ_DOWN_CHAR,   "move down 1 character" },
69     { KEY_END,       REQ_LAST_FIELD,  "go to last field" },
70     { KEY_HOME,      REQ_FIRST_FIELD, "go to first field" },
71     { KEY_LEFT,      REQ_LEFT_CHAR,   "move left 1 character" },
72     { KEY_NEXT,      REQ_NEXT_FIELD,  "go to next field" },
73     { KEY_PREVIOUS,  REQ_PREV_FIELD,  "go to previous field" },
74     { KEY_RIGHT,     REQ_RIGHT_CHAR,  "move right 1 character" },
75     { KEY_UP,        REQ_UP_CHAR,     "move up 1 character" },
76     { DO_DEMO,       MY_DEMO,         "move current field with cursor keys" }
77 };
78 /* *INDENT-ON* */
79
80 static void
81 my_help_edit_field(void)
82 {
83     int used = 0;
84     unsigned n;
85     char **msgs = typeCalloc(char *, 3 + SIZEOF(commands));
86
87     msgs[used++] = strdup("Defined form edit/traversal keys:");
88     for (n = 0; n < SIZEOF(commands); ++n) {
89         char *msg;
90         const char *name;
91         const char *code = keyname(commands[n].code);
92         size_t need = 5;
93 #ifdef NCURSES_VERSION
94         if ((name = form_request_name(commands[n].result)) == 0)
95 #endif
96             name = commands[n].help;
97         need = 5 + strlen(code) + strlen(name);
98         msg = typeMalloc(char, need);
99         _nc_SPRINTF(msg, _nc_SLIMIT(need) "%s -- %s", code, name);
100         msgs[used++] = msg;
101     }
102     msgs[used++] =
103         strdup("Arrow keys move within a field as you would expect.");
104     msgs[used] = 0;
105     popup_msg2(stdscr, msgs);
106     for (n = 0; msgs[n] != 0; ++n) {
107         free(msgs[n]);
108     }
109     free(msgs);
110 }
111
112 static FIELD *
113 make_label(const char *label, int frow, int fcol)
114 {
115     FIELD *f = new_field(1, (int) strlen(label), frow, fcol, 0, 0);
116
117     if (f) {
118         set_field_buffer(f, 0, label);
119         set_field_opts(f, (int) ((unsigned) field_opts(f) & ~O_ACTIVE));
120     }
121     return (f);
122 }
123
124 static FIELD *
125 make_field(int frow, int fcol, int rows, int cols)
126 {
127     FIELD *f = new_field(rows, cols, frow, fcol, 0, 1);
128
129     if (f) {
130         set_field_back(f, A_UNDERLINE);
131         init_edit_field(f, empty);
132     }
133     return (f);
134 }
135
136 static void
137 erase_form(FORM *f)
138 {
139     WINDOW *w = form_win(f);
140     WINDOW *s = form_sub(f);
141
142     unpost_form(f);
143     werase(w);
144     wrefresh(w);
145     delwin(s);
146 }
147
148 static FieldAttrs *
149 my_field_attrs(FIELD *f)
150 {
151     return (FieldAttrs *) field_userptr(f);
152 }
153
154 static int
155 buffer_length(FIELD *f)
156 {
157     return my_field_attrs(f)->row_lengths[0];
158 }
159
160 static void
161 set_buffer_length(FIELD *f, int length)
162 {
163     my_field_attrs(f)->row_lengths[0] = length;
164 }
165
166 static int
167 offset_in_field(FORM *form)
168 {
169     FIELD *field = current_field(form);
170     int currow, curcol;
171
172     form_getyx(form, currow, curcol);
173     return curcol + currow * (int) field->dcols;
174 }
175
176 static void
177 inactive_field(FIELD *f)
178 {
179     set_field_back(f, my_field_attrs(f)->background);
180 }
181
182 static int
183 my_edit_field(FORM *form, int *result)
184 {
185     int ch = wgetch(form_win(form));
186     int status;
187     FIELD *before;
188     unsigned n;
189     int before_row;
190     int before_col;
191     int before_off = offset_in_field(form);
192
193     form_getyx(form, before_row, before_col);
194     before = current_field(form);
195     set_field_back(before, A_NORMAL);
196     if (ch <= KEY_MAX) {
197         set_field_back(before, A_REVERSE);
198     } else if (ch <= MAX_FORM_COMMAND) {
199         inactive_field(before);
200     }
201
202     *result = ch;
203     for (n = 0; n < SIZEOF(commands); ++n) {
204         if (commands[n].code == ch) {
205             *result = commands[n].result;
206             break;
207         }
208     }
209
210     status = form_driver(form, *result);
211
212     if (status == E_OK) {
213         bool modified = TRUE;
214         int length = buffer_length(before);
215
216         if (length < before_off)
217             length = before_off;
218         switch (*result) {
219         case REQ_CLR_EOF:
220             length = before_off;
221             break;
222         case REQ_CLR_EOL:
223             if ((int) (before_row + 1) == (int) (before->rows))
224                 length = before_off;
225             break;
226         case REQ_CLR_FIELD:
227             length = 0;
228             break;
229         case REQ_DEL_CHAR:
230             if (length > before_off)
231                 --length;
232             break;
233         case REQ_DEL_PREV:
234             if (length > 0) {
235                 if (before_col > 0) {
236                     --length;
237                 } else if (before_row > 0) {
238                     length -= (int) before->cols + before_col;
239                 }
240             }
241             break;
242         case REQ_NEW_LINE:
243             length += (int) before->cols;
244             break;
245
246         default:
247             modified = (ch < MIN_FORM_COMMAND
248                         && isprint(ch));
249             break;
250         }
251
252         /*
253          * If we do not force a re-validation, then field_buffer 0 will
254          * be lagging by one character.
255          */
256         if (modified && form_driver(form, REQ_VALIDATION) == E_OK && *result
257             < MIN_FORM_COMMAND)
258             ++length;
259
260         set_buffer_length(before, length);
261     }
262
263     if (current_field(form) != before)
264         inactive_field(before);
265     return status;
266 }
267
268 static FIELD **
269 copy_fields(FIELD **source, size_t length)
270 {
271     FIELD **target = typeCalloc(FIELD *, length + 1);
272     memcpy(target, source, length * sizeof(FIELD *));
273     return target;
274 }
275
276 /* display a status message to show what's happening */
277 static void
278 show_status(FORM *form, FIELD *field)
279 {
280     WINDOW *sub = form_sub(form);
281     int currow, curcol;
282
283     getyx(stdscr, currow, curcol);
284     mvprintw(LINES - 1, 0,
285              "Field at [%d,%d].  Press %s to quit moving.",
286              getbegy(sub) + form_field_row(field),
287              getbegx(sub) + form_field_col(field),
288              keyname(DO_DEMO));
289     clrtobot();
290     move(currow, curcol);
291     refresh();
292 }
293
294 /*
295  * Move the current label+field in response to cursor-keys (or h,j,k,l) until
296  * a control/F is read.
297  */
298 static void
299 do_demo(FORM *form)
300 {
301     int count = field_count(form);
302     FIELD *my_field = current_field(form);
303     FIELD **old_fields = form_fields(form);
304
305     if (count > 0 && old_fields != NULL && my_field != NULL) {
306         size_t needed = (size_t) count;
307         FIELD **new_fields = copy_fields(old_fields, needed);
308
309         if (new_fields != NULL) {
310             bool found = FALSE;
311             int ch;
312
313             /* TODO: move the label too, in parallel with the editing field */
314
315             /* remove the current field from the newer list */
316             for (ch = 0; ch <= count; ++ch) {
317                 if (found) {
318                     new_fields[ch - 1] = new_fields[ch];
319                 } else if (new_fields[ch] == my_field) {
320                     found = TRUE;
321                 }
322             }
323
324             if (found) {
325                 int currow, curcol;
326
327                 getyx(stdscr, currow, curcol);
328
329                 show_status(form, my_field);
330                 while ((ch = wgetch(form_win(form))) != DO_DEMO) {
331                     int field_y = form_field_row(my_field);
332                     int field_x = form_field_col(my_field);
333
334                     switch (ch) {
335                     case 'h':
336                     case KEY_LEFT:
337                         if (field_x > 0)
338                             field_x--;
339                         break;
340                     case 'j':
341                     case KEY_DOWN:
342                         field_y++;
343                         break;
344                     case 'k':
345                     case KEY_UP:
346                         if (field_y > 0)
347                             field_y--;
348                         break;
349                     case 'l':
350                     case KEY_RIGHT:
351                         field_x++;
352                         break;
353                     case CTRL('Q'):
354                     case CTRL('['):
355                         ch = DO_DEMO;
356                         /* FALLTHRU */
357                     case DO_DEMO:
358                         break;
359                     default:
360                         continue;
361                     }
362
363                     if (ch == DO_DEMO)
364                         break;
365
366                     /* alter connected fields temporarily to move the field */
367                     unpost_form(form);
368                     set_form_fields(form, new_fields);
369                     post_form(form);
370
371                     /* TODO: update screen position on success */
372                     move_field(my_field, field_y, field_x);
373
374                     /* restore the form's list of fields */
375                     unpost_form(form);
376                     set_form_fields(form, old_fields);
377                     post_form(form);
378
379                     show_status(form, my_field);
380                 }
381
382                 /* cleanup */
383                 move(LINES - 1, 0);
384                 clrtobot();
385                 move(currow, curcol);
386                 refresh();
387             }
388         }
389         free(new_fields);
390     }
391 }
392
393 static int
394 my_form_driver(FORM *form, int c)
395 {
396     switch (c) {
397     case MY_QUIT:
398         if (form_driver(form, REQ_VALIDATION) == E_OK)
399             return (TRUE);
400         break;
401     case MY_HELP:
402         my_help_edit_field();
403         break;
404     case MY_DEMO:
405         do_demo(form);
406         break;
407     default:
408         beep();
409         break;
410     }
411     return (FALSE);
412 }
413
414 static void
415 demo_forms(void)
416 {
417     FORM *form;
418     int c;
419     unsigned n = 0;
420     const char *fname;
421
422     /* describe the form */
423     all_fields[n++] = make_label("Sample Form", 0, 15);
424
425     fname = "Last Name";
426     all_fields[n++] = make_label(fname, 2, 0);
427     all_fields[n++] = make_field(3, 0, 1, 18);
428     set_field_type(all_fields[n - 1], TYPE_ALPHA, 1);
429
430     fname = "First Name";
431     all_fields[n++] = make_label(fname, 2, 20);
432     all_fields[n++] = make_field(3, 20, 1, 12);
433     set_field_type(all_fields[n - 1], TYPE_ALPHA, 1);
434
435     fname = "Middle Name";
436     all_fields[n++] = make_label(fname, 2, 34);
437     all_fields[n++] = make_field(3, 34, 1, 12);
438     set_field_type(all_fields[n - 1], TYPE_ALPHA, 1);
439
440     fname = "Comments";
441     all_fields[n++] = make_label(fname, 5, 0);
442     all_fields[n++] = make_field(6, 0, 4, 46);
443     init_edit_field(all_fields[n - 1], empty);
444
445     all_fields[n] = (FIELD *) 0;
446
447     if ((form = new_form(all_fields)) != 0) {
448         int finished = 0;
449
450         post_form(form);
451
452         while (!finished) {
453             switch (my_edit_field(form, &c)) {
454             case E_OK:
455                 break;
456             case E_UNKNOWN_COMMAND:
457                 finished = my_form_driver(form, c);
458                 break;
459             default:
460                 beep();
461                 break;
462             }
463         }
464
465         erase_form(form);
466
467         free_form(form);
468     }
469     for (c = 0; all_fields[c] != 0; c++) {
470         free_edit_field(all_fields[c]);
471         free_field(all_fields[c]);
472     }
473     noraw();
474     nl();
475 }
476
477 int
478 main(void)
479 {
480     setlocale(LC_ALL, "");
481
482     initscr();
483     cbreak();
484     noecho();
485     raw();
486     nonl();                     /* lets us read ^M's */
487     intrflush(stdscr, FALSE);
488     keypad(stdscr, TRUE);
489
490     if (has_colors()) {
491         start_color();
492         init_pair(1, COLOR_WHITE, COLOR_BLUE);
493         init_pair(2, COLOR_GREEN, COLOR_BLACK);
494         init_pair(3, COLOR_CYAN, COLOR_BLACK);
495         bkgd((chtype) COLOR_PAIR(1));
496         refresh();
497     }
498
499     demo_forms();
500
501     endwin();
502     ExitProgram(EXIT_SUCCESS);
503 }
504
505 #else
506 int
507 main(void)
508 {
509     printf("This program requires the curses form library\n");
510     ExitProgram(EXIT_FAILURE);
511 }
512 #endif