xref: /openbsd/lib/libcurses/tty/lib_mvcur.c (revision 3bef86f7)
1 /* $OpenBSD: lib_mvcur.c,v 1.14 2023/10/17 09:52:09 nicm Exp $ */
2 
3 /****************************************************************************
4  * Copyright 2018-2022,2023 Thomas E. Dickey                                *
5  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
6  *                                                                          *
7  * Permission is hereby granted, free of charge, to any person obtaining a  *
8  * copy of this software and associated documentation files (the            *
9  * "Software"), to deal in the Software without restriction, including      *
10  * without limitation the rights to use, copy, modify, merge, publish,      *
11  * distribute, distribute with modifications, sublicense, and/or sell       *
12  * copies of the Software, and to permit persons to whom the Software is    *
13  * furnished to do so, subject to the following conditions:                 *
14  *                                                                          *
15  * The above copyright notice and this permission notice shall be included  *
16  * in all copies or substantial portions of the Software.                   *
17  *                                                                          *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
21  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
22  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
23  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
24  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
25  *                                                                          *
26  * Except as contained in this notice, the name(s) of the above copyright   *
27  * holders shall not be used in advertising or otherwise to promote the     *
28  * sale, use or other dealings in this Software without prior written       *
29  * authorization.                                                           *
30  ****************************************************************************/
31 
32 /****************************************************************************
33  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
34  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
35  *     and: Thomas E. Dickey                        1996-on                 *
36  *     and: Juergen Pfeifer                         2009                    *
37  ****************************************************************************/
38 
39 /*
40 **	lib_mvcur.c
41 **
42 **	The routines for moving the physical cursor and scrolling:
43 **
44 **		void _nc_mvcur_init(void)
45 **
46 **		void _nc_mvcur_resume(void)
47 **
48 **		int mvcur(int old_y, int old_x, int new_y, int new_x)
49 **
50 **		void _nc_mvcur_wrap(void)
51 **
52 ** Comparisons with older movement optimizers:
53 **    SVr3 curses mvcur() can't use cursor_to_ll or auto_left_margin.
54 **    4.4BSD curses can't use cuu/cud/cuf/cub/hpa/vpa/tab/cbt for local
55 ** motions.  It doesn't use tactics based on auto_left_margin.  Weirdly
56 ** enough, it doesn't use its own hardware-scrolling routine to scroll up
57 ** destination lines for out-of-bounds addresses!
58 **    old ncurses optimizer: less accurate cost computations (in fact,
59 ** it was broken and had to be commented out!).
60 **
61 ** Compile with -DMAIN to build an interactive tester/timer for the movement
62 ** optimizer.  You can use it to investigate the optimizer's behavior.
63 ** You can also use it for tuning the formulas used to determine whether
64 ** or not full optimization is attempted.
65 **
66 ** This code has a nasty tendency to find bugs in terminfo entries, because it
67 ** exercises the non-cup movement capabilities heavily.  If you think you've
68 ** found a bug, try deleting subsets of the following capabilities (arranged
69 ** in decreasing order of suspiciousness): it, tab, cbt, hpa, vpa, cuu, cud,
70 ** cuf, cub, cuu1, cud1, cuf1, cub1.  It may be that one or more are wrong.
71 **
72 ** Note: you should expect this code to look like a resource hog in a profile.
73 ** That's because it does a lot of I/O, through the tputs() calls.  The I/O
74 ** cost swamps the computation overhead (and as machines get faster, this
75 ** will become even more true).  Comments in the test exerciser at the end
76 ** go into detail about tuning and how you can gauge the optimizer's
77 ** effectiveness.
78 **/
79 
80 /****************************************************************************
81  *
82  * Constants and macros for optimizer tuning.
83  *
84  ****************************************************************************/
85 
86 /*
87  * The average overhead of a full optimization computation in character
88  * transmission times.  If it is too high, the algorithm will be a bit
89  * over-biased toward using cup rather than local motions; if it is too
90  * low, the algorithm may spend more time than is strictly optimal
91  * looking for non-cup motions.  Profile the optimizer using the `t'
92  * command of the exerciser (see below), and round to the nearest integer.
93  *
94  * Yes, I (esr) thought about computing expected overhead dynamically, say
95  * by derivation from a running average of optimizer times.  But the
96  * whole point of this optimization is to *decrease* the frequency of
97  * system calls. :-)
98  */
99 #define COMPUTE_OVERHEAD	1	/* I use a 90MHz Pentium @ 9.6Kbps */
100 
101 /*
102  * LONG_DIST is the distance we consider to be just as costly to move over as a
103  * cup sequence is to emit.  In other words, it is the length of a cup sequence
104  * adjusted for average computation overhead.  The magic number is the length
105  * of "\033[yy;xxH", the typical cup sequence these days.
106  */
107 #define LONG_DIST		(8 - COMPUTE_OVERHEAD)
108 
109 /*
110  * Tell whether a motion is optimizable by local motions.  Needs to be cheap to
111  * compute. In general, all the fast moves go to either the right or left edge
112  * of the screen.  So any motion to a location that is (a) further away than
113  * LONG_DIST and (b) further inward from the right or left edge than LONG_DIST,
114  * we'll consider nonlocal.
115  */
116 #define NOT_LOCAL(sp, fy, fx, ty, tx)	((tx > LONG_DIST) \
117 		 && (tx < screen_columns(sp) - 1 - LONG_DIST) \
118 		 && (abs(ty-fy) + abs(tx-fx) > LONG_DIST))
119 
120 /****************************************************************************
121  *
122  * External interfaces
123  *
124  ****************************************************************************/
125 
126 /*
127  * For this code to work OK, the following components must live in the
128  * screen structure:
129  *
130  *	int		_char_padding;	// cost of character put
131  *	int		_cr_cost;	// cost of (carriage_return)
132  *	int		_cup_cost;	// cost of (cursor_address)
133  *	int		_home_cost;	// cost of (cursor_home)
134  *	int		_ll_cost;	// cost of (cursor_to_ll)
135  *#if USE_HARD_TABS
136  *	int		_ht_cost;	// cost of (tab)
137  *	int		_cbt_cost;	// cost of (back_tab)
138  *#endif USE_HARD_TABS
139  *	int		_cub1_cost;	// cost of (cursor_left)
140  *	int		_cuf1_cost;	// cost of (cursor_right)
141  *	int		_cud1_cost;	// cost of (cursor_down)
142  *	int		_cuu1_cost;	// cost of (cursor_up)
143  *	int		_cub_cost;	// cost of (parm_cursor_left)
144  *	int		_cuf_cost;	// cost of (parm_cursor_right)
145  *	int		_cud_cost;	// cost of (parm_cursor_down)
146  *	int		_cuu_cost;	// cost of (parm_cursor_up)
147  *	int		_hpa_cost;	// cost of (column_address)
148  *	int		_vpa_cost;	// cost of (row_address)
149  *	int		_ech_cost;	// cost of (erase_chars)
150  *	int		_rep_cost;	// cost of (repeat_char)
151  *
152  * The USE_HARD_TABS switch controls whether it is reliable to use tab/backtabs
153  * for local motions.  On many systems, it is not, due to uncertainties about
154  * tab delays and whether or not tabs will be expanded in raw mode.  If you
155  * have parm_right_cursor, tab motions don't win you a lot anyhow.
156  */
157 
158 #include <curses.priv.h>
159 #include <ctype.h>
160 
161 #ifndef CUR
162 #define CUR SP_TERMTYPE
163 #endif
164 
165 MODULE_ID("$Id: lib_mvcur.c,v 1.14 2023/10/17 09:52:09 nicm Exp $")
166 
167 #define WANT_CHAR(sp, y, x) NewScreen(sp)->_line[y].text[x]	/* desired state */
168 
169 #if NCURSES_SP_FUNCS
170 #define BAUDRATE(sp)	sp->_term->_baudrate	/* bits per second */
171 #else
172 #define BAUDRATE(sp)	cur_term->_baudrate	/* bits per second */
173 #endif
174 
175 #if defined(MAIN) || defined(NCURSES_TEST)
176 #include <sys/time.h>
177 
178 static bool profiling = FALSE;
179 static float diff;
180 #endif /* MAIN */
181 
182 #undef NCURSES_OUTC_FUNC
183 #define NCURSES_OUTC_FUNC myOutCh
184 
185 #define OPT_SIZE 512
186 
187 static int normalized_cost(NCURSES_SP_DCLx const char *const cap, int affcnt);
188 
189 /****************************************************************************
190  *
191  * Initialization/wrapup (including cost pre-computation)
192  *
193  ****************************************************************************/
194 
195 #ifdef TRACE
196 static int
197 trace_cost_of(NCURSES_SP_DCLx const char *capname, const char *cap, int affcnt)
198 {
199     int result = NCURSES_SP_NAME(_nc_msec_cost) (NCURSES_SP_ARGx cap, affcnt);
200     TR(TRACE_CHARPUT | TRACE_MOVE,
201        ("CostOf %s %d %s", capname, result, _nc_visbuf(cap)));
202     return result;
203 }
204 #define CostOf(cap,affcnt) trace_cost_of(NCURSES_SP_ARGx #cap, cap, affcnt)
205 
206 static int
207 trace_normalized_cost(NCURSES_SP_DCLx const char *capname, const char *cap, int affcnt)
208 {
209     int result = normalized_cost(NCURSES_SP_ARGx cap, affcnt);
210     TR(TRACE_CHARPUT | TRACE_MOVE,
211        ("NormalizedCost %s %d %s", capname, result, _nc_visbuf(cap)));
212     return result;
213 }
214 #define NormalizedCost(cap,affcnt) trace_normalized_cost(NCURSES_SP_ARGx #cap, cap, affcnt)
215 
216 #else
217 
218 #define CostOf(cap,affcnt) NCURSES_SP_NAME(_nc_msec_cost)(NCURSES_SP_ARGx cap, affcnt)
219 #define NormalizedCost(cap,affcnt) normalized_cost(NCURSES_SP_ARGx cap, affcnt)
220 
221 #endif
222 
223 NCURSES_EXPORT(int)
224 NCURSES_SP_NAME(_nc_msec_cost) (NCURSES_SP_DCLx const char *const cap, int affcnt)
225 /* compute the cost of a given operation */
226 {
227     if (cap == 0)
228 	return (INFINITY);
229     else {
230 	const char *cp;
231 	float cum_cost = 0.0;
232 
233 	for (cp = cap; *cp; cp++) {
234 	    /* extract padding, either mandatory or required */
235 	    if (cp[0] == '$' && cp[1] == '<' && strchr(cp, '>')) {
236 		float number = 0.0;
237 
238 		for (cp += 2; *cp != '>'; cp++) {
239 		    if (isdigit(UChar(*cp)))
240 			number = number * 10 + (float) (*cp - '0');
241 		    else if (*cp == '*')
242 			number *= (float) affcnt;
243 		    else if (*cp == '.' && (*++cp != '>') && isdigit(UChar(*cp)))
244 			number += (float) ((*cp - '0') / 10.0);
245 		}
246 
247 #if NCURSES_NO_PADDING
248 		if (!GetNoPadding(SP_PARM))
249 #endif
250 		    cum_cost += number * 10;
251 	    } else if (SP_PARM) {
252 		cum_cost += (float) SP_PARM->_char_padding;
253 	    }
254 	}
255 
256 	return ((int) cum_cost);
257     }
258 }
259 
260 #if NCURSES_SP_FUNCS
261 NCURSES_EXPORT(int)
262 _nc_msec_cost(const char *const cap, int affcnt)
263 {
264     return NCURSES_SP_NAME(_nc_msec_cost) (CURRENT_SCREEN, cap, affcnt);
265 }
266 #endif
267 
268 static int
269 normalized_cost(NCURSES_SP_DCLx const char *const cap, int affcnt)
270 /* compute the effective character-count for an operation (round up) */
271 {
272     int cost = NCURSES_SP_NAME(_nc_msec_cost) (NCURSES_SP_ARGx cap, affcnt);
273     if (cost != INFINITY)
274 	cost = (cost + SP_PARM->_char_padding - 1) / SP_PARM->_char_padding;
275     return cost;
276 }
277 
278 static void
279 reset_scroll_region(NCURSES_SP_DCL0)
280 /* Set the scroll-region to a known state (the default) */
281 {
282     if (change_scroll_region) {
283 	NCURSES_PUTP2("change_scroll_region",
284 		      TIPARM_2(change_scroll_region,
285 			       0, screen_lines(SP_PARM) - 1));
286     }
287 }
288 
289 NCURSES_EXPORT(void)
290 NCURSES_SP_NAME(_nc_mvcur_resume) (NCURSES_SP_DCL0)
291 /* what to do at initialization time and after each shellout */
292 {
293     if (!SP_PARM || !IsTermInfo(SP_PARM))
294 	return;
295 
296     /* initialize screen for cursor access */
297     if (enter_ca_mode) {
298 	NCURSES_PUTP2("enter_ca_mode", enter_ca_mode);
299     }
300 
301     /*
302      * Doing this here rather than in _nc_mvcur_wrap() ensures that
303      * ncurses programs will see a reset scroll region even if a
304      * program that messed with it died ungracefully.
305      *
306      * This also undoes the effects of terminal init strings that assume
307      * they know the screen size.  This is useful when you're running
308      * a vt100 emulation through xterm.
309      */
310     reset_scroll_region(NCURSES_SP_ARG);
311     SP_PARM->_cursrow = SP_PARM->_curscol = -1;
312 
313     /* restore cursor shape */
314     if (SP_PARM->_cursor != -1) {
315 	int cursor = SP_PARM->_cursor;
316 	SP_PARM->_cursor = -1;
317 	NCURSES_SP_NAME(curs_set) (NCURSES_SP_ARGx cursor);
318     }
319 }
320 
321 #if NCURSES_SP_FUNCS
322 NCURSES_EXPORT(void)
323 _nc_mvcur_resume(void)
324 {
325     NCURSES_SP_NAME(_nc_mvcur_resume) (CURRENT_SCREEN);
326 }
327 #endif
328 
329 NCURSES_EXPORT(void)
330 NCURSES_SP_NAME(_nc_mvcur_init) (NCURSES_SP_DCL0)
331 /* initialize the cost structure */
332 {
333     if (SP_PARM->_ofp && NC_ISATTY(fileno(SP_PARM->_ofp))) {
334 	SP_PARM->_char_padding = ((BAUDBYTE * 1000 * 10)
335 				  / (BAUDRATE(SP_PARM) > 0
336 				     ? BAUDRATE(SP_PARM)
337 				     : 9600));
338     } else {
339 	SP_PARM->_char_padding = 1;	/* must be nonzero */
340     }
341     if (SP_PARM->_char_padding <= 0)
342 	SP_PARM->_char_padding = 1;	/* must be nonzero */
343     TR(TRACE_CHARPUT | TRACE_MOVE, ("char_padding %d msecs", SP_PARM->_char_padding));
344 
345     /* non-parameterized local-motion strings */
346     SP_PARM->_cr_cost = CostOf(carriage_return, 0);
347     SP_PARM->_home_cost = CostOf(cursor_home, 0);
348     SP_PARM->_ll_cost = CostOf(cursor_to_ll, 0);
349 #if USE_HARD_TABS
350     if (getenv("NCURSES_NO_HARD_TABS") == 0
351 	&& dest_tabs_magic_smso == 0
352 	&& HasHardTabs()) {
353 	SP_PARM->_ht_cost = CostOf(tab, 0);
354 	SP_PARM->_cbt_cost = CostOf(back_tab, 0);
355     } else {
356 	SP_PARM->_ht_cost = INFINITY;
357 	SP_PARM->_cbt_cost = INFINITY;
358     }
359 #endif /* USE_HARD_TABS */
360     SP_PARM->_cub1_cost = CostOf(cursor_left, 0);
361     SP_PARM->_cuf1_cost = CostOf(cursor_right, 0);
362     SP_PARM->_cud1_cost = CostOf(cursor_down, 0);
363     SP_PARM->_cuu1_cost = CostOf(cursor_up, 0);
364 
365     SP_PARM->_smir_cost = CostOf(enter_insert_mode, 0);
366     SP_PARM->_rmir_cost = CostOf(exit_insert_mode, 0);
367     SP_PARM->_ip_cost = 0;
368     if (insert_padding) {
369 	SP_PARM->_ip_cost = CostOf(insert_padding, 0);
370     }
371 
372     /*
373      * Assumption: if the terminal has memory_relative addressing, the
374      * initialization strings or smcup will set single-page mode so we
375      * can treat it like absolute screen addressing.  This seems to be true
376      * for all cursor_mem_address terminal types in the terminfo database.
377      */
378     SP_PARM->_address_cursor = cursor_address ? cursor_address : cursor_mem_address;
379 
380     /*
381      * Parametrized local-motion strings.  This static cost computation
382      * depends on the following assumptions:
383      *
384      * (1) They never have * padding.  In the entire master terminfo database
385      *     as of March 1995, only the obsolete Zenith Z-100 pc violates this.
386      *     (Proportional padding is found mainly in insert, delete and scroll
387      *     capabilities).
388      *
389      * (2) The average case of cup has two two-digit parameters.  Strictly,
390      *     the average case for a 24 * 80 screen has ((10*10*(1 + 1)) +
391      *     (14*10*(1 + 2)) + (10*70*(2 + 1)) + (14*70*4)) / (24*80) = 3.458
392      *     digits of parameters.  On a 25x80 screen the average is 3.6197.
393      *     On larger screens the value gets much closer to 4.
394      *
395      * (3) The average case of cub/cuf/hpa/ech/rep has 2 digits of parameters
396      *     (strictly, (((10 * 1) + (70 * 2)) / 80) = 1.8750).
397      *
398      * (4) The average case of cud/cuu/vpa has 2 digits of parameters
399      *     (strictly, (((10 * 1) + (14 * 2)) / 24) = 1.5833).
400      *
401      * All these averages depend on the assumption that all parameter values
402      * are equally probable.
403      */
404     SP_PARM->_cup_cost = CostOf(TIPARM_2(SP_PARM->_address_cursor, 23, 23), 1);
405     SP_PARM->_cub_cost = CostOf(TIPARM_1(parm_left_cursor, 23), 1);
406     SP_PARM->_cuf_cost = CostOf(TIPARM_1(parm_right_cursor, 23), 1);
407     SP_PARM->_cud_cost = CostOf(TIPARM_1(parm_down_cursor, 23), 1);
408     SP_PARM->_cuu_cost = CostOf(TIPARM_1(parm_up_cursor, 23), 1);
409     SP_PARM->_hpa_cost = CostOf(TIPARM_1(column_address, 23), 1);
410     SP_PARM->_vpa_cost = CostOf(TIPARM_1(row_address, 23), 1);
411 
412     /* non-parameterized screen-update strings */
413     SP_PARM->_ed_cost = NormalizedCost(clr_eos, 1);
414     SP_PARM->_el_cost = NormalizedCost(clr_eol, 1);
415     SP_PARM->_el1_cost = NormalizedCost(clr_bol, 1);
416     SP_PARM->_dch1_cost = NormalizedCost(delete_character, 1);
417     SP_PARM->_ich1_cost = NormalizedCost(insert_character, 1);
418 
419     /*
420      * If this is a bce-terminal, we want to bias the choice so we use clr_eol
421      * rather than spaces at the end of a line.
422      */
423     if (back_color_erase)
424 	SP_PARM->_el_cost = 0;
425 
426     /* parameterized screen-update strings */
427     SP_PARM->_dch_cost = NormalizedCost(TIPARM_1(parm_dch, 23), 1);
428     SP_PARM->_ich_cost = NormalizedCost(TIPARM_1(parm_ich, 23), 1);
429     SP_PARM->_ech_cost = NormalizedCost(TIPARM_1(erase_chars, 23), 1);
430     SP_PARM->_rep_cost = NormalizedCost(TIPARM_2(repeat_char, ' ', 23), 1);
431 
432     SP_PARM->_cup_ch_cost = NormalizedCost(TIPARM_2(SP_PARM->_address_cursor,
433 						    23, 23),
434 					   1);
435     SP_PARM->_hpa_ch_cost = NormalizedCost(TIPARM_1(column_address, 23), 1);
436     SP_PARM->_cuf_ch_cost = NormalizedCost(TIPARM_1(parm_right_cursor, 23), 1);
437     SP_PARM->_inline_cost = min(SP_PARM->_cup_ch_cost,
438 				min(SP_PARM->_hpa_ch_cost,
439 				    SP_PARM->_cuf_ch_cost));
440 
441     /*
442      * If save_cursor is used within enter_ca_mode, we should not use it for
443      * scrolling optimization, since the corresponding restore_cursor is not
444      * nested on the various terminals (vt100, xterm, etc.) which use this
445      * feature.
446      */
447     if (save_cursor != 0
448 	&& enter_ca_mode != 0
449 	&& strstr(enter_ca_mode, save_cursor) != 0) {
450 	T(("...suppressed sc/rc capability due to conflict with smcup/rmcup"));
451 	save_cursor = 0;
452 	restore_cursor = 0;
453     }
454 
455     /*
456      * A different, possibly better way to arrange this would be to set the
457      * SCREEN's _endwin at window initialization time and let this be called by
458      * doupdate's return-from-shellout code.
459      */
460     NCURSES_SP_NAME(_nc_mvcur_resume) (NCURSES_SP_ARG);
461 }
462 
463 #if NCURSES_SP_FUNCS
464 NCURSES_EXPORT(void)
465 _nc_mvcur_init(void)
466 {
467     NCURSES_SP_NAME(_nc_mvcur_init) (CURRENT_SCREEN);
468 }
469 #endif
470 
471 NCURSES_EXPORT(void)
472 NCURSES_SP_NAME(_nc_mvcur_wrap) (NCURSES_SP_DCL0)
473 /* wrap up cursor-addressing mode */
474 {
475     if (!SP_PARM || !IsTermInfo(SP_PARM))
476 	return;
477 
478     /* leave cursor at screen bottom */
479     TINFO_MVCUR(NCURSES_SP_ARGx -1, -1, screen_lines(SP_PARM) - 1, 0);
480 
481     /* set cursor to normal mode */
482     if (SP_PARM->_cursor != -1) {
483 	int cursor = SP_PARM->_cursor;
484 	NCURSES_SP_NAME(curs_set) (NCURSES_SP_ARGx 1);
485 	SP_PARM->_cursor = cursor;
486     }
487 
488     if (exit_ca_mode) {
489 	NCURSES_PUTP2("exit_ca_mode", exit_ca_mode);
490     }
491     /*
492      * Reset terminal's tab counter.  There's a long-time bug that
493      * if you exit a "curses" program such as vi or more, tab
494      * forward, and then backspace, the cursor doesn't go to the
495      * right place.  The problem is that the kernel counts the
496      * escape sequences that reset things as column positions.
497      * Utter a \r to reset this invisibly.
498      */
499     NCURSES_SP_NAME(_nc_outch) (NCURSES_SP_ARGx '\r');
500 }
501 
502 #if NCURSES_SP_FUNCS
503 NCURSES_EXPORT(void)
504 _nc_mvcur_wrap(void)
505 {
506     NCURSES_SP_NAME(_nc_mvcur_wrap) (CURRENT_SCREEN);
507 }
508 #endif
509 
510 /****************************************************************************
511  *
512  * Optimized cursor movement
513  *
514  ****************************************************************************/
515 
516 /*
517  * Perform repeated-append, returning cost
518  */
519 static NCURSES_INLINE int
520 repeated_append(string_desc * target, int total, int num, int repeat, const char *src)
521 {
522     size_t need = (size_t) repeat * strlen(src);
523 
524     if (need < target->s_size) {
525 	while (repeat-- > 0) {
526 	    if (_nc_safe_strcat(target, src)) {
527 		total += num;
528 	    } else {
529 		total = INFINITY;
530 		break;
531 	    }
532 	}
533     } else {
534 	total = INFINITY;
535     }
536     return total;
537 }
538 
539 #ifndef NO_OPTIMIZE
540 #define NEXTTAB(fr)	(fr + init_tabs - (fr % init_tabs))
541 
542 /*
543  * Assume back_tab (CBT) does not wrap backwards at the left margin, return
544  * a negative value at that point to simplify the loop.
545  */
546 #define LASTTAB(fr)	((fr > 0) ? ((fr - 1) / init_tabs) * init_tabs : -1)
547 
548 static int
549 relative_move(NCURSES_SP_DCLx
550 	      string_desc * target,
551 	      int from_y,
552 	      int from_x,
553 	      int to_y,
554 	      int to_x,
555 	      int ovw)
556 /* move via local motions (cuu/cuu1/cud/cud1/cub1/cub/cuf1/cuf/vpa/hpa) */
557 {
558     string_desc save;
559     int n, vcost = 0, hcost = 0;
560 
561     (void) _nc_str_copy(&save, target);
562 
563     if (to_y != from_y) {
564 	vcost = INFINITY;
565 
566 	if (row_address != 0
567 	    && _nc_safe_strcat(target, TIPARM_1(row_address, to_y))) {
568 	    vcost = SP_PARM->_vpa_cost;
569 	}
570 
571 	if (to_y > from_y) {
572 	    n = (to_y - from_y);
573 
574 	    if (parm_down_cursor
575 		&& SP_PARM->_cud_cost < vcost
576 		&& _nc_safe_strcat(_nc_str_copy(target, &save),
577 				   TIPARM_1(parm_down_cursor, n))) {
578 		vcost = SP_PARM->_cud_cost;
579 	    }
580 
581 	    if (cursor_down
582 		&& (*cursor_down != '\n')
583 		&& (n * SP_PARM->_cud1_cost < vcost)) {
584 		vcost = repeated_append(_nc_str_copy(target, &save), 0,
585 					SP_PARM->_cud1_cost, n, cursor_down);
586 	    }
587 	} else {		/* (to_y < from_y) */
588 	    n = (from_y - to_y);
589 
590 	    if (parm_up_cursor
591 		&& SP_PARM->_cuu_cost < vcost
592 		&& _nc_safe_strcat(_nc_str_copy(target, &save),
593 				   TIPARM_1(parm_up_cursor, n))) {
594 		vcost = SP_PARM->_cuu_cost;
595 	    }
596 
597 	    if (cursor_up && (n * SP_PARM->_cuu1_cost < vcost)) {
598 		vcost = repeated_append(_nc_str_copy(target, &save), 0,
599 					SP_PARM->_cuu1_cost, n, cursor_up);
600 	    }
601 	}
602 
603 	if (vcost == INFINITY)
604 	    return (INFINITY);
605     }
606 
607     save = *target;
608 
609     if (to_x != from_x) {
610 	char str[OPT_SIZE];
611 	string_desc check;
612 
613 	hcost = INFINITY;
614 
615 	if (column_address
616 	    && _nc_safe_strcat(_nc_str_copy(target, &save),
617 			       TIPARM_1(column_address, to_x))) {
618 	    hcost = SP_PARM->_hpa_cost;
619 	}
620 
621 	if (to_x > from_x) {
622 	    n = to_x - from_x;
623 
624 	    if (parm_right_cursor
625 		&& SP_PARM->_cuf_cost < hcost
626 		&& _nc_safe_strcat(_nc_str_copy(target, &save),
627 				   TIPARM_1(parm_right_cursor, n))) {
628 		hcost = SP_PARM->_cuf_cost;
629 	    }
630 
631 	    if (cursor_right) {
632 		int lhcost = 0;
633 
634 		(void) _nc_str_init(&check, str, sizeof(str));
635 
636 #if USE_HARD_TABS
637 		/* use hard tabs, if we have them, to do as much as possible */
638 		if (init_tabs > 0 && tab) {
639 		    int nxt, fr;
640 
641 		    for (fr = from_x; (nxt = NEXTTAB(fr)) <= to_x; fr = nxt) {
642 			lhcost = repeated_append(&check, lhcost,
643 						 SP_PARM->_ht_cost, 1, tab);
644 			if (lhcost == INFINITY)
645 			    break;
646 		    }
647 
648 		    n = to_x - fr;
649 		    from_x = fr;
650 		}
651 #endif /* USE_HARD_TABS */
652 
653 		if (n <= 0 || n >= (int) check.s_size)
654 		    ovw = FALSE;
655 #if BSD_TPUTS
656 		/*
657 		 * If we're allowing BSD-style padding in tputs, don't generate
658 		 * a string with a leading digit.  Otherwise, that will be
659 		 * interpreted as a padding value rather than sent to the
660 		 * screen.
661 		 */
662 		if (ovw
663 		    && n > 0
664 		    && n < (int) check.s_size
665 		    && vcost == 0
666 		    && str[0] == '\0') {
667 		    int wanted = CharOf(WANT_CHAR(SP_PARM, to_y, from_x));
668 		    if (is8bits(wanted) && isdigit(wanted))
669 			ovw = FALSE;
670 		}
671 #endif
672 		/*
673 		 * If we have no attribute changes, overwrite is cheaper.
674 		 * Note: must suppress this by passing in ovw = FALSE whenever
675 		 * WANT_CHAR would return invalid data.  In particular, this
676 		 * is true between the time a hardware scroll has been done
677 		 * and the time the structure WANT_CHAR would access has been
678 		 * updated.
679 		 */
680 		if (ovw && to_y >= 0) {
681 		    int i;
682 
683 		    for (i = 0; i < n; i++) {
684 			NCURSES_CH_T ch = WANT_CHAR(SP_PARM, to_y, from_x + i);
685 			if (!SameAttrOf(ch, SCREEN_ATTRS(SP_PARM))
686 #if USE_WIDEC_SUPPORT
687 			    || !Charable(ch)
688 #endif
689 			    ) {
690 			    ovw = FALSE;
691 			    break;
692 			}
693 		    }
694 		}
695 		if (ovw && to_y >= 0) {
696 		    int i;
697 
698 		    for (i = 0; i < n; i++)
699 			*check.s_tail++ = (char) CharOf(WANT_CHAR(SP_PARM, to_y,
700 								  from_x + i));
701 		    *check.s_tail = '\0';
702 		    check.s_size -= (size_t) n;
703 		    lhcost += n * SP_PARM->_char_padding;
704 		} else {
705 		    lhcost = repeated_append(&check, lhcost, SP_PARM->_cuf1_cost,
706 					     n, cursor_right);
707 		}
708 
709 		if (lhcost < hcost
710 		    && _nc_safe_strcat(_nc_str_copy(target, &save), str)) {
711 		    hcost = lhcost;
712 		}
713 	    }
714 	} else {		/* (to_x < from_x) */
715 	    n = from_x - to_x;
716 
717 	    if (parm_left_cursor
718 		&& SP_PARM->_cub_cost < hcost
719 		&& _nc_safe_strcat(_nc_str_copy(target, &save),
720 				   TIPARM_1(parm_left_cursor, n))) {
721 		hcost = SP_PARM->_cub_cost;
722 	    }
723 
724 	    if (cursor_left) {
725 		int lhcost = 0;
726 
727 		(void) _nc_str_init(&check, str, sizeof(str));
728 
729 #if USE_HARD_TABS
730 		if (init_tabs > 0 && back_tab) {
731 		    int nxt, fr;
732 
733 		    for (fr = from_x; (nxt = LASTTAB(fr)) >= to_x; fr = nxt) {
734 			lhcost = repeated_append(&check, lhcost,
735 						 SP_PARM->_cbt_cost,
736 						 1, back_tab);
737 			if (lhcost == INFINITY)
738 			    break;
739 		    }
740 
741 		    n = fr - to_x;
742 		}
743 #endif /* USE_HARD_TABS */
744 
745 		lhcost = repeated_append(&check, lhcost,
746 					 SP_PARM->_cub1_cost,
747 					 n, cursor_left);
748 
749 		if (lhcost < hcost
750 		    && _nc_safe_strcat(_nc_str_copy(target, &save), str)) {
751 		    hcost = lhcost;
752 		}
753 	    }
754 	}
755 
756 	if (hcost == INFINITY)
757 	    return (INFINITY);
758     }
759 
760     return (vcost + hcost);
761 }
762 #endif /* !NO_OPTIMIZE */
763 
764 /*
765  * With the machinery set up above, it is conceivable that
766  * onscreen_mvcur could be modified into a recursive function that does
767  * an alpha-beta search of motion space, as though it were a chess
768  * move tree, with the weight function being boolean and the search
769  * depth equated to length of string.  However, this would jack up the
770  * computation cost a lot, especially on terminals without a cup
771  * capability constraining the search tree depth.  So we settle for
772  * the simpler method below.
773  */
774 
775 static NCURSES_INLINE int
776 onscreen_mvcur(NCURSES_SP_DCLx
777 	       int yold, int xold,
778 	       int ynew, int xnew, int ovw,
779 	       NCURSES_SP_OUTC myOutCh)
780 /* onscreen move from (yold, xold) to (ynew, xnew) */
781 {
782     string_desc result;
783     char buffer[OPT_SIZE];
784     int tactic = 0, newcost, usecost = INFINITY;
785     int t5_cr_cost;
786 
787 #if defined(MAIN) || defined(NCURSES_TEST)
788     struct timeval before, after;
789 
790     gettimeofday(&before, NULL);
791 #endif /* MAIN */
792 
793 #define NullResult _nc_str_null(&result, sizeof(buffer))
794 #define InitResult _nc_str_init(&result, buffer, sizeof(buffer))
795 
796     /* tactic #0: use direct cursor addressing */
797     if (_nc_safe_strcpy(InitResult, TIPARM_2(SP_PARM->_address_cursor,
798 					     ynew, xnew))) {
799 	tactic = 0;
800 	usecost = SP_PARM->_cup_cost;
801 
802 #if defined(TRACE) || defined(NCURSES_TEST)
803 	if (!(_nc_optimize_enable & OPTIMIZE_MVCUR))
804 	    goto nonlocal;
805 #endif /* TRACE */
806 
807 	/*
808 	 * We may be able to tell in advance that the full optimization
809 	 * will probably not be worth its overhead.  Also, don't try to
810 	 * use local movement if the current attribute is anything but
811 	 * A_NORMAL...there are just too many ways this can screw up
812 	 * (like, say, local-movement \n getting mapped to some obscure
813 	 * character because A_ALTCHARSET is on).
814 	 */
815 	if (yold == -1 || xold == -1 || NOT_LOCAL(SP_PARM, yold, xold, ynew, xnew)) {
816 #if defined(MAIN) || defined(NCURSES_TEST)
817 	    if (!profiling) {
818 		(void) fputs("nonlocal\n", stderr);
819 		goto nonlocal;	/* always run the optimizer if profiling */
820 	    }
821 #else
822 	    goto nonlocal;
823 #endif /* MAIN */
824 	}
825     }
826 #ifndef NO_OPTIMIZE
827     /* tactic #1: use local movement */
828     if (yold != -1 && xold != -1
829 	&& ((newcost = relative_move(NCURSES_SP_ARGx
830 				     NullResult,
831 				     yold, xold,
832 				     ynew, xnew, ovw)) != INFINITY)
833 	&& newcost < usecost) {
834 	tactic = 1;
835 	usecost = newcost;
836     }
837 
838     /* tactic #2: use carriage-return + local movement */
839     if (yold != -1 && carriage_return
840 	&& ((newcost = relative_move(NCURSES_SP_ARGx
841 				     NullResult,
842 				     yold, 0,
843 				     ynew, xnew, ovw)) != INFINITY)
844 	&& SP_PARM->_cr_cost + newcost < usecost) {
845 	tactic = 2;
846 	usecost = SP_PARM->_cr_cost + newcost;
847     }
848 
849     /* tactic #3: use home-cursor + local movement */
850     if (cursor_home
851 	&& ((newcost = relative_move(NCURSES_SP_ARGx
852 				     NullResult,
853 				     0, 0,
854 				     ynew, xnew, ovw)) != INFINITY)
855 	&& SP_PARM->_home_cost + newcost < usecost) {
856 	tactic = 3;
857 	usecost = SP_PARM->_home_cost + newcost;
858     }
859 
860     /* tactic #4: use home-down + local movement */
861     if (cursor_to_ll
862 	&& ((newcost = relative_move(NCURSES_SP_ARGx
863 				     NullResult,
864 				     screen_lines(SP_PARM) - 1, 0,
865 				     ynew, xnew, ovw)) != INFINITY)
866 	&& SP_PARM->_ll_cost + newcost < usecost) {
867 	tactic = 4;
868 	usecost = SP_PARM->_ll_cost + newcost;
869     }
870 
871     /*
872      * tactic #5: use left margin for wrap to right-hand side,
873      * unless strange wrap behavior indicated by xenl might hose us.
874      */
875     t5_cr_cost = (xold > 0 ? SP_PARM->_cr_cost : 0);
876     if (auto_left_margin && !eat_newline_glitch
877 	&& yold > 0 && cursor_left
878 	&& ((newcost = relative_move(NCURSES_SP_ARGx
879 				     NullResult,
880 				     yold - 1, screen_columns(SP_PARM) - 1,
881 				     ynew, xnew, ovw)) != INFINITY)
882 	&& t5_cr_cost + SP_PARM->_cub1_cost + newcost < usecost) {
883 	tactic = 5;
884 	usecost = t5_cr_cost + SP_PARM->_cub1_cost + newcost;
885     }
886 
887     /*
888      * These cases are ordered by estimated relative frequency.
889      */
890     if (tactic)
891 	InitResult;
892     switch (tactic) {
893     case 1:
894 	(void) relative_move(NCURSES_SP_ARGx
895 			     &result,
896 			     yold, xold,
897 			     ynew, xnew, ovw);
898 	break;
899     case 2:
900 	(void) _nc_safe_strcpy(&result, carriage_return);
901 	(void) relative_move(NCURSES_SP_ARGx
902 			     &result,
903 			     yold, 0,
904 			     ynew, xnew, ovw);
905 	break;
906     case 3:
907 	(void) _nc_safe_strcpy(&result, cursor_home);
908 	(void) relative_move(NCURSES_SP_ARGx
909 			     &result, 0, 0,
910 			     ynew, xnew, ovw);
911 	break;
912     case 4:
913 	(void) _nc_safe_strcpy(&result, cursor_to_ll);
914 	(void) relative_move(NCURSES_SP_ARGx
915 			     &result,
916 			     screen_lines(SP_PARM) - 1, 0,
917 			     ynew, xnew, ovw);
918 	break;
919     case 5:
920 	if (xold > 0)
921 	    (void) _nc_safe_strcat(&result, carriage_return);
922 	(void) _nc_safe_strcat(&result, cursor_left);
923 	(void) relative_move(NCURSES_SP_ARGx
924 			     &result,
925 			     yold - 1, screen_columns(SP_PARM) - 1,
926 			     ynew, xnew, ovw);
927 	break;
928     }
929 #endif /* !NO_OPTIMIZE */
930 
931   nonlocal:
932 #if defined(MAIN) || defined(NCURSES_TEST)
933     gettimeofday(&after, NULL);
934     diff = after.tv_usec - before.tv_usec
935 	+ (after.tv_sec - before.tv_sec) * 1000000;
936     if (!profiling)
937 	(void) fprintf(stderr,
938 		       "onscreen: %d microsec, %f 28.8Kbps char-equivalents\n",
939 		       (int) diff, diff / 288);
940 #endif /* MAIN */
941 
942     if (usecost != INFINITY) {
943 	TR(TRACE_MOVE, ("mvcur tactic %d", tactic));
944 	TPUTS_TRACE("mvcur");
945 	NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
946 				buffer, 1, myOutCh);
947 	SP_PARM->_cursrow = ynew;
948 	SP_PARM->_curscol = xnew;
949 	return (OK);
950     } else
951 	return (ERR);
952 }
953 
954 /*
955  * optimized cursor move from (yold, xold) to (ynew, xnew)
956  */
957 static int
958 _nc_real_mvcur(NCURSES_SP_DCLx
959 	       int yold, int xold,
960 	       int ynew, int xnew,
961 	       NCURSES_SP_OUTC myOutCh,
962 	       int ovw)
963 {
964     NCURSES_CH_T oldattr;
965     int code;
966 
967     TR(TRACE_CALLS | TRACE_MOVE, (T_CALLED("_nc_real_mvcur(%p,%d,%d,%d,%d)"),
968 				  (void *) SP_PARM, yold, xold, ynew, xnew));
969 
970     if (SP_PARM == 0) {
971 	code = ERR;
972     } else if (yold == ynew && xold == xnew) {
973 	code = OK;
974     } else {
975 
976 	/*
977 	 * Most work here is rounding for terminal boundaries getting the
978 	 * column position implied by wraparound or the lack thereof and
979 	 * rolling up the screen to get ynew on the screen.
980 	 */
981 	if (xnew >= screen_columns(SP_PARM)) {
982 	    ynew += xnew / screen_columns(SP_PARM);
983 	    xnew %= screen_columns(SP_PARM);
984 	}
985 
986 	/*
987 	 * Force restore even if msgr is on when we're in an alternate
988 	 * character set -- these have a strong tendency to screw up the CR &
989 	 * LF used for local character motions!
990 	 */
991 	oldattr = SCREEN_ATTRS(SP_PARM);
992 	if ((AttrOf(oldattr) & A_ALTCHARSET)
993 	    || (AttrOf(oldattr) && !move_standout_mode)) {
994 	    TR(TRACE_CHARPUT, ("turning off (%#lx) %s before move",
995 			       (unsigned long) AttrOf(oldattr),
996 			       _traceattr(AttrOf(oldattr))));
997 	    VIDPUTS(SP_PARM, A_NORMAL, 0);
998 	}
999 
1000 	if (xold >= screen_columns(SP_PARM)) {
1001 
1002 	    int l = (xold + 1) / screen_columns(SP_PARM);
1003 
1004 	    yold += l;
1005 	    if (yold >= screen_lines(SP_PARM))
1006 		l -= (yold - screen_lines(SP_PARM) - 1);
1007 
1008 	    if (l > 0) {
1009 		if (carriage_return) {
1010 		    NCURSES_PUTP2("carriage_return", carriage_return);
1011 		} else {
1012 		    myOutCh(NCURSES_SP_ARGx '\r');
1013 		}
1014 		xold = 0;
1015 
1016 		while (l > 0) {
1017 		    if (newline) {
1018 			NCURSES_PUTP2("newline", newline);
1019 		    } else {
1020 			myOutCh(NCURSES_SP_ARGx '\n');
1021 		    }
1022 		    l--;
1023 		}
1024 	    }
1025 	}
1026 
1027 	if (yold > screen_lines(SP_PARM) - 1)
1028 	    yold = screen_lines(SP_PARM) - 1;
1029 	if (ynew > screen_lines(SP_PARM) - 1)
1030 	    ynew = screen_lines(SP_PARM) - 1;
1031 
1032 	/* destination location is on screen now */
1033 	code = onscreen_mvcur(NCURSES_SP_ARGx yold, xold, ynew, xnew, ovw, myOutCh);
1034 
1035 	/*
1036 	 * Restore attributes if we disabled them before moving.
1037 	 */
1038 	if (!SameAttrOf(oldattr, SCREEN_ATTRS(SP_PARM))) {
1039 	    TR(TRACE_CHARPUT, ("turning on (%#lx) %s after move",
1040 			       (unsigned long) AttrOf(oldattr),
1041 			       _traceattr(AttrOf(oldattr))));
1042 	    VIDPUTS(SP_PARM, AttrOf(oldattr), GetPair(oldattr));
1043 	}
1044     }
1045     returnCode(code);
1046 }
1047 
1048 /*
1049  * These entrypoints are used within the library.
1050  */
1051 NCURSES_EXPORT(int)
1052 NCURSES_SP_NAME(_nc_mvcur) (NCURSES_SP_DCLx
1053 			    int yold, int xold,
1054 			    int ynew, int xnew)
1055 {
1056     int rc;
1057     rc = _nc_real_mvcur(NCURSES_SP_ARGx yold, xold, ynew, xnew,
1058 			NCURSES_SP_NAME(_nc_outch),
1059 			TRUE);
1060     /*
1061      * With the terminal-driver, we cannot distinguish between internal and
1062      * external calls.  Flush the output if the screen has not been
1063      * initialized, e.g., when used from low-level terminfo programs.
1064      */
1065     if ((SP_PARM != 0) && (SP_PARM->_endwin == ewInitial))
1066 	NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
1067     return rc;
1068 }
1069 
1070 #if NCURSES_SP_FUNCS
1071 NCURSES_EXPORT(int)
1072 _nc_mvcur(int yold, int xold,
1073 	  int ynew, int xnew)
1074 {
1075     return NCURSES_SP_NAME(_nc_mvcur) (CURRENT_SCREEN, yold, xold, ynew, xnew);
1076 }
1077 #endif
1078 
1079 #if defined(USE_TERM_DRIVER)
1080 /*
1081  * The terminal driver does not support the external "mvcur()".
1082  */
1083 NCURSES_EXPORT(int)
1084 TINFO_MVCUR(NCURSES_SP_DCLx int yold, int xold, int ynew, int xnew)
1085 {
1086     int rc;
1087     rc = _nc_real_mvcur(NCURSES_SP_ARGx
1088 			yold, xold,
1089 			ynew, xnew,
1090 			NCURSES_SP_NAME(_nc_outch),
1091 			TRUE);
1092     if ((SP_PARM != 0) && (SP_PARM->_endwin == ewInitial))
1093 	NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
1094     NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
1095     return rc;
1096 }
1097 
1098 #else /* !USE_TERM_DRIVER */
1099 
1100 /*
1101  * These entrypoints support users of the library.
1102  */
1103 NCURSES_EXPORT(int)
1104 NCURSES_SP_NAME(mvcur) (NCURSES_SP_DCLx int yold, int xold, int ynew,
1105 			int xnew)
1106 {
1107     return _nc_real_mvcur(NCURSES_SP_ARGx
1108 			  yold, xold,
1109 			  ynew, xnew,
1110 			  NCURSES_SP_NAME(_nc_putchar),
1111 			  FALSE);
1112 }
1113 
1114 #if NCURSES_SP_FUNCS
1115 NCURSES_EXPORT(int)
1116 mvcur(int yold, int xold, int ynew, int xnew)
1117 {
1118     return NCURSES_SP_NAME(mvcur) (CURRENT_SCREEN, yold, xold, ynew, xnew);
1119 }
1120 #endif
1121 #endif /* USE_TERM_DRIVER */
1122 
1123 #if defined(TRACE) || defined(NCURSES_TEST)
1124 NCURSES_EXPORT_VAR(int) _nc_optimize_enable = OPTIMIZE_ALL;
1125 #endif
1126 
1127 #if defined(MAIN) || defined(NCURSES_TEST)
1128 /****************************************************************************
1129  *
1130  * Movement optimizer test code
1131  *
1132  ****************************************************************************/
1133 
1134 #include <tic.h>
1135 #include <dump_entry.h>
1136 #include <time.h>
1137 
1138 NCURSES_EXPORT_VAR(const char *) _nc_progname = "mvcur";
1139 
1140 static unsigned long xmits;
1141 
1142 /* these override lib_tputs.c */
1143 NCURSES_EXPORT(int)
1144 tputs(const char *string, int affcnt GCC_UNUSED, int (*outc) (int) GCC_UNUSED)
1145 /* stub tputs() that dumps sequences in a visible form */
1146 {
1147     if (profiling)
1148 	xmits += strlen(string);
1149     else
1150 	(void) fputs(_nc_visbuf(string), stdout);
1151     return (OK);
1152 }
1153 
1154 NCURSES_EXPORT(int)
1155 putp(const char *string)
1156 {
1157     return (tputs(string, 1, _nc_outch));
1158 }
1159 
1160 NCURSES_EXPORT(int)
1161 _nc_outch(int ch)
1162 {
1163     putc(ch, stdout);
1164     return OK;
1165 }
1166 
1167 NCURSES_EXPORT(int)
1168 delay_output(int ms GCC_UNUSED)
1169 {
1170     return OK;
1171 }
1172 
1173 static char tname[PATH_MAX];
1174 
1175 static void
1176 load_term(void)
1177 {
1178     (void) setupterm(tname, STDOUT_FILENO, NULL);
1179 }
1180 
1181 static int
1182 roll(int n)
1183 {
1184     int i, j;
1185 
1186     i = (RAND_MAX / n) * n;
1187     while ((j = rand()) >= i)
1188 	continue;
1189     return (j % n);
1190 }
1191 
1192 int
1193 main(int argc GCC_UNUSED, char *argv[]GCC_UNUSED)
1194 {
1195     _nc_STRCPY(tname, getenv("TERM"), sizeof(tname));
1196     load_term();
1197     _nc_setupscreen(lines, columns, stdout, FALSE, 0);
1198     baudrate();
1199 
1200     _nc_mvcur_init();
1201 
1202     (void) puts("The mvcur tester.  Type ? for help");
1203 
1204     fputs("smcup:", stdout);
1205     putchar('\n');
1206 
1207     for (;;) {
1208 	int fy, fx, ty, tx, n, i;
1209 	char buf[BUFSIZ], capname[BUFSIZ];
1210 
1211 	if (fputs("> ", stdout) == EOF)
1212 	    break;
1213 	if (fgets(buf, sizeof(buf), stdin) == 0)
1214 	    break;
1215 
1216 #define PUTS(s)   (void) puts(s)
1217 #define PUTF(s,t) (void) printf(s,t)
1218 	if (buf[0] == '?') {
1219 	    PUTS("?                -- display this help message");
1220 	    PUTS("fy fx ty tx      -- (4 numbers) display (fy,fx)->(ty,tx) move");
1221 	    PUTS("s[croll] n t b m -- display scrolling sequence");
1222 	    PUTF("r[eload]         -- reload terminal info for %s\n",
1223 		 termname());
1224 	    PUTS("l[oad] <term>    -- load terminal info for type <term>");
1225 	    PUTS("d[elete] <cap>   -- delete named capability");
1226 	    PUTS("i[nspect]        -- display terminal capabilities");
1227 	    PUTS("c[ost]           -- dump cursor-optimization cost table");
1228 	    PUTS("o[optimize]      -- toggle movement optimization");
1229 	    PUTS("t[orture] <num>  -- torture-test with <num> random moves");
1230 	    PUTS("q[uit]           -- quit the program");
1231 	} else if (sscanf(buf, "%d %d %d %d", &fy, &fx, &ty, &tx) == 4) {
1232 	    struct timeval before, after;
1233 
1234 	    putchar('"');
1235 
1236 	    gettimeofday(&before, NULL);
1237 	    mvcur(fy, fx, ty, tx);
1238 	    gettimeofday(&after, NULL);
1239 
1240 	    printf("\" (%ld msec)\n",
1241 		   (long) (after.tv_usec - before.tv_usec
1242 			   + (after.tv_sec - before.tv_sec)
1243 			   * 1000000));
1244 	} else if (sscanf(buf, "s %d %d %d %d", &fy, &fx, &ty, &tx) == 4) {
1245 	    struct timeval before, after;
1246 
1247 	    putchar('"');
1248 
1249 	    gettimeofday(&before, NULL);
1250 	    _nc_scrolln(fy, fx, ty, tx);
1251 	    gettimeofday(&after, NULL);
1252 
1253 	    printf("\" (%ld msec)\n",
1254 		   (long) (after.tv_usec - before.tv_usec + (after.tv_sec -
1255 							     before.tv_sec)
1256 			   * 1000000));
1257 	} else if (buf[0] == 'r') {
1258 	    _nc_STRCPY(tname, termname(), sizeof(tname));
1259 	    load_term();
1260 	} else if (sscanf(buf, "l %s", tname) == 1) {
1261 	    load_term();
1262 	} else if (sscanf(buf, "d %s", capname) == 1) {
1263 	    struct name_table_entry const *np = _nc_find_entry(capname,
1264 							       _nc_get_hash_table(FALSE));
1265 
1266 	    if (np == NULL)
1267 		(void) printf("No such capability as \"%s\"\n", capname);
1268 	    else {
1269 		switch (np->nte_type) {
1270 		case BOOLEAN:
1271 		    cur_term->type.Booleans[np->nte_index] = FALSE;
1272 		    (void)
1273 			printf("Boolean capability `%s' (%d) turned off.\n",
1274 			       np->nte_name, np->nte_index);
1275 		    break;
1276 
1277 		case NUMBER:
1278 		    cur_term->type.Numbers[np->nte_index] = ABSENT_NUMERIC;
1279 		    (void) printf("Number capability `%s' (%d) set to -1.\n",
1280 				  np->nte_name, np->nte_index);
1281 		    break;
1282 
1283 		case STRING:
1284 		    cur_term->type.Strings[np->nte_index] = ABSENT_STRING;
1285 		    (void) printf("String capability `%s' (%d) deleted.\n",
1286 				  np->nte_name, np->nte_index);
1287 		    break;
1288 		}
1289 	    }
1290 	} else if (buf[0] == 'i') {
1291 	    dump_init(NULL, F_TERMINFO, S_TERMINFO,
1292 		      FALSE, 70, 0, 0, FALSE, FALSE, 0);
1293 	    dump_entry(&TerminalType(cur_term), FALSE, TRUE, 0, 0);
1294 	    putchar('\n');
1295 	} else if (buf[0] == 'o') {
1296 	    if (_nc_optimize_enable & OPTIMIZE_MVCUR) {
1297 		_nc_optimize_enable &= ~OPTIMIZE_MVCUR;
1298 		(void) puts("Optimization is now off.");
1299 	    } else {
1300 		_nc_optimize_enable |= OPTIMIZE_MVCUR;
1301 		(void) puts("Optimization is now on.");
1302 	    }
1303 	}
1304 	/*
1305 	 * You can use the `t' test to profile and tune the movement
1306 	 * optimizer.  Use iteration values in three digits or more.
1307 	 * At above 5000 iterations the profile timing averages are stable
1308 	 * to within a millisecond or three.
1309 	 *
1310 	 * The `overhead' field of the report will help you pick a
1311 	 * COMPUTE_OVERHEAD figure appropriate for your processor and
1312 	 * expected line speed.  The `total estimated time' is
1313 	 * computation time plus a character-transmission time
1314 	 * estimate computed from the number of transmits and the baud
1315 	 * rate.
1316 	 *
1317 	 * Use this together with the `o' command to get a read on the
1318 	 * optimizer's effectiveness.  Compare the total estimated times
1319 	 * for `t' runs of the same length in both optimized and un-optimized
1320 	 * modes.  As long as the optimized times are less, the optimizer
1321 	 * is winning.
1322 	 */
1323 	else if (sscanf(buf, "t %d", &n) == 1) {
1324 	    float cumtime = 0.0, perchar;
1325 	    int speeds[] =
1326 	    {2400, 9600, 14400, 19200, 28800, 38400, 0};
1327 
1328 	    srand((unsigned) (getpid() + time((time_t *) 0)));
1329 	    profiling = TRUE;
1330 	    xmits = 0;
1331 	    for (i = 0; i < n; i++) {
1332 		/*
1333 		 * This does a move test between two random locations,
1334 		 * Random moves probably short-change the optimizer,
1335 		 * which will work better on the short moves probably
1336 		 * typical of doupdate()'s usage pattern.  Still,
1337 		 * until we have better data...
1338 		 */
1339 #ifdef FIND_COREDUMP
1340 		int from_y = roll(lines);
1341 		int to_y = roll(lines);
1342 		int from_x = roll(columns);
1343 		int to_x = roll(columns);
1344 
1345 		printf("(%d,%d) -> (%d,%d)\n", from_y, from_x, to_y, to_x);
1346 		mvcur(from_y, from_x, to_y, to_x);
1347 #else
1348 		mvcur(roll(lines), roll(columns), roll(lines), roll(columns));
1349 #endif /* FIND_COREDUMP */
1350 		if (diff)
1351 		    cumtime += diff;
1352 	    }
1353 	    profiling = FALSE;
1354 
1355 	    /*
1356 	     * Average milliseconds per character optimization time.
1357 	     * This is the key figure to watch when tuning the optimizer.
1358 	     */
1359 	    perchar = cumtime / n;
1360 
1361 	    (void) printf("%d moves (%ld chars) in %d msec, %f msec each:\n",
1362 			  n, xmits, (int) cumtime, perchar);
1363 
1364 	    for (i = 0; speeds[i]; i++) {
1365 		/*
1366 		 * Total estimated time for the moves, computation and
1367 		 * transmission both. Transmission time is an estimate
1368 		 * assuming 9 bits/char, 8 bits + 1 stop bit.
1369 		 */
1370 		float totalest = cumtime + xmits * 9 * 1e6 / speeds[i];
1371 
1372 		/*
1373 		 * Per-character optimization overhead in character transmits
1374 		 * at the current speed.  Round this to the nearest integer
1375 		 * to figure COMPUTE_OVERHEAD for the speed.
1376 		 */
1377 		float overhead = speeds[i] * perchar / 1e6;
1378 
1379 		(void)
1380 		    printf("%6d bps: %3.2f char-xmits overhead; total estimated time %15.2f\n",
1381 			   speeds[i], overhead, totalest);
1382 	    }
1383 	} else if (buf[0] == 'c') {
1384 	    (void) printf("char padding: %d\n", CURRENT_SCREEN->_char_padding);
1385 	    (void) printf("cr cost: %d\n", CURRENT_SCREEN->_cr_cost);
1386 	    (void) printf("cup cost: %d\n", CURRENT_SCREEN->_cup_cost);
1387 	    (void) printf("home cost: %d\n", CURRENT_SCREEN->_home_cost);
1388 	    (void) printf("ll cost: %d\n", CURRENT_SCREEN->_ll_cost);
1389 #if USE_HARD_TABS
1390 	    (void) printf("ht cost: %d\n", CURRENT_SCREEN->_ht_cost);
1391 	    (void) printf("cbt cost: %d\n", CURRENT_SCREEN->_cbt_cost);
1392 #endif /* USE_HARD_TABS */
1393 	    (void) printf("cub1 cost: %d\n", CURRENT_SCREEN->_cub1_cost);
1394 	    (void) printf("cuf1 cost: %d\n", CURRENT_SCREEN->_cuf1_cost);
1395 	    (void) printf("cud1 cost: %d\n", CURRENT_SCREEN->_cud1_cost);
1396 	    (void) printf("cuu1 cost: %d\n", CURRENT_SCREEN->_cuu1_cost);
1397 	    (void) printf("cub cost: %d\n", CURRENT_SCREEN->_cub_cost);
1398 	    (void) printf("cuf cost: %d\n", CURRENT_SCREEN->_cuf_cost);
1399 	    (void) printf("cud cost: %d\n", CURRENT_SCREEN->_cud_cost);
1400 	    (void) printf("cuu cost: %d\n", CURRENT_SCREEN->_cuu_cost);
1401 	    (void) printf("hpa cost: %d\n", CURRENT_SCREEN->_hpa_cost);
1402 	    (void) printf("vpa cost: %d\n", CURRENT_SCREEN->_vpa_cost);
1403 	} else if (buf[0] == 'x' || buf[0] == 'q')
1404 	    break;
1405 	else
1406 	    (void) puts("Invalid command.");
1407     }
1408 
1409     (void) fputs("rmcup:", stdout);
1410     _nc_mvcur_wrap();
1411     putchar('\n');
1412 
1413     return (0);
1414 }
1415 
1416 #endif /* MAIN */
1417 
1418 /* lib_mvcur.c ends here */
1419