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