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