summaryrefslogtreecommitdiff
path: root/lib/libcurses/hardscroll.c
blob: 7e6d1cc3bce0e883b196328eb62c8f9c9c82b926 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

/***************************************************************************
*                            COPYRIGHT NOTICE                              *
****************************************************************************
*                ncurses is copyright (C) 1992-1995                        *
*                          Zeyd M. Ben-Halim                               *
*                          zmbenhal@netcom.com                             *
*                          Eric S. Raymond                                 *
*                          esr@snark.thyrsus.com                           *
*                                                                          *
*        Permission is hereby granted to reproduce and distribute ncurses  *
*        by any means and for any fee, whether alone or as part of a       *
*        larger distribution, in source or in binary form, PROVIDED        *
*        this notice is included with any such distribution, and is not    *
*        removed from any of its header files. Mention of ncurses in any   *
*        applications linked with it is highly appreciated.                *
*                                                                          *
*        ncurses comes AS IS with no warranty, implied or expressed.       *
*                                                                          *
***************************************************************************/


/******************************************************************************

NAME
   hardscroll.c -- hardware-scrolling optimization for ncurses

SYNOPSIS
   void _nc_scroll_optimize(void)

DESCRIPTION
			OVERVIEW

This algorithm for computes optimum hardware scrolling to transform an
old screen (curscr) into a new screen (newscr) via vertical line moves.

Because the screen has a `grain' (there are insert/delete/scroll line
operations but no insert/delete/scroll column operations), it is efficient
break the update algorithm into two pieces: a first stage that does only line
moves, optimizing the end product of user-invoked insertions, deletions, and
scrolls; and a second phase (corresponding to the present doupdate code in
ncurses) that does only line transformations.

The common case we want hardware scrolling for is to handle line insertions
and deletions in screen-oriented text-editors.  This two-stage approach will
accomplish that at a low computation and code-size cost.

			LINE-MOVE COMPUTATION

Now, to a discussion of the line-move computation.

For expository purposes, consider the screen lines to be represented by
integers 0..23 (with the understanding that the value of 23 may vary).
Let a new line introduced by insertion, scrolling, or at the bottom of
the screen following a line delete be given the index -1.

Assume that the real screen starts with lines 0..23.  Now, we have
the following possible line-oriented operations on the screen:

Insertion: inserts a line at a given screen row, forcing all lines below
to scroll forward.  The last screen line is lost.  For example, an insertion
at line 5 would produce: 0..4 -1 5..23.

Deletion: deletes a line at a given screen row, forcing all lines below
to scroll forward.  The last screen line is made new.  For example, a deletion
at line 7 would produce: 0..6 8..23 -1.

Scroll up: move a range of lines up 1.  The bottom line of the range
becomes new.  For example, scrolling up the region from 9 to 14 will
produce 0..8 10..14 -1 15..23.

Scroll down: move a range of lines down 1.  The top line of the range
becomes new.  For example, scrolling down the region from 12 to 16 will produce
0..11 -1 12..15 17..23.

Now, an obvious property of all these operations is that they preserve the
order of old lines, though not their position in the sequence.

The key trick of this algorithm is that the original line indices described
above are actually maintained as _line[].oldindex fields in the window
structure, and stick to each line through scroll and insert/delete operations.

Thus, it is possible at update time to look at the oldnum fields and compute
an optimal set of il/dl/scroll operations that will take the real screen
lines to the virtual screen lines.  Once these vertical moves have been done,
we can hand off to the second stage of the update algorithm, which does line
transformations.

Note that the move computation does not need to have the full generality
of a diff algorithm (which it superficially resembles) because lines cannot
be moved out of order.

			THE ALGORITHM

First, mark each line on the real screen that is *not* carried over to the
virtual screen discarded (that is, with a -1 oldnum index).

Second, optionally run through each virtual line with a non -1 oldnum.  If the
line is sufficiently changed, mark it -1 (we don't want to move it).  The exact
test for "sufficiently changed" is not relevant to the control flow of this
algorithm.  Cases the test should detect are those in which rewriting
the line from whatever might be on the real screen would be cheaper than the
move.  Blank lines on a terminal with clear-to-eol probably meet this test.

Here is pseudo-code for the remainder of the algorithm:

  repeat
1:    first = 0;
2:    no_hunk_moved = TRUE;

      # on each pass, try to find a movable hunk
3:    while (first < screen_depth)

          # scan for start of hunk
4:        while (oldnum field of first == -1)
              first++

          # if we have no hunk, quit this pass
5:        if (first >= screen_depth)
              break;

          # we found a hunk
6:        last = (end of longest continues oldnum range starting here)

7:        ofirst = (first line's oldnum, where it was on real screen)
8:        olast = (last line's oldnum, where it was on real screen)

          # figure the hunk's displacement
9:        disp = first - (first virtual line's oldnum field)

          # does the hunk want to move?
10:       if (disp != 0)
              # is the hunk movable without destroying info?
11:           if (real [ofirst+disp, olast+disp] are all in range or DISCARDED)
12:               if (disp > 0)
13:                   scroll real [ofirst, olast+disp] down by disp
                      (mark [ofirst, olast+disp] DISCARDED)
14:               else if (disp < 0)
15:                   scroll real [ofirst+disp, olast] up by disp
                      (mark [ofirst+disp, olast] DISCARDED)
16:               no_hunk_moved = FALSE

          # done trying to move this hunk
17:       first = last + 1;
       end while
    until
18:    no_hunk_moved;    # quit when a complete pass finds no movable hunks

HOW TO TEST THIS:

Use the following production:

hardscroll: hardscroll.c
	$(CC) -g -DSCROLLDEBUG hardscroll.c -o hardscroll

Then just type scramble vectors and watch.  The following test loads are
a representative sample of cases:

-----------------------------  CUT HERE ------------------------------------
# No lines moved
 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# A scroll up
 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 -1
#
# A scroll down
-1  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# An insertion (after line 12)
 0  1  2  3  4  5  6  7  8  9 10 11 12 -1 13 14 15 16 17 18 19 20 21 22
#
# A simple deletion (line 10)
 0  1  2  3  4  5  6  7  8  9  11 12 13 14 15 16 17 18 19 20 21 22 23 -1
#
# A more complex case
-1 -1 -1 -1 -1  3  4  5  6  7  -1 -1  8  9 10 11 12 13 14 15 16 17 -1 -1
-----------------------------  CUT HERE ------------------------------------

AUTHOR
    Eric S. Raymond <esr@snark.thyrsus.com>, November 1994

*****************************************************************************/

