xref: /freebsd/usr.bin/top/display.c (revision 780fb4a2)
1 /*
2  *  Top users/processes display for Unix
3  *  Version 3
4  *
5  *  This program may be freely redistributed,
6  *  but this entire comment MUST remain intact.
7  *
8  *  Copyright (c) 1984, 1989, William LeFebvre, Rice University
9  *  Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
10  *
11  * $FreeBSD$
12  */
13 
14 /*
15  *  This file contains the routines that display information on the screen.
16  *  Each section of the screen has two routines:  one for initially writing
17  *  all constant and dynamic text, and one for only updating the text that
18  *  changes.  The prefix "i_" is used on all the "initial" routines and the
19  *  prefix "u_" is used for all the "updating" routines.
20  *
21  *  ASSUMPTIONS:
22  *        None of the "i_" routines use any of the termcap capabilities.
23  *        In this way, those routines can be safely used on terminals that
24  *        have minimal (or nonexistant) terminal capabilities.
25  *
26  *        The routines are called in this order:  *_loadave, i_timeofday,
27  *        *_procstates, *_cpustates, *_memory, *_message, *_header,
28  *        *_process, u_endscreen.
29  */
30 
31 #include <sys/cdefs.h>
32 #include <sys/resource.h>
33 #include <sys/time.h>
34 
35 #include <assert.h>
36 #include <ctype.h>
37 #include <stdarg.h>
38 #include <stdbool.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <termcap.h>
43 #include <time.h>
44 #include <unistd.h>
45 
46 #include "screen.h"		/* interface to screen package */
47 #include "layout.h"		/* defines for screen position layout */
48 #include "display.h"
49 #include "top.h"
50 #include "machine.h"		/* we should eliminate this!!! */
51 #include "utils.h"
52 
53 #ifdef DEBUG
54 FILE *debug;
55 #endif
56 
57 static int lmpid = 0;
58 static int last_hi = 0;		/* used in u_process and u_endscreen */
59 static int lastline = 0;
60 
61 #define lineindex(l) ((l)*screen_width)
62 
63 
64 /* things initialized by display_init and used thruout */
65 
66 /* buffer of proc information lines for display updating */
67 static char *screenbuf = NULL;
68 
69 static const char * const *procstate_names;
70 static const char * const *cpustate_names;
71 static const char * const *memory_names;
72 static const char * const *arc_names;
73 static const char * const *carc_names;
74 static const char * const *swap_names;
75 
76 static int num_procstates;
77 static int num_cpustates;
78 static int num_memory;
79 static int num_swap;
80 
81 static int *lprocstates;
82 static int *lcpustates;
83 static int *lmemory;
84 static int *lswap;
85 
86 static int num_cpus;
87 static int *cpustate_columns;
88 static int cpustate_total_length;
89 static int cpustates_column;
90 
91 static enum { OFF, ON, ERASE } header_status = ON;
92 
93 static void summary_format(char *, int *, const char * const *);
94 static void line_update(char *, char *, int, int);
95 
96 static int setup_buffer_bufsiz = 0;
97 static char * setup_buffer(char *, int);
98 
99 int  x_lastpid =	10;
100 int  y_lastpid =	0;
101 int  x_loadave =	33;
102 int  x_loadave_nompid =	15;
103 int  y_loadave =	0;
104 int  x_procstate =	0;
105 int  y_procstate =	1;
106 int  x_brkdn =		15;
107 int  y_brkdn =		1;
108 int  x_mem =		5;
109 int  y_mem =		3;
110 int  x_arc =		5;
111 int  y_arc =		4;
112 int  x_carc =		5;
113 int  y_carc =		5;
114 int  x_swap =		6;
115 int  y_swap =		4;
116 int  y_message =	5;
117 int  x_header =		0;
118 int  y_header =		6;
119 int  x_idlecursor =	0;
120 int  y_idlecursor =	5;
121 int  y_procs =		7;
122 
123 int  y_cpustates =	2;
124 int  Header_lines =	7;
125 
126 int
127 display_resize(void)
128 {
129     int lines;
130 
131     /* first, deallocate any previous buffer that may have been there */
132     if (screenbuf != NULL)
133     {
134 	free(screenbuf);
135     }
136 
137     /* calculate the current dimensions */
138     /* if operating in "dumb" mode, we only need one line */
139     lines = smart_terminal ? screen_length - Header_lines : 1;
140 
141     if (lines < 0)
142 	lines = 0;
143 
144     /* now, allocate space for the screen buffer */
145     screenbuf = calloc(lines, screen_width);
146     if (screenbuf == NULL)
147     {
148 	/* oops! */
149 	return(-1);
150     }
151 
152     /* return number of lines available */
153     /* for dumb terminals, pretend like we can show any amount */
154     return(smart_terminal ? lines : Largest);
155 }
156 
157 int
158 display_updatecpus(struct statics *statics)
159 {
160     int lines;
161     int i;
162 
163     /* call resize to do the dirty work */
164     lines = display_resize();
165     if (pcpu_stats)
166 		num_cpus = statics->ncpus;
167     else
168 		num_cpus = 1;
169     cpustates_column = 5;	/* CPU: */
170     if (num_cpus > 1) {
171 		cpustates_column += 1 + digits(num_cpus); /* CPU #: */
172 	}
173 
174     /* fill the "last" array with all -1s, to insure correct updating */
175 	for (i = 0; i < num_cpustates * num_cpus; ++i) {
176 		lcpustates[i] = -1;
177     }
178 
179     return(lines);
180 }
181 
182 int
183 display_init(struct statics * statics)
184 {
185     int lines;
186     char **pp;
187     int *ip;
188     int i;
189 
190     lines = display_updatecpus(statics);
191 
192     /* only do the rest if we need to */
193     if (lines > -1)
194     {
195 	/* save pointers and allocate space for names */
196 	procstate_names = statics->procstate_names;
197 	num_procstates = 8;
198 	assert(num_procstates > 0);
199 	lprocstates = calloc(num_procstates, sizeof(int));
200 
201 	cpustate_names = statics->cpustate_names;
202 
203 	swap_names = statics->swap_names;
204 	num_swap = 7;
205 	assert(num_swap > 0);
206 	lswap = calloc(num_swap, sizeof(int));
207 	num_cpustates = CPUSTATES;
208 	assert(num_cpustates > 0);
209 	lcpustates = calloc(num_cpustates * sizeof(int), statics->ncpus);
210 	cpustate_columns = calloc(num_cpustates, sizeof(int));
211 
212 	memory_names = statics->memory_names;
213 	num_memory = 7;
214 	assert(num_memory > 0);
215 	lmemory = calloc(num_memory, sizeof(int));
216 
217 	arc_names = statics->arc_names;
218 	carc_names = statics->carc_names;
219 
220 	/* calculate starting columns where needed */
221 	cpustate_total_length = 0;
222 	pp = cpustate_names;
223 	ip = cpustate_columns;
224 	while (*pp != NULL)
225 	{
226 	    *ip++ = cpustate_total_length;
227 	    if ((i = strlen(*pp++)) > 0)
228 	    {
229 		cpustate_total_length += i + 8;
230 	    }
231 	}
232     }
233 
234     /* return number of lines available */
235     return(lines);
236 }
237 
238 void
239 i_loadave(int mpid, double avenrun[])
240 {
241     int i;
242 
243     /* i_loadave also clears the screen, since it is first */
244     top_clear();
245 
246     /* mpid == -1 implies this system doesn't have an _mpid */
247     if (mpid != -1)
248     {
249 	printf("last pid: %5d;  ", mpid);
250     }
251 
252     printf("load averages");
253 
254     for (i = 0; i < 3; i++)
255     {
256 	printf("%c %5.2f",
257 	    i == 0 ? ':' : ',',
258 	    avenrun[i]);
259     }
260     lmpid = mpid;
261 }
262 
263 void
264 u_loadave(int mpid, double *avenrun)
265 {
266     int i;
267 
268     if (mpid != -1)
269     {
270 	/* change screen only when value has really changed */
271 	if (mpid != lmpid)
272 	{
273 	    Move_to(x_lastpid, y_lastpid);
274 	    printf("%5d", mpid);
275 	    lmpid = mpid;
276 	}
277 
278 	/* i remembers x coordinate to move to */
279 	i = x_loadave;
280     }
281     else
282     {
283 	i = x_loadave_nompid;
284     }
285 
286     /* move into position for load averages */
287     Move_to(i, y_loadave);
288 
289     /* display new load averages */
290     /* we should optimize this and only display changes */
291     for (i = 0; i < 3; i++)
292     {
293 	printf("%s%5.2f",
294 	    i == 0 ? "" : ", ",
295 	    avenrun[i]);
296     }
297 }
298 
299 void
300 i_timeofday(time_t *tod)
301 {
302     /*
303      *  Display the current time.
304      *  "ctime" always returns a string that looks like this:
305      *
306      *	Sun Sep 16 01:03:52 1973
307      *      012345678901234567890123
308      *	          1         2
309      *
310      *  We want indices 11 thru 18 (length 8).
311      */
312 
313     if (smart_terminal)
314     {
315 	Move_to(screen_width - 8, 0);
316     }
317     else
318     {
319 	fputs("    ", stdout);
320     }
321 #ifdef DEBUG
322     {
323 	char *foo;
324 	foo = ctime(tod);
325 	fputs(foo, stdout);
326     }
327 #endif
328     printf("%-8.8s\n", &(ctime(tod)[11]));
329     lastline = 1;
330 }
331 
332 static int ltotal = 0;
333 static char *procstates_buffer = NULL;
334 
335 /*
336  *  *_procstates(total, brkdn, names) - print the process summary line
337  *
338  *  Assumptions:  cursor is at the beginning of the line on entry
339  *		  lastline is valid
340  */
341 
342 void
343 i_procstates(int total, int *brkdn)
344 {
345     int i;
346 
347     procstates_buffer = setup_buffer(procstates_buffer, 0);
348 
349     /* write current number of processes and remember the value */
350     printf("%d %s:", total, ps.thread ? "threads" : "processes");
351     ltotal = total;
352 
353     /* put out enough spaces to get to column 15 */
354     i = digits(total);
355     while (i++ < (ps.thread ? 6 : 4))
356     {
357 	putchar(' ');
358     }
359 
360     /* format and print the process state summary */
361     summary_format(procstates_buffer, brkdn, procstate_names);
362     fputs(procstates_buffer, stdout);
363 
364     /* save the numbers for next time */
365     memcpy(lprocstates, brkdn, num_procstates * sizeof(int));
366 }
367 
368 void
369 u_procstates(int total, int *brkdn)
370 {
371     static char *new = NULL;
372     int i;
373 
374     new = setup_buffer(new, 0);
375 
376     /* update number of processes only if it has changed */
377     if (ltotal != total)
378     {
379 	/* move and overwrite */
380 if (x_procstate == 0) {
381 	Move_to(x_procstate, y_procstate);
382 }
383 else {
384 	/* cursor is already there...no motion needed */
385 	assert(lastline == 1);
386 }
387 	printf("%d", total);
388 
389 	/* if number of digits differs, rewrite the label */
390 	if (digits(total) != digits(ltotal))
391 	{
392 	    printf(" %s:", ps.thread ? "threads" : "processes");
393 	    /* put out enough spaces to get to column 15 */
394 	    i = digits(total);
395 	    while (i++ < (ps.thread ? 6 : 4))
396 	    {
397 		putchar(' ');
398 	    }
399 	    /* cursor may end up right where we want it!!! */
400 	}
401 
402 	/* save new total */
403 	ltotal = total;
404     }
405 
406     /* see if any of the state numbers has changed */
407     if (memcmp(lprocstates, brkdn, num_procstates * sizeof(int)) != 0)
408     {
409 	/* format and update the line */
410 	summary_format(new, brkdn, procstate_names);
411 	line_update(procstates_buffer, new, x_brkdn, y_brkdn);
412 	memcpy(lprocstates, brkdn, num_procstates * sizeof(int));
413     }
414 }
415 
416 void
417 i_cpustates(int *states)
418 {
419     int i = 0;
420     int value;
421     const char * const *names;
422     const char *thisname;
423     int cpu;
424 
425 for (cpu = 0; cpu < num_cpus; cpu++) {
426     names = cpustate_names;
427 
428     /* print tag and bump lastline */
429     if (num_cpus == 1)
430 	printf("\nCPU: ");
431     else {
432 	value = printf("\nCPU %d: ", cpu);
433 	while (value++ <= cpustates_column)
434 		printf(" ");
435     }
436     lastline++;
437 
438     /* now walk thru the names and print the line */
439     while ((thisname = *names++) != NULL)
440     {
441 	if (*thisname != '\0')
442 	{
443 	    /* retrieve the value and remember it */
444 	    value = *states++;
445 
446 	    /* if percentage is >= 1000, print it as 100% */
447 	    printf((value >= 1000 ? "%s%4.0f%% %s" : "%s%4.1f%% %s"),
448 		   (i++ % num_cpustates) == 0 ? "" : ", ",
449 		   ((float)value)/10.,
450 		   thisname);
451 	}
452     }
453 }
454 
455     /* copy over values into "last" array */
456     memcpy(lcpustates, states, num_cpustates * sizeof(int) * num_cpus);
457 }
458 
459 void
460 u_cpustates(int *states)
461 {
462     int value;
463     const char * const *names;
464     const char *thisname;
465     int *lp;
466     int *colp;
467     int cpu;
468 
469 for (cpu = 0; cpu < num_cpus; cpu++) {
470     names = cpustate_names;
471 
472     Move_to(cpustates_column, y_cpustates + cpu);
473     lastline = y_cpustates + cpu;
474     lp = lcpustates + (cpu * num_cpustates);
475     colp = cpustate_columns;
476 
477     /* we could be much more optimal about this */
478     while ((thisname = *names++) != NULL)
479     {
480 	if (*thisname != '\0')
481 	{
482 	    /* did the value change since last time? */
483 	    if (*lp != *states)
484 	    {
485 		/* yes, move and change */
486 		Move_to(cpustates_column + *colp, y_cpustates + cpu);
487 		lastline = y_cpustates + cpu;
488 
489 		/* retrieve value and remember it */
490 		value = *states;
491 
492 		/* if percentage is >= 1000, print it as 100% */
493 		printf((value >= 1000 ? "%4.0f" : "%4.1f"),
494 		       ((double)value)/10.);
495 
496 		/* remember it for next time */
497 		*lp = value;
498 	    }
499 	}
500 
501 	/* increment and move on */
502 	lp++;
503 	states++;
504 	colp++;
505     }
506 }
507 }
508 
509 void
510 z_cpustates(void)
511 {
512     int i = 0;
513     const char **names;
514     char *thisname;
515     int cpu, value;
516 
517     for (cpu = 0; cpu < num_cpus; cpu++) {
518 	    names = cpustate_names;
519 
520 	    /* show tag and bump lastline */
521 	    if (num_cpus == 1)
522 		    printf("\nCPU: ");
523 	    else {
524 		    value = printf("\nCPU %d: ", cpu);
525 		    while (value++ <= cpustates_column)
526 			    printf(" ");
527 	    }
528 	    lastline++;
529 
530 	    while ((thisname = *names++) != NULL)
531 	    {
532 		    if (*thisname != '\0')
533 		    {
534 			    printf("%s    %% %s", (i++ % num_cpustates) == 0 ? "" : ", ", thisname);
535 		    }
536 	    }
537     }
538 
539     /* fill the "last" array with all -1s, to insure correct updating */
540 	for (i = 0; i < num_cpustates * num_cpus; ++i) {
541 		lcpustates[i] = -1;
542     }
543 }
544 
545 /*
546  *  *_memory(stats) - print "Memory: " followed by the memory summary string
547  *
548  *  Assumptions:  cursor is on "lastline"
549  *                for i_memory ONLY: cursor is on the previous line
550  */
551 
552 static char *memory_buffer = NULL;
553 
554 void
555 i_memory(int *stats)
556 {
557     memory_buffer = setup_buffer(memory_buffer, 0);
558 
559     fputs("\nMem: ", stdout);
560     lastline++;
561 
562     /* format and print the memory summary */
563     summary_format(memory_buffer, stats, memory_names);
564     fputs(memory_buffer, stdout);
565 }
566 
567 void
568 u_memory(int *stats)
569 {
570     static char *new = NULL;
571 
572     new = setup_buffer(new, 0);
573 
574     /* format the new line */
575     summary_format(new, stats, memory_names);
576     line_update(memory_buffer, new, x_mem, y_mem);
577 }
578 
579 /*
580  *  *_arc(stats) - print "ARC: " followed by the ARC summary string
581  *
582  *  Assumptions:  cursor is on "lastline"
583  *                for i_arc ONLY: cursor is on the previous line
584  */
585 static char *arc_buffer = NULL;
586 
587 void
588 i_arc(int *stats)
589 {
590     arc_buffer = setup_buffer(arc_buffer, 0);
591 
592     if (arc_names == NULL)
593 	return;
594 
595     fputs("\nARC: ", stdout);
596     lastline++;
597 
598     /* format and print the memory summary */
599     summary_format(arc_buffer, stats, arc_names);
600     fputs(arc_buffer, stdout);
601 }
602 
603 void
604 u_arc(int *stats)
605 {
606     static char *new = NULL;
607 
608     new = setup_buffer(new, 0);
609 
610     if (arc_names == NULL)
611 	return;
612 
613     /* format the new line */
614     summary_format(new, stats, arc_names);
615     line_update(arc_buffer, new, x_arc, y_arc);
616 }
617 
618 
619 /*
620  *  *_carc(stats) - print "Compressed ARC: " followed by the summary string
621  *
622  *  Assumptions:  cursor is on "lastline"
623  *                for i_carc ONLY: cursor is on the previous line
624  */
625 static char *carc_buffer = NULL;
626 
627 void
628 i_carc(int *stats)
629 {
630     carc_buffer = setup_buffer(carc_buffer, 0);
631 
632     if (carc_names == NULL)
633 	return;
634 
635     fputs("\n     ", stdout);
636     lastline++;
637 
638     /* format and print the memory summary */
639     summary_format(carc_buffer, stats, carc_names);
640     fputs(carc_buffer, stdout);
641 }
642 
643 void
644 u_carc(int *stats)
645 {
646     static char *new = NULL;
647 
648     new = setup_buffer(new, 0);
649 
650     if (carc_names == NULL)
651 	return;
652 
653     /* format the new line */
654     summary_format(new, stats, carc_names);
655     line_update(carc_buffer, new, x_carc, y_carc);
656 }
657 
658 /*
659  *  *_swap(stats) - print "Swap: " followed by the swap summary string
660  *
661  *  Assumptions:  cursor is on "lastline"
662  *                for i_swap ONLY: cursor is on the previous line
663  */
664 
665 static char *swap_buffer = NULL;
666 
667 void
668 i_swap(int *stats)
669 {
670     swap_buffer = setup_buffer(swap_buffer, 0);
671 
672     fputs("\nSwap: ", stdout);
673     lastline++;
674 
675     /* format and print the swap summary */
676     summary_format(swap_buffer, stats, swap_names);
677     fputs(swap_buffer, stdout);
678 }
679 
680 void
681 u_swap(int *stats)
682 {
683     static char *new = NULL;
684 
685     new = setup_buffer(new, 0);
686 
687     /* format the new line */
688     summary_format(new, stats, swap_names);
689     line_update(swap_buffer, new, x_swap, y_swap);
690 }
691 
692 /*
693  *  *_message() - print the next pending message line, or erase the one
694  *                that is there.
695  *
696  *  Note that u_message is (currently) the same as i_message.
697  *
698  *  Assumptions:  lastline is consistent
699  */
700 
701 /*
702  *  i_message is funny because it gets its message asynchronously (with
703  *	respect to screen updates).
704  */
705 
706 #define NEXT_MSG_ADDLEN 5
707 static char *next_msg = NULL;
708 static int msglen = 0;
709 /* Invariant: msglen is always the length of the message currently displayed
710    on the screen (even when next_msg doesn't contain that message). */
711 
712 void
713 i_message(void)
714 {
715     next_msg = setup_buffer(next_msg, NEXT_MSG_ADDLEN);
716 
717     while (lastline < y_message)
718     {
719 	fputc('\n', stdout);
720 	lastline++;
721     }
722     if (next_msg[0] != '\0')
723     {
724 	top_standout(next_msg);
725 	msglen = strlen(next_msg);
726 	next_msg[0] = '\0';
727     }
728     else if (msglen > 0)
729     {
730 	(void) clear_eol(msglen);
731 	msglen = 0;
732     }
733 }
734 
735 void
736 u_message(void)
737 {
738     i_message();
739 }
740 
741 static int header_length;
742 
743 /*
744  * Trim a header string to the current display width and return a newly
745  * allocated area with the trimmed header.
746  */
747 
748 const char *
749 trim_header(const char *text)
750 {
751 	char *s;
752 	int width;
753 
754 	s = NULL;
755 	width = screen_width;
756 	header_length = strlen(text);
757 	if (header_length >= width) {
758 		s = strndup(text, width);
759 		if (s == NULL)
760 			return (NULL);
761 	}
762 	return (s);
763 }
764 
765 /*
766  *  *_header(text) - print the header for the process area
767  *
768  *  Assumptions:  cursor is on the previous line and lastline is consistent
769  */
770 
771 void
772 i_header(const char *text)
773 {
774     char *s;
775 
776     s = trim_header(text);
777     if (s != NULL)
778 	text = s;
779 
780     if (header_status == ON)
781     {
782 	putchar('\n');
783 	fputs(text, stdout);
784 	lastline++;
785     }
786     else if (header_status == ERASE)
787     {
788 	header_status = OFF;
789     }
790     free(s);
791 }
792 
793 void
794 u_header(const char *text __unused)
795 {
796 
797     if (header_status == ERASE)
798     {
799 	putchar('\n');
800 	lastline++;
801 	clear_eol(header_length);
802 	header_status = OFF;
803     }
804 }
805 
806 /*
807  *  *_process(line, thisline) - print one process line
808  *
809  *  Assumptions:  lastline is consistent
810  */
811 
812 void
813 i_process(int line, char *thisline)
814 {
815     char *p;
816     char *base;
817 
818     /* make sure we are on the correct line */
819     while (lastline < y_procs + line)
820     {
821 	putchar('\n');
822 	lastline++;
823     }
824 
825     /* truncate the line to conform to our current screen width */
826     thisline[screen_width] = '\0';
827 
828     /* write the line out */
829     fputs(thisline, stdout);
830 
831     /* copy it in to our buffer */
832     base = smart_terminal ? screenbuf + lineindex(line) : screenbuf;
833     p = stpcpy(base, thisline);
834 
835     /* zero fill the rest of it */
836     memset(p, 0, screen_width - (p - base));
837 }
838 
839 void
840 u_process(int line, char *newline)
841 {
842     char *optr;
843     int screen_line = line + Header_lines;
844     char *bufferline;
845 
846     /* remember a pointer to the current line in the screen buffer */
847     bufferline = &screenbuf[lineindex(line)];
848 
849     /* truncate the line to conform to our current screen width */
850     newline[screen_width] = '\0';
851 
852     /* is line higher than we went on the last display? */
853     if (line >= last_hi)
854     {
855 	/* yes, just ignore screenbuf and write it out directly */
856 	/* get positioned on the correct line */
857 	if (screen_line - lastline == 1)
858 	{
859 	    putchar('\n');
860 	    lastline++;
861 	}
862 	else
863 	{
864 	    Move_to(0, screen_line);
865 	    lastline = screen_line;
866 	}
867 
868 	/* now write the line */
869 	fputs(newline, stdout);
870 
871 	/* copy it in to the buffer */
872 	optr = stpcpy(bufferline, newline);
873 
874 	/* zero fill the rest of it */
875 	memset(optr, 0, screen_width - (optr - bufferline));
876     }
877     else
878     {
879 	line_update(bufferline, newline, 0, line + Header_lines);
880     }
881 }
882 
883 void
884 u_endscreen(int hi)
885 {
886     int screen_line = hi + Header_lines;
887     int i;
888 
889     if (smart_terminal)
890     {
891 	if (hi < last_hi)
892 	{
893 	    /* need to blank the remainder of the screen */
894 	    /* but only if there is any screen left below this line */
895 	    if (lastline + 1 < screen_length)
896 	    {
897 		/* efficiently move to the end of currently displayed info */
898 		if (screen_line - lastline < 5)
899 		{
900 		    while (lastline < screen_line)
901 		    {
902 			putchar('\n');
903 			lastline++;
904 		    }
905 		}
906 		else
907 		{
908 		    Move_to(0, screen_line);
909 		    lastline = screen_line;
910 		}
911 
912 		if (clear_to_end)
913 		{
914 		    /* we can do this the easy way */
915 		    putcap(clear_to_end);
916 		}
917 		else
918 		{
919 		    /* use clear_eol on each line */
920 		    i = hi;
921 		    while ((void) clear_eol(strlen(&screenbuf[lineindex(i++)])), i < last_hi)
922 		    {
923 			putchar('\n');
924 		    }
925 		}
926 	    }
927 	}
928 	last_hi = hi;
929 
930 	/* move the cursor to a pleasant place */
931 	Move_to(x_idlecursor, y_idlecursor);
932 	lastline = y_idlecursor;
933     }
934     else
935     {
936 	/* separate this display from the next with some vertical room */
937 	fputs("\n\n", stdout);
938     }
939 }
940 
941 void
942 display_header(int t)
943 {
944 
945     if (t)
946     {
947 	header_status = ON;
948     }
949     else if (header_status == ON)
950     {
951 	header_status = ERASE;
952     }
953 }
954 
955 void
956 new_message(int type, const char *msgfmt, ...)
957 {
958     va_list args;
959     size_t i;
960 
961     va_start(args, msgfmt);
962 
963     /* first, format the message */
964     vsnprintf(next_msg, setup_buffer_bufsiz + NEXT_MSG_ADDLEN,
965 		    msgfmt, args);
966 
967     va_end(args);
968 
969     if (msglen > 0)
970     {
971 	/* message there already -- can we clear it? */
972 	if (!overstrike)
973 	{
974 	    /* yes -- write it and clear to end */
975 	    i = strlen(next_msg);
976 	    if ((type & MT_delayed) == 0)
977 	    {
978 			if (type & MT_standout) {
979 				top_standout(next_msg);
980 			} else {
981 				fputs(next_msg, stdout);
982 			}
983 			clear_eol(msglen - i);
984 			msglen = i;
985 			next_msg[0] = '\0';
986 	    }
987 	}
988     }
989     else
990     {
991 	if ((type & MT_delayed) == 0)
992 	{
993 		if (type & MT_standout) {
994 			top_standout(next_msg);
995 		} else {
996 			fputs(next_msg, stdout);
997 		}
998 	    msglen = strlen(next_msg);
999 	    next_msg[0] = '\0';
1000 	}
1001     }
1002 }
1003 
1004 void
1005 clear_message(void)
1006 {
1007     if (clear_eol(msglen) == 1)
1008     {
1009 	putchar('\r');
1010     }
1011 }
1012 
1013 int
1014 readline(char *buffer, int size, int numeric)
1015 {
1016     char *ptr = buffer;
1017     char ch;
1018     char cnt = 0;
1019     char maxcnt = 0;
1020 
1021     /* allow room for null terminator */
1022     size -= 1;
1023 
1024     /* read loop */
1025     while ((fflush(stdout), read(0, ptr, 1) > 0))
1026     {
1027 	/* newline means we are done */
1028 	if ((ch = *ptr) == '\n' || ch == '\r')
1029 	{
1030 	    break;
1031 	}
1032 
1033 	/* handle special editing characters */
1034 	if (ch == ch_kill)
1035 	{
1036 	    /* kill line -- account for overstriking */
1037 	    if (overstrike)
1038 	    {
1039 		msglen += maxcnt;
1040 	    }
1041 
1042 	    /* return null string */
1043 	    *buffer = '\0';
1044 	    putchar('\r');
1045 	    return(-1);
1046 	}
1047 	else if (ch == ch_erase)
1048 	{
1049 	    /* erase previous character */
1050 	    if (cnt <= 0)
1051 	    {
1052 		/* none to erase! */
1053 		putchar('\7');
1054 	    }
1055 	    else
1056 	    {
1057 		fputs("\b \b", stdout);
1058 		ptr--;
1059 		cnt--;
1060 	    }
1061 	}
1062 	/* check for character validity and buffer overflow */
1063 	else if (cnt == size || (numeric && !isdigit(ch)) ||
1064 		!isprint(ch))
1065 	{
1066 	    /* not legal */
1067 	    putchar('\7');
1068 	}
1069 	else
1070 	{
1071 	    /* echo it and store it in the buffer */
1072 	    putchar(ch);
1073 	    ptr++;
1074 	    cnt++;
1075 	    if (cnt > maxcnt)
1076 	    {
1077 		maxcnt = cnt;
1078 	    }
1079 	}
1080     }
1081 
1082     /* all done -- null terminate the string */
1083     *ptr = '\0';
1084 
1085     /* account for the extra characters in the message area */
1086     /* (if terminal overstrikes, remember the furthest they went) */
1087     msglen += overstrike ? maxcnt : cnt;
1088 
1089     /* return either inputted number or string length */
1090     putchar('\r');
1091     return(cnt == 0 ? -1 : numeric ? atoi(buffer) : cnt);
1092 }
1093 
1094 /* internal support routines */
1095 
1096 static void
1097 summary_format(char *str, int *numbers, const char * const *names)
1098 {
1099     char *p;
1100     int num;
1101     const char *thisname;
1102     char rbuf[6];
1103 
1104     /* format each number followed by its string */
1105     p = str;
1106     while ((thisname = *names++) != NULL)
1107     {
1108 	/* get the number to format */
1109 	num = *numbers++;
1110 
1111 	/* display only non-zero numbers */
1112 	if (num > 0)
1113 	{
1114 	    /* is this number in kilobytes? */
1115 	    if (thisname[0] == 'K')
1116 	    {
1117 		/* yes: format it as a memory value */
1118 		p = stpcpy(p, format_k(num));
1119 
1120 		/* skip over the K, since it was included by format_k */
1121 		p = stpcpy(p, thisname+1);
1122 	    }
1123 	    /* is this number a ratio? */
1124 	    else if (thisname[0] == ':')
1125 	    {
1126 		(void) snprintf(rbuf, sizeof(rbuf), "%.2f",
1127 		    (float)*(numbers - 2) / (float)num);
1128 		p = stpcpy(p, rbuf);
1129 		p = stpcpy(p, thisname);
1130 	    }
1131 	    else
1132 	    {
1133 		p = stpcpy(p, itoa(num));
1134 		p = stpcpy(p, thisname);
1135 	    }
1136 	}
1137 
1138 	/* ignore negative numbers, but display corresponding string */
1139 	else if (num < 0)
1140 	{
1141 	    p = stpcpy(p, thisname);
1142 	}
1143     }
1144 
1145     /* if the last two characters in the string are ", ", delete them */
1146     p -= 2;
1147     if (p >= str && p[0] == ',' && p[1] == ' ')
1148     {
1149 	*p = '\0';
1150     }
1151 }
1152 
1153 static void
1154 line_update(char *old, char *new, int start, int line)
1155 {
1156     int ch;
1157     int diff;
1158     int newcol = start + 1;
1159     int lastcol = start;
1160     char cursor_on_line = false;
1161     char *current;
1162 
1163     /* compare the two strings and only rewrite what has changed */
1164     current = old;
1165 #ifdef DEBUG
1166     fprintf(debug, "line_update, starting at %d\n", start);
1167     fputs(old, debug);
1168     fputc('\n', debug);
1169     fputs(new, debug);
1170     fputs("\n-\n", debug);
1171 #endif
1172 
1173     /* start things off on the right foot		    */
1174     /* this is to make sure the invariants get set up right */
1175     if ((ch = *new++) != *old)
1176     {
1177 	if (line - lastline == 1 && start == 0)
1178 	{
1179 	    putchar('\n');
1180 	}
1181 	else
1182 	{
1183 	    Move_to(start, line);
1184 	}
1185 	cursor_on_line = true;
1186 	putchar(ch);
1187 	*old = ch;
1188 	lastcol = 1;
1189     }
1190     old++;
1191 
1192     /*
1193      *  main loop -- check each character.  If the old and new aren't the
1194      *	same, then update the display.  When the distance from the
1195      *	current cursor position to the new change is small enough,
1196      *	the characters that belong there are written to move the
1197      *	cursor over.
1198      *
1199      *	Invariants:
1200      *	    lastcol is the column where the cursor currently is sitting
1201      *		(always one beyond the end of the last mismatch).
1202      */
1203     do		/* yes, a do...while */
1204     {
1205 	if ((ch = *new++) != *old)
1206 	{
1207 	    /* new character is different from old	  */
1208 	    /* make sure the cursor is on top of this character */
1209 	    diff = newcol - lastcol;
1210 	    if (diff > 0)
1211 	    {
1212 		/* some motion is required--figure out which is shorter */
1213 		if (diff < 6 && cursor_on_line)
1214 		{
1215 		    /* overwrite old stuff--get it out of the old buffer */
1216 		    printf("%.*s", diff, &current[lastcol-start]);
1217 		}
1218 		else
1219 		{
1220 		    /* use cursor addressing */
1221 		    Move_to(newcol, line);
1222 		    cursor_on_line = true;
1223 		}
1224 		/* remember where the cursor is */
1225 		lastcol = newcol + 1;
1226 	    }
1227 	    else
1228 	    {
1229 		/* already there, update position */
1230 		lastcol++;
1231 	    }
1232 
1233 	    /* write what we need to */
1234 	    if (ch == '\0')
1235 	    {
1236 		/* at the end--terminate with a clear-to-end-of-line */
1237 		(void) clear_eol(strlen(old));
1238 	    }
1239 	    else
1240 	    {
1241 		/* write the new character */
1242 		putchar(ch);
1243 	    }
1244 	    /* put the new character in the screen buffer */
1245 	    *old = ch;
1246 	}
1247 
1248 	/* update working column and screen buffer pointer */
1249 	newcol++;
1250 	old++;
1251 
1252     } while (ch != '\0');
1253 
1254     /* zero out the rest of the line buffer -- MUST BE DONE! */
1255     diff = screen_width - newcol;
1256     if (diff > 0)
1257     {
1258 	memset(old, 0, diff);
1259     }
1260 
1261     /* remember where the current line is */
1262     if (cursor_on_line)
1263     {
1264 	lastline = line;
1265     }
1266 }
1267 
1268 /*
1269  *  printable(str) - make the string pointed to by "str" into one that is
1270  *	printable (i.e.: all ascii), by converting all non-printable
1271  *	characters into '?'.  Replacements are done in place and a pointer
1272  *	to the original buffer is returned.
1273  */
1274 
1275 char *
1276 printable(char str[])
1277 {
1278     char *ptr;
1279     char ch;
1280 
1281     ptr = str;
1282     while ((ch = *ptr) != '\0')
1283     {
1284 	if (!isprint(ch))
1285 	{
1286 	    *ptr = '?';
1287 	}
1288 	ptr++;
1289     }
1290     return(str);
1291 }
1292 
1293 void
1294 i_uptime(struct timeval *bt, time_t *tod)
1295 {
1296     time_t uptime;
1297     int days, hrs, mins, secs;
1298 
1299     if (bt->tv_sec != -1) {
1300 	uptime = *tod - bt->tv_sec;
1301 	days = uptime / 86400;
1302 	uptime %= 86400;
1303 	hrs = uptime / 3600;
1304 	uptime %= 3600;
1305 	mins = uptime / 60;
1306 	secs = uptime % 60;
1307 
1308 	/*
1309 	 *  Display the uptime.
1310 	 */
1311 
1312 	if (smart_terminal)
1313 	{
1314 	    Move_to((screen_width - 24) - (days > 9 ? 1 : 0), 0);
1315 	}
1316 	else
1317 	{
1318 	    fputs(" ", stdout);
1319 	}
1320 	printf(" up %d+%02d:%02d:%02d", days, hrs, mins, secs);
1321     }
1322 }
1323 
1324 #define SETUPBUFFER_REQUIRED_ADDBUFSIZ 2
1325 
1326 static char *
1327 setup_buffer(char *buffer, int addlen)
1328 {
1329 	char *b = NULL;
1330 
1331 	if (NULL == buffer) {
1332 		setup_buffer_bufsiz = screen_width;
1333 		b = calloc(setup_buffer_bufsiz + addlen +
1334 				SETUPBUFFER_REQUIRED_ADDBUFSIZ,
1335 				sizeof(char));
1336 	} else {
1337 		if (screen_width > setup_buffer_bufsiz) {
1338 			setup_buffer_bufsiz = screen_width;
1339 			free(buffer);
1340 			b = calloc(setup_buffer_bufsiz + addlen +
1341 					SETUPBUFFER_REQUIRED_ADDBUFSIZ,
1342 					sizeof(char));
1343 		} else {
1344 			b = buffer;
1345 		}
1346 	}
1347 
1348 	if (NULL == b) {
1349 		fprintf(stderr, "%s: can't allocate sufficient memory\n",
1350 				myname);
1351 		exit(4);
1352 	}
1353 
1354 	return b;
1355 }
1356