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