#include <curses.priv.h>

MODULE_ID("Id: hardscroll.c,v 1.17 1997/02/15 22:33:12 tom Exp $")

#if defined(TRACE) || defined(SCROLLDEBUG)
void _nc_linedump(void);
#endif /* defined(TRACE) || defined(SCROLLDEBUG) */

/* if only this number of lines is carried over, nuke the screen and redraw */
#define CLEAR_THRESHOLD		3

#if defined(SCROLLDEBUG) || defined(HASHDEBUG)
#define LINES	24
int oldnums[LINES], reallines[LINES];
#define OLDNUM(n)	oldnums[n]
#define REAL(m)		reallines[m]
#undef T
#define T(x)		(void) printf x ; (void) putchar('\n');
#else
#include <curses.h>
#define OLDNUM(n)	newscr->_line[n].oldindex
#define REAL(m)		curscr->_line[m].oldindex
#ifndef _NEWINDEX
#define _NEWINDEX	-1
#endif /* _NEWINDEX */
#endif /* defined(SCROLLDEBUG) || defined(HASHDEBUG) */

static bool all_discarded(int const top, int const bottom, int const disp)
/* has the given range of real lines been marked discarded? */
{
    int		n;

    for (n = top + disp; n <= bottom + disp; n++)
	if (REAL(n) != _NEWINDEX && !(REAL(n) <= bottom && REAL(n) >= top))
	    return(FALSE);

    return(TRUE);
}

