]> ncurses.scripts.mit.edu Git - ncurses.git/blob - form/frm_driver.c
ncurses 6.1 - patch 20181117
[ncurses.git] / form / frm_driver.c
1 /****************************************************************************
2  * Copyright (c) 1998-2017,2018 Free Software Foundation, Inc.              *
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 /****************************************************************************
30  *   Author:  Juergen Pfeifer, 1995,1997                                    *
31  ****************************************************************************/
32
33 #include "form.priv.h"
34
35 MODULE_ID("$Id: frm_driver.c,v 1.127 2018/09/08 19:03:39 tom Exp $")
36
37 /*----------------------------------------------------------------------------
38   This is the core module of the form library. It contains the majority
39   of the driver routines as well as the form_driver function.
40
41   Essentially this module is nearly the whole library. This is because
42   all the functions in this module depends on some others in the module,
43   so it makes no sense to split them into separate files because they
44   will always be linked together. The only acceptable concern is turnaround
45   time for this module, but now we have all Pentiums or RISCs, so what!
46
47   The driver routines are grouped into nine generic categories:
48
49    a)   Page Navigation            ( all functions prefixed by PN_ )
50         The current page of the form is left and some new page is
51         entered.
52    b)   Inter-Field Navigation     ( all functions prefixed by FN_ )
53         The current field of the form is left and some new field is
54         entered.
55    c)   Intra-Field Navigation     ( all functions prefixed by IFN_ )
56         The current position in the current field is changed.
57    d)   Vertical Scrolling         ( all functions prefixed by VSC_ )
58         Essentially this is a specialization of Intra-Field navigation.
59         It has to check for a multi-line field.
60    e)   Horizontal Scrolling       ( all functions prefixed by HSC_ )
61         Essentially this is a specialization of Intra-Field navigation.
62         It has to check for a single-line field.
63    f)   Field Editing              ( all functions prefixed by FE_ )
64         The content of the current field is changed
65    g)   Edit Mode requests         ( all functions prefixed by EM_ )
66         Switching between insert and overlay mode
67    h)   Field-Validation requests  ( all functions prefixed by FV_ )
68         Perform verifications of the field.
69    i)   Choice requests            ( all functions prefixed by CR_ )
70         Requests to enumerate possible field values
71   --------------------------------------------------------------------------*/
72
73 /*----------------------------------------------------------------------------
74   Some remarks on the placements of assert() macros :
75   I use them only on "strategic" places, i.e. top level entries where
76   I want to make sure that things are set correctly. Throughout subordinate
77   routines I omit them mostly.
78   --------------------------------------------------------------------------*/
79
80 /*
81 Some options that may effect compatibility in behavior to SVr4 forms,
82 but they are here to allow a more intuitive and user friendly behavior of
83 our form implementation. This doesn't affect the API, so we feel it is
84 uncritical.
85
86 The initial implementation tries to stay very close with the behavior
87 of the original SVr4 implementation, although in some areas it is quite
88 clear that this isn't the most appropriate way. As far as possible this
89 sources will allow you to build a forms lib that behaves quite similar
90 to SVr4, but now and in the future we will give you better options.
91 Perhaps at some time we will make this configurable at runtime.
92 */
93
94 /* Implement a more user-friendly previous/next word behavior */
95 #define FRIENDLY_PREV_NEXT_WORD (1)
96 /* Fix the wrong behavior for forms with all fields inactive */
97 #define FIX_FORM_INACTIVE_BUG (1)
98 /* Allow dynamic field growth also when navigating past the end */
99 #define GROW_IF_NAVIGATE (1)
100
101 #if USE_WIDEC_SUPPORT
102 #define myADDNSTR(w, s, n) wide_waddnstr(w, s, n)
103 #define myINSNSTR(w, s, n) wide_winsnstr(w, s, n)
104 #define myINNSTR(w, s, n)  wide_winnstr(w, s, n)
105 #define myWCWIDTH(w, y, x) cell_width(w, y, x)
106 #else
107 #define myADDNSTR(w, s, n) waddnstr(w, s, n)
108 #define myINSNSTR(w, s, n) winsnstr(w, s, n)
109 #define myINNSTR(w, s, n)  winnstr(w, s, n)
110 #define myWCWIDTH(w, y, x) 1
111 #endif
112
113 /*----------------------------------------------------------------------------
114   Forward references to some internally used static functions
115   --------------------------------------------------------------------------*/
116 static int Inter_Field_Navigation(int (*const fct) (FORM *), FORM *form);
117 static int FN_Next_Field(FORM *form);
118 static int FN_Previous_Field(FORM *form);
119 static int FE_New_Line(FORM *);
120 static int FE_Delete_Previous(FORM *);
121
122 /*----------------------------------------------------------------------------
123   Macro Definitions.
124
125   Some Remarks on that: I use the convention to use UPPERCASE for constants
126   defined by Macros. If I provide a macro as a kind of inline routine to
127   provide some logic, I use my Upper_Lower case style.
128   --------------------------------------------------------------------------*/
129
130 /* Calculate the position of a single row in a field buffer */
131 #define Position_Of_Row_In_Buffer(field,row) ((row)*(field)->dcols)
132
133 /* Calculate start address for the fields buffer# N */
134 #define Address_Of_Nth_Buffer(field,N) \
135   ((field)->buf + (N)*(1+Buffer_Length(field)))
136
137 /* Calculate the start address of the row in the fields specified buffer# N */
138 #define Address_Of_Row_In_Nth_Buffer(field,N,row) \
139   (Address_Of_Nth_Buffer(field,N) + Position_Of_Row_In_Buffer(field,row))
140
141 /* Calculate the start address of the row in the fields primary buffer */
142 #define Address_Of_Row_In_Buffer(field,row) \
143   Address_Of_Row_In_Nth_Buffer(field,0,row)
144
145 /* Calculate the start address of the row in the forms current field
146    buffer# N */
147 #define Address_Of_Current_Row_In_Nth_Buffer(form,N) \
148    Address_Of_Row_In_Nth_Buffer((form)->current,N,(form)->currow)
149
150 /* Calculate the start address of the row in the forms current field
151    primary buffer */
152 #define Address_Of_Current_Row_In_Buffer(form) \
153    Address_Of_Current_Row_In_Nth_Buffer(form,0)
154
155 /* Calculate the address of the cursor in the forms current field
156    primary buffer */
157 #define Address_Of_Current_Position_In_Nth_Buffer(form,N) \
158    (Address_Of_Current_Row_In_Nth_Buffer(form,N) + (form)->curcol)
159
160 /* Calculate the address of the cursor in the forms current field
161    buffer# N */
162 #define Address_Of_Current_Position_In_Buffer(form) \
163   Address_Of_Current_Position_In_Nth_Buffer(form,0)
164
165 /* Logic to decide whether or not a field is actually a field with
166    vertical or horizontal scrolling */
167 #define Is_Scroll_Field(field)          \
168    (((field)->drows > (field)->rows) || \
169     ((field)->dcols > (field)->cols))
170
171 /* Logic to decide whether or not a field needs to have an individual window
172    instead of a derived window because it contains invisible parts.
173    This is true for non-public fields and for scrollable fields. */
174 #define Has_Invisible_Parts(field)     \
175   (!(Field_Has_Option(field, O_PUBLIC)) || \
176    Is_Scroll_Field(field))
177
178 /* Logic to decide whether or not a field needs justification */
179 #define Justification_Allowed(field)        \
180    (((field)->just != NO_JUSTIFICATION)  && \
181     (Single_Line_Field(field))           && \
182     ((Field_Has_Option(field, O_STATIC)  && \
183      ((field)->dcols == (field)->cols))  || \
184     Field_Has_Option(field, O_DYNAMIC_JUSTIFY)))
185
186 /* Logic to determine whether or not a dynamic field may still grow */
187 #define Growable(field) ((field)->status & _MAY_GROW)
188
189 /* Macro to set the attributes for a fields window */
190 #define Set_Field_Window_Attributes(field,win) \
191 (  wbkgdset((win),(chtype)((chtype)((field)->pad) | (field)->back)), \
192    (void) wattrset((win), (int)(field)->fore) )
193
194 /* Logic to decide whether or not a field really appears on the form */
195 #define Field_Really_Appears(field)         \
196   ((field->form)                          &&\
197    (field->form->status & _POSTED)        &&\
198    (Field_Has_Option(field, O_VISIBLE))   &&\
199    (field->page == field->form->curpage))
200
201 /* Logic to determine whether or not we are on the first position in the
202    current field */
203 #define First_Position_In_Current_Field(form) \
204   (((form)->currow==0) && ((form)->curcol==0))
205
206 #define Minimum(a,b) (((a)<=(b)) ? (a) : (b))
207 #define Maximum(a,b) (((a)>=(b)) ? (a) : (b))
208
209 /*----------------------------------------------------------------------------
210   Useful constants
211   --------------------------------------------------------------------------*/
212 static FIELD_CELL myBLANK = BLANK;
213 static FIELD_CELL myZEROS;
214
215 #ifdef TRACE
216 static void
217 check_pos(FORM *form, int lineno)
218 {
219   int y, x;
220
221   if (form && form->w)
222     {
223       getyx(form->w, y, x);
224       if (y != form->currow || x != form->curcol)
225         {
226           T(("CHECKPOS %s@%d have position %d,%d vs want %d,%d",
227              __FILE__, lineno,
228              y, x,
229              form->currow, form->curcol));
230         }
231     }
232 }
233 #define CHECKPOS(form) check_pos(form, __LINE__)
234 #else
235 #define CHECKPOS(form)          /* nothing */
236 #endif
237
238 /*----------------------------------------------------------------------------
239   Wide-character special functions
240   --------------------------------------------------------------------------*/
241 #if USE_WIDEC_SUPPORT
242 /* add like waddnstr, but using cchar_t* rather than char*
243  */
244 static int
245 wide_waddnstr(WINDOW *w, const cchar_t *s, int n)
246 {
247   int rc = OK;
248
249   while (n-- > 0)
250     {
251       if ((rc = wadd_wch(w, s)) != OK)
252         break;
253       ++s;
254     }
255   return rc;
256 }
257
258 /* insert like winsnstr, but using cchar_t* rather than char*
259  *
260  * X/Open Curses has no close equivalent; inserts are done only with wchar_t
261  * strings.
262  */
263 static int
264 wide_winsnstr(WINDOW *w, const cchar_t *s, int n)
265 {
266   int code = ERR;
267   int y, x;
268
269   while (n-- > 0)
270     {
271       getyx(w, y, x);
272       if ((code = wins_wch(w, s++)) != OK)
273         break;
274       if ((code = wmove(w, y, x + 1)) != OK)
275         break;
276     }
277   return code;
278 }
279
280 /* retrieve like winnstr, but using cchar_t*, rather than char*.
281  *
282  * X/Open Curses' closest equivalent, win_wchnstr(), is inconsistent with
283  * winnstr(), since it returns OK rather than the number of items transferred.
284  */
285 static int
286 wide_winnstr(WINDOW *w, cchar_t *s, int n)
287 {
288   int x;
289
290   win_wchnstr(w, s, n);
291   /*
292    * This function is used to extract the text only from the window.
293    * Strip attributes and color from the string so they will not be added
294    * back when copying the string to the window.
295    */
296   for (x = 0; x < n; ++x)
297     {
298       RemAttr(s[x], A_ATTRIBUTES);
299       SetPair(s[x], 0);
300     }
301   return n;
302 }
303
304 /*
305  * Returns the column of the base of the given cell.
306  */
307 static int
308 cell_base(WINDOW *win, int y, int x)
309 {
310   int result = x;
311
312   while (LEGALYX(win, y, x))
313     {
314       cchar_t *data = &(win->_line[y].text[x]);
315
316       if (isWidecBase(CHDEREF(data)) || !isWidecExt(CHDEREF(data)))
317         {
318           result = x;
319           break;
320         }
321       --x;
322     }
323   return result;
324 }
325
326 /*
327  * Returns the number of columns needed for the given cell in a window.
328  */
329 static int
330 cell_width(WINDOW *win, int y, int x)
331 {
332   int result = 1;
333
334   if (LEGALYX(win, y, x))
335     {
336       cchar_t *data = &(win->_line[y].text[x]);
337
338       if (isWidecExt(CHDEREF(data)))
339         {
340           /* recur, providing the number of columns to the next character */
341           result = cell_width(win, y, x - 1);
342         }
343       else
344         {
345           result = wcwidth(CharOf(CHDEREF(data)));
346         }
347     }
348   return result;
349 }
350
351 /*
352  * There is no wide-character function such as wdel_wch(), so we must find
353  * all of the cells that comprise a multi-column character and delete them
354  * one-by-one.
355  */
356 static void
357 delete_char(FORM *form)
358 {
359   int cells = cell_width(form->w, form->currow, form->curcol);
360
361   form->curcol = cell_base(form->w, form->currow, form->curcol);
362   wmove(form->w, form->currow, form->curcol);
363   while (cells-- > 0)
364     {
365       wdelch(form->w);
366     }
367 }
368 #define DeleteChar(form) delete_char(form)
369 #else
370 #define DeleteChar(form) \
371           wmove((form)->w, (form)->currow, (form)->curcol), \
372           wdelch((form)->w)
373 #endif
374
375 /*---------------------------------------------------------------------------
376 |   Facility      :  libnform
377 |   Function      :  static char *Get_Start_Of_Data(char * buf, int blen)
378 |
379 |   Description   :  Return pointer to first non-blank position in buffer.
380 |                    If buffer is empty return pointer to buffer itself.
381 |
382 |   Return Values :  Pointer to first non-blank position in buffer
383 +--------------------------------------------------------------------------*/
384 NCURSES_INLINE static FIELD_CELL *
385 Get_Start_Of_Data(FIELD_CELL *buf, int blen)
386 {
387   FIELD_CELL *p = buf;
388   FIELD_CELL *end = &buf[blen];
389
390   assert(buf && blen >= 0);
391   while ((p < end) && ISBLANK(*p))
392     p++;
393   return ((p == end) ? buf : p);
394 }
395
396 /*---------------------------------------------------------------------------
397 |   Facility      :  libnform
398 |   Function      :  static char *After_End_Of_Data(char * buf, int blen)
399 |
400 |   Description   :  Return pointer after last non-blank position in buffer.
401 |                    If buffer is empty, return pointer to buffer itself.
402 |
403 |   Return Values :  Pointer to position after last non-blank position in
404 |                    buffer.
405 +--------------------------------------------------------------------------*/
406 NCURSES_INLINE static FIELD_CELL *
407 After_End_Of_Data(FIELD_CELL *buf, int blen)
408 {
409   FIELD_CELL *p = &buf[blen];
410
411   assert(buf && blen >= 0);
412   while ((p > buf) && ISBLANK(p[-1]))
413     p--;
414   return (p);
415 }
416
417 /*---------------------------------------------------------------------------
418 |   Facility      :  libnform
419 |   Function      :  static char *Get_First_Whitespace_Character(
420 |                                     char * buf, int   blen)
421 |
422 |   Description   :  Position to the first whitespace character.
423 |
424 |   Return Values :  Pointer to first whitespace character in buffer.
425 +--------------------------------------------------------------------------*/
426 NCURSES_INLINE static FIELD_CELL *
427 Get_First_Whitespace_Character(FIELD_CELL *buf, int blen)
428 {
429   FIELD_CELL *p = buf;
430   FIELD_CELL *end = &p[blen];
431
432   assert(buf && blen >= 0);
433   while ((p < end) && !ISBLANK(*p))
434     p++;
435   return ((p == end) ? buf : p);
436 }
437
438 /*---------------------------------------------------------------------------
439 |   Facility      :  libnform
440 |   Function      :  static char *After_Last_Whitespace_Character(
441 |                                     char * buf, int blen)
442 |
443 |   Description   :  Get the position after the last whitespace character.
444 |
445 |   Return Values :  Pointer to position after last whitespace character in
446 |                    buffer.
447 +--------------------------------------------------------------------------*/
448 NCURSES_INLINE static FIELD_CELL *
449 After_Last_Whitespace_Character(FIELD_CELL *buf, int blen)
450 {
451   FIELD_CELL *p = &buf[blen];
452
453   assert(buf && blen >= 0);
454   while ((p > buf) && !ISBLANK(p[-1]))
455     p--;
456   return (p);
457 }
458
459 /* Set this to 1 to use the div_t version. This is a good idea if your
460    compiler has an intrinsic div() support. Unfortunately GNU-C has it
461    not yet.
462    N.B.: This only works if form->curcol follows immediately form->currow
463          and both are of type int.
464 */
465 #define USE_DIV_T (0)
466
467 /*---------------------------------------------------------------------------
468 |   Facility      :  libnform
469 |   Function      :  static void Adjust_Cursor_Position(
470 |                                       FORM * form, const char * pos)
471 |
472 |   Description   :  Set current row and column of the form to values
473 |                    corresponding to the buffer position.
474 |
475 |   Return Values :  -
476 +--------------------------------------------------------------------------*/
477 NCURSES_INLINE static void
478 Adjust_Cursor_Position(FORM *form, const FIELD_CELL *pos)
479 {
480   FIELD *field;
481   int idx;
482
483   field = form->current;
484   assert(pos >= field->buf && field->dcols > 0);
485   idx = (int)(pos - field->buf);
486 #if USE_DIV_T
487   *((div_t *) & (form->currow)) = div(idx, field->dcols);
488 #else
489   form->currow = idx / field->dcols;
490   form->curcol = idx - field->cols * form->currow;
491 #endif
492   if (field->drows < form->currow)
493     form->currow = 0;
494 }
495
496 /*---------------------------------------------------------------------------
497 |   Facility      :  libnform
498 |   Function      :  static void Buffer_To_Window(
499 |                                      const FIELD  * field,
500 |                                      WINDOW * win)
501 |
502 |   Description   :  Copy the buffer to the window. If it is a multi-line
503 |                    field, the buffer is split to the lines of the
504 |                    window without any editing.
505 |
506 |   Return Values :  -
507 +--------------------------------------------------------------------------*/
508 static void
509 Buffer_To_Window(const FIELD *field, WINDOW *win)
510 {
511   int width, height;
512   int y, x;
513   int len;
514   int row;
515   FIELD_CELL *pBuffer;
516
517   assert(win && field);
518
519   getyx(win, y, x);
520   width = getmaxx(win);
521   height = getmaxy(win);
522
523   for (row = 0, pBuffer = field->buf;
524        row < height;
525        row++, pBuffer += width)
526     {
527       if ((len = (int)(After_End_Of_Data(pBuffer, width) - pBuffer)) > 0)
528         {
529           wmove(win, row, 0);
530           myADDNSTR(win, pBuffer, len);
531         }
532     }
533   wmove(win, y, x);
534 }
535
536 /*---------------------------------------------------------------------------
537 |   Facility      :  libnform
538 |   Function      :  void _nc_get_fieldbuffer(
539 |                                          WINDOW * win,
540 |                                          FIELD  * field,
541 |                                          FIELD_CELL * buf)
542 |
543 |   Description   :  Copy the content of the window into the buffer.
544 |                    The multiple lines of a window are simply
545 |                    concatenated into the buffer. Pad characters in
546 |                    the window will be replaced by blanks in the buffer.
547 |
548 |   Return Values :  -
549 +--------------------------------------------------------------------------*/
550 NCURSES_EXPORT(void)
551 _nc_get_fieldbuffer(FORM *form, FIELD *field, FIELD_CELL *buf)
552 {
553   int pad;
554   int len = 0;
555   FIELD_CELL *p;
556   int row, height;
557   WINDOW *win;
558
559   assert(form && field && buf);
560
561   win = form->w;
562   assert(win);
563
564   pad = field->pad;
565   p = buf;
566   height = getmaxy(win);
567
568   for (row = 0; (row < height) && (row < field->drows); row++)
569     {
570       wmove(win, row, 0);
571       len += myINNSTR(win, p + len, field->dcols);
572     }
573   p[len] = myZEROS;
574
575   /* replace visual padding character by blanks in buffer */
576   if (pad != C_BLANK)
577     {
578       int i;
579
580       for (i = 0; i < len; i++, p++)
581         {
582           if ((unsigned long)CharOf(*p) == ChCharOf(pad)
583 #if USE_WIDEC_SUPPORT
584               && p->chars[1] == 0
585 #endif
586             )
587             *p = myBLANK;
588         }
589     }
590 }
591
592 /*---------------------------------------------------------------------------
593 |   Facility      :  libnform
594 |   Function      :  static void Window_To_Buffer(
595 |                                          FORM   * form,
596 |                                          FIELD  * field)
597 |
598 |   Description   :  Copy the content of the window into the buffer.
599 |                    The multiple lines of a window are simply
600 |                    concatenated into the buffer. Pad characters in
601 |                    the window will be replaced by blanks in the buffer.
602 |
603 |   Return Values :  -
604 +--------------------------------------------------------------------------*/
605 static void
606 Window_To_Buffer(FORM *form, FIELD *field)
607 {
608   _nc_get_fieldbuffer(form, field, field->buf);
609 }
610
611 /*---------------------------------------------------------------------------
612 |   Facility      :  libnform
613 |   Function      :  static void Synchronize_Buffer(FORM * form)
614 |
615 |   Description   :  If there was a change, copy the content of the
616 |                    window into the buffer, so the buffer is synchronized
617 |                    with the windows content. We have to indicate that the
618 |                    buffer needs validation due to the change.
619 |
620 |   Return Values :  -
621 +--------------------------------------------------------------------------*/
622 NCURSES_INLINE static void
623 Synchronize_Buffer(FORM *form)
624 {
625   if (form->status & _WINDOW_MODIFIED)
626     {
627       ClrStatus(form, _WINDOW_MODIFIED);
628       SetStatus(form, _FCHECK_REQUIRED);
629       Window_To_Buffer(form, form->current);
630       wmove(form->w, form->currow, form->curcol);
631     }
632 }
633
634 /*---------------------------------------------------------------------------
635 |   Facility      :  libnform
636 |   Function      :  static bool Field_Grown( FIELD *field, int amount)
637 |
638 |   Description   :  This function is called for growable dynamic fields
639 |                    only. It has to increase the buffers and to allocate
640 |                    a new window for this field.
641 |                    This function has the side effect to set a new
642 |                    field-buffer pointer, the dcols and drows values
643 |                    as well as a new current Window for the field.
644 |
645 |   Return Values :  TRUE     - field successfully increased
646 |                    FALSE    - there was some error
647 +--------------------------------------------------------------------------*/
648 static bool
649 Field_Grown(FIELD *field, int amount)
650 {
651   bool result = FALSE;
652
653   if (field && Growable(field))
654     {
655       bool single_line_field = Single_Line_Field(field);
656       int old_buflen = Buffer_Length(field);
657       int new_buflen;
658       int old_dcols = field->dcols;
659       int old_drows = field->drows;
660       FIELD_CELL *oldbuf = field->buf;
661       FIELD_CELL *newbuf;
662
663       int growth;
664       FORM *form = field->form;
665       bool need_visual_update = ((form != (FORM *)0) &&
666                                  (form->status & _POSTED) &&
667                                  (form->current == field));
668
669       if (need_visual_update)
670         Synchronize_Buffer(form);
671
672       if (single_line_field)
673         {
674           growth = field->cols * amount;
675           if (field->maxgrow)
676             growth = Minimum(field->maxgrow - field->dcols, growth);
677           field->dcols += growth;
678           if (field->dcols == field->maxgrow)
679             ClrStatus(field, _MAY_GROW);
680         }
681       else
682         {
683           growth = (field->rows + field->nrow) * amount;
684           if (field->maxgrow)
685             growth = Minimum(field->maxgrow - field->drows, growth);
686           field->drows += growth;
687           if (field->drows == field->maxgrow)
688             ClrStatus(field, _MAY_GROW);
689         }
690       /* drows, dcols changed, so we get really the new buffer length */
691       new_buflen = Buffer_Length(field);
692       newbuf = (FIELD_CELL *)malloc(Total_Buffer_Size(field));
693       if (!newbuf)
694         {
695           /* restore to previous state */
696           field->dcols = old_dcols;
697           field->drows = old_drows;
698           if ((single_line_field && (field->dcols != field->maxgrow)) ||
699               (!single_line_field && (field->drows != field->maxgrow)))
700             SetStatus(field, _MAY_GROW);
701         }
702       else
703         {
704           /* Copy all the buffers.  This is the reason why we can't just use
705            * realloc().
706            */
707           int i, j;
708           FIELD_CELL *old_bp;
709           FIELD_CELL *new_bp;
710
711           result = TRUE;        /* allow sharing of recovery on failure */
712
713           T((T_CREATE("fieldcell %p"), (void *)newbuf));
714           field->buf = newbuf;
715           for (i = 0; i <= field->nbuf; i++)
716             {
717               new_bp = Address_Of_Nth_Buffer(field, i);
718               old_bp = oldbuf + i * (1 + old_buflen);
719               for (j = 0; j < old_buflen; ++j)
720                 new_bp[j] = old_bp[j];
721               while (j < new_buflen)
722                 new_bp[j++] = myBLANK;
723               new_bp[new_buflen] = myZEROS;
724             }
725
726 #if USE_WIDEC_SUPPORT && NCURSES_EXT_FUNCS
727           if (wresize(field->working, 1, Buffer_Length(field) + 1) == ERR)
728             result = FALSE;
729 #endif
730
731           if (need_visual_update && result)
732             {
733               WINDOW *new_window = newpad(field->drows, field->dcols);
734
735               if (new_window != 0)
736                 {
737                   assert(form != (FORM *)0);
738                   if (form->w)
739                     delwin(form->w);
740                   form->w = new_window;
741                   Set_Field_Window_Attributes(field, form->w);
742                   werase(form->w);
743                   Buffer_To_Window(field, form->w);
744                   untouchwin(form->w);
745                   wmove(form->w, form->currow, form->curcol);
746                 }
747               else
748                 result = FALSE;
749             }
750
751           if (result)
752             {
753               free(oldbuf);
754               /* reflect changes in linked fields */
755               if (field != field->link)
756                 {
757                   FIELD *linked_field;
758
759                   for (linked_field = field->link;
760                        linked_field != field;
761                        linked_field = linked_field->link)
762                     {
763                       linked_field->buf = field->buf;
764                       linked_field->drows = field->drows;
765                       linked_field->dcols = field->dcols;
766                     }
767                 }
768             }
769           else
770             {
771               /* restore old state */
772               field->dcols = old_dcols;
773               field->drows = old_drows;
774               field->buf = oldbuf;
775               if ((single_line_field &&
776                    (field->dcols != field->maxgrow)) ||
777                   (!single_line_field &&
778                    (field->drows != field->maxgrow)))
779                 SetStatus(field, _MAY_GROW);
780               free(newbuf);
781             }
782         }
783     }
784   return (result);
785 }
786
787 #ifdef NCURSES_MOUSE_VERSION
788 /*---------------------------------------------------------------------------
789 |   Facility      :  libnform
790 |   Function      :  int Field_encloses(FIELD *field, int ry, int rx)
791 |
792 |   Description   :  Check if the given coordinates lie within the given field.
793 |
794 |   Return Values :  E_OK              - success
795 |                    E_BAD_ARGUMENT    - invalid form pointer
796 |                    E_SYSTEM_ERROR    - form has no current field or
797 |                                        field-window
798 +--------------------------------------------------------------------------*/
799 static int
800 Field_encloses(FIELD *field, int ry, int rx)
801 {
802   T((T_CALLED("Field_encloses(%p)"), (void *)field));
803   if (field != 0
804       && field->frow <= ry
805       && (field->frow + field->rows) > ry
806       && field->fcol <= rx
807       && (field->fcol + field->cols) > rx)
808     {
809       RETURN(E_OK);
810     }
811   RETURN(E_INVALID_FIELD);
812 }
813 #endif
814
815 /*---------------------------------------------------------------------------
816 |   Facility      :  libnform
817 |   Function      :  int _nc_Position_Form_Cursor(FORM * form)
818 |
819 |   Description   :  Position the cursor in the window for the current
820 |                    field to be in sync. with the currow and curcol
821 |                    values.
822 |
823 |   Return Values :  E_OK              - success
824 |                    E_BAD_ARGUMENT    - invalid form pointer
825 |                    E_SYSTEM_ERROR    - form has no current field or
826 |                                        field-window
827 +--------------------------------------------------------------------------*/
828 NCURSES_EXPORT(int)
829 _nc_Position_Form_Cursor(FORM *form)
830 {
831   FIELD *field;
832   WINDOW *formwin;
833
834   if (!form)
835     return (E_BAD_ARGUMENT);
836
837   if (!form->w || !form->current)
838     return (E_SYSTEM_ERROR);
839
840   field = form->current;
841   formwin = Get_Form_Window(form);
842
843   wmove(form->w, form->currow, form->curcol);
844   if (Has_Invisible_Parts(field))
845     {
846       /* in this case fieldwin isn't derived from formwin, so we have
847          to move the cursor in formwin by hand... */
848       wmove(formwin,
849             field->frow + form->currow - form->toprow,
850             field->fcol + form->curcol - form->begincol);
851       wcursyncup(formwin);
852     }
853   else
854     wcursyncup(form->w);
855   return (E_OK);
856 }
857
858 /*---------------------------------------------------------------------------
859 |   Facility      :  libnform
860 |   Function      :  int _nc_Refresh_Current_Field(FORM * form)
861 |
862 |   Description   :  Propagate the changes in the fields window to the
863 |                    window of the form.
864 |
865 |   Return Values :  E_OK              - on success
866 |                    E_BAD_ARGUMENT    - invalid form pointer
867 |                    E_SYSTEM_ERROR    - general error
868 +--------------------------------------------------------------------------*/
869 static bool move_after_insert = true;
870 NCURSES_EXPORT(int)
871 _nc_Refresh_Current_Field(FORM *form)
872 {
873   WINDOW *formwin;
874   FIELD *field;
875   bool is_public;
876
877   T((T_CALLED("_nc_Refresh_Current_Field(%p)"), (void *)form));
878
879   if (!form)
880     RETURN(E_BAD_ARGUMENT);
881
882   if (!form->w || !form->current)
883     RETURN(E_SYSTEM_ERROR);
884
885   field = form->current;
886   formwin = Get_Form_Window(form);
887
888   is_public = Field_Has_Option(field, O_PUBLIC);
889
890   if (Is_Scroll_Field(field))
891     {
892       /* Again, in this case the fieldwin isn't derived from formwin,
893          so we have to perform a copy operation. */
894       if (Single_Line_Field(field))
895         {
896           /* horizontal scrolling */
897           if (form->curcol < form->begincol)
898             form->begincol = form->curcol;
899           else
900             {
901               if (form->curcol >= (form->begincol + field->cols))
902                 form->begincol = form->curcol - field->cols
903                   + (move_after_insert ? 1 : 0);
904             }
905           if (is_public)
906             copywin(form->w,
907                     formwin,
908                     0,
909                     form->begincol,
910                     field->frow,
911                     field->fcol,
912                     field->frow,
913                     field->cols + field->fcol - 1,
914                     0);
915         }
916       else
917         {
918           /* A multi-line, i.e. vertical scrolling field */
919           int row_after_bottom, first_modified_row, first_unmodified_row;
920
921           if (field->drows > field->rows)
922             {
923               row_after_bottom = form->toprow + field->rows;
924               if (form->currow < form->toprow)
925                 {
926                   form->toprow = form->currow;
927                   SetStatus(field, _NEWTOP);
928                 }
929               if (form->currow >= row_after_bottom)
930                 {
931                   form->toprow = form->currow - field->rows + 1;
932                   SetStatus(field, _NEWTOP);
933                 }
934               if (field->status & _NEWTOP)
935                 {
936                   /* means we have to copy whole range */
937                   first_modified_row = form->toprow;
938                   first_unmodified_row = first_modified_row + field->rows;
939                   ClrStatus(field, _NEWTOP);
940                 }
941               else
942                 {
943                   /* we try to optimize : finding the range of touched
944                      lines */
945                   first_modified_row = form->toprow;
946                   while (first_modified_row < row_after_bottom)
947                     {
948                       if (is_linetouched(form->w, first_modified_row))
949                         break;
950                       first_modified_row++;
951                     }
952                   first_unmodified_row = first_modified_row;
953                   while (first_unmodified_row < row_after_bottom)
954                     {
955                       if (!is_linetouched(form->w, first_unmodified_row))
956                         break;
957                       first_unmodified_row++;
958                     }
959                 }
960             }
961           else
962             {
963               first_modified_row = form->toprow;
964               first_unmodified_row = first_modified_row + field->rows;
965             }
966           if (first_unmodified_row != first_modified_row && is_public)
967             copywin(form->w,
968                     formwin,
969                     first_modified_row,
970                     0,
971                     field->frow + first_modified_row - form->toprow,
972                     field->fcol,
973                     field->frow + first_unmodified_row - form->toprow - 1,
974                     field->cols + field->fcol - 1,
975                     0);
976         }
977       if (is_public)
978         wsyncup(formwin);
979     }
980   else
981     {
982       /* if the field-window is simply a derived window, i.e. contains no
983        * invisible parts, the whole thing is trivial
984        */
985       if (is_public)
986         wsyncup(form->w);
987     }
988   untouchwin(form->w);
989   returnCode(_nc_Position_Form_Cursor(form));
990 }
991
992 /*---------------------------------------------------------------------------
993 |   Facility      :  libnform
994 |   Function      :  static void Perform_Justification(
995 |                                        FIELD  * field,
996 |                                        WINDOW * win)
997 |
998 |   Description   :  Output field with requested justification
999 |
1000 |   Return Values :  -
1001 +--------------------------------------------------------------------------*/
1002 static void
1003 Perform_Justification(FIELD *field, WINDOW *win)
1004 {
1005   FIELD_CELL *bp;
1006   int len;
1007   int col = 0;
1008
1009   bp = (Field_Has_Option(field, O_NO_LEFT_STRIP)
1010         ? field->buf
1011         : Get_Start_Of_Data(field->buf, Buffer_Length(field)));
1012   len = (int)(After_End_Of_Data(field->buf, Buffer_Length(field)) - bp);
1013
1014   if (len > 0)
1015     {
1016       assert(win && (field->drows == 1));
1017
1018       if (field->cols - len >= 0)
1019         switch (field->just)
1020           {
1021           case JUSTIFY_LEFT:
1022             break;
1023           case JUSTIFY_CENTER:
1024             col = (field->cols - len) / 2;
1025             break;
1026           case JUSTIFY_RIGHT:
1027             col = field->cols - len;
1028             break;
1029           default:
1030             break;
1031           }
1032
1033       wmove(win, 0, col);
1034       myADDNSTR(win, bp, len);
1035     }
1036 }
1037
1038 /*---------------------------------------------------------------------------
1039 |   Facility      :  libnform
1040 |   Function      :  static void Undo_Justification(
1041 |                                     FIELD  * field,
1042 |                                     WINDOW * win)
1043 |
1044 |   Description   :  Display field without any justification, i.e.
1045 |                    left justified
1046 |
1047 |   Return Values :  -
1048 +--------------------------------------------------------------------------*/
1049 static void
1050 Undo_Justification(FIELD *field, WINDOW *win)
1051 {
1052   FIELD_CELL *bp;
1053   int y, x;
1054   int len;
1055
1056   getyx(win, y, x);
1057
1058   bp = (Field_Has_Option(field, O_NO_LEFT_STRIP)
1059         ? field->buf
1060         : Get_Start_Of_Data(field->buf, Buffer_Length(field)));
1061   len = (int)(After_End_Of_Data(field->buf, Buffer_Length(field)) - bp);
1062
1063   if (len > 0)
1064     {
1065       assert(win);
1066       wmove(win, 0, 0);
1067       myADDNSTR(win, bp, len);
1068     }
1069   wmove(win, y, x);
1070 }
1071
1072 /*---------------------------------------------------------------------------
1073 |   Facility      :  libnform
1074 |   Function      :  static bool Check_Char(FORM  *form,
1075 |                                           FIELD *field,
1076 |                                           FIELDTYPE * typ,
1077 |                                           int ch,
1078 |                                           TypeArgument *argp)
1079 |
1080 |   Description   :  Perform a single character check for character ch
1081 |                    according to the fieldtype instance.
1082 |
1083 |   Return Values :  TRUE             - Character is valid
1084 |                    FALSE            - Character is invalid
1085 +--------------------------------------------------------------------------*/
1086 static bool
1087 Check_Char(FORM *form,
1088            FIELD *field,
1089            FIELDTYPE *typ,
1090            int ch,
1091            TypeArgument *argp)
1092 {
1093   if (typ)
1094     {
1095       if (typ->status & _LINKED_TYPE)
1096         {
1097           assert(argp);
1098           return (
1099                    Check_Char(form, field, typ->left, ch, argp->left) ||
1100                    Check_Char(form, field, typ->right, ch, argp->right));
1101         }
1102       else
1103         {
1104 #if NCURSES_INTEROP_FUNCS
1105           if (typ->charcheck.occheck)
1106             {
1107               if (typ->status & _GENERIC)
1108                 return typ->charcheck.gccheck(ch, form, field, (void *)argp);
1109               else
1110                 return typ->charcheck.occheck(ch, (void *)argp);
1111             }
1112 #else
1113           if (typ->ccheck)
1114             return typ->ccheck(ch, (void *)argp);
1115 #endif
1116         }
1117     }
1118   return (!iscntrl(UChar(ch)) ? TRUE : FALSE);
1119 }
1120
1121 /*---------------------------------------------------------------------------
1122 |   Facility      :  libnform
1123 |   Function      :  static int Display_Or_Erase_Field(
1124 |                                           FIELD * field,
1125 |                                           bool bEraseFlag)
1126 |
1127 |   Description   :  Create a subwindow for the field and display the
1128 |                    buffer contents (apply justification if required)
1129 |                    or simply erase the field.
1130 |
1131 |   Return Values :  E_OK           - on success
1132 |                    E_SYSTEM_ERROR - some error (typical no memory)
1133 +--------------------------------------------------------------------------*/
1134 static int
1135 Display_Or_Erase_Field(FIELD *field, bool bEraseFlag)
1136 {
1137   WINDOW *win;
1138   WINDOW *fwin;
1139
1140   if (!field)
1141     return E_SYSTEM_ERROR;
1142
1143   fwin = Get_Form_Window(field->form);
1144   win = derwin(fwin,
1145                field->rows, field->cols, field->frow, field->fcol);
1146
1147   if (!win)
1148     return E_SYSTEM_ERROR;
1149   else
1150     {
1151       if (Field_Has_Option(field, O_VISIBLE))
1152         {
1153           Set_Field_Window_Attributes(field, win);
1154         }
1155       else
1156         {
1157           (void)wattrset(win, (int)WINDOW_ATTRS(fwin));
1158         }
1159       werase(win);
1160     }
1161
1162   if (!bEraseFlag)
1163     {
1164       if (Field_Has_Option(field, O_PUBLIC))
1165         {
1166           if (Justification_Allowed(field))
1167             Perform_Justification(field, win);
1168           else
1169             Buffer_To_Window(field, win);
1170         }
1171       ClrStatus(field, _NEWTOP);
1172     }
1173   wsyncup(win);
1174   delwin(win);
1175   return E_OK;
1176 }
1177
1178 /* Macros to preset the bEraseFlag */
1179 #define Display_Field(field) Display_Or_Erase_Field(field,FALSE)
1180 #define Erase_Field(field)   Display_Or_Erase_Field(field,TRUE)
1181
1182 /*---------------------------------------------------------------------------
1183 |   Facility      :  libnform
1184 |   Function      :  static int Synchronize_Field(FIELD * field)
1185 |
1186 |   Description   :  Synchronize the windows content with the value in
1187 |                    the buffer.
1188 |
1189 |   Return Values :  E_OK                - success
1190 |                    E_BAD_ARGUMENT      - invalid field pointer
1191 |                    E_SYSTEM_ERROR      - some severe basic error
1192 +--------------------------------------------------------------------------*/
1193 static int
1194 Synchronize_Field(FIELD *field)
1195 {
1196   FORM *form;
1197   int res = E_OK;
1198
1199   if (!field)
1200     return (E_BAD_ARGUMENT);
1201
1202   if (((form = field->form) != (FORM *)0)
1203       && Field_Really_Appears(field))
1204     {
1205       if (field == form->current)
1206         {
1207           form->currow = form->curcol = form->toprow = form->begincol = 0;
1208           werase(form->w);
1209
1210           if ((Field_Has_Option(field, O_PUBLIC)) && Justification_Allowed(field))
1211             Undo_Justification(field, form->w);
1212           else
1213             Buffer_To_Window(field, form->w);
1214
1215           SetStatus(field, _NEWTOP);
1216           res = _nc_Refresh_Current_Field(form);
1217         }
1218       else
1219         res = Display_Field(field);
1220     }
1221   SetStatus(field, _CHANGED);
1222   return (res);
1223 }
1224
1225 /*---------------------------------------------------------------------------
1226 |   Facility      :  libnform
1227 |   Function      :  static int Synchronize_Linked_Fields(FIELD * field)
1228 |
1229 |   Description   :  Propagate the Synchronize_Field function to all linked
1230 |                    fields. The first error that occurs in the sequence
1231 |                    of updates is the return value.
1232 |
1233 |   Return Values :  E_OK                - success
1234 |                    E_BAD_ARGUMENT      - invalid field pointer
1235 |                    E_SYSTEM_ERROR      - some severe basic error
1236 +--------------------------------------------------------------------------*/
1237 static int
1238 Synchronize_Linked_Fields(FIELD *field)
1239 {
1240   FIELD *linked_field;
1241   int res = E_OK;
1242   int syncres;
1243
1244   if (!field)
1245     return (E_BAD_ARGUMENT);
1246
1247   if (!field->link)
1248     return (E_SYSTEM_ERROR);
1249
1250   for (linked_field = field->link;
1251        (linked_field != field) && (linked_field != 0);
1252        linked_field = linked_field->link)
1253     {
1254       if (((syncres = Synchronize_Field(linked_field)) != E_OK) &&
1255           (res == E_OK))
1256         res = syncres;
1257     }
1258   return (res);
1259 }
1260
1261 /*---------------------------------------------------------------------------
1262 |   Facility      :  libnform
1263 |   Function      :  int _nc_Synchronize_Attributes(FIELD * field)
1264 |
1265 |   Description   :  If a fields visual attributes have changed, this
1266 |                    routine is called to propagate those changes to the
1267 |                    screen.
1268 |
1269 |   Return Values :  E_OK             - success
1270 |                    E_BAD_ARGUMENT   - invalid field pointer
1271 |                    E_SYSTEM_ERROR   - some severe basic error
1272 +--------------------------------------------------------------------------*/
1273 NCURSES_EXPORT(int)
1274 _nc_Synchronize_Attributes(FIELD *field)
1275 {
1276   FORM *form;
1277   int res = E_OK;
1278   WINDOW *formwin;
1279
1280   T((T_CALLED("_nc_Synchronize_Attributes(%p)"), (void *)field));
1281
1282   if (!field)
1283     returnCode(E_BAD_ARGUMENT);
1284
1285   CHECKPOS(field->form);
1286   if (((form = field->form) != (FORM *)0)
1287       && Field_Really_Appears(field))
1288     {
1289       if (form->current == field)
1290         {
1291           Synchronize_Buffer(form);
1292           Set_Field_Window_Attributes(field, form->w);
1293           werase(form->w);
1294           wmove(form->w, form->currow, form->curcol);
1295
1296           if (Field_Has_Option(field, O_PUBLIC))
1297             {
1298               if (Justification_Allowed(field))
1299                 Undo_Justification(field, form->w);
1300               else
1301                 Buffer_To_Window(field, form->w);
1302             }
1303           else
1304             {
1305               formwin = Get_Form_Window(form);
1306               copywin(form->w, formwin,
1307                       0, 0,
1308                       field->frow, field->fcol,
1309                       field->frow + field->rows - 1,
1310                       field->fcol + field->cols - 1, 0);
1311               wsyncup(formwin);
1312               Buffer_To_Window(field, form->w);
1313               SetStatus(field, _NEWTOP);        /* fake refresh to paint all */
1314               _nc_Refresh_Current_Field(form);
1315             }
1316         }
1317       else
1318         {
1319           res = Display_Field(field);
1320         }
1321     }
1322   CHECKPOS(form);
1323   returnCode(res);
1324 }
1325
1326 /*---------------------------------------------------------------------------
1327 |   Facility      :  libnform
1328 |   Function      :  int _nc_Synchronize_Options(FIELD * field,
1329 |                                                Field_Options newopts)
1330 |
1331 |   Description   :  If a fields options have changed, this routine is
1332 |                    called to propagate these changes to the screen and
1333 |                    to really change the behavior of the field.
1334 |
1335 |   Return Values :  E_OK                - success
1336 |                    E_BAD_ARGUMENT      - invalid field pointer
1337 |                    E_CURRENT           - field is the current one
1338 |                    E_SYSTEM_ERROR      - some severe basic error
1339 +--------------------------------------------------------------------------*/
1340 NCURSES_EXPORT(int)
1341 _nc_Synchronize_Options(FIELD *field, Field_Options newopts)
1342 {
1343   Field_Options oldopts;
1344   Field_Options changed_opts;
1345   FORM *form;
1346   int res = E_OK;
1347
1348   T((T_CALLED("_nc_Synchronize_Options(%p,%#x)"), (void *)field, newopts));
1349
1350   if (!field)
1351     returnCode(E_BAD_ARGUMENT);
1352
1353   oldopts = field->opts;
1354   changed_opts = oldopts ^ newopts;
1355   field->opts = newopts;
1356   form = field->form;
1357
1358   if (form)
1359     {
1360       if (form->status & _POSTED)
1361         {
1362           if (form->current == field)
1363             {
1364               field->opts = oldopts;
1365               returnCode(E_CURRENT);
1366             }
1367           if (form->curpage == field->page)
1368             {
1369               if ((unsigned)changed_opts & O_VISIBLE)
1370                 {
1371                   if ((unsigned)newopts & O_VISIBLE)
1372                     res = Display_Field(field);
1373                   else
1374                     res = Erase_Field(field);
1375                 }
1376               else
1377                 {
1378                   if (((unsigned)changed_opts & O_PUBLIC) &&
1379                       ((unsigned)newopts & O_VISIBLE))
1380                     res = Display_Field(field);
1381                 }
1382             }
1383         }
1384     }
1385
1386   if ((unsigned)changed_opts & O_STATIC)
1387     {
1388       bool single_line_field = Single_Line_Field(field);
1389       int res2 = E_OK;
1390
1391       if ((unsigned)newopts & O_STATIC)
1392         {
1393           /* the field becomes now static */
1394           ClrStatus(field, _MAY_GROW);
1395           /* if actually we have no hidden columns, justification may
1396              occur again */
1397           if (single_line_field &&
1398               (field->cols == field->dcols) &&
1399               (field->just != NO_JUSTIFICATION) &&
1400               Field_Really_Appears(field))
1401             {
1402               res2 = Display_Field(field);
1403             }
1404         }
1405       else
1406         {
1407           /* field is no longer static */
1408           if ((field->maxgrow == 0) ||
1409               (single_line_field && (field->dcols < field->maxgrow)) ||
1410               (!single_line_field && (field->drows < field->maxgrow)))
1411             {
1412               SetStatus(field, _MAY_GROW);
1413               /* a field with justification now changes its behavior,
1414                  so we must redisplay it */
1415               if (single_line_field &&
1416                   (field->just != NO_JUSTIFICATION) &&
1417                   Field_Really_Appears(field))
1418                 {
1419                   res2 = Display_Field(field);
1420                 }
1421             }
1422         }
1423       if (res2 != E_OK)
1424         res = res2;
1425     }
1426
1427   returnCode(res);
1428 }
1429
1430 /*
1431  * Removes the focus from the current field of the form.
1432  */
1433 void
1434 _nc_Unset_Current_Field(FORM *form)
1435 {
1436   FIELD *field = form->current;
1437
1438   _nc_Refresh_Current_Field(form);
1439   if (Field_Has_Option(field, O_PUBLIC))
1440     {
1441       if (field->drows > field->rows)
1442         {
1443           if (form->toprow == 0)
1444             ClrStatus(field, _NEWTOP);
1445           else
1446             SetStatus(field, _NEWTOP);
1447         }
1448       else
1449         {
1450           if (Justification_Allowed(field))
1451             {
1452               Window_To_Buffer(form, field);
1453               werase(form->w);
1454               Perform_Justification(field, form->w);
1455               if (Field_Has_Option(field, O_DYNAMIC_JUSTIFY) &&
1456                   (form->w->_parent == 0))
1457                 {
1458                   copywin(form->w,
1459                           Get_Form_Window(form),
1460                           0,
1461                           0,
1462                           field->frow,
1463                           field->fcol,
1464                           field->frow,
1465                           field->cols + field->fcol - 1,
1466                           0);
1467                   wsyncup(Get_Form_Window(form));
1468                 }
1469               else
1470                 {
1471                   wsyncup(form->w);
1472                 }
1473             }
1474         }
1475     }
1476   delwin(form->w);
1477   form->w = (WINDOW *)0;
1478   form->current = 0;
1479 }
1480
1481 /*---------------------------------------------------------------------------
1482 |   Facility      :  libnform
1483 |   Function      :  int _nc_Set_Current_Field(FORM  * form,
1484 |                                              FIELD * newfield)
1485 |
1486 |   Description   :  Make the newfield the new current field.
1487 |
1488 |   Return Values :  E_OK              - success
1489 |                    E_BAD_ARGUMENT    - invalid form or field pointer
1490 |                    E_SYSTEM_ERROR    - some severe basic error
1491 |                    E_NOT_CONNECTED   - no fields are connected to the form
1492 +--------------------------------------------------------------------------*/
1493 NCURSES_EXPORT(int)
1494 _nc_Set_Current_Field(FORM *form, FIELD *newfield)
1495 {
1496   FIELD *field;
1497   WINDOW *new_window;
1498
1499   T((T_CALLED("_nc_Set_Current_Field(%p,%p)"), (void *)form, (void *)newfield));
1500
1501   if (!form || !newfield || (newfield->form != form))
1502     returnCode(E_BAD_ARGUMENT);
1503
1504   if ((form->status & _IN_DRIVER))
1505     returnCode(E_BAD_STATE);
1506
1507   if (!(form->field))
1508     returnCode(E_NOT_CONNECTED);
1509
1510   field = form->current;
1511
1512   if ((field != newfield) ||
1513       !(form->status & _POSTED))
1514     {
1515       if (field && (form->w) &&
1516           (Field_Has_Option(field, O_VISIBLE)) &&
1517           (field->form->curpage == field->page))
1518         _nc_Unset_Current_Field(form);
1519
1520       field = newfield;
1521
1522       if (Has_Invisible_Parts(field))
1523         new_window = newpad(field->drows, field->dcols);
1524       else
1525         new_window = derwin(Get_Form_Window(form),
1526                             field->rows, field->cols, field->frow, field->fcol);
1527
1528       if (!new_window)
1529         returnCode(E_SYSTEM_ERROR);
1530
1531       form->current = field;
1532
1533       if (form->w)
1534         delwin(form->w);
1535       form->w = new_window;
1536
1537       ClrStatus(form, _WINDOW_MODIFIED);
1538       Set_Field_Window_Attributes(field, form->w);
1539
1540       if (Has_Invisible_Parts(field))
1541         {
1542           werase(form->w);
1543           Buffer_To_Window(field, form->w);
1544         }
1545       else
1546         {
1547           if (Justification_Allowed(field))
1548             {
1549               werase(form->w);
1550               Undo_Justification(field, form->w);
1551               wsyncup(form->w);
1552             }
1553         }
1554
1555       untouchwin(form->w);
1556     }
1557
1558   form->currow = form->curcol = form->toprow = form->begincol = 0;
1559   returnCode(E_OK);
1560 }
1561
1562 /*----------------------------------------------------------------------------
1563   Intra-Field Navigation routines
1564   --------------------------------------------------------------------------*/
1565
1566 /*---------------------------------------------------------------------------
1567 |   Facility      :  libnform
1568 |   Function      :  static int IFN_Next_Character(FORM * form)
1569 |
1570 |   Description   :  Move to the next character in the field. In a multi-line
1571 |                    field this wraps at the end of the line.
1572 |
1573 |   Return Values :  E_OK                - success
1574 |                    E_REQUEST_DENIED    - at the rightmost position
1575 +--------------------------------------------------------------------------*/
1576 static int
1577 IFN_Next_Character(FORM *form)
1578 {
1579   FIELD *field = form->current;
1580   int step = myWCWIDTH(form->w, form->currow, form->curcol);
1581
1582   T((T_CALLED("IFN_Next_Character(%p)"), (void *)form));
1583   if ((form->curcol += step) == field->dcols)
1584     {
1585       if ((++(form->currow)) == field->drows)
1586         {
1587 #if GROW_IF_NAVIGATE
1588           if (!Single_Line_Field(field) && Field_Grown(field, 1))
1589             {
1590               form->curcol = 0;
1591               returnCode(E_OK);
1592             }
1593 #endif
1594           form->currow--;
1595 #if GROW_IF_NAVIGATE
1596           if (Single_Line_Field(field) && Field_Grown(field, 1))
1597             returnCode(E_OK);
1598 #endif
1599           form->curcol -= step;
1600           returnCode(E_REQUEST_DENIED);
1601         }
1602       form->curcol = 0;
1603     }
1604   returnCode(E_OK);
1605 }
1606
1607 /*---------------------------------------------------------------------------
1608 |   Facility      :  libnform
1609 |   Function      :  static int IFN_Previous_Character(FORM * form)
1610 |
1611 |   Description   :  Move to the previous character in the field. In a
1612 |                    multi-line field this wraps and the beginning of the
1613 |                    line.
1614 |
1615 |   Return Values :  E_OK                - success
1616 |                    E_REQUEST_DENIED    - at the leftmost position
1617 +--------------------------------------------------------------------------*/
1618 static int
1619 IFN_Previous_Character(FORM *form)
1620 {
1621   int amount = myWCWIDTH(form->w, form->currow, form->curcol - 1);
1622   int oldcol = form->curcol;
1623
1624   T((T_CALLED("IFN_Previous_Character(%p)"), (void *)form));
1625   if ((form->curcol -= amount) < 0)
1626     {
1627       if ((--(form->currow)) < 0)
1628         {
1629           form->currow++;
1630           form->curcol = oldcol;
1631           returnCode(E_REQUEST_DENIED);
1632         }
1633       form->curcol = form->current->dcols - 1;
1634     }
1635   returnCode(E_OK);
1636 }
1637
1638 /*---------------------------------------------------------------------------
1639 |   Facility      :  libnform
1640 |   Function      :  static int IFN_Next_Line(FORM * form)
1641 |
1642 |   Description   :  Move to the beginning of the next line in the field
1643 |
1644 |   Return Values :  E_OK                - success
1645 |                    E_REQUEST_DENIED    - at the last line
1646 +--------------------------------------------------------------------------*/
1647 static int
1648 IFN_Next_Line(FORM *form)
1649 {
1650   FIELD *field = form->current;
1651
1652   T((T_CALLED("IFN_Next_Line(%p)"), (void *)form));
1653   if ((++(form->currow)) == field->drows)
1654     {
1655 #if GROW_IF_NAVIGATE
1656       if (!Single_Line_Field(field) && Field_Grown(field, 1))
1657         returnCode(E_OK);
1658 #endif
1659       form->currow--;
1660       returnCode(E_REQUEST_DENIED);
1661     }
1662   form->curcol = 0;
1663   returnCode(E_OK);
1664 }
1665
1666 /*---------------------------------------------------------------------------
1667 |   Facility      :  libnform
1668 |   Function      :  static int IFN_Previous_Line(FORM * form)
1669 |
1670 |   Description   :  Move to the beginning of the previous line in the field
1671 |
1672 |   Return Values :  E_OK                - success
1673 |                    E_REQUEST_DENIED    - at the first line
1674 +--------------------------------------------------------------------------*/
1675 static int
1676 IFN_Previous_Line(FORM *form)
1677 {
1678   T((T_CALLED("IFN_Previous_Line(%p)"), (void *)form));
1679   if ((--(form->currow)) < 0)
1680     {
1681       form->currow++;
1682       returnCode(E_REQUEST_DENIED);
1683     }
1684   form->curcol = 0;
1685   returnCode(E_OK);
1686 }
1687
1688 /*---------------------------------------------------------------------------
1689 |   Facility      :  libnform
1690 |   Function      :  static int IFN_Next_Word(FORM * form)
1691 |
1692 |   Description   :  Move to the beginning of the next word in the field.
1693 |
1694 |   Return Values :  E_OK             - success
1695 |                    E_REQUEST_DENIED - there is no next word
1696 +--------------------------------------------------------------------------*/
1697 static int
1698 IFN_Next_Word(FORM *form)
1699 {
1700   FIELD *field = form->current;
1701   FIELD_CELL *bp = Address_Of_Current_Position_In_Buffer(form);
1702   FIELD_CELL *s;
1703   FIELD_CELL *t;
1704
1705   T((T_CALLED("IFN_Next_Word(%p)"), (void *)form));
1706
1707   /* We really need access to the data, so we have to synchronize */
1708   Synchronize_Buffer(form);
1709
1710   /* Go to the first whitespace after the current position (including
1711      current position). This is then the starting point to look for the
1712      next non-blank data */
1713   s = Get_First_Whitespace_Character(bp, Buffer_Length(field) -
1714                                      (int)(bp - field->buf));
1715
1716   /* Find the start of the next word */
1717   t = Get_Start_Of_Data(s, Buffer_Length(field) -
1718                         (int)(s - field->buf));
1719 #if !FRIENDLY_PREV_NEXT_WORD
1720   if (s == t)
1721     returnCode(E_REQUEST_DENIED);
1722   else
1723 #endif
1724     {
1725       Adjust_Cursor_Position(form, t);
1726       returnCode(E_OK);
1727     }
1728 }
1729
1730 /*---------------------------------------------------------------------------
1731 |   Facility      :  libnform
1732 |   Function      :  static int IFN_Previous_Word(FORM * form)
1733 |
1734 |   Description   :  Move to the beginning of the previous word in the field.
1735 |
1736 |   Return Values :  E_OK             - success
1737 |                    E_REQUEST_DENIED - there is no previous word
1738 +--------------------------------------------------------------------------*/
1739 static int
1740 IFN_Previous_Word(FORM *form)
1741 {
1742   FIELD *field = form->current;
1743   FIELD_CELL *bp = Address_Of_Current_Position_In_Buffer(form);
1744   FIELD_CELL *s;
1745   FIELD_CELL *t;
1746   bool again = FALSE;
1747
1748   T((T_CALLED("IFN_Previous_Word(%p)"), (void *)form));
1749
1750   /* We really need access to the data, so we have to synchronize */
1751   Synchronize_Buffer(form);
1752
1753   s = After_End_Of_Data(field->buf, (int)(bp - field->buf));
1754   /* s points now right after the last non-blank in the buffer before bp.
1755      If bp was in a word, s equals bp. In this case we must find the last
1756      whitespace in the buffer before bp and repeat the game to really find
1757      the previous word! */
1758   if (s == bp)
1759     again = TRUE;
1760
1761   /* And next call now goes backward to look for the last whitespace
1762      before that, pointing right after this, so it points to the begin
1763      of the previous word.
1764    */
1765   t = After_Last_Whitespace_Character(field->buf, (int)(s - field->buf));
1766 #if !FRIENDLY_PREV_NEXT_WORD
1767   if (s == t)
1768     returnCode(E_REQUEST_DENIED);
1769 #endif
1770   if (again)
1771     {
1772       /* and do it again, replacing bp by t */
1773       s = After_End_Of_Data(field->buf, (int)(t - field->buf));
1774       t = After_Last_Whitespace_Character(field->buf, (int)(s - field->buf));
1775 #if !FRIENDLY_PREV_NEXT_WORD
1776       if (s == t)
1777         returnCode(E_REQUEST_DENIED);
1778 #endif
1779     }
1780   Adjust_Cursor_Position(form, t);
1781   returnCode(E_OK);
1782 }
1783
1784 /*---------------------------------------------------------------------------
1785 |   Facility      :  libnform
1786 |   Function      :  static int IFN_Beginning_Of_Field(FORM * form)
1787 |
1788 |   Description   :  Place the cursor at the first non-pad character in
1789 |                    the field.
1790 |
1791 |   Return Values :  E_OK             - success
1792 +--------------------------------------------------------------------------*/
1793 static int
1794 IFN_Beginning_Of_Field(FORM *form)
1795 {
1796   FIELD *field = form->current;
1797
1798   T((T_CALLED("IFN_Beginning_Of_Field(%p)"), (void *)form));
1799   Synchronize_Buffer(form);
1800   Adjust_Cursor_Position(form,
1801                          Get_Start_Of_Data(field->buf, Buffer_Length(field)));
1802   returnCode(E_OK);
1803 }
1804
1805 /*---------------------------------------------------------------------------
1806 |   Facility      :  libnform
1807 |   Function      :  static int IFN_End_Of_Field(FORM * form)
1808 |
1809 |   Description   :  Place the cursor after the last non-pad character in
1810 |                    the field. If the field occupies the last position in
1811 |                    the buffer, the cursor is positioned on the last
1812 |                    character.
1813 |
1814 |   Return Values :  E_OK              - success
1815 +--------------------------------------------------------------------------*/
1816 static int
1817 IFN_End_Of_Field(FORM *form)
1818 {
1819   FIELD *field = form->current;
1820   FIELD_CELL *pos;
1821
1822   T((T_CALLED("IFN_End_Of_Field(%p)"), (void *)form));
1823   Synchronize_Buffer(form);
1824   pos = After_End_Of_Data(field->buf, Buffer_Length(field));
1825   if (pos == (field->buf + Buffer_Length(field)))
1826     pos--;
1827   Adjust_Cursor_Position(form, pos);
1828   returnCode(E_OK);
1829 }
1830
1831 /*---------------------------------------------------------------------------
1832 |   Facility      :  libnform
1833 |   Function      :  static int IFN_Beginning_Of_Line(FORM * form)
1834 |
1835 |   Description   :  Place the cursor on the first non-pad character in
1836 |                    the current line of the field.
1837 |
1838 |   Return Values :  E_OK         - success
1839 +--------------------------------------------------------------------------*/
1840 static int
1841 IFN_Beginning_Of_Line(FORM *form)
1842 {
1843   FIELD *field = form->current;
1844
1845   T((T_CALLED("IFN_Beginning_Of_Line(%p)"), (void *)form));
1846   Synchronize_Buffer(form);
1847   Adjust_Cursor_Position(form,
1848                          Get_Start_Of_Data(Address_Of_Current_Row_In_Buffer(form),
1849                                            field->dcols));
1850   returnCode(E_OK);
1851 }
1852
1853 /*---------------------------------------------------------------------------
1854 |   Facility      :  libnform
1855 |   Function      :  static int IFN_End_Of_Line(FORM * form)
1856 |
1857 |   Description   :  Place the cursor after the last non-pad character in the
1858 |                    current line of the field. If the field occupies the
1859 |                    last column in the line, the cursor is positioned on the
1860 |                    last character of the line.
1861 |
1862 |   Return Values :  E_OK        - success
1863 +--------------------------------------------------------------------------*/
1864 static int
1865 IFN_End_Of_Line(FORM *form)
1866 {
1867   FIELD *field = form->current;
1868   FIELD_CELL *pos;
1869   FIELD_CELL *bp;
1870
1871   T((T_CALLED("IFN_End_Of_Line(%p)"), (void *)form));
1872   Synchronize_Buffer(form);
1873   bp = Address_Of_Current_Row_In_Buffer(form);
1874   pos = After_End_Of_Data(bp, field->dcols);
1875   if (pos == (bp + field->dcols))
1876     pos--;
1877   Adjust_Cursor_Position(form, pos);
1878   returnCode(E_OK);
1879 }
1880
1881 /*---------------------------------------------------------------------------
1882 |   Facility      :  libnform
1883 |   Function      :  static int IFN_Left_Character(FORM * form)
1884 |
1885 |   Description   :  Move one character to the left in the current line.
1886 |                    This doesn't cycle.
1887 |
1888 |   Return Values :  E_OK             - success
1889 |                    E_REQUEST_DENIED - already in first column
1890 +--------------------------------------------------------------------------*/
1891 static int
1892 IFN_Left_Character(FORM *form)
1893 {
1894   int amount = myWCWIDTH(form->w, form->currow, form->curcol - 1);
1895   int oldcol = form->curcol;
1896
1897   T((T_CALLED("IFN_Left_Character(%p)"), (void *)form));
1898   if ((form->curcol -= amount) < 0)
1899     {
1900       form->curcol = oldcol;
1901       returnCode(E_REQUEST_DENIED);
1902     }
1903   returnCode(E_OK);
1904 }
1905
1906 /*---------------------------------------------------------------------------
1907 |   Facility      :  libnform
1908 |   Function      :  static int IFN_Right_Character(FORM * form)
1909 |
1910 |   Description   :  Move one character to the right in the current line.
1911 |                    This doesn't cycle.
1912 |
1913 |   Return Values :  E_OK              - success
1914 |                    E_REQUEST_DENIED  - already in last column
1915 +--------------------------------------------------------------------------*/
1916 static int
1917 IFN_Right_Character(FORM *form)
1918 {
1919   int amount = myWCWIDTH(form->w, form->currow, form->curcol);
1920   int oldcol = form->curcol;
1921
1922   T((T_CALLED("IFN_Right_Character(%p)"), (void *)form));
1923   if ((form->curcol += amount) >= form->current->dcols)
1924     {
1925 #if GROW_IF_NAVIGATE
1926       FIELD *field = form->current;
1927
1928       if (Single_Line_Field(field) && Field_Grown(field, 1))
1929         returnCode(E_OK);
1930 #endif
1931       form->curcol = oldcol;
1932       returnCode(E_REQUEST_DENIED);
1933     }
1934   returnCode(E_OK);
1935 }
1936
1937 /*---------------------------------------------------------------------------
1938 |   Facility      :  libnform
1939 |   Function      :  static int IFN_Up_Character(FORM * form)
1940 |
1941 |   Description   :  Move one line up. This doesn't cycle through the lines
1942 |                    of the field.
1943 |
1944 |   Return Values :  E_OK              - success
1945 |                    E_REQUEST_DENIED  - already in last column
1946 +--------------------------------------------------------------------------*/
1947 static int
1948 IFN_Up_Character(FORM *form)
1949 {
1950   T((T_CALLED("IFN_Up_Character(%p)"), (void *)form));
1951   if ((--(form->currow)) < 0)
1952     {
1953       form->currow++;
1954       returnCode(E_REQUEST_DENIED);
1955     }
1956   returnCode(E_OK);
1957 }
1958
1959 /*---------------------------------------------------------------------------
1960 |   Facility      :  libnform
1961 |   Function      :  static int IFN_Down_Character(FORM * form)
1962 |
1963 |   Description   :  Move one line down. This doesn't cycle through the
1964 |                    lines of the field.
1965 |
1966 |   Return Values :  E_OK              - success
1967 |                    E_REQUEST_DENIED  - already in last column
1968 +--------------------------------------------------------------------------*/
1969 static int
1970 IFN_Down_Character(FORM *form)
1971 {
1972   FIELD *field = form->current;
1973
1974   T((T_CALLED("IFN_Down_Character(%p)"), (void *)form));
1975   if ((++(form->currow)) == field->drows)
1976     {
1977 #if GROW_IF_NAVIGATE
1978       if (!Single_Line_Field(field) && Field_Grown(field, 1))
1979         returnCode(E_OK);
1980 #endif
1981       --(form->currow);
1982       returnCode(E_REQUEST_DENIED);
1983     }
1984   returnCode(E_OK);
1985 }
1986 /*----------------------------------------------------------------------------
1987   END of Intra-Field Navigation routines
1988   --------------------------------------------------------------------------*/
1989
1990 /*----------------------------------------------------------------------------
1991   Vertical scrolling helper routines
1992   --------------------------------------------------------------------------*/
1993
1994 /*---------------------------------------------------------------------------
1995 |   Facility      :  libnform
1996 |   Function      :  static int VSC_Generic(FORM *form, int nlines)
1997 |
1998 |   Description   :  Scroll multi-line field forward (nlines>0) or
1999 |                    backward (nlines<0) this many lines.
2000 |
2001 |   Return Values :  E_OK              - success
2002 |                    E_REQUEST_DENIED  - can't scroll
2003 +--------------------------------------------------------------------------*/
2004 static int
2005 VSC_Generic(FORM *form, int nlines)
2006 {
2007   FIELD *field = form->current;
2008   int res = E_REQUEST_DENIED;
2009   int rows_to_go = (nlines > 0 ? nlines : -nlines);
2010
2011   if (nlines > 0)
2012     {
2013       if ((rows_to_go + form->toprow) > (field->drows - field->rows))
2014         rows_to_go = (field->drows - field->rows - form->toprow);
2015
2016       if (rows_to_go > 0)
2017         {
2018           form->currow += rows_to_go;
2019           form->toprow += rows_to_go;
2020           res = E_OK;
2021         }
2022     }
2023   else
2024     {
2025       if (rows_to_go > form->toprow)
2026         rows_to_go = form->toprow;
2027
2028       if (rows_to_go > 0)
2029         {
2030           form->currow -= rows_to_go;
2031           form->toprow -= rows_to_go;
2032           res = E_OK;
2033         }
2034     }
2035   return (res);
2036 }
2037 /*----------------------------------------------------------------------------
2038   End of Vertical scrolling helper routines
2039   --------------------------------------------------------------------------*/
2040
2041 /*----------------------------------------------------------------------------
2042   Vertical scrolling routines
2043   --------------------------------------------------------------------------*/
2044
2045 /*---------------------------------------------------------------------------
2046 |   Facility      :  libnform
2047 |   Function      :  static int Vertical_Scrolling(
2048 |                                           int (* const fct) (FORM *),
2049 |                                           FORM * form)
2050 |
2051 |   Description   :  Performs the generic vertical scrolling routines.
2052 |                    This has to check for a multi-line field and to set
2053 |                    the _NEWTOP flag if scrolling really occurred.
2054 |
2055 |   Return Values :  Propagated error code from low-level driver calls
2056 +--------------------------------------------------------------------------*/
2057 static int
2058 Vertical_Scrolling(int (*const fct) (FORM *), FORM *form)
2059 {
2060   int res = E_REQUEST_DENIED;
2061
2062   if (!Single_Line_Field(form->current))
2063     {
2064       res = fct(form);
2065       if (res == E_OK)
2066         SetStatus(form->current, _NEWTOP);
2067     }
2068   return (res);
2069 }
2070
2071 /*---------------------------------------------------------------------------
2072 |   Facility      :  libnform
2073 |   Function      :  static int VSC_Scroll_Line_Forward(FORM * form)
2074 |
2075 |   Description   :  Scroll multi-line field forward a line
2076 |
2077 |   Return Values :  E_OK                - success
2078 |                    E_REQUEST_DENIED    - no data ahead
2079 +--------------------------------------------------------------------------*/
2080 static int
2081 VSC_Scroll_Line_Forward(FORM *form)
2082 {
2083   T((T_CALLED("VSC_Scroll_Line_Forward(%p)"), (void *)form));
2084   returnCode(VSC_Generic(form, 1));
2085 }
2086
2087 /*---------------------------------------------------------------------------
2088 |   Facility      :  libnform
2089 |   Function      :  static int VSC_Scroll_Line_Backward(FORM * form)
2090 |
2091 |   Description   :  Scroll multi-line field backward a line
2092 |
2093 |   Return Values :  E_OK                - success
2094 |                    E_REQUEST_DENIED    - no data behind
2095 +--------------------------------------------------------------------------*/
2096 static int
2097 VSC_Scroll_Line_Backward(FORM *form)
2098 {
2099   T((T_CALLED("VSC_Scroll_Line_Backward(%p)"), (void *)form));
2100   returnCode(VSC_Generic(form, -1));
2101 }
2102
2103 /*---------------------------------------------------------------------------
2104 |   Facility      :  libnform
2105 |   Function      :  static int VSC_Scroll_Page_Forward(FORM * form)
2106 |
2107 |   Description   :  Scroll a multi-line field forward a page
2108 |
2109 |   Return Values :  E_OK              - success
2110 |                    E_REQUEST_DENIED  - no data ahead
2111 +--------------------------------------------------------------------------*/
2112 static int
2113 VSC_Scroll_Page_Forward(FORM *form)
2114 {
2115   T((T_CALLED("VSC_Scroll_Page_Forward(%p)"), (void *)form));
2116   returnCode(VSC_Generic(form, form->current->rows));
2117 }
2118
2119 /*---------------------------------------------------------------------------
2120 |   Facility      :  libnform
2121 |   Function      :  static int VSC_Scroll_Half_Page_Forward(FORM * form)
2122 |
2123 |   Description   :  Scroll a multi-line field forward half a page
2124 |
2125 |   Return Values :  E_OK              - success
2126 |                    E_REQUEST_DENIED  - no data ahead
2127 +--------------------------------------------------------------------------*/
2128 static int
2129 VSC_Scroll_Half_Page_Forward(FORM *form)
2130 {
2131   T((T_CALLED("VSC_Scroll_Half_Page_Forward(%p)"), (void *)form));
2132   returnCode(VSC_Generic(form, (form->current->rows + 1) / 2));
2133 }
2134
2135 /*---------------------------------------------------------------------------
2136 |   Facility      :  libnform
2137 |   Function      :  static int VSC_Scroll_Page_Backward(FORM * form)
2138 |
2139 |   Description   :  Scroll a multi-line field backward a page
2140 |
2141 |   Return Values :  E_OK              - success
2142 |                    E_REQUEST_DENIED  - no data behind
2143 +--------------------------------------------------------------------------*/
2144 static int
2145 VSC_Scroll_Page_Backward(FORM *form)
2146 {
2147   T((T_CALLED("VSC_Scroll_Page_Backward(%p)"), (void *)form));
2148   returnCode(VSC_Generic(form, -(form->current->rows)));
2149 }
2150
2151 /*---------------------------------------------------------------------------
2152 |   Facility      :  libnform
2153 |   Function      :  static int VSC_Scroll_Half_Page_Backward(FORM * form)
2154 |
2155 |   Description   :  Scroll a multi-line field backward half a page
2156 |
2157 |   Return Values :  E_OK              - success
2158 |                    E_REQUEST_DENIED  - no data behind
2159 +--------------------------------------------------------------------------*/
2160 static int
2161 VSC_Scroll_Half_Page_Backward(FORM *form)
2162 {
2163   T((T_CALLED("VSC_Scroll_Half_Page_Backward(%p)"), (void *)form));
2164   returnCode(VSC_Generic(form, -((form->current->rows + 1) / 2)));
2165 }
2166 /*----------------------------------------------------------------------------
2167   End of Vertical scrolling routines
2168   --------------------------------------------------------------------------*/
2169
2170 /*----------------------------------------------------------------------------
2171   Horizontal scrolling helper routines
2172   --------------------------------------------------------------------------*/
2173
2174 /*---------------------------------------------------------------------------
2175 |   Facility      :  libnform
2176 |   Function      :  static int HSC_Generic(FORM *form, int ncolumns)
2177 |
2178 |   Description   :  Scroll single-line field forward (ncolumns>0) or
2179 |                    backward (ncolumns<0) this many columns.
2180 |
2181 |   Return Values :  E_OK              - success
2182 |                    E_REQUEST_DENIED  - can't scroll
2183 +--------------------------------------------------------------------------*/
2184 static int
2185 HSC_Generic(FORM *form, int ncolumns)
2186 {
2187   FIELD *field = form->current;
2188   int res = E_REQUEST_DENIED;
2189   int cols_to_go = (ncolumns > 0 ? ncolumns : -ncolumns);
2190
2191   if (ncolumns > 0)
2192     {
2193       if ((cols_to_go + form->begincol) > (field->dcols - field->cols))
2194         cols_to_go = field->dcols - field->cols - form->begincol;
2195
2196       if (cols_to_go > 0)
2197         {
2198           form->curcol += cols_to_go;
2199           form->begincol += cols_to_go;
2200           res = E_OK;
2201         }
2202     }
2203   else
2204     {
2205       if (cols_to_go > form->begincol)
2206         cols_to_go = form->begincol;
2207
2208       if (cols_to_go > 0)
2209         {
2210           form->curcol -= cols_to_go;
2211           form->begincol -= cols_to_go;
2212           res = E_OK;
2213         }
2214     }
2215   return (res);
2216 }
2217 /*----------------------------------------------------------------------------
2218   End of Horizontal scrolling helper routines
2219   --------------------------------------------------------------------------*/
2220
2221 /*----------------------------------------------------------------------------
2222   Horizontal scrolling routines
2223   --------------------------------------------------------------------------*/
2224
2225 /*---------------------------------------------------------------------------
2226 |   Facility      :  libnform
2227 |   Function      :  static int Horizontal_Scrolling(
2228 |                                          int (* const fct) (FORM *),
2229 |                                          FORM * form)
2230 |
2231 |   Description   :  Performs the generic horizontal scrolling routines.
2232 |                    This has to check for a single-line field.
2233 |
2234 |   Return Values :  Propagated error code from low-level driver calls
2235 +--------------------------------------------------------------------------*/
2236 static int
2237 Horizontal_Scrolling(int (*const fct) (FORM *), FORM *form)
2238 {
2239   if (Single_Line_Field(form->current))
2240     return fct(form);
2241   else
2242     return (E_REQUEST_DENIED);
2243 }
2244
2245 /*---------------------------------------------------------------------------
2246 |   Facility      :  libnform
2247 |   Function      :  static int HSC_Scroll_Char_Forward(FORM * form)
2248 |
2249 |   Description   :  Scroll single-line field forward a character
2250 |
2251 |   Return Values :  E_OK                - success
2252 |                    E_REQUEST_DENIED    - no data ahead
2253 +--------------------------------------------------------------------------*/
2254 static int
2255 HSC_Scroll_Char_Forward(FORM *form)
2256 {
2257   T((T_CALLED("HSC_Scroll_Char_Forward(%p)"), (void *)form));
2258   returnCode(HSC_Generic(form, 1));
2259 }
2260
2261 /*---------------------------------------------------------------------------
2262 |   Facility      :  libnform
2263 |   Function      :  static int HSC_Scroll_Char_Backward(FORM * form)
2264 |
2265 |   Description   :  Scroll single-line field backward a character
2266 |
2267 |   Return Values :  E_OK                - success
2268 |                    E_REQUEST_DENIED    - no data behind
2269 +--------------------------------------------------------------------------*/
2270 static int
2271 HSC_Scroll_Char_Backward(FORM *form)
2272 {
2273   T((T_CALLED("HSC_Scroll_Char_Backward(%p)"), (void *)form));
2274   returnCode(HSC_Generic(form, -1));
2275 }
2276
2277 /*---------------------------------------------------------------------------
2278 |   Facility      :  libnform
2279 |   Function      :  static int HSC_Horizontal_Line_Forward(FORM* form)
2280 |
2281 |   Description   :  Scroll single-line field forward a line
2282 |
2283 |   Return Values :  E_OK                - success
2284 |                    E_REQUEST_DENIED    - no data ahead
2285 +--------------------------------------------------------------------------*/
2286 static int
2287 HSC_Horizontal_Line_Forward(FORM *form)
2288 {
2289   T((T_CALLED("HSC_Horizontal_Line_Forward(%p)"), (void *)form));
2290   returnCode(HSC_Generic(form, form->current->cols));
2291 }
2292
2293 /*---------------------------------------------------------------------------
2294 |   Facility      :  libnform
2295 |   Function      :  static int HSC_Horizontal_Half_Line_Forward(FORM* form)
2296 |
2297 |   Description   :  Scroll single-line field forward half a line
2298 |
2299 |   Return Values :  E_OK               - success
2300 |                    E_REQUEST_DENIED   - no data ahead
2301 +--------------------------------------------------------------------------*/
2302 static int
2303 HSC_Horizontal_Half_Line_Forward(FORM *form)
2304 {
2305   T((T_CALLED("HSC_Horizontal_Half_Line_Forward(%p)"), (void *)form));
2306   returnCode(HSC_Generic(form, (form->current->cols + 1) / 2));
2307 }
2308
2309 /*---------------------------------------------------------------------------
2310 |   Facility      :  libnform
2311 |   Function      :  static int HSC_Horizontal_Line_Backward(FORM* form)
2312 |
2313 |   Description   :  Scroll single-line field backward a line
2314 |
2315 |   Return Values :  E_OK                - success
2316 |                    E_REQUEST_DENIED    - no data behind
2317 +--------------------------------------------------------------------------*/
2318 static int
2319 HSC_Horizontal_Line_Backward(FORM *form)
2320 {
2321   T((T_CALLED("HSC_Horizontal_Line_Backward(%p)"), (void *)form));
2322   returnCode(HSC_Generic(form, -(form->current->cols)));
2323 }
2324
2325 /*---------------------------------------------------------------------------
2326 |   Facility      :  libnform
2327 |   Function      :  static int HSC_Horizontal_Half_Line_Backward(FORM* form)
2328 |
2329 |   Description   :  Scroll single-line field backward half a line
2330 |
2331 |   Return Values :  E_OK                - success
2332 |                    E_REQUEST_DENIED    - no data behind
2333 +--------------------------------------------------------------------------*/
2334 static int
2335 HSC_Horizontal_Half_Line_Backward(FORM *form)
2336 {
2337   T((T_CALLED("HSC_Horizontal_Half_Line_Backward(%p)"), (void *)form));
2338   returnCode(HSC_Generic(form, -((form->current->cols + 1) / 2)));
2339 }
2340
2341 /*----------------------------------------------------------------------------
2342   End of Horizontal scrolling routines
2343   --------------------------------------------------------------------------*/
2344
2345 /*----------------------------------------------------------------------------
2346   Helper routines for Field Editing
2347   --------------------------------------------------------------------------*/
2348
2349 /*---------------------------------------------------------------------------
2350 |   Facility      :  libnform
2351 |   Function      :  static bool Is_There_Room_For_A_Line(FORM * form)
2352 |
2353 |   Description   :  Check whether or not there is enough room in the
2354 |                    buffer to enter a whole line.
2355 |
2356 |   Return Values :  TRUE   - there is enough space
2357 |                    FALSE  - there is not enough space
2358 +--------------------------------------------------------------------------*/
2359 NCURSES_INLINE static bool
2360 Is_There_Room_For_A_Line(FORM *form)
2361 {
2362   FIELD *field = form->current;
2363   FIELD_CELL *begin_of_last_line, *s;
2364
2365   Synchronize_Buffer(form);
2366   begin_of_last_line = Address_Of_Row_In_Buffer(field, (field->drows - 1));
2367   s = After_End_Of_Data(begin_of_last_line, field->dcols);
2368   return ((s == begin_of_last_line) ? TRUE : FALSE);
2369 }
2370
2371 /*---------------------------------------------------------------------------
2372 |   Facility      :  libnform
2373 |   Function      :  static bool Is_There_Room_For_A_Char_In_Line(FORM * form)
2374 |
2375 |   Description   :  Checks whether or not there is room for a new character
2376 |                    in the current line.
2377 |
2378 |   Return Values :  TRUE    - there is room
2379 |                    FALSE   - there is not enough room (line full)
2380 +--------------------------------------------------------------------------*/
2381 NCURSES_INLINE static bool
2382 Is_There_Room_For_A_Char_In_Line(FORM *form)
2383 {
2384   int last_char_in_line;
2385
2386   wmove(form->w, form->currow, form->current->dcols - 1);
2387   last_char_in_line = (int)(winch(form->w) & A_CHARTEXT);
2388   wmove(form->w, form->currow, form->curcol);
2389   return (((last_char_in_line == form->current->pad) ||
2390            is_blank(last_char_in_line)) ? TRUE : FALSE);
2391 }
2392
2393 #define There_Is_No_Room_For_A_Char_In_Line(f) \
2394   !Is_There_Room_For_A_Char_In_Line(f)
2395
2396 /*---------------------------------------------------------------------------
2397 |   Facility      :  libnform
2398 |   Function      :  static int Insert_String(
2399 |                                             FORM * form,
2400 |                                             int row,
2401 |                                             char *txt,
2402 |                                             int  len )
2403 |
2404 |   Description   :  Insert the 'len' characters beginning at pointer 'txt'
2405 |                    into the 'row' of the 'form'. The insertion occurs
2406 |                    on the beginning of the row, all other characters are
2407 |                    moved to the right. After the text a pad character will
2408 |                    be inserted to separate the text from the rest. If
2409 |                    necessary the insertion moves characters on the next
2410 |                    line to make place for the requested insertion string.
2411 |
2412 |   Return Values :  E_OK              - success
2413 |                    E_REQUEST_DENIED  -
2414 |                    E_SYSTEM_ERROR    - system error
2415 +--------------------------------------------------------------------------*/
2416 static int
2417 Insert_String(FORM *form, int row, FIELD_CELL *txt, int len)
2418 {
2419   FIELD *field = form->current;
2420   FIELD_CELL *bp = Address_Of_Row_In_Buffer(field, row);
2421   int datalen = (int)(After_End_Of_Data(bp, field->dcols) - bp);
2422   int freelen = field->dcols - datalen;
2423   int requiredlen = len + 1;
2424   FIELD_CELL *split;
2425   int result = E_REQUEST_DENIED;
2426
2427   if (freelen >= requiredlen)
2428     {
2429       wmove(form->w, row, 0);
2430       myINSNSTR(form->w, txt, len);
2431       wmove(form->w, row, len);
2432       myINSNSTR(form->w, &myBLANK, 1);
2433       return E_OK;
2434     }
2435   else
2436     {
2437       /* we have to move characters on the next line. If we are on the
2438          last line this may work, if the field is growable */
2439       if ((row == (field->drows - 1)) && Growable(field))
2440         {
2441           if (!Field_Grown(field, 1))
2442             return (E_SYSTEM_ERROR);
2443           /* !!!Side-Effect : might be changed due to growth!!! */
2444           bp = Address_Of_Row_In_Buffer(field, row);
2445         }
2446
2447       if (row < (field->drows - 1))
2448         {
2449           split =
2450             After_Last_Whitespace_Character(bp,
2451                                             (int)(Get_Start_Of_Data(bp
2452                                                                     + field->dcols
2453                                                                     - requiredlen,
2454                                                                     requiredlen)
2455                                                   - bp));
2456           /* split points now to the first character of the portion of the
2457              line that must be moved to the next line */
2458           datalen = (int)(split - bp);  /* + freelen has to stay on this line   */
2459           freelen = field->dcols - (datalen + freelen);         /* for the next line */
2460
2461           if ((result = Insert_String(form, row + 1, split, freelen)) == E_OK)
2462             {
2463               wmove(form->w, row, datalen);
2464               wclrtoeol(form->w);
2465               wmove(form->w, row, 0);
2466               myINSNSTR(form->w, txt, len);
2467               wmove(form->w, row, len);
2468               myINSNSTR(form->w, &myBLANK, 1);
2469               return E_OK;
2470             }
2471         }
2472       return (result);
2473     }
2474 }
2475
2476 /*---------------------------------------------------------------------------
2477 |   Facility      :  libnform
2478 |   Function      :  static int Wrapping_Not_Necessary_Or_Wrapping_Ok(
2479 |                                             FORM * form)
2480 |
2481 |   Description   :  If a character has been entered into a field, it may
2482 |                    be that wrapping has to occur. This routine checks
2483 |                    whether or not wrapping is required and if so, performs
2484 |                    the wrapping.
2485 |
2486 |   Return Values :  E_OK              - no wrapping required or wrapping
2487 |                                        was successful
2488 |                    E_REQUEST_DENIED  -
2489 |                    E_SYSTEM_ERROR    - some system error
2490 +--------------------------------------------------------------------------*/
2491 static int
2492 Wrapping_Not_Necessary_Or_Wrapping_Ok(FORM *form)
2493 {
2494   FIELD *field = form->current;
2495   int result = E_REQUEST_DENIED;
2496   bool Last_Row = ((field->drows - 1) == form->currow);
2497
2498   if ((Field_Has_Option(field, O_WRAP)) &&      /* wrapping wanted     */
2499       (!Single_Line_Field(field)) &&    /* must be multi-line  */
2500       (There_Is_No_Room_For_A_Char_In_Line(form)) &&    /* line is full        */
2501       (!Last_Row || Growable(field)))   /* there are more lines */
2502     {
2503       FIELD_CELL *bp;
2504       FIELD_CELL *split;
2505       int chars_to_be_wrapped;
2506       int chars_to_remain_on_line;
2507
2508       if (Last_Row)
2509         {
2510           /* the above logic already ensures, that in this case the field
2511              is growable */
2512           if (!Field_Grown(field, 1))
2513             return E_SYSTEM_ERROR;
2514         }
2515       bp = Address_Of_Current_Row_In_Buffer(form);
2516       Window_To_Buffer(form, field);
2517       split = After_Last_Whitespace_Character(bp, field->dcols);
2518       /* split points to the first character of the sequence to be brought
2519          on the next line */
2520       chars_to_remain_on_line = (int)(split - bp);
2521       chars_to_be_wrapped = field->dcols - chars_to_remain_on_line;
2522       if (chars_to_remain_on_line > 0)
2523         {
2524           if ((result = Insert_String(form, form->currow + 1, split,
2525                                       chars_to_be_wrapped)) == E_OK)
2526             {
2527               wmove(form->w, form->currow, chars_to_remain_on_line);
2528               wclrtoeol(form->w);
2529               if (form->curcol >= chars_to_remain_on_line)
2530                 {
2531                   form->currow++;
2532                   form->curcol -= chars_to_remain_on_line;
2533                 }
2534               return E_OK;
2535             }
2536         }
2537       else
2538         return E_OK;
2539       if (result != E_OK)
2540         {
2541           DeleteChar(form);
2542           Window_To_Buffer(form, field);
2543           result = E_REQUEST_DENIED;
2544         }
2545     }
2546   else
2547     result = E_OK;              /* wrapping was not necessary */
2548   return (result);
2549 }
2550
2551 /*----------------------------------------------------------------------------
2552   Field Editing routines
2553   --------------------------------------------------------------------------*/
2554
2555 /*---------------------------------------------------------------------------
2556 |   Facility      :  libnform
2557 |   Function      :  static int Field_Editing(
2558 |                                    int (* const fct) (FORM *),
2559 |                                    FORM * form)
2560 |
2561 |   Description   :  Generic routine for field editing requests. The driver
2562 |                    routines are only called for editable fields, the
2563 |                    _WINDOW_MODIFIED flag is set if editing occurred.
2564 |                    This is somewhat special due to the overload semantics
2565 |                    of the NEW_LINE and DEL_PREV requests.
2566 |
2567 |   Return Values :  Error code from low level drivers.
2568 +--------------------------------------------------------------------------*/
2569 static int
2570 Field_Editing(int (*const fct) (FORM *), FORM *form)
2571 {
2572   int res = E_REQUEST_DENIED;
2573
2574   /* We have to deal here with the specific case of the overloaded
2575      behavior of New_Line and Delete_Previous requests.
2576      They may end up in navigational requests if we are on the first
2577      character in a field. But navigation is also allowed on non-
2578      editable fields.
2579    */
2580   if ((fct == FE_Delete_Previous) &&
2581       ((unsigned)form->opts & O_BS_OVERLOAD) &&
2582       First_Position_In_Current_Field(form))
2583     {
2584       res = Inter_Field_Navigation(FN_Previous_Field, form);
2585     }
2586   else
2587     {
2588       if (fct == FE_New_Line)
2589         {
2590           if (((unsigned)form->opts & O_NL_OVERLOAD) &&
2591               First_Position_In_Current_Field(form))
2592             {
2593               res = Inter_Field_Navigation(FN_Next_Field, form);
2594             }
2595           else
2596             /* FE_New_Line deals itself with the _WINDOW_MODIFIED flag */
2597             res = fct(form);
2598         }
2599       else
2600         {
2601           /* From now on, everything must be editable */
2602           if ((unsigned)form->current->opts & O_EDIT)
2603             {
2604               res = fct(form);
2605               if (res == E_OK)
2606                 SetStatus(form, _WINDOW_MODIFIED);
2607             }
2608         }
2609     }
2610   return res;
2611 }
2612
2613 /*---------------------------------------------------------------------------
2614 |   Facility      :  libnform
2615 |   Function      :  static int FE_New_Line(FORM * form)
2616 |
2617 |   Description   :  Perform a new line request. This is rather complex
2618 |                    compared to other routines in this code due to the
2619 |                    rather difficult to understand description in the
2620 |                    manuals.
2621 |
2622 |   Return Values :  E_OK               - success
2623 |                    E_REQUEST_DENIED   - new line not allowed
2624 |                    E_SYSTEM_ERROR     - system error
2625 +--------------------------------------------------------------------------*/
2626 static int
2627 FE_New_Line(FORM *form)
2628 {
2629   FIELD *field = form->current;
2630   FIELD_CELL *bp, *t;
2631   bool Last_Row = ((field->drows - 1) == form->currow);
2632
2633   T((T_CALLED("FE_New_Line(%p)"), (void *)form));
2634   if (form->status & _OVLMODE)
2635     {
2636       if (Last_Row &&
2637           (!(Growable(field) && !Single_Line_Field(field))))
2638         {
2639           if (!((unsigned)form->opts & O_NL_OVERLOAD))
2640             returnCode(E_REQUEST_DENIED);
2641           wmove(form->w, form->currow, form->curcol);
2642           wclrtoeol(form->w);
2643           /* we have to set this here, although it is also
2644              handled in the generic routine. The reason is,
2645              that FN_Next_Field may fail, but the form is
2646              definitively changed */
2647           SetStatus(form, _WINDOW_MODIFIED);
2648           returnCode(Inter_Field_Navigation(FN_Next_Field, form));
2649         }
2650       else
2651         {
2652           if (Last_Row && !Field_Grown(field, 1))
2653             {
2654               /* N.B.: due to the logic in the 'if', LastRow==TRUE
2655                  means here that the field is growable and not
2656                  a single-line field */
2657               returnCode(E_SYSTEM_ERROR);
2658             }
2659           wmove(form->w, form->currow, form->curcol);
2660           wclrtoeol(form->w);
2661           form->currow++;
2662           form->curcol = 0;
2663           SetStatus(form, _WINDOW_MODIFIED);
2664           returnCode(E_OK);
2665         }
2666     }
2667   else
2668     {
2669       /* Insert Mode */
2670       if (Last_Row &&
2671           !(Growable(field) && !Single_Line_Field(field)))
2672         {
2673           if (!((unsigned)form->opts & O_NL_OVERLOAD))
2674             returnCode(E_REQUEST_DENIED);
2675           returnCode(Inter_Field_Navigation(FN_Next_Field, form));
2676         }
2677       else
2678         {
2679           bool May_Do_It = !Last_Row && Is_There_Room_For_A_Line(form);
2680
2681           if (!(May_Do_It || Growable(field)))
2682             returnCode(E_REQUEST_DENIED);
2683           if (!May_Do_It && !Field_Grown(field, 1))
2684             returnCode(E_SYSTEM_ERROR);
2685
2686           bp = Address_Of_Current_Position_In_Buffer(form);
2687           t = After_End_Of_Data(bp, field->dcols - form->curcol);
2688           wmove(form->w, form->currow, form->curcol);
2689           wclrtoeol(form->w);
2690           form->currow++;
2691           form->curcol = 0;
2692           wmove(form->w, form->currow, form->curcol);
2693           winsertln(form->w);
2694           myADDNSTR(form->w, bp, (int)(t - bp));
2695           SetStatus(form, _WINDOW_MODIFIED);
2696           returnCode(E_OK);
2697         }
2698     }
2699 }
2700
2701 /*---------------------------------------------------------------------------
2702 |   Facility      :  libnform
2703 |   Function      :  static int FE_Insert_Character(FORM * form)
2704 |
2705 |   Description   :  Insert blank character at the cursor position
2706 |
2707 |   Return Values :  E_OK
2708 |                    E_REQUEST_DENIED
2709 +--------------------------------------------------------------------------*/
2710 static int
2711 FE_Insert_Character(FORM *form)
2712 {
2713   FIELD *field = form->current;
2714   int result = E_REQUEST_DENIED;
2715
2716   T((T_CALLED("FE_Insert_Character(%p)"), (void *)form));
2717   if (Check_Char(form, field, field->type, (int)C_BLANK,
2718                  (TypeArgument *)(field->arg)))
2719     {
2720       bool There_Is_Room = Is_There_Room_For_A_Char_In_Line(form);
2721
2722       if (There_Is_Room ||
2723           ((Single_Line_Field(field) && Growable(field))))
2724         {
2725           if (!There_Is_Room && !Field_Grown(field, 1))
2726             result = E_SYSTEM_ERROR;
2727           else
2728             {
2729               winsch(form->w, (chtype)C_BLANK);
2730               result = Wrapping_Not_Necessary_Or_Wrapping_Ok(form);
2731             }
2732         }
2733     }
2734   returnCode(result);
2735 }
2736
2737 /*---------------------------------------------------------------------------
2738 |   Facility      :  libnform
2739 |   Function      :  static int FE_Insert_Line(FORM * form)
2740 |
2741 |   Description   :  Insert a blank line at the cursor position
2742 |
2743 |   Return Values :  E_OK               - success
2744 |                    E_REQUEST_DENIED   - line can not be inserted
2745 +--------------------------------------------------------------------------*/
2746 static int
2747 FE_Insert_Line(FORM *form)
2748 {
2749   FIELD *field = form->current;
2750   int result = E_REQUEST_DENIED;
2751
2752   T((T_CALLED("FE_Insert_Line(%p)"), (void *)form));
2753   if (Check_Char(form, field,
2754                  field->type, (int)C_BLANK, (TypeArgument *)(field->arg)))
2755     {
2756       bool Maybe_Done = (form->currow != (field->drows - 1)) &&
2757       Is_There_Room_For_A_Line(form);
2758
2759       if (!Single_Line_Field(field) &&
2760           (Maybe_Done || Growable(field)))
2761         {
2762           if (!Maybe_Done && !Field_Grown(field, 1))
2763             result = E_SYSTEM_ERROR;
2764           else
2765             {
2766               form->curcol = 0;
2767               winsertln(form->w);
2768               result = E_OK;
2769             }
2770         }
2771     }
2772   returnCode(result);
2773 }
2774
2775 /*---------------------------------------------------------------------------
2776 |   Facility      :  libnform
2777 |   Function      :  static int FE_Delete_Character(FORM * form)
2778 |
2779 |   Description   :  Delete character at the cursor position
2780 |
2781 |   Return Values :  E_OK    - success
2782 +--------------------------------------------------------------------------*/
2783 static int
2784 FE_Delete_Character(FORM *form)
2785 {
2786   T((T_CALLED("FE_Delete_Character(%p)"), (void *)form));
2787   DeleteChar(form);
2788   returnCode(E_OK);
2789 }
2790
2791 /*---------------------------------------------------------------------------
2792 |   Facility      :  libnform
2793 |   Function      :  static int FE_Delete_Previous(FORM * form)
2794 |
2795 |   Description   :  Delete character before cursor. Again this is a rather
2796 |                    difficult piece compared to others due to the overloading
2797 |                    semantics of backspace.
2798 |                    N.B.: The case of overloaded BS on first field position
2799 |                          is already handled in the generic routine.
2800 |
2801 |   Return Values :  E_OK                - success
2802 |                    E_REQUEST_DENIED    - Character can't be deleted
2803 +--------------------------------------------------------------------------*/
2804 static int
2805 FE_Delete_Previous(FORM *form)
2806 {
2807   FIELD *field = form->current;
2808
2809   T((T_CALLED("FE_Delete_Previous(%p)"), (void *)form));
2810   if (First_Position_In_Current_Field(form))
2811     returnCode(E_REQUEST_DENIED);
2812
2813   if ((--(form->curcol)) < 0)
2814     {
2815       FIELD_CELL *this_line, *prev_line, *prev_end, *this_end;
2816       int this_row = form->currow;
2817
2818       form->curcol++;
2819       if (form->status & _OVLMODE)
2820         returnCode(E_REQUEST_DENIED);
2821
2822       prev_line = Address_Of_Row_In_Buffer(field, (form->currow - 1));
2823       this_line = Address_Of_Row_In_Buffer(field, (form->currow));
2824       Synchronize_Buffer(form);
2825       prev_end = After_End_Of_Data(prev_line, field->dcols);
2826       this_end = After_End_Of_Data(this_line, field->dcols);
2827       if ((int)(this_end - this_line) >
2828           (field->cols - (int)(prev_end - prev_line)))
2829         returnCode(E_REQUEST_DENIED);
2830       wmove(form->w, form->currow, form->curcol);
2831       wdeleteln(form->w);
2832       Adjust_Cursor_Position(form, prev_end);
2833       /*
2834        * If we did not really move to the previous line, help the user a
2835        * little.  It is however a little inconsistent.  Normally, when
2836        * backspacing around the point where text wraps to a new line in a
2837        * multi-line form, we absorb one keystroke for the wrapping point.  That
2838        * is consistent with SVr4 forms.  However, SVr4 does not allow typing
2839        * into the last column of the field, and requires the user to enter a
2840        * newline to move to the next line.  Therefore it can consistently eat
2841        * that keystroke.  Since ncurses allows the last column, it wraps
2842        * automatically (given the proper options).  But we cannot eat the
2843        * keystroke to back over the wrapping point, since that would put the
2844        * cursor past the end of the form field.  In this case, just delete the
2845        * character at the end of the field.
2846        */
2847       if (form->currow == this_row && this_row > 0)
2848         {
2849           form->currow -= 1;
2850           form->curcol = field->dcols - 1;
2851           DeleteChar(form);
2852         }
2853       else
2854         {
2855           wmove(form->w, form->currow, form->curcol);
2856           myADDNSTR(form->w, this_line, (int)(this_end - this_line));
2857         }
2858     }
2859   else
2860     {
2861       DeleteChar(form);
2862     }
2863   returnCode(E_OK);
2864 }
2865
2866 /*---------------------------------------------------------------------------
2867 |   Facility      :  libnform
2868 |   Function      :  static int FE_Delete_Line(FORM * form)
2869 |
2870 |   Description   :  Delete line at cursor position.
2871 |
2872 |   Return Values :  E_OK  - success
2873 +--------------------------------------------------------------------------*/
2874 static int
2875 FE_Delete_Line(FORM *form)
2876 {
2877   T((T_CALLED("FE_Delete_Line(%p)"), (void *)form));
2878   form->curcol = 0;
2879   wdeleteln(form->w);
2880   returnCode(E_OK);
2881 }
2882
2883 /*---------------------------------------------------------------------------
2884 |   Facility      :  libnform
2885 |   Function      :  static int FE_Delete_Word(FORM * form)
2886 |
2887 |   Description   :  Delete word at cursor position
2888 |
2889 |   Return Values :  E_OK               - success
2890 |                    E_REQUEST_DENIED   - failure
2891 +--------------------------------------------------------------------------*/
2892 static int
2893 FE_Delete_Word(FORM *form)
2894 {
2895   FIELD *field = form->current;
2896   FIELD_CELL *bp = Address_Of_Current_Row_In_Buffer(form);
2897   FIELD_CELL *ep = bp + field->dcols;
2898   FIELD_CELL *cp = bp + form->curcol;
2899   FIELD_CELL *s;
2900
2901   T((T_CALLED("FE_Delete_Word(%p)"), (void *)form));
2902   Synchronize_Buffer(form);
2903   if (ISBLANK(*cp))
2904     returnCode(E_REQUEST_DENIED);       /* not in word */
2905
2906   /* move cursor to begin of word and erase to end of screen-line */
2907   Adjust_Cursor_Position(form,
2908                          After_Last_Whitespace_Character(bp, form->curcol));
2909   wmove(form->w, form->currow, form->curcol);
2910   wclrtoeol(form->w);
2911
2912   /* skip over word in buffer */
2913   s = Get_First_Whitespace_Character(cp, (int)(ep - cp));
2914   /* to begin of next word    */
2915   s = Get_Start_Of_Data(s, (int)(ep - s));
2916   if ((s != cp) && !ISBLANK(*s))
2917     {
2918       /* copy remaining line to window */
2919       myADDNSTR(form->w, s, (int)(s - After_End_Of_Data(s, (int)(ep - s))));
2920     }
2921   returnCode(E_OK);
2922 }
2923
2924 /*---------------------------------------------------------------------------
2925 |   Facility      :  libnform
2926 |   Function      :  static int FE_Clear_To_End_Of_Line(FORM * form)
2927 |
2928 |   Description   :  Clear to end of current line.
2929 |
2930 |   Return Values :  E_OK   - success
2931 +--------------------------------------------------------------------------*/
2932 static int
2933 FE_Clear_To_End_Of_Line(FORM *form)
2934 {
2935   T((T_CALLED("FE_Clear_To_End_Of_Line(%p)"), (void *)form));
2936   wmove(form->w, form->currow, form->curcol);
2937   wclrtoeol(form->w);
2938   returnCode(E_OK);
2939 }
2940
2941 /*---------------------------------------------------------------------------
2942 |   Facility      :  libnform
2943 |   Function      :  static int FE_Clear_To_End_Of_Field(FORM * form)
2944 |
2945 |   Description   :  Clear to end of field.
2946 |
2947 |   Return Values :  E_OK   - success
2948 +--------------------------------------------------------------------------*/
2949 static int
2950 FE_Clear_To_End_Of_Field(FORM *form)
2951 {
2952   T((T_CALLED("FE_Clear_To_End_Of_Field(%p)"), (void *)form));
2953   wmove(form->w, form->currow, form->curcol);
2954   wclrtobot(form->w);
2955   returnCode(E_OK);
2956 }
2957
2958 /*---------------------------------------------------------------------------
2959 |   Facility      :  libnform
2960 |   Function      :  static int FE_Clear_Field(FORM * form)
2961 |
2962 |   Description   :  Clear entire field.
2963 |
2964 |   Return Values :  E_OK   - success
2965 +--------------------------------------------------------------------------*/
2966 static int
2967 FE_Clear_Field(FORM *form)
2968 {
2969   T((T_CALLED("FE_Clear_Field(%p)"), (void *)form));
2970   form->currow = form->curcol = 0;
2971   werase(form->w);
2972   returnCode(E_OK);
2973 }
2974 /*----------------------------------------------------------------------------
2975   END of Field Editing routines
2976   --------------------------------------------------------------------------*/
2977
2978 /*----------------------------------------------------------------------------
2979   Edit Mode routines
2980   --------------------------------------------------------------------------*/
2981
2982 /*---------------------------------------------------------------------------
2983 |   Facility      :  libnform
2984 |   Function      :  static int EM_Overlay_Mode(FORM * form)
2985 |
2986 |   Description   :  Switch to overlay mode.
2987 |
2988 |   Return Values :  E_OK   - success
2989 +--------------------------------------------------------------------------*/
2990 static int
2991 EM_Overlay_Mode(FORM *form)
2992 {
2993   T((T_CALLED("EM_Overlay_Mode(%p)"), (void *)form));
2994   SetStatus(form, _OVLMODE);
2995   returnCode(E_OK);
2996 }
2997
2998 /*---------------------------------------------------------------------------
2999 |   Facility      :  libnform
3000 |   Function      :  static int EM_Insert_Mode(FORM * form)
3001 |
3002 |   Description   :  Switch to insert mode
3003 |
3004 |   Return Values :  E_OK   - success
3005 +--------------------------------------------------------------------------*/
3006 static int
3007 EM_Insert_Mode(FORM *form)
3008 {
3009   T((T_CALLED("EM_Insert_Mode(%p)"), (void *)form));
3010   ClrStatus(form, _OVLMODE);
3011   returnCode(E_OK);
3012 }
3013
3014 /*----------------------------------------------------------------------------
3015   END of Edit Mode routines
3016   --------------------------------------------------------------------------*/
3017
3018 /*----------------------------------------------------------------------------
3019   Helper routines for Choice Requests
3020   --------------------------------------------------------------------------*/
3021
3022 /*---------------------------------------------------------------------------
3023 |   Facility      :  libnform
3024 |   Function      :  static bool Next_Choice(FORM * form,
3025 |                                            FIELDTYPE * typ,
3026 |                                            FIELD * field,
3027 |                                            TypeArgument *argp)
3028 |
3029 |   Description   :  Get the next field choice. For linked types this is
3030 |                    done recursively.
3031 |
3032 |   Return Values :  TRUE    - next choice successfully retrieved
3033 |                    FALSE   - couldn't retrieve next choice
3034 +--------------------------------------------------------------------------*/
3035 static bool
3036 Next_Choice(FORM *form, FIELDTYPE *typ, FIELD *field, TypeArgument *argp)
3037 {
3038   if (!typ || !(typ->status & _HAS_CHOICE))
3039     return FALSE;
3040
3041   if (typ->status & _LINKED_TYPE)
3042     {
3043       assert(argp);
3044       return (
3045                Next_Choice(form, typ->left, field, argp->left) ||
3046                Next_Choice(form, typ->right, field, argp->right));
3047     }
3048   else
3049     {
3050 #if NCURSES_INTEROP_FUNCS
3051       assert(typ->enum_next.onext);
3052       if (typ->status & _GENERIC)
3053         return typ->enum_next.gnext(form, field, (void *)argp);
3054       else
3055         return typ->enum_next.onext(field, (void *)argp);
3056 #else
3057       assert(typ->next);
3058       return typ->next(field, (void *)argp);
3059 #endif
3060     }
3061 }
3062
3063 /*---------------------------------------------------------------------------
3064 |   Facility      :  libnform
3065 |   Function      :  static bool Previous_Choice(FORM * form,
3066 |                                                FIELDTYPE * typ,
3067 |                                                FIELD * field,
3068 |                                                TypeArgument *argp)
3069 |
3070 |   Description   :  Get the previous field choice. For linked types this
3071 |                    is done recursively.
3072 |
3073 |   Return Values :  TRUE    - previous choice successfully retrieved
3074 |                    FALSE   - couldn't retrieve previous choice
3075 +--------------------------------------------------------------------------*/
3076 static bool
3077 Previous_Choice(FORM *form, FIELDTYPE *typ, FIELD *field, TypeArgument *argp)
3078 {
3079   if (!typ || !(typ->status & _HAS_CHOICE))
3080     return FALSE;
3081
3082   if (typ->status & _LINKED_TYPE)
3083     {
3084       assert(argp);
3085       return (
3086                Previous_Choice(form, typ->left, field, argp->left) ||
3087                Previous_Choice(form, typ->right, field, argp->right));
3088     }
3089   else
3090     {
3091 #if NCURSES_INTEROP_FUNCS
3092       assert(typ->enum_prev.oprev);
3093       if (typ->status & _GENERIC)
3094         return typ->enum_prev.gprev(form, field, (void *)argp);
3095       else
3096         return typ->enum_prev.oprev(field, (void *)argp);
3097 #else
3098       assert(typ->prev);
3099       return typ->prev(field, (void *)argp);
3100 #endif
3101     }
3102 }
3103 /*----------------------------------------------------------------------------
3104   End of Helper routines for Choice Requests
3105   --------------------------------------------------------------------------*/
3106
3107 /*----------------------------------------------------------------------------
3108   Routines for Choice Requests
3109   --------------------------------------------------------------------------*/
3110
3111 /*---------------------------------------------------------------------------
3112 |   Facility      :  libnform
3113 |   Function      :  static int CR_Next_Choice(FORM * form)
3114 |
3115 |   Description   :  Get the next field choice.
3116 |
3117 |   Return Values :  E_OK              - success
3118 |                    E_REQUEST_DENIED  - next choice couldn't be retrieved
3119 +--------------------------------------------------------------------------*/
3120 static int
3121 CR_Next_Choice(FORM *form)
3122 {
3123   FIELD *field = form->current;
3124
3125   T((T_CALLED("CR_Next_Choice(%p)"), (void *)form));
3126   Synchronize_Buffer(form);
3127   returnCode((Next_Choice(form, field->type, field, (TypeArgument *)(field->arg)))
3128              ? E_OK
3129              : E_REQUEST_DENIED);
3130 }
3131
3132 /*---------------------------------------------------------------------------
3133 |   Facility      :  libnform
3134 |   Function      :  static int CR_Previous_Choice(FORM * form)
3135 |
3136 |   Description   :  Get the previous field choice.
3137 |
3138 |   Return Values :  E_OK              - success
3139 |                    E_REQUEST_DENIED  - prev. choice couldn't be retrieved
3140 +--------------------------------------------------------------------------*/
3141 static int
3142 CR_Previous_Choice(FORM *form)
3143 {
3144   FIELD *field = form->current;
3145
3146   T((T_CALLED("CR_Previous_Choice(%p)"), (void *)form));
3147   Synchronize_Buffer(form);
3148   returnCode((Previous_Choice(form, field->type, field, (TypeArgument *)(field->arg)))
3149              ? E_OK
3150              : E_REQUEST_DENIED);
3151 }
3152 /*----------------------------------------------------------------------------
3153   End of Routines for Choice Requests
3154   --------------------------------------------------------------------------*/
3155
3156 /*----------------------------------------------------------------------------
3157   Helper routines for Field Validations.
3158   --------------------------------------------------------------------------*/
3159
3160 /*---------------------------------------------------------------------------
3161 |   Facility      :  libnform
3162 |   Function      :  static bool Check_Field(FORM* form,
3163 |                                            FIELDTYPE * typ,
3164 |                                            FIELD * field,
3165 |                                            TypeArgument * argp)
3166 |
3167 |   Description   :  Check the field according to its fieldtype and its
3168 |                    actual arguments. For linked fieldtypes this is done
3169 |                    recursively.
3170 |
3171 |   Return Values :  TRUE       - field is valid
3172 |                    FALSE      - field is invalid.
3173 +--------------------------------------------------------------------------*/
3174 static bool
3175 Check_Field(FORM *form, FIELDTYPE *typ, FIELD *field, TypeArgument *argp)
3176 {
3177   if (typ)
3178     {
3179       if (Field_Has_Option(field, O_NULLOK))
3180         {
3181           FIELD_CELL *bp = field->buf;
3182
3183           assert(bp);
3184           while (ISBLANK(*bp))
3185             {
3186               bp++;
3187             }
3188           if (CharOf(*bp) == 0)
3189             return TRUE;
3190         }
3191
3192       if (typ->status & _LINKED_TYPE)
3193         {
3194           assert(argp);
3195           return (
3196                    Check_Field(form, typ->left, field, argp->left) ||
3197                    Check_Field(form, typ->right, field, argp->right));
3198         }
3199       else
3200         {
3201 #if NCURSES_INTEROP_FUNCS
3202           if (typ->fieldcheck.ofcheck)
3203             {
3204               if (typ->status & _GENERIC)
3205                 return typ->fieldcheck.gfcheck(form, field, (void *)argp);
3206               else
3207                 return typ->fieldcheck.ofcheck(field, (void *)argp);
3208             }
3209 #else
3210           if (typ->fcheck)
3211             return typ->fcheck(field, (void *)argp);
3212 #endif
3213         }
3214     }
3215   return TRUE;
3216 }
3217
3218 /*---------------------------------------------------------------------------
3219 |   Facility      :  libnform
3220 |   Function      :  bool _nc_Internal_Validation(FORM * form )
3221 |
3222 |   Description   :  Validate the current field of the form.
3223 |
3224 |   Return Values :  TRUE  - field is valid
3225 |                    FALSE - field is invalid
3226 +--------------------------------------------------------------------------*/
3227 NCURSES_EXPORT(bool)
3228 _nc_Internal_Validation(FORM *form)
3229 {
3230   FIELD *field;
3231
3232   field = form->current;
3233
3234   Synchronize_Buffer(form);
3235   if ((form->status & _FCHECK_REQUIRED) ||
3236       (!(Field_Has_Option(field, O_PASSOK))))
3237     {
3238       if (!Check_Field(form, field->type, field, (TypeArgument *)(field->arg)))
3239         return FALSE;
3240       ClrStatus(form, _FCHECK_REQUIRED);
3241       SetStatus(field, _CHANGED);
3242       Synchronize_Linked_Fields(field);
3243     }
3244   return TRUE;
3245 }
3246 /*----------------------------------------------------------------------------
3247   End of Helper routines for Field Validations.
3248   --------------------------------------------------------------------------*/
3249
3250 /*----------------------------------------------------------------------------
3251   Routines for Field Validation.
3252   --------------------------------------------------------------------------*/
3253
3254 /*---------------------------------------------------------------------------
3255 |   Facility      :  libnform
3256 |   Function      :  static int FV_Validation(FORM * form)
3257 |
3258 |   Description   :  Validate the current field of the form.
3259 |
3260 |   Return Values :  E_OK             - field valid
3261 |                    E_INVALID_FIELD  - field not valid
3262 +--------------------------------------------------------------------------*/
3263 static int
3264 FV_Validation(FORM *form)
3265 {
3266   T((T_CALLED("FV_Validation(%p)"), (void *)form));
3267   if (_nc_Internal_Validation(form))
3268     returnCode(E_OK);
3269   else
3270     returnCode(E_INVALID_FIELD);
3271 }
3272 /*----------------------------------------------------------------------------
3273   End of routines for Field Validation.
3274   --------------------------------------------------------------------------*/
3275
3276 /*----------------------------------------------------------------------------
3277   Helper routines for Inter-Field Navigation
3278   --------------------------------------------------------------------------*/
3279
3280 /*---------------------------------------------------------------------------
3281 |   Facility      :  libnform
3282 |   Function      :  static FIELD *Next_Field_On_Page(FIELD * field)
3283 |
3284 |   Description   :  Get the next field after the given field on the current
3285 |                    page. The order of fields is the one defined by the
3286 |                    fields array. Only visible and active fields are
3287 |                    counted.
3288 |
3289 |   Return Values :  Pointer to the next field.
3290 +--------------------------------------------------------------------------*/
3291 NCURSES_INLINE static FIELD *
3292 Next_Field_On_Page(FIELD *field)
3293 {
3294   FORM *form = field->form;
3295   FIELD **field_on_page = &form->field[field->index];
3296   FIELD **first_on_page = &form->field[form->page[form->curpage].pmin];
3297   FIELD **last_on_page = &form->field[form->page[form->curpage].pmax];
3298
3299   do
3300     {
3301       field_on_page =
3302         (field_on_page == last_on_page) ? first_on_page : field_on_page + 1;
3303       if (Field_Is_Selectable(*field_on_page))
3304         break;
3305     }
3306   while (field != (*field_on_page));
3307   return (*field_on_page);
3308 }
3309
3310 /*---------------------------------------------------------------------------
3311 |   Facility      :  libnform
3312 |   Function      :  FIELD* _nc_First_Active_Field(FORM * form)
3313 |
3314 |   Description   :  Get the first active field on the current page,
3315 |                    if there are such. If there are none, get the first
3316 |                    visible field on the page. If there are also none,
3317 |                    we return the first field on page and hope the best.
3318 |
3319 |   Return Values :  Pointer to calculated field.
3320 +--------------------------------------------------------------------------*/
3321 NCURSES_EXPORT(FIELD *)
3322 _nc_First_Active_Field(FORM *form)
3323 {
3324   FIELD **last_on_page = &form->field[form->page[form->curpage].pmax];
3325   FIELD *proposed = Next_Field_On_Page(*last_on_page);
3326
3327   if (proposed == *last_on_page)
3328     {
3329       /* there might be the special situation, where there is no
3330          active and visible field on the current page. We then select
3331          the first visible field on this readonly page
3332        */
3333       if (Field_Is_Not_Selectable(proposed))
3334         {
3335           FIELD **field = &form->field[proposed->index];
3336           FIELD **first = &form->field[form->page[form->curpage].pmin];
3337
3338           do
3339             {
3340               field = (field == last_on_page) ? first : field + 1;
3341               if (Field_Has_Option(*field, O_VISIBLE))
3342                 break;
3343             }
3344           while (proposed != (*field));
3345
3346           proposed = *field;
3347
3348           if ((proposed == *last_on_page) &&
3349               !((unsigned)proposed->opts & O_VISIBLE))
3350             {
3351               /* This means, there is also no visible field on the page.
3352                  So we propose the first one and hope the very best...
3353                  Some very clever user has designed a readonly and invisible
3354                  page on this form.
3355                */
3356               proposed = *first;
3357             }
3358         }
3359     }
3360   return (proposed);
3361 }
3362
3363 /*---------------------------------------------------------------------------
3364 |   Facility      :  libnform
3365 |   Function      :  static FIELD *Previous_Field_On_Page(FIELD * field)
3366 |
3367 |   Description   :  Get the previous field before the given field on the
3368 |                    current page. The order of fields is the one defined by
3369 |                    the fields array. Only visible and active fields are
3370 |                    counted.
3371 |
3372 |   Return Values :  Pointer to the previous field.
3373 +--------------------------------------------------------------------------*/
3374 NCURSES_INLINE static FIELD *
3375 Previous_Field_On_Page(FIELD *field)
3376 {
3377   FORM *form = field->form;
3378   FIELD **field_on_page = &form->field[field->index];
3379   FIELD **first_on_page = &form->field[form->page[form->curpage].pmin];
3380   FIELD **last_on_page = &form->field[form->page[form->curpage].pmax];
3381
3382   do
3383     {
3384       field_on_page =
3385         (field_on_page == first_on_page) ? last_on_page : field_on_page - 1;
3386       if (Field_Is_Selectable(*field_on_page))
3387         break;
3388     }
3389   while (field != (*field_on_page));
3390
3391   return (*field_on_page);
3392 }
3393
3394 /*---------------------------------------------------------------------------
3395 |   Facility      :  libnform
3396 |   Function      :  static FIELD *Sorted_Next_Field(FIELD * field)
3397 |
3398 |   Description   :  Get the next field after the given field on the current
3399 |                    page. The order of fields is the one defined by the
3400 |                    (row,column) geometry, rows are major.
3401 |
3402 |   Return Values :  Pointer to the next field.
3403 +--------------------------------------------------------------------------*/
3404 NCURSES_INLINE static FIELD *
3405 Sorted_Next_Field(FIELD *field)
3406 {
3407   FIELD *field_on_page = field;
3408
3409   do
3410     {
3411       field_on_page = field_on_page->snext;
3412       if (Field_Is_Selectable(field_on_page))
3413         break;
3414     }
3415   while (field_on_page != field);
3416
3417   return (field_on_page);
3418 }
3419
3420 /*---------------------------------------------------------------------------
3421 |   Facility      :  libnform
3422 |   Function      :  static FIELD *Sorted_Previous_Field(FIELD * field)
3423 |
3424 |   Description   :  Get the previous field before the given field on the
3425 |                    current page. The order of fields is the one defined
3426 |                    by the (row,column) geometry, rows are major.
3427 |
3428 |   Return Values :  Pointer to the previous field.
3429 +--------------------------------------------------------------------------*/
3430 NCURSES_INLINE static FIELD *
3431 Sorted_Previous_Field(FIELD *field)
3432 {
3433   FIELD *field_on_page = field;
3434
3435   do
3436     {
3437       field_on_page = field_on_page->sprev;
3438       if (Field_Is_Selectable(field_on_page))
3439         break;
3440     }
3441   while (field_on_page != field);
3442
3443   return (field_on_page);
3444 }
3445
3446 /*---------------------------------------------------------------------------
3447 |   Facility      :  libnform
3448 |   Function      :  static FIELD *Left_Neighbor_Field(FIELD * field)
3449 |
3450 |   Description   :  Get the left neighbor of the field on the same line
3451 |                    and the same page. Cycles through the line.
3452 |
3453 |   Return Values :  Pointer to left neighbor field.
3454 +--------------------------------------------------------------------------*/
3455 NCURSES_INLINE static FIELD *
3456 Left_Neighbor_Field(FIELD *field)
3457 {
3458   FIELD *field_on_page = field;
3459
3460   /* For a field that has really a left neighbor, the while clause
3461      immediately fails and the loop is left, positioned at the right
3462      neighbor. Otherwise we cycle backwards through the sorted field list
3463      until we enter the same line (from the right end).
3464    */
3465   do
3466     {
3467       field_on_page = Sorted_Previous_Field(field_on_page);
3468     }
3469   while (field_on_page->frow != field->frow);
3470
3471   return (field_on_page);
3472 }
3473
3474 /*---------------------------------------------------------------------------
3475 |   Facility      :  libnform
3476 |   Function      :  static FIELD *Right_Neighbor_Field(FIELD * field)
3477 |
3478 |   Description   :  Get the right neighbor of the field on the same line
3479 |                    and the same page.
3480 |
3481 |   Return Values :  Pointer to right neighbor field.
3482 +--------------------------------------------------------------------------*/
3483 NCURSES_INLINE static FIELD *
3484 Right_Neighbor_Field(FIELD *field)
3485 {
3486   FIELD *field_on_page = field;
3487
3488   /* See the comments on Left_Neighbor_Field to understand how it works */
3489   do
3490     {
3491       field_on_page = Sorted_Next_Field(field_on_page);
3492     }
3493   while (field_on_page->frow != field->frow);
3494
3495   return (field_on_page);
3496 }
3497
3498 /*---------------------------------------------------------------------------
3499 |   Facility      :  libnform
3500 |   Function      :  static FIELD *Upper_Neighbor_Field(FIELD * field)
3501 |
3502 |   Description   :  Because of the row-major nature of sorting the fields,
3503 |                    it is more difficult to define whats the upper neighbor
3504 |                    field really means. We define that it must be on a
3505 |                    'previous' line (cyclic order!) and is the rightmost
3506 |                    field laying on the left side of the given field. If
3507 |                    this set is empty, we take the first field on the line.
3508 |
3509 |   Return Values :  Pointer to the upper neighbor field.
3510 +--------------------------------------------------------------------------*/
3511 static FIELD *
3512 Upper_Neighbor_Field(FIELD *field)
3513 {
3514   FIELD *field_on_page = field;
3515   int frow = field->frow;
3516   int fcol = field->fcol;
3517
3518   /* Walk back to the 'previous' line. The second term in the while clause
3519      just guarantees that we stop if we cycled through the line because
3520      there might be no 'previous' line if the page has just one line.
3521    */
3522   do
3523     {
3524       field_on_page = Sorted_Previous_Field(field_on_page);
3525     }
3526   while (field_on_page->frow == frow && field_on_page->fcol != fcol);
3527
3528   if (field_on_page->frow != frow)
3529     {
3530       /* We really found a 'previous' line. We are positioned at the
3531          rightmost field on this line */
3532       frow = field_on_page->frow;
3533
3534       /* We walk to the left as long as we are really right of the
3535          field. */
3536       while (field_on_page->frow == frow && field_on_page->fcol > fcol)
3537         field_on_page = Sorted_Previous_Field(field_on_page);
3538
3539       /* If we wrapped, just go to the right which is the first field on
3540          the row */
3541       if (field_on_page->frow != frow)
3542         field_on_page = Sorted_Next_Field(field_on_page);
3543     }
3544
3545   return (field_on_page);
3546 }
3547
3548 /*---------------------------------------------------------------------------
3549 |   Facility      :  libnform
3550 |   Function      :  static FIELD *Down_Neighbor_Field(FIELD * field)
3551 |
3552 |   Description   :  Because of the row-major nature of sorting the fields,
3553 |                    its more difficult to define whats the down neighbor
3554 |                    field really means. We define that it must be on a
3555 |                    'next' line (cyclic order!) and is the leftmost
3556 |                    field laying on the right side of the given field. If
3557 |                    this set is empty, we take the last field on the line.
3558 |
3559 |   Return Values :  Pointer to the upper neighbor field.
3560 +--------------------------------------------------------------------------*/
3561 static FIELD *
3562 Down_Neighbor_Field(FIELD *field)
3563 {
3564   FIELD *field_on_page = field;
3565   int frow = field->frow;
3566   int fcol = field->fcol;
3567
3568   /* Walk forward to the 'next' line. The second term in the while clause
3569      just guarantees that we stop if we cycled through the line because
3570      there might be no 'next' line if the page has just one line.
3571    */
3572   do
3573     {
3574       field_on_page = Sorted_Next_Field(field_on_page);
3575     }
3576   while (field_on_page->frow == frow && field_on_page->fcol != fcol);
3577
3578   if (field_on_page->frow != frow)
3579     {
3580       /* We really found a 'next' line. We are positioned at the rightmost
3581          field on this line */
3582       frow = field_on_page->frow;
3583
3584       /* We walk to the right as long as we are really left of the
3585          field. */
3586       while (field_on_page->frow == frow && field_on_page->fcol < fcol)
3587         field_on_page = Sorted_Next_Field(field_on_page);
3588
3589       /* If we wrapped, just go to the left which is the last field on
3590          the row */
3591       if (field_on_page->frow != frow)
3592         field_on_page = Sorted_Previous_Field(field_on_page);
3593     }
3594
3595   return (field_on_page);
3596 }
3597
3598 /*----------------------------------------------------------------------------
3599   Inter-Field Navigation routines
3600   --------------------------------------------------------------------------*/
3601
3602 /*---------------------------------------------------------------------------
3603 |   Facility      :  libnform
3604 |   Function      :  static int Inter_Field_Navigation(
3605 |                                           int (* const fct) (FORM *),
3606 |                                           FORM * form)
3607 |
3608 |   Description   :  Generic behavior for changing the current field, the
3609 |                    field is left and a new field is entered. So the field
3610 |                    must be validated and the field init/term hooks must
3611 |                    be called.
3612 |
3613 |   Return Values :  E_OK                - success
3614 |                    E_INVALID_FIELD     - field is invalid
3615 |                    some other          - error from subordinate call
3616 +--------------------------------------------------------------------------*/
3617 static int
3618 Inter_Field_Navigation(int (*const fct) (FORM *), FORM *form)
3619 {
3620   int res;
3621
3622   if (!_nc_Internal_Validation(form))
3623     res = E_INVALID_FIELD;
3624   else
3625     {
3626       Call_Hook(form, fieldterm);
3627       res = fct(form);
3628       Call_Hook(form, fieldinit);
3629     }
3630   return res;
3631 }
3632
3633 /*---------------------------------------------------------------------------
3634 |   Facility      :  libnform
3635 |   Function      :  static int FN_Next_Field(FORM * form)
3636 |
3637 |   Description   :  Move to the next field on the current page of the form
3638 |
3639 |   Return Values :  E_OK                 - success
3640 |                    != E_OK              - error from subordinate call
3641 +--------------------------------------------------------------------------*/
3642 static int
3643 FN_Next_Field(FORM *form)
3644 {
3645   T((T_CALLED("FN_Next_Field(%p)"), (void *)form));
3646   returnCode(_nc_Set_Current_Field(form,
3647                                    Next_Field_On_Page(form->current)));
3648 }
3649
3650 /*---------------------------------------------------------------------------
3651 |   Facility      :  libnform
3652 |   Function      :  static int FN_Previous_Field(FORM * form)
3653 |
3654 |   Description   :  Move to the previous field on the current page of the
3655 |                    form
3656 |
3657 |   Return Values :  E_OK                 - success
3658 |                    != E_OK              - error from subordinate call
3659 +--------------------------------------------------------------------------*/
3660 static int
3661 FN_Previous_Field(FORM *form)
3662 {
3663   T((T_CALLED("FN_Previous_Field(%p)"), (void *)form));
3664   returnCode(_nc_Set_Current_Field(form,
3665                                    Previous_Field_On_Page(form->current)));
3666 }
3667
3668 /*---------------------------------------------------------------------------
3669 |   Facility      :  libnform
3670 |   Function      :  static int FN_First_Field(FORM * form)
3671 |
3672 |   Description   :  Move to the first field on the current page of the form
3673 |
3674 |   Return Values :  E_OK                 - success
3675 |                    != E_OK              - error from subordinate call
3676 +--------------------------------------------------------------------------*/
3677 static int
3678 FN_First_Field(FORM *form)
3679 {
3680   T((T_CALLED("FN_First_Field(%p)"), (void *)form));
3681   returnCode(_nc_Set_Current_Field(form,
3682                                    Next_Field_On_Page(form->field[form->page[form->curpage].pmax])));
3683 }
3684
3685 /*---------------------------------------------------------------------------
3686 |   Facility      :  libnform
3687 |   Function      :  static int FN_Last_Field(FORM * form)
3688 |
3689 |   Description   :  Move to the last field on the current page of the form
3690 |
3691 |   Return Values :  E_OK                 - success
3692 |                    != E_OK              - error from subordinate call
3693 +--------------------------------------------------------------------------*/
3694 static int
3695 FN_Last_Field(FORM *form)
3696 {
3697   T((T_CALLED("FN_Last_Field(%p)"), (void *)form));
3698   returnCode(
3699               _nc_Set_Current_Field(form,
3700                                     Previous_Field_On_Page(form->field[form->page[form->curpage].pmin])));
3701 }
3702
3703 /*---------------------------------------------------------------------------
3704 |   Facility      :  libnform
3705 |   Function      :  static int FN_Sorted_Next_Field(FORM * form)
3706 |
3707 |   Description   :  Move to the sorted next field on the current page
3708 |                    of the form.
3709 |
3710 |   Return Values :  E_OK            - success
3711 |                    != E_OK         - error from subordinate call
3712 +--------------------------------------------------------------------------*/
3713 static int
3714 FN_Sorted_Next_Field(FORM *form)
3715 {
3716   T((T_CALLED("FN_Sorted_Next_Field(%p)"), (void *)form));
3717   returnCode(_nc_Set_Current_Field(form,
3718                                    Sorted_Next_Field(form->current)));
3719 }
3720
3721 /*---------------------------------------------------------------------------
3722 |   Facility      :  libnform
3723 |   Function      :  static int FN_Sorted_Previous_Field(FORM * form)
3724 |
3725 |   Description   :  Move to the sorted previous field on the current page
3726 |                    of the form.
3727 |
3728 |   Return Values :  E_OK            - success
3729 |                    != E_OK         - error from subordinate call
3730 +--------------------------------------------------------------------------*/
3731 static int
3732 FN_Sorted_Previous_Field(FORM *form)
3733 {
3734   T((T_CALLED("FN_Sorted_Previous_Field(%p)"), (void *)form));
3735   returnCode(_nc_Set_Current_Field(form,
3736                                    Sorted_Previous_Field(form->current)));
3737 }
3738
3739 /*---------------------------------------------------------------------------
3740 |   Facility      :  libnform
3741 |   Function      :  static int FN_Sorted_First_Field(FORM * form)
3742 |
3743 |   Description   :  Move to the sorted first field on the current page
3744 |                    of the form.
3745 |
3746 |   Return Values :  E_OK            - success
3747 |                    != E_OK         - error from subordinate call
3748 +--------------------------------------------------------------------------*/
3749 static int
3750 FN_Sorted_First_Field(FORM *form)
3751 {
3752   T((T_CALLED("FN_Sorted_First_Field(%p)"), (void *)form));
3753   returnCode(_nc_Set_Current_Field(form,
3754                                    Sorted_Next_Field(form->field[form->page[form->curpage].smax])));
3755 }
3756
3757 /*---------------------------------------------------------------------------
3758 |   Facility      :  libnform
3759 |   Function      :  static int FN_Sorted_Last_Field(FORM * form)
3760 |
3761 |   Description   :  Move to the sorted last field on the current page
3762 |                    of the form.
3763 |
3764 |   Return Values :  E_OK            - success
3765 |                    != E_OK         - error from subordinate call
3766 +--------------------------------------------------------------------------*/
3767 static int
3768 FN_Sorted_Last_Field(FORM *form)
3769 {
3770   T((T_CALLED("FN_Sorted_Last_Field(%p)"), (void *)form));
3771   returnCode(_nc_Set_Current_Field(form,
3772                                    Sorted_Previous_Field(form->field[form->page[form->curpage].smin])));
3773 }
3774
3775 /*---------------------------------------------------------------------------
3776 |   Facility      :  libnform
3777 |   Function      :  static int FN_Left_Field(FORM * form)
3778 |
3779 |   Description   :  Get the field on the left of the current field on the
3780 |                    same line and the same page. Cycles through the line.
3781 |
3782 |   Return Values :  E_OK            - success
3783 |                    != E_OK         - error from subordinate call
3784 +--------------------------------------------------------------------------*/
3785 static int
3786 FN_Left_Field(FORM *form)
3787 {
3788   T((T_CALLED("FN_Left_Field(%p)"), (void *)form));
3789   returnCode(_nc_Set_Current_Field(form,
3790                                    Left_Neighbor_Field(form->current)));
3791 }
3792
3793 /*---------------------------------------------------------------------------
3794 |   Facility      :  libnform
3795 |   Function      :  static int FN_Right_Field(FORM * form)
3796 |
3797 |   Description   :  Get the field on the right of the current field on the
3798 |                    same line and the same page. Cycles through the line.
3799 |
3800 |   Return Values :  E_OK            - success
3801 |                    != E_OK         - error from subordinate call
3802 +--------------------------------------------------------------------------*/
3803 static int
3804 FN_Right_Field(FORM *form)
3805 {
3806   T((T_CALLED("FN_Right_Field(%p)"), (void *)form));
3807   returnCode(_nc_Set_Current_Field(form,
3808                                    Right_Neighbor_Field(form->current)));
3809 }
3810
3811 /*---------------------------------------------------------------------------
3812 |   Facility      :  libnform
3813 |   Function      :  static int FN_Up_Field(FORM * form)
3814 |
3815 |   Description   :  Get the upper neighbor of the current field. This
3816 |                    cycles through the page. See the comments of the
3817 |                    Upper_Neighbor_Field function to understand how
3818 |                    'upper' is defined.
3819 |
3820 |   Return Values :  E_OK            - success
3821 |                    != E_OK         - error from subordinate call
3822 +--------------------------------------------------------------------------*/
3823 static int
3824 FN_Up_Field(FORM *form)
3825 {
3826   T((T_CALLED("FN_Up_Field(%p)"), (void *)form));
3827   returnCode(_nc_Set_Current_Field(form,
3828                                    Upper_Neighbor_Field(form->current)));
3829 }
3830
3831 /*---------------------------------------------------------------------------
3832 |   Facility      :  libnform
3833 |   Function      :  static int FN_Down_Field(FORM * form)
3834 |
3835 |   Description   :  Get the down neighbor of the current field. This
3836 |                    cycles through the page. See the comments of the
3837 |                    Down_Neighbor_Field function to understand how
3838 |                    'down' is defined.
3839 |
3840 |   Return Values :  E_OK            - success
3841 |                    != E_OK         - error from subordinate call
3842 +--------------------------------------------------------------------------*/
3843 static int
3844 FN_Down_Field(FORM *form)
3845 {
3846   T((T_CALLED("FN_Down_Field(%p)"), (void *)form));
3847   returnCode(_nc_Set_Current_Field(form,
3848                                    Down_Neighbor_Field(form->current)));
3849 }
3850 /*----------------------------------------------------------------------------
3851   END of Field Navigation routines
3852   --------------------------------------------------------------------------*/
3853
3854 /*----------------------------------------------------------------------------
3855   Helper routines for Page Navigation
3856   --------------------------------------------------------------------------*/
3857
3858 /*---------------------------------------------------------------------------
3859 |   Facility      :  libnform
3860 |   Function      :  int _nc_Set_Form_Page(FORM * form,
3861 |                                          int page,
3862 |                                          FIELD * field)
3863 |
3864 |   Description   :  Make the given page number the current page and make
3865 |                    the given field the current field on the page. If
3866 |                    for the field NULL is given, make the first field on
3867 |                    the page the current field. The routine acts only
3868 |                    if the requested page is not the current page.
3869 |
3870 |   Return Values :  E_OK                - success
3871 |                    != E_OK             - error from subordinate call
3872 |                    E_BAD_ARGUMENT      - invalid field pointer
3873 |                    E_SYSTEM_ERROR      - some severe basic error
3874 +--------------------------------------------------------------------------*/
3875 NCURSES_EXPORT(int)
3876 _nc_Set_Form_Page(FORM *form, int page, FIELD *field)
3877 {
3878   int res = E_OK;
3879
3880   if ((form->curpage != page))
3881     {
3882       FIELD *last_field, *field_on_page;
3883
3884       werase(Get_Form_Window(form));
3885       form->curpage = (short)page;
3886       last_field = field_on_page = form->field[form->page[page].smin];
3887       do
3888         {
3889           if ((unsigned)field_on_page->opts & O_VISIBLE)
3890             if ((res = Display_Field(field_on_page)) != E_OK)
3891               return (res);
3892           field_on_page = field_on_page->snext;
3893         }
3894       while (field_on_page != last_field);
3895
3896       if (field)
3897         res = _nc_Set_Current_Field(form, field);
3898       else
3899         /* N.B.: we don't encapsulate this by Inter_Field_Navigation(),
3900            because this is already executed in a page navigation
3901            context that contains field navigation
3902          */
3903         res = FN_First_Field(form);
3904     }
3905   return (res);
3906 }
3907
3908 /*---------------------------------------------------------------------------
3909 |   Facility      :  libnform
3910 |   Function      :  static int Next_Page_Number(const FORM * form)
3911 |
3912 |   Description   :  Calculate the page number following the current page
3913 |                    number. This cycles if the highest page number is
3914 |                    reached.
3915 |
3916 |   Return Values :  The next page number
3917 +--------------------------------------------------------------------------*/
3918 NCURSES_INLINE static int
3919 Next_Page_Number(const FORM *form)
3920 {
3921   return (form->curpage + 1) % form->maxpage;
3922 }
3923
3924 /*---------------------------------------------------------------------------
3925 |   Facility      :  libnform
3926 |   Function      :  static int Previous_Page_Number(const FORM * form)
3927 |
3928 |   Description   :  Calculate the page number before the current page
3929 |                    number. This cycles if the first page number is
3930 |                    reached.
3931 |
3932 |   Return Values :  The previous page number
3933 +--------------------------------------------------------------------------*/
3934 NCURSES_INLINE static int
3935 Previous_Page_Number(const FORM *form)
3936 {
3937   return (form->curpage != 0 ? form->curpage - 1 : form->maxpage - 1);
3938 }
3939
3940 /*----------------------------------------------------------------------------
3941   Page Navigation routines
3942   --------------------------------------------------------------------------*/
3943
3944 /*---------------------------------------------------------------------------
3945 |   Facility      :  libnform
3946 |   Function      :  static int Page_Navigation(
3947 |                                               int (* const fct) (FORM *),
3948 |                                               FORM * form)
3949 |
3950 |   Description   :  Generic behavior for changing a page. This means
3951 |                    that the field is left and a new field is entered.
3952 |                    So the field must be validated and the field init/term
3953 |                    hooks must be called. Because also the page is changed,
3954 |                    the forms init/term hooks must be called also.
3955 |
3956 |   Return Values :  E_OK                - success
3957 |                    E_INVALID_FIELD     - field is invalid
3958 |                    some other          - error from subordinate call
3959 +--------------------------------------------------------------------------*/
3960 static int
3961 Page_Navigation(int (*const fct) (FORM *), FORM *form)
3962 {
3963   int res;
3964
3965   if (!_nc_Internal_Validation(form))
3966     res = E_INVALID_FIELD;
3967   else
3968     {
3969       Call_Hook(form, fieldterm);
3970       Call_Hook(form, formterm);
3971       res = fct(form);
3972       Call_Hook(form, forminit);
3973       Call_Hook(form, fieldinit);
3974     }
3975   return res;
3976 }
3977
3978 /*---------------------------------------------------------------------------
3979 |   Facility      :  libnform
3980 |   Function      :  static int PN_Next_Page(FORM * form)
3981 |
3982 |   Description   :  Move to the next page of the form
3983 |
3984 |   Return Values :  E_OK                - success
3985 |                    != E_OK             - error from subordinate call
3986 +--------------------------------------------------------------------------*/
3987 static int
3988 PN_Next_Page(FORM *form)
3989 {
3990   T((T_CALLED("PN_Next_Page(%p)"), (void *)form));
3991   returnCode(_nc_Set_Form_Page(form, Next_Page_Number(form), (FIELD *)0));
3992 }
3993
3994 /*---------------------------------------------------------------------------
3995 |   Facility      :  libnform
3996 |   Function      :  static int PN_Previous_Page(FORM * form)
3997 |
3998 |   Description   :  Move to the previous page of the form
3999 |
4000 |   Return Values :  E_OK              - success
4001 |                    != E_OK           - error from subordinate call
4002 +--------------------------------------------------------------------------*/
4003 static int
4004 PN_Previous_Page(FORM *form)
4005 {
4006   T((T_CALLED("PN_Previous_Page(%p)"), (void *)form));
4007   returnCode(_nc_Set_Form_Page(form, Previous_Page_Number(form), (FIELD *)0));
4008 }
4009
4010 /*---------------------------------------------------------------------------
4011 |   Facility      :  libnform
4012 |   Function      :  static int PN_First_Page(FORM * form)
4013 |
4014 |   Description   :  Move to the first page of the form
4015 |
4016 |   Return Values :  E_OK              - success
4017 |                    != E_OK           - error from subordinate call
4018 +--------------------------------------------------------------------------*/
4019 static int
4020 PN_First_Page(FORM *form)
4021 {
4022   T((T_CALLED("PN_First_Page(%p)"), (void *)form));
4023   returnCode(_nc_Set_Form_Page(form, 0, (FIELD *)0));
4024 }
4025
4026 /*---------------------------------------------------------------------------
4027 |   Facility      :  libnform
4028 |   Function      :  static int PN_Last_Page(FORM * form)
4029 |
4030 |   Description   :  Move to the last page of the form
4031 |
4032 |   Return Values :  E_OK              - success
4033 |                    != E_OK           - error from subordinate call
4034 +--------------------------------------------------------------------------*/
4035 static int
4036 PN_Last_Page(FORM *form)
4037 {
4038   T((T_CALLED("PN_Last_Page(%p)"), (void *)form));
4039   returnCode(_nc_Set_Form_Page(form, form->maxpage - 1, (FIELD *)0));
4040 }
4041
4042 /*----------------------------------------------------------------------------
4043   END of Field Navigation routines
4044   --------------------------------------------------------------------------*/
4045
4046 /*----------------------------------------------------------------------------
4047   Helper routines for the core form driver.
4048   --------------------------------------------------------------------------*/
4049
4050 # if USE_WIDEC_SUPPORT
4051 /*---------------------------------------------------------------------------
4052 |   Facility      :  libnform
4053 |   Function      :  static int Data_Entry_w(FORM * form, wchar_t c)
4054 |
4055 |   Description   :  Enter the wide character c into at the current
4056 |                    position of the current field of the form.
4057 |
4058 |   Return Values :  E_OK              - success
4059 |                    E_REQUEST_DENIED  - driver could not process the request
4060 |                    E_SYSTEM_ERROR    -
4061 +--------------------------------------------------------------------------*/
4062 static int
4063 Data_Entry_w(FORM *form, wchar_t c)
4064 {
4065   FIELD *field = form->current;
4066   int result = E_REQUEST_DENIED;
4067
4068   T((T_CALLED("Data_Entry(%p,%s)"), (void *)form, _tracechtype((chtype)c)));
4069   if ((Field_Has_Option(field, O_EDIT))
4070 #if FIX_FORM_INACTIVE_BUG
4071       && (Field_Has_Option(field, O_ACTIVE))
4072 #endif
4073     )
4074     {
4075       wchar_t given[2];
4076       cchar_t temp_ch;
4077
4078       given[0] = c;
4079       given[1] = 0;
4080       setcchar(&temp_ch, given, 0, 0, (void *)0);
4081       if ((Field_Has_Option(field, O_BLANK)) &&
4082           First_Position_In_Current_Field(form) &&
4083           !(form->status & _FCHECK_REQUIRED) &&
4084           !(form->status & _WINDOW_MODIFIED))
4085         werase(form->w);
4086
4087       if (form->status & _OVLMODE)
4088         {
4089           wadd_wch(form->w, &temp_ch);
4090         }
4091       else
4092         /* no _OVLMODE */
4093         {
4094           bool There_Is_Room = Is_There_Room_For_A_Char_In_Line(form);
4095
4096           if (!(There_Is_Room ||
4097                 ((Single_Line_Field(field) && Growable(field)))))
4098             RETURN(E_REQUEST_DENIED);
4099
4100           if (!There_Is_Room && !Field_Grown(field, 1))
4101             RETURN(E_SYSTEM_ERROR);
4102
4103           wins_wch(form->w, &temp_ch);
4104         }
4105
4106       if ((result = Wrapping_Not_Necessary_Or_Wrapping_Ok(form)) == E_OK)
4107         {
4108           bool End_Of_Field = (((field->drows - 1) == form->currow) &&
4109                                ((field->dcols - 1) == form->curcol));
4110
4111           form->status |= _WINDOW_MODIFIED;
4112           if (End_Of_Field && !Growable(field) && (Field_Has_Option(field, O_AUTOSKIP)))
4113             result = Inter_Field_Navigation(FN_Next_Field, form);
4114           else
4115             {
4116               if (End_Of_Field && Growable(field) && !Field_Grown(field, 1))
4117                 result = E_SYSTEM_ERROR;
4118               else
4119                 {
4120                   /*
4121                    * We have just added a byte to the form field.  It may have
4122                    * been part of a multibyte character.  If it was, the
4123                    * addch_used field is nonzero and we should not try to move
4124                    * to a new column.
4125                    */
4126                   if (WINDOW_EXT(form->w, addch_used) == 0)
4127                     IFN_Next_Character(form);
4128
4129                   result = E_OK;
4130                 }
4131             }
4132         }
4133     }
4134   RETURN(result);
4135 }
4136 # endif
4137
4138 /*---------------------------------------------------------------------------
4139 |   Facility      :  libnform
4140 |   Function      :  static int Data_Entry(FORM * form,int c)
4141 |
4142 |   Description   :  Enter character c into at the current position of the
4143 |                    current field of the form.
4144 |
4145 |   Return Values :  E_OK              - success
4146 |                    E_REQUEST_DENIED  - driver could not process the request
4147 |                    E_SYSTEM_ERROR    -
4148 +--------------------------------------------------------------------------*/
4149 static int
4150 Data_Entry(FORM *form, int c)
4151 {
4152   FIELD *field = form->current;
4153   int result = E_REQUEST_DENIED;
4154
4155   T((T_CALLED("Data_Entry(%p,%s)"), (void *)form, _tracechtype((chtype)c)));
4156   if ((Field_Has_Option(field, O_EDIT))
4157 #if FIX_FORM_INACTIVE_BUG
4158       && (Field_Has_Option(field, O_ACTIVE))
4159 #endif
4160     )
4161     {
4162       if ((Field_Has_Option(field, O_BLANK)) &&
4163           First_Position_In_Current_Field(form) &&
4164           !(form->status & _FCHECK_REQUIRED) &&
4165           !(form->status & _WINDOW_MODIFIED))
4166         werase(form->w);
4167
4168       if (form->status & _OVLMODE)
4169         {
4170           waddch(form->w, (chtype)c);
4171         }
4172       else
4173         /* no _OVLMODE */
4174         {
4175           bool There_Is_Room = Is_There_Room_For_A_Char_In_Line(form);
4176
4177           if (!(There_Is_Room ||
4178                 ((Single_Line_Field(field) && Growable(field)))))
4179             RETURN(E_REQUEST_DENIED);
4180
4181           if (!There_Is_Room && !Field_Grown(field, 1))
4182             RETURN(E_SYSTEM_ERROR);
4183
4184           winsch(form->w, (chtype)c);
4185         }
4186
4187       if ((result = Wrapping_Not_Necessary_Or_Wrapping_Ok(form)) == E_OK)
4188         {
4189           bool End_Of_Field = (((field->drows - 1) == form->currow) &&
4190                                ((field->dcols - 1) == form->curcol));
4191
4192           if (Field_Has_Option(field, O_EDGE_INSERT_STAY))
4193             move_after_insert = !!(form->curcol
4194                                    - form->begincol
4195                                    - field->cols
4196                                    + 1);
4197
4198           SetStatus(form, _WINDOW_MODIFIED);
4199           if (End_Of_Field && !Growable(field) && (Field_Has_Option(field, O_AUTOSKIP)))
4200             result = Inter_Field_Navigation(FN_Next_Field, form);
4201           else
4202             {
4203               if (End_Of_Field && Growable(field) && !Field_Grown(field, 1))
4204                 result = E_SYSTEM_ERROR;
4205               else
4206                 {
4207 #if USE_WIDEC_SUPPORT
4208                   /*
4209                    * We have just added a byte to the form field.  It may have
4210                    * been part of a multibyte character.  If it was, the
4211                    * addch_used field is nonzero and we should not try to move
4212                    * to a new column.
4213                    */
4214                   if (WINDOW_EXT(form->w, addch_used) == 0)
4215                     IFN_Next_Character(form);
4216 #else
4217                   IFN_Next_Character(form);
4218 #endif
4219                   result = E_OK;
4220                 }
4221             }
4222         }
4223     }
4224   RETURN(result);
4225 }
4226
4227 /* Structure to describe the binding of a request code to a function.
4228    The member keycode codes the request value as well as the generic
4229    routine to use for the request. The code for the generic routine
4230    is coded in the upper 16 Bits while the request code is coded in
4231    the lower 16 bits.
4232
4233    In terms of C++ you might think of a request as a class with a
4234    virtual method "perform". The different types of request are
4235    derived from this base class and overload (or not) the base class
4236    implementation of perform.
4237 */
4238 typedef struct
4239 {
4240   int keycode;                  /* must be at least 32 bit: hi:mode, lo: key */
4241   int (*cmd) (FORM *);          /* low level driver routine for this key     */
4242 }
4243 Binding_Info;
4244
4245 /* You may see this is the class-id of the request type class */
4246 #define ID_PN    (0x00000000)   /* Page navigation           */
4247 #define ID_FN    (0x00010000)   /* Inter-Field navigation    */
4248 #define ID_IFN   (0x00020000)   /* Intra-Field navigation    */
4249 #define ID_VSC   (0x00030000)   /* Vertical Scrolling        */
4250 #define ID_HSC   (0x00040000)   /* Horizontal Scrolling      */
4251 #define ID_FE    (0x00050000)   /* Field Editing             */
4252 #define ID_EM    (0x00060000)   /* Edit Mode                 */
4253 #define ID_FV    (0x00070000)   /* Field Validation          */
4254 #define ID_CH    (0x00080000)   /* Choice                    */
4255 #define ID_Mask  (0xffff0000)
4256 #define Key_Mask (0x0000ffff)
4257 #define ID_Shft  (16)
4258
4259 /* This array holds all the Binding Infos */
4260 /* *INDENT-OFF* */
4261 static const Binding_Info bindings[MAX_FORM_COMMAND - MIN_FORM_COMMAND + 1] =
4262 {
4263   { REQ_NEXT_PAGE    |ID_PN  ,PN_Next_Page},
4264   { REQ_PREV_PAGE    |ID_PN  ,PN_Previous_Page},
4265   { REQ_FIRST_PAGE   |ID_PN  ,PN_First_Page},
4266   { REQ_LAST_PAGE    |ID_PN  ,PN_Last_Page},
4267
4268   { REQ_NEXT_FIELD   |ID_FN  ,FN_Next_Field},
4269   { REQ_PREV_FIELD   |ID_FN  ,FN_Previous_Field},
4270   { REQ_FIRST_FIELD  |ID_FN  ,FN_First_Field},
4271   { REQ_LAST_FIELD   |ID_FN  ,FN_Last_Field},
4272   { REQ_SNEXT_FIELD  |ID_FN  ,FN_Sorted_Next_Field},
4273   { REQ_SPREV_FIELD  |ID_FN  ,FN_Sorted_Previous_Field},
4274   { REQ_SFIRST_FIELD |ID_FN  ,FN_Sorted_First_Field},
4275   { REQ_SLAST_FIELD  |ID_FN  ,FN_Sorted_Last_Field},
4276   { REQ_LEFT_FIELD   |ID_FN  ,FN_Left_Field},
4277   { REQ_RIGHT_FIELD  |ID_FN  ,FN_Right_Field},
4278   { REQ_UP_FIELD     |ID_FN  ,FN_Up_Field},
4279   { REQ_DOWN_FIELD   |ID_FN  ,FN_Down_Field},
4280
4281   { REQ_NEXT_CHAR    |ID_IFN ,IFN_Next_Character},
4282   { REQ_PREV_CHAR    |ID_IFN ,IFN_Previous_Character},
4283   { REQ_NEXT_LINE    |ID_IFN ,IFN_Next_Line},
4284   { REQ_PREV_LINE    |ID_IFN ,IFN_Previous_Line},
4285   { REQ_NEXT_WORD    |ID_IFN ,IFN_Next_Word},
4286   { REQ_PREV_WORD    |ID_IFN ,IFN_Previous_Word},
4287   { REQ_BEG_FIELD    |ID_IFN ,IFN_Beginning_Of_Field},
4288   { REQ_END_FIELD    |ID_IFN ,IFN_End_Of_Field},
4289   { REQ_BEG_LINE     |ID_IFN ,IFN_Beginning_Of_Line},
4290   { REQ_END_LINE     |ID_IFN ,IFN_End_Of_Line},
4291   { REQ_LEFT_CHAR    |ID_IFN ,IFN_Left_Character},
4292   { REQ_RIGHT_CHAR   |ID_IFN ,IFN_Right_Character},
4293   { REQ_UP_CHAR      |ID_IFN ,IFN_Up_Character},
4294   { REQ_DOWN_CHAR    |ID_IFN ,IFN_Down_Character},
4295
4296   { REQ_NEW_LINE     |ID_FE  ,FE_New_Line},
4297   { REQ_INS_CHAR     |ID_FE  ,FE_Insert_Character},
4298   { REQ_INS_LINE     |ID_FE  ,FE_Insert_Line},
4299   { REQ_DEL_CHAR     |ID_FE  ,FE_Delete_Character},
4300   { REQ_DEL_PREV     |ID_FE  ,FE_Delete_Previous},
4301   { REQ_DEL_LINE     |ID_FE  ,FE_Delete_Line},
4302   { REQ_DEL_WORD     |ID_FE  ,FE_Delete_Word},
4303   { REQ_CLR_EOL      |ID_FE  ,FE_Clear_To_End_Of_Line},
4304   { REQ_CLR_EOF      |ID_FE  ,FE_Clear_To_End_Of_Field},
4305   { REQ_CLR_FIELD    |ID_FE  ,FE_Clear_Field},
4306
4307   { REQ_OVL_MODE     |ID_EM  ,EM_Overlay_Mode},
4308   { REQ_INS_MODE     |ID_EM  ,EM_Insert_Mode},
4309
4310   { REQ_SCR_FLINE    |ID_VSC ,VSC_Scroll_Line_Forward},
4311   { REQ_SCR_BLINE    |ID_VSC ,VSC_Scroll_Line_Backward},
4312   { REQ_SCR_FPAGE    |ID_VSC ,VSC_Scroll_Page_Forward},
4313   { REQ_SCR_BPAGE    |ID_VSC ,VSC_Scroll_Page_Backward},
4314   { REQ_SCR_FHPAGE   |ID_VSC ,VSC_Scroll_Half_Page_Forward},
4315   { REQ_SCR_BHPAGE   |ID_VSC ,VSC_Scroll_Half_Page_Backward},
4316
4317   { REQ_SCR_FCHAR    |ID_HSC ,HSC_Scroll_Char_Forward},
4318   { REQ_SCR_BCHAR    |ID_HSC ,HSC_Scroll_Char_Backward},
4319   { REQ_SCR_HFLINE   |ID_HSC ,HSC_Horizontal_Line_Forward},
4320   { REQ_SCR_HBLINE   |ID_HSC ,HSC_Horizontal_Line_Backward},
4321   { REQ_SCR_HFHALF   |ID_HSC ,HSC_Horizontal_Half_Line_Forward},
4322   { REQ_SCR_HBHALF   |ID_HSC ,HSC_Horizontal_Half_Line_Backward},
4323
4324   { REQ_VALIDATION   |ID_FV  ,FV_Validation},
4325
4326   { REQ_NEXT_CHOICE  |ID_CH  ,CR_Next_Choice},
4327   { REQ_PREV_CHOICE  |ID_CH  ,CR_Previous_Choice}
4328 };
4329 /* *INDENT-ON* */
4330
4331 /*---------------------------------------------------------------------------
4332 |   Facility      :  libnform
4333 |   Function      :  int form_driver(FORM * form,int  c)
4334 |
4335 |   Description   :  This is the workhorse of the forms system. It checks
4336 |                    to determine whether the character c is a request or
4337 |                    data. If it is a request, the form driver executes
4338 |                    the request and returns the result. If it is data
4339 |                    (printable character), it enters the data into the
4340 |                    current position in the current field. If it is not
4341 |                    recognized, the form driver assumes it is an application
4342 |                    defined command and returns E_UNKNOWN_COMMAND.
4343 |                    Application defined command should be defined relative
4344 |                    to MAX_FORM_COMMAND, the maximum value of a request.
4345 |
4346 |   Return Values :  E_OK              - success
4347 |                    E_SYSTEM_ERROR    - system error
4348 |                    E_BAD_ARGUMENT    - an argument is incorrect
4349 |                    E_NOT_POSTED      - form is not posted
4350 |                    E_INVALID_FIELD   - field contents are invalid
4351 |                    E_BAD_STATE       - called from inside a hook routine
4352 |                    E_REQUEST_DENIED  - request failed
4353 |                    E_NOT_CONNECTED   - no fields are connected to the form
4354 |                    E_UNKNOWN_COMMAND - command not known
4355 +--------------------------------------------------------------------------*/
4356 NCURSES_EXPORT(int)
4357 form_driver(FORM *form, int c)
4358 {
4359   const Binding_Info *BI = (Binding_Info *) 0;
4360   int res = E_UNKNOWN_COMMAND;
4361
4362   move_after_insert = true;
4363
4364   T((T_CALLED("form_driver(%p,%d)"), (void *)form, c));
4365
4366   if (!form)
4367     RETURN(E_BAD_ARGUMENT);
4368
4369   if (!(form->field) || !(form->current))
4370     RETURN(E_NOT_CONNECTED);
4371
4372   assert(form->page);
4373
4374   if (c == FIRST_ACTIVE_MAGIC)
4375     {
4376       form->current = _nc_First_Active_Field(form);
4377       RETURN(E_OK);
4378     }
4379
4380   assert(form->current &&
4381          form->current->buf &&
4382          (form->current->form == form)
4383     );
4384
4385   if (form->status & _IN_DRIVER)
4386     RETURN(E_BAD_STATE);
4387
4388   if (!(form->status & _POSTED))
4389     RETURN(E_NOT_POSTED);
4390
4391   if ((c >= MIN_FORM_COMMAND && c <= MAX_FORM_COMMAND) &&
4392       ((bindings[c - MIN_FORM_COMMAND].keycode & Key_Mask) == c))
4393     {
4394       TR(TRACE_CALLS, ("form_request %s", form_request_name(c)));
4395       BI = &(bindings[c - MIN_FORM_COMMAND]);
4396     }
4397
4398   if (BI)
4399     {
4400       typedef int (*Generic_Method) (int (*const) (FORM *), FORM *);
4401       static const Generic_Method Generic_Methods[] =
4402       {
4403         Page_Navigation,        /* overloaded to call field&form hooks */
4404         Inter_Field_Navigation, /* overloaded to call field hooks      */
4405         NULL,                   /* Intra-Field is generic              */
4406         Vertical_Scrolling,     /* Overloaded to check multi-line      */
4407         Horizontal_Scrolling,   /* Overloaded to check single-line     */
4408         Field_Editing,          /* Overloaded to mark modification     */
4409         NULL,                   /* Edit Mode is generic                */
4410         NULL,                   /* Field Validation is generic         */
4411         NULL                    /* Choice Request is generic           */
4412       };
4413       size_t nMethods = (sizeof(Generic_Methods) / sizeof(Generic_Methods[0]));
4414       size_t method = (size_t) ((BI->keycode >> ID_Shft) & 0xffff);     /* see ID_Mask */
4415
4416       if ((method >= nMethods) || !(BI->cmd))
4417         res = E_SYSTEM_ERROR;
4418       else
4419         {
4420           Generic_Method fct = Generic_Methods[method];
4421
4422           if (fct)
4423             {
4424               res = fct(BI->cmd, form);
4425             }
4426           else
4427             {
4428               res = (BI->cmd) (form);
4429             }
4430         }
4431     }
4432 #ifdef NCURSES_MOUSE_VERSION
4433   else if (KEY_MOUSE == c)
4434     {
4435       MEVENT event;
4436       WINDOW *win = form->win ? form->win : StdScreen(Get_Form_Screen(form));
4437       WINDOW *sub = form->sub ? form->sub : win;
4438
4439       getmouse(&event);
4440       if ((event.bstate & (BUTTON1_CLICKED |
4441                            BUTTON1_DOUBLE_CLICKED |
4442                            BUTTON1_TRIPLE_CLICKED))
4443           && wenclose(win, event.y, event.x))
4444         {                       /* we react only if the click was in the userwin, that means
4445                                  * inside the form display area or at the decoration window.
4446                                  */
4447           int ry = event.y, rx = event.x;       /* screen coordinates */
4448
4449           res = E_REQUEST_DENIED;
4450           if (mouse_trafo(&ry, &rx, FALSE))
4451             {                   /* rx, ry are now "curses" coordinates */
4452               if (ry < sub->_begy)
4453                 {               /* we clicked above the display region; this is
4454                                  * interpreted as "scroll up" request
4455                                  */
4456                   if (event.bstate & BUTTON1_CLICKED)
4457                     res = form_driver(form, REQ_PREV_FIELD);
4458                   else if (event.bstate & BUTTON1_DOUBLE_CLICKED)
4459                     res = form_driver(form, REQ_PREV_PAGE);
4460                   else if (event.bstate & BUTTON1_TRIPLE_CLICKED)
4461                     res = form_driver(form, REQ_FIRST_FIELD);
4462                 }
4463               else if (ry > sub->_begy + sub->_maxy)
4464                 {               /* we clicked below the display region; this is
4465                                  * interpreted as "scroll down" request
4466                                  */
4467                   if (event.bstate & BUTTON1_CLICKED)
4468                     res = form_driver(form, REQ_NEXT_FIELD);
4469                   else if (event.bstate & BUTTON1_DOUBLE_CLICKED)
4470                     res = form_driver(form, REQ_NEXT_PAGE);
4471                   else if (event.bstate & BUTTON1_TRIPLE_CLICKED)
4472                     res = form_driver(form, REQ_LAST_FIELD);
4473                 }
4474               else if (wenclose(sub, event.y, event.x))
4475                 {               /* Inside the area we try to find the hit item */
4476                   int i;
4477
4478                   ry = event.y;
4479                   rx = event.x;
4480                   if (wmouse_trafo(sub, &ry, &rx, FALSE))
4481                     {
4482                       int min_field = form->page[form->curpage].pmin;
4483                       int max_field = form->page[form->curpage].pmax;
4484
4485                       for (i = min_field; i <= max_field; ++i)
4486                         {
4487                           FIELD *field = form->field[i];
4488
4489                           if (Field_Is_Selectable(field)
4490                               && Field_encloses(field, ry, rx) == E_OK)
4491                             {
4492                               res = _nc_Set_Current_Field(form, field);
4493                               if (res == E_OK)
4494                                 res = _nc_Position_Form_Cursor(form);
4495                               if (res == E_OK
4496                                   && (event.bstate & BUTTON1_DOUBLE_CLICKED))
4497                                 res = E_UNKNOWN_COMMAND;
4498                               break;
4499                             }
4500                         }
4501                     }
4502                 }
4503             }
4504         }
4505       else
4506         res = E_REQUEST_DENIED;
4507     }
4508 #endif /* NCURSES_MOUSE_VERSION */
4509   else if (!(c & (~(int)MAX_REGULAR_CHARACTER)))
4510     {
4511       /*
4512        * If we're using 8-bit characters, iscntrl+isprint cover the whole set.
4513        * But with multibyte characters, there is a third possibility, i.e.,
4514        * parts of characters that build up into printable characters which are
4515        * not considered printable.
4516        *
4517        * FIXME: the wide-character branch should also use Check_Char().
4518        */
4519 #if USE_WIDEC_SUPPORT
4520       if (!iscntrl(UChar(c)))
4521 #else
4522       if (isprint(UChar(c)) &&
4523           Check_Char(form, form->current, form->current->type, c,
4524                      (TypeArgument *)(form->current->arg)))
4525 #endif
4526         res = Data_Entry(form, c);
4527     }
4528   _nc_Refresh_Current_Field(form);
4529   RETURN(res);
4530 }
4531
4532 # if USE_WIDEC_SUPPORT
4533 /*---------------------------------------------------------------------------
4534 |   Facility      :  libnform
4535 |   Function      :  int form_driver_w(FORM * form,int type,wchar_t  c)
4536 |
4537 |   Description   :  This is the workhorse of the forms system.
4538 |
4539 |                    Input is either a key code (request) or a wide char
4540 |                    returned by e.g. get_wch (). The type must be passed
4541 |                    as well,so that we are able to determine whether the char
4542 |                    is a multibyte char or a request.
4543
4544 |                    If it is a request, the form driver executes
4545 |                    the request and returns the result. If it is data
4546 |                    (printable character), it enters the data into the
4547 |                    current position in the current field. If it is not
4548 |                    recognized, the form driver assumes it is an application
4549 |                    defined command and returns E_UNKNOWN_COMMAND.
4550 |                    Application defined command should be defined relative
4551 |                    to MAX_FORM_COMMAND, the maximum value of a request.
4552 |
4553 |   Return Values :  E_OK              - success
4554 |                    E_SYSTEM_ERROR    - system error
4555 |                    E_BAD_ARGUMENT    - an argument is incorrect
4556 |                    E_NOT_POSTED      - form is not posted
4557 |                    E_INVALID_FIELD   - field contents are invalid
4558 |                    E_BAD_STATE       - called from inside a hook routine
4559 |                    E_REQUEST_DENIED  - request failed
4560 |                    E_NOT_CONNECTED   - no fields are connected to the form
4561 |                    E_UNKNOWN_COMMAND - command not known
4562 +--------------------------------------------------------------------------*/
4563 NCURSES_EXPORT(int)
4564 form_driver_w(FORM *form, int type, wchar_t c)
4565 {
4566   const Binding_Info *BI = (Binding_Info *) 0;
4567   int res = E_UNKNOWN_COMMAND;
4568
4569   T((T_CALLED("form_driver(%p,%d)"), (void *)form, (int)c));
4570
4571   if (!form)
4572     RETURN(E_BAD_ARGUMENT);
4573
4574   if (!(form->field))
4575     RETURN(E_NOT_CONNECTED);
4576
4577   assert(form->page);
4578
4579   if (c == (wchar_t)FIRST_ACTIVE_MAGIC)
4580     {
4581       form->current = _nc_First_Active_Field(form);
4582       RETURN(E_OK);
4583     }
4584
4585   assert(form->current &&
4586          form->current->buf &&
4587          (form->current->form == form)
4588     );
4589
4590   if (form->status & _IN_DRIVER)
4591     RETURN(E_BAD_STATE);
4592
4593   if (!(form->status & _POSTED))
4594     RETURN(E_NOT_POSTED);
4595
4596   /* check if this is a keycode or a (wide) char */
4597   if (type == KEY_CODE_YES)
4598     {
4599       if ((c >= MIN_FORM_COMMAND && c <= MAX_FORM_COMMAND) &&
4600           ((bindings[c - MIN_FORM_COMMAND].keycode & Key_Mask) == c))
4601         BI = &(bindings[c - MIN_FORM_COMMAND]);
4602     }
4603
4604   if (BI)
4605     {
4606       typedef int (*Generic_Method) (int (*const) (FORM *), FORM *);
4607       static const Generic_Method Generic_Methods[] =
4608       {
4609         Page_Navigation,        /* overloaded to call field&form hooks */
4610         Inter_Field_Navigation, /* overloaded to call field hooks      */
4611         NULL,                   /* Intra-Field is generic              */
4612         Vertical_Scrolling,     /* Overloaded to check multi-line      */
4613         Horizontal_Scrolling,   /* Overloaded to check single-line     */
4614         Field_Editing,          /* Overloaded to mark modification     */
4615         NULL,                   /* Edit Mode is generic                */
4616         NULL,                   /* Field Validation is generic         */
4617         NULL                    /* Choice Request is generic           */
4618       };
4619       size_t nMethods = (sizeof(Generic_Methods) / sizeof(Generic_Methods[0]));
4620       size_t method = (size_t) (BI->keycode >> ID_Shft) & 0xffff;       /* see ID_Mask */
4621
4622       if ((method >= nMethods) || !(BI->cmd))
4623         res = E_SYSTEM_ERROR;
4624       else
4625         {
4626           Generic_Method fct = Generic_Methods[method];
4627
4628           if (fct)
4629             res = fct(BI->cmd, form);
4630           else
4631             res = (BI->cmd) (form);
4632         }
4633     }
4634 #ifdef NCURSES_MOUSE_VERSION
4635   else if (KEY_MOUSE == c)
4636     {
4637       MEVENT event;
4638       WINDOW *win = form->win ? form->win : StdScreen(Get_Form_Screen(form));
4639       WINDOW *sub = form->sub ? form->sub : win;
4640
4641       getmouse(&event);
4642       if ((event.bstate & (BUTTON1_CLICKED |
4643                            BUTTON1_DOUBLE_CLICKED |
4644                            BUTTON1_TRIPLE_CLICKED))
4645           && wenclose(win, event.y, event.x))
4646         {                       /* we react only if the click was in the userwin, that means
4647                                    * inside the form display area or at the decoration window.
4648                                  */
4649           int ry = event.y, rx = event.x;       /* screen coordinates */
4650
4651           res = E_REQUEST_DENIED;
4652           if (mouse_trafo(&ry, &rx, FALSE))
4653             {                   /* rx, ry are now "curses" coordinates */
4654               if (ry < sub->_begy)
4655                 {               /* we clicked above the display region; this is
4656                                    * interpreted as "scroll up" request
4657                                  */
4658                   if (event.bstate & BUTTON1_CLICKED)
4659                     res = form_driver(form, REQ_PREV_FIELD);
4660                   else if (event.bstate & BUTTON1_DOUBLE_CLICKED)
4661                     res = form_driver(form, REQ_PREV_PAGE);
4662                   else if (event.bstate & BUTTON1_TRIPLE_CLICKED)
4663                     res = form_driver(form, REQ_FIRST_FIELD);
4664                 }
4665               else if (ry > sub->_begy + sub->_maxy)
4666                 {               /* we clicked below the display region; this is
4667                                    * interpreted as "scroll down" request
4668                                  */
4669                   if (event.bstate & BUTTON1_CLICKED)
4670                     res = form_driver(form, REQ_NEXT_FIELD);
4671                   else if (event.bstate & BUTTON1_DOUBLE_CLICKED)
4672                     res = form_driver(form, REQ_NEXT_PAGE);
4673                   else if (event.bstate & BUTTON1_TRIPLE_CLICKED)
4674                     res = form_driver(form, REQ_LAST_FIELD);
4675                 }
4676               else if (wenclose(sub, event.y, event.x))
4677                 {               /* Inside the area we try to find the hit item */
4678                   int i;
4679
4680                   ry = event.y;
4681                   rx = event.x;
4682                   if (wmouse_trafo(sub, &ry, &rx, FALSE))
4683                     {
4684                       int min_field = form->page[form->curpage].pmin;
4685                       int max_field = form->page[form->curpage].pmax;
4686
4687                       for (i = min_field; i <= max_field; ++i)
4688                         {
4689                           FIELD *field = form->field[i];
4690
4691                           if (Field_Is_Selectable(field)
4692                               && Field_encloses(field, ry, rx) == E_OK)
4693                             {
4694                               res = _nc_Set_Current_Field(form, field);
4695                               if (res == E_OK)
4696                                 res = _nc_Position_Form_Cursor(form);
4697                               if (res == E_OK
4698                                   && (event.bstate & BUTTON1_DOUBLE_CLICKED))
4699                                 res = E_UNKNOWN_COMMAND;
4700                               break;
4701                             }
4702                         }
4703                     }
4704                 }
4705             }
4706         }
4707       else
4708         res = E_REQUEST_DENIED;
4709     }
4710 #endif /* NCURSES_MOUSE_VERSION */
4711   else if (type == OK)
4712     {
4713       res = Data_Entry_w(form, c);
4714     }
4715
4716   _nc_Refresh_Current_Field(form);
4717   RETURN(res);
4718 }
4719 # endif /* USE_WIDEC_SUPPORT */
4720
4721 /*----------------------------------------------------------------------------
4722   Field-Buffer manipulation routines.
4723   The effects of setting a buffer are tightly coupled to the core of the form
4724   driver logic. This is especially true in the case of growable fields.
4725   So I don't separate this into a separate module.
4726   --------------------------------------------------------------------------*/
4727
4728 /*---------------------------------------------------------------------------
4729 |   Facility      :  libnform
4730 |   Function      :  int set_field_buffer(FIELD *field,
4731 |                                         int buffer, char *value)
4732 |
4733 |   Description   :  Set the given buffer of the field to the given value.
4734 |                    Buffer 0 stores the displayed content of the field.
4735 |                    For dynamic fields this may grow the fieldbuffers if
4736 |                    the length of the value exceeds the current buffer
4737 |                    length. For buffer 0 only printable values are allowed.
4738 |                    For static fields, the value needs not to be zero ter-
4739 |                    minated. It is copied up to the length of the buffer.
4740 |
4741 |   Return Values :  E_OK            - success
4742 |                    E_BAD_ARGUMENT  - invalid argument
4743 |                    E_SYSTEM_ERROR  - system error
4744 +--------------------------------------------------------------------------*/
4745 NCURSES_EXPORT(int)
4746 set_field_buffer(FIELD *field, int buffer, const char *value)
4747 {
4748   FIELD_CELL *p;
4749   int res = E_OK;
4750   int i;
4751   int len;
4752
4753 #if USE_WIDEC_SUPPORT
4754   FIELD_CELL *widevalue = 0;
4755 #endif
4756
4757   T((T_CALLED("set_field_buffer(%p,%d,%s)"), (void *)field, buffer, _nc_visbuf(value)));
4758
4759   if (!field || !value || ((buffer < 0) || (buffer > field->nbuf)))
4760     RETURN(E_BAD_ARGUMENT);
4761
4762   len = Buffer_Length(field);
4763
4764   if (Growable(field))
4765     {
4766       /* for a growable field we must assume zero terminated strings, because
4767          somehow we have to detect the length of what should be copied.
4768        */
4769       int vlen = (int)strlen(value);
4770
4771       if (vlen > len)
4772         {
4773           if (!Field_Grown(field,
4774                            (int)(1 + (vlen - len) / ((field->rows + field->nrow)
4775                                                      * field->cols))))
4776             RETURN(E_SYSTEM_ERROR);
4777
4778 #if !USE_WIDEC_SUPPORT
4779           len = vlen;
4780 #endif
4781         }
4782     }
4783
4784   p = Address_Of_Nth_Buffer(field, buffer);
4785
4786 #if USE_WIDEC_SUPPORT
4787   /*
4788    * Use addstr's logic for converting a string to an array of cchar_t's.
4789    * There should be a better way, but this handles nonspacing characters
4790    * and other special cases that we really do not want to handle here.
4791    */
4792 #if NCURSES_EXT_FUNCS
4793   if (wresize(field->working, 1, Buffer_Length(field) + 1) == ERR)
4794 #endif
4795     {
4796       delwin(field->working);
4797       field->working = newpad(1, Buffer_Length(field) + 1);
4798     }
4799   len = Buffer_Length(field);
4800   wclear(field->working);
4801   (void)mvwaddstr(field->working, 0, 0, value);
4802
4803   if ((widevalue = typeCalloc(FIELD_CELL, len + 1)) == 0)
4804     {
4805       RETURN(E_SYSTEM_ERROR);
4806     }
4807   else
4808     {
4809       for (i = 0; i < field->drows; ++i)
4810         {
4811           (void)mvwin_wchnstr(field->working, 0, (int)i * field->dcols,
4812                               widevalue + ((int)i * field->dcols),
4813                               field->dcols);
4814         }
4815       for (i = 0; i < len; ++i)
4816         {
4817           if (CharEq(myZEROS, widevalue[i]))
4818             {
4819               while (i < len)
4820                 p[i++] = myBLANK;
4821               break;
4822             }
4823           p[i] = widevalue[i];
4824         }
4825       free(widevalue);
4826     }
4827 #else
4828   for (i = 0; i < len; ++i)
4829     {
4830       if (value[i] == '\0')
4831         {
4832           while (i < len)
4833             p[i++] = myBLANK;
4834           break;
4835         }
4836       p[i] = value[i];
4837     }
4838 #endif
4839
4840   if (buffer == 0)
4841     {
4842       int syncres;
4843
4844       if (((syncres = Synchronize_Field(field)) != E_OK) &&
4845           (res == E_OK))
4846         res = syncres;
4847       if (((syncres = Synchronize_Linked_Fields(field)) != E_OK) &&
4848           (res == E_OK))
4849         res = syncres;
4850     }
4851   RETURN(res);
4852 }
4853
4854 /*---------------------------------------------------------------------------
4855 |   Facility      :  libnform
4856 |   Function      :  char *field_buffer(const FIELD *field,int buffer)
4857 |
4858 |   Description   :  Return the address of the buffer for the field.
4859 |
4860 |   Return Values :  Pointer to buffer or NULL if arguments were invalid.
4861 +--------------------------------------------------------------------------*/
4862 NCURSES_EXPORT(char *)
4863 field_buffer(const FIELD *field, int buffer)
4864 {
4865   char *result = 0;
4866
4867   T((T_CALLED("field_buffer(%p,%d)"), (const void *)field, buffer));
4868
4869   if (field && (buffer >= 0) && (buffer <= field->nbuf))
4870     {
4871 #if USE_WIDEC_SUPPORT
4872       FIELD_CELL *data = Address_Of_Nth_Buffer(field, buffer);
4873       size_t need = 0;
4874       int size = Buffer_Length(field);
4875       int n;
4876
4877       /* determine the number of bytes needed to store the expanded string */
4878       for (n = 0; n < size; ++n)
4879         {
4880           if (!isWidecExt(data[n]) && data[n].chars[0] != L'\0')
4881             {
4882               mbstate_t state;
4883               size_t next;
4884
4885               init_mb(state);
4886               next = _nc_wcrtomb(0, data[n].chars[0], &state);
4887               if (next > 0)
4888                 need += next;
4889             }
4890         }
4891
4892       /* allocate a place to store the expanded string */
4893       if (field->expanded[buffer] != 0)
4894         free(field->expanded[buffer]);
4895       field->expanded[buffer] = typeMalloc(char, need + 1);
4896
4897       /*
4898        * Expand the multibyte data.
4899        *
4900        * It may also be multi-column data.  In that case, the data for a row
4901        * may be null-padded to align to the dcols/drows layout (or it may
4902        * contain embedded wide-character extensions).  Change the null-padding
4903        * to blanks as needed.
4904        */
4905       if ((result = field->expanded[buffer]) != 0)
4906         {
4907           wclear(field->working);
4908           wmove(field->working, 0, 0);
4909           for (n = 0; n < size; ++n)
4910             {
4911               if (!isWidecExt(data[n]) && data[n].chars[0] != L'\0')
4912                 wadd_wch(field->working, &data[n]);
4913             }
4914           wmove(field->working, 0, 0);
4915           winnstr(field->working, result, (int)need);
4916         }
4917 #else
4918       result = Address_Of_Nth_Buffer(field, buffer);
4919 #endif
4920     }
4921   returnPtr(result);
4922 }
4923
4924 #if USE_WIDEC_SUPPORT
4925
4926 /*---------------------------------------------------------------------------
4927 | Convert a multibyte string to a wide-character string.  The result must be
4928 | freed by the caller.
4929 +--------------------------------------------------------------------------*/
4930 NCURSES_EXPORT(wchar_t *)
4931 _nc_Widen_String(char *source, int *lengthp)
4932 {
4933   wchar_t *result = 0;
4934   wchar_t wch;
4935   size_t given = strlen(source);
4936   size_t tries;
4937   int pass;
4938   int status;
4939
4940 #ifndef state_unused
4941   mbstate_t state;
4942 #endif
4943
4944   for (pass = 0; pass < 2; ++pass)
4945     {
4946       unsigned need = 0;
4947       size_t passed = 0;
4948
4949       while (passed < given)
4950         {
4951           bool found = FALSE;
4952
4953           for (tries = 1, status = 0; tries <= (given - passed); ++tries)
4954             {
4955               int save = source[passed + tries];
4956
4957               source[passed + tries] = 0;
4958               reset_mbytes(state);
4959               status = check_mbytes(wch, source + passed, tries, state);
4960               source[passed + tries] = (char)save;
4961
4962               if (status > 0)
4963                 {
4964                   found = TRUE;
4965                   break;
4966                 }
4967             }
4968           if (found)
4969             {
4970               if (pass)
4971                 {
4972                   result[need] = wch;
4973                 }
4974               passed += (size_t) status;
4975               ++need;
4976             }
4977           else
4978             {
4979               if (pass)
4980                 {
4981                   result[need] = (wchar_t)source[passed];
4982                 }
4983               ++need;
4984               ++passed;
4985             }
4986         }
4987
4988       if (!pass)
4989         {
4990           if (!need)
4991             break;
4992           result = typeCalloc(wchar_t, need);
4993
4994           *lengthp = (int)need;
4995           if (result == 0)
4996             break;
4997         }
4998     }
4999
5000   return result;
5001 }
5002 #endif
5003
5004 /* frm_driver.c ends here */