void _nc_scroll_optimize(void)
/* scroll optimization to transform curscr to newscr */
{
    bool no_hunk_moved;		/* no hunk moved on this pass? */
    int	n, new_lines;
#if defined(TRACE) || defined(SCROLLDEBUG)
    int	pass = 0;
#endif /* defined(TRACE) || defined(SCROLLDEBUG) */

    TR(TRACE_ICALLS, ("_nc_scroll_optimize() begins"));

    /* mark any line not carried over with _NEWINDEX */
    for (n = 0; n < LINES; n++)
	REAL(n) += (MAXLINES + 1);
    for (n = 0; n < LINES; n++)
	if (OLDNUM(n) != _NEWINDEX
	 && REAL(OLDNUM(n)) >= MAXLINES)
	    REAL(OLDNUM(n)) -= (MAXLINES + 1);
    for (n = new_lines = 0; n < LINES; n++)
	if (REAL(n) > MAXLINES)
	{
	    REAL(n) = _NEWINDEX;
	    new_lines++;
	}

    /*
     * ^F in vi (which scrolls forward by LINES-2 in the file) exposes
     * a weakness in this design.  Ideally, vertical motion
     * optimization should cost its actions and then force a
     * ClrUpdate() and complete redraw if that would be faster than
     * the scroll.  Unfortunately, this would be a serious pain to
     * arrange; hence, this hack.  If there are few enough lines
     * carried over, don't bother with the scrolling, we just nuke the
     * screen and redraw the whole thing.  Keith Bostic argues that
     * this will be a win on strictly visual grounds even if the
     * resulting update is theoretically sub-optimal.  Experience
     * with vi says he's probably right.
     */
    if (LINES - new_lines <= CLEAR_THRESHOLD)
    {
	T(("too few lines carried over, nuking screen"));
#if !defined(SCROLLDEBUG) && !defined(HASHDEBUG)
	clearok(stdscr, TRUE);
#endif /* !defined(SCROLLDEBUG) && !defined(HASHDEBUG) */
	return;
    }

#ifdef TRACE
    TR(TRACE_UPDATE | TRACE_MOVE, ("After real line marking:"));
    if (_nc_tracing & (TRACE_UPDATE | TRACE_MOVE))
	_nc_linedump();
#endif /* TRACE */

    /* time to shuffle lines to do scroll optimization */
    do {
	int	first;		/* first line of current hunk */
	int	last;		/* last line of current hunk */
	int	ofirst;		/* oldnum index of first line */
	int	olast;		/* oldnum index of last line */
	int	disp;		/* hunk displacement */

	TR(TRACE_UPDATE | TRACE_MOVE, ("Pass %d:", pass++));

	first = 0;		/* start scan at top line */
	no_hunk_moved = TRUE;

	while (first < LINES)
	{
	    /* find the beginning of a hunk */
	    while (first < LINES && OLDNUM(first) == _NEWINDEX)
		first++;
	    if (first >= LINES)
		break;

	    /* find the end of the hunk */
	    for (last = first; last < LINES; last++)
		if (last == LINES - 1 || OLDNUM(last + 1) != OLDNUM(last) + 1)
		    break;

	    /* find the corresponding range on the old screen */
	    ofirst = OLDNUM(first);
	    olast = OLDNUM(last);

	    /* compute the hunk's displacement */
	    disp = first - OLDNUM(first);

	    TR(TRACE_UPDATE | TRACE_MOVE, ("found hunk: first = %2d, last = %2d, ofirst = %2d, olast = %2d, disp = %2d",
			   first, last, ofirst, olast, disp));

	    /* OK, time to try to move the hunk? */
	    if (disp != 0)
		if (all_discarded(ofirst, olast, disp))
		{
		    int	m;

		    if (disp > 0)
			olast += disp;
		    else /* (disp < 0) */
			ofirst += disp;

		    TR(TRACE_UPDATE | TRACE_MOVE, ("scroll [%d, %d] by %d", ofirst, olast, -disp));
#if !defined(SCROLLDEBUG) && !defined(HASHDEBUG)
		    if (_nc_mvcur_scrolln(-disp, ofirst, olast, LINES - 1) == ERR)
		    	break;
		    _nc_scroll_window(curscr, -disp, ofirst, olast);
#endif /* !defined(SCROLLDEBUG) && !defined(HASHDEBUG) */

		    for (m = ofirst; m <= olast; m++)
		    {
			REAL(m) = _NEWINDEX;
#if !defined(SCROLLDEBUG) && !defined(HASHDEBUG)
			/*
			 * This will tell the second stage of the optimizer
			 * that every line in the hunk on the real screen has
			 * been changed.
			 */
			curscr->_line[m].firstchar = 0;
			curscr->_line[m].lastchar = curscr->_maxx;
#endif /* !defined(SCROLLDEBUG) && !defined(HASHDEBUG) */
		    }
		    for (m = first; m <= last; m++)
			OLDNUM(m) = _NEWINDEX;

		    no_hunk_moved = FALSE;
		}

	    /* OK, done with this hunk */
	    first = last + 1;
	}
    } while
	(!no_hunk_moved);
}

#if defined(TRACE) || defined(SCROLLDEBUG)
void _nc_linedump(void)
/* dump the state of the real and virtual oldnum fields */
{
    int	n;
    char	buf[BUFSIZ];

    (void) strcpy(buf, "real");
    for (n = 0; n < LINES; n++)
	(void) sprintf(buf + strlen(buf), " %02d", REAL(n));
    TR(TRACE_UPDATE | TRACE_MOVE, (buf));

    (void) strcpy(buf, "virt");
    for (n = 0; n < LINES; n++)
	(void) sprintf(buf + strlen(buf), " %02d", OLDNUM(n));
    TR(TRACE_UPDATE | TRACE_MOVE, (buf));
}
#endif /* defined(TRACE) || defined(SCROLLDEBUG) */

#ifdef SCROLLDEBUG

int
main(int argc GCC_UNUSED, char *argv[] GCC_UNUSED)
{
    char	line[BUFSIZ], *st;

    _nc_tracing = TRACE_MOVE;
    for (;;)
    {
	int	n;

	for (n = 0; n < LINES; n++)
	{
	    reallines[n] = n;
	    oldnums[n] = _NEWINDEX;
	}

	/* grab the test vector */
	if (fgets(line, sizeof(line), stdin) == (char *)NULL)
	    exit(EXIT_SUCCESS);

	/* parse it */
	n = 0;
	if (line[0] == '#')
	{
	    (void) fputs(line, stderr);
	    continue;
	}
	st = strtok(line, " ");
	do {
	    oldnums[n++] = atoi(st);
	} while
	    ((st = strtok((char *)NULL, " ")) != 0);

	/* display it */
	(void) fputs("Initial input:\n", stderr);
	_nc_linedump();

	_nc_scroll_optimize();
    }
}

#endif /* SCROLLDEBUG */

/* hardscroll.c ends here */