top(1): Raise WARNS to 6 and fix warnings.
[dragonfly.git] / contrib / top / display.c
blobe9c3ac431bb92534c61be31bf9b9ba3932ea0f48
1 /*
2 * Top users/processes display for Unix
3 * Version 3
5 * This program may be freely redistributed,
6 * but this entire comment MUST remain intact.
8 * Copyright (c) 1984, 1989, William LeFebvre, Rice University
9 * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University
11 * $FreeBSD: src/contrib/top/display.c,v 1.4.6.3 2003/04/27 15:32:26 dwmalone Exp $
12 * $DragonFly: src/contrib/top/display.c,v 1.3 2006/10/03 12:20:11 y0netan1 Exp $
16 * This file contains the routines that display information on the screen.
17 * Each section of the screen has two routines: one for initially writing
18 * all constant and dynamic text, and one for only updating the text that
19 * changes. The prefix "i_" is used on all the "initial" routines and the
20 * prefix "u_" is used for all the "updating" routines.
22 * ASSUMPTIONS:
23 * None of the "i_" routines use any of the termcap capabilities.
24 * In this way, those routines can be safely used on terminals that
25 * have minimal (or nonexistant) terminal capabilities.
27 * The routines are called in this order: *_loadave, i_timeofday,
28 * *_procstates, *_cpustates, *_memory, *_message, *_header,
29 * *_process, u_endscreen.
32 #include <sys/types.h>
33 #include <sys/time.h>
34 #include "os.h"
35 #include <ctype.h>
36 #include <time.h>
37 #include <curses.h>
38 #include <term.h>
39 #include <unistd.h>
41 #include "screen.h" /* interface to screen package */
42 #include "layout.h" /* defines for screen position layout */
43 #include "display.h"
44 #include "top.h"
45 #include "top.local.h"
46 #include "boolean.h"
47 #include "machine.h" /* we should eliminate this!!! */
48 #include "utils.h"
50 #ifdef DEBUG
51 FILE *debug;
52 #endif
54 /* imported from screen.c */
55 extern int overstrike;
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;
62 #define lineindex(l) ((l)*display_width)
64 /* things initialized by display_init and used thruout */
66 /* buffer of proc information lines for display updating */
67 char *screenbuf = NULL;
69 static const char **procstate_names;
70 static const char **cpustate_names;
71 static const char **memory_names;
72 static const char **swap_names;
74 static int num_procstates;
75 static int num_cpustates;
76 static int num_memory;
77 static int num_swap;
79 static int *lprocstates;
80 static int *lmemory;
81 static int *lswap;
83 static int *cpustate_columns;
84 static int cpustate_total_length;
86 static enum { OFF, ON, ERASE } header_status = ON;
88 static int string_count(const char **);
89 static void summary_format(char *str, int *numbers, const char **names);
90 static void line_update(char *old, char *new, int start, int line);
92 int
93 display_resize(void)
95 int xlines;
97 /* first, deallocate any previous buffer that may have been there */
98 if (screenbuf != NULL)
100 free(screenbuf);
103 /* calculate the current dimensions */
104 /* if operating in "dumb" mode, we only need one line */
105 xlines = smart_terminal ? screen_length - Header_lines : 1;
107 if (xlines < 0)
108 xlines = 0;
109 /* we don't want more than MAX_COLS columns, since the machine-dependent
110 modules make static allocations based on MAX_COLS and we don't want
111 to run off the end of their buffers */
112 display_width = screen_width;
113 if (display_width >= MAX_COLS)
115 display_width = MAX_COLS - 1;
118 /* now, allocate space for the screen buffer */
119 screenbuf = (char *)malloc(xlines * display_width);
120 if (screenbuf == (char *)NULL)
122 /* oops! */
123 return(-1);
126 /* return number of lines available */
127 /* for dumb terminals, pretend like we can show any amount */
128 return(smart_terminal ? xlines : Largest);
132 display_init(struct statics *statics)
134 int xlines;
135 const char **pp;
136 int *ip;
137 int i;
139 /* call resize to do the dirty work */
140 xlines = display_resize();
142 /* only do the rest if we need to */
143 if (xlines > -1)
145 /* save pointers and allocate space for names */
146 procstate_names = statics->procstate_names;
147 num_procstates = string_count(procstate_names);
148 lprocstates = (int *)malloc(num_procstates * sizeof(int));
150 cpustate_names = statics->cpustate_names;
152 swap_names = statics->swap_names;
153 num_swap = string_count(swap_names);
154 lswap = (int *)malloc(num_swap * sizeof(int));
155 num_cpustates = string_count(cpustate_names);
156 cpustate_columns = (int *)malloc(num_cpustates * sizeof(int));
158 memory_names = statics->memory_names;
159 num_memory = string_count(memory_names);
160 lmemory = (int *)malloc(num_memory * sizeof(int));
162 /* calculate starting columns where needed */
163 cpustate_total_length = 0;
164 pp = cpustate_names;
165 ip = cpustate_columns;
166 while (*pp != NULL)
168 *ip++ = cpustate_total_length;
169 if ((i = strlen(*pp++)) > 0)
171 cpustate_total_length += i + 8;
176 /* return number of lines available */
177 return(xlines);
180 void
181 i_loadave(int mpid, double *avenrun)
183 int i;
185 /* i_loadave also clears the screen, since it is first */
186 clear_myscreen();
188 /* mpid == -1 implies this system doesn't have an _mpid */
189 if (mpid != -1)
191 printf("last pid: %5d; ", mpid);
194 printf("load averages");
196 for (i = 0; i < 3; i++)
198 printf("%c %5.2f",
199 i == 0 ? ':' : ',',
200 avenrun[i]);
202 lmpid = mpid;
205 void
206 u_loadave(int mpid, double *avenrun)
208 register int i;
210 if (mpid != -1)
212 /* change screen only when value has really changed */
213 if (mpid != lmpid)
215 Move_to(x_lastpid, y_lastpid);
216 printf("%5d", mpid);
217 lmpid = mpid;
220 /* i remembers x coordinate to move to */
221 i = x_loadave;
223 else
225 i = x_loadave_nompid;
228 /* move into position for load averages */
229 Move_to(i, y_loadave);
231 /* display new load averages */
232 /* we should optimize this and only display changes */
233 for (i = 0; i < 3; i++)
235 printf("%s%5.2f",
236 i == 0 ? "" : ", ",
237 avenrun[i]);
241 void
242 i_timeofday(time_t *tod)
245 * Display the current time.
246 * "ctime" always returns a string that looks like this:
248 * Sun Sep 16 01:03:52 1973
249 * 012345678901234567890123
250 * 1 2
252 * We want indices 11 thru 18 (length 8).
255 if (smart_terminal)
257 Move_to(screen_width - 8, 0);
259 else
261 fputs(" ", stdout);
263 #ifdef DEBUG
265 char *foo;
266 foo = ctime(tod);
267 fputs(foo, stdout);
269 #endif
270 printf("%-8.8s\n", &(ctime(tod)[11]));
271 lastline = 1;
274 static int ltotal = 0;
275 static char procstates_buffer[MAX_COLS];
278 * *_procstates(total, brkdn, names) - print the process summary line
280 * Assumptions: cursor is at the beginning of the line on entry
281 * lastline is valid
284 void
285 i_procstates(int total, int *brkdn)
287 register int i;
289 /* write current number of processes and remember the value */
290 printf("%d processes:", total);
291 ltotal = total;
293 /* put out enough spaces to get to column 15 */
294 i = digits(total);
295 while (i++ < 4)
297 putchar(' ');
300 /* format and print the process state summary */
301 summary_format(procstates_buffer, brkdn, procstate_names);
302 fputs(procstates_buffer, stdout);
304 /* save the numbers for next time */
305 memcpy(lprocstates, brkdn, num_procstates * sizeof(int));
308 void
309 u_procstates(int total, int *brkdn)
311 static char new[MAX_COLS];
312 register int i;
314 /* update number of processes only if it has changed */
315 if (ltotal != total)
317 /* move and overwrite */
318 #if (x_procstate == 0)
319 Move_to(x_procstate, y_procstate);
320 #else
321 /* cursor is already there...no motion needed */
322 /* assert(lastline == 1); */
323 #endif
324 printf("%d", total);
326 /* if number of digits differs, rewrite the label */
327 if (digits(total) != digits(ltotal))
329 fputs(" processes:", stdout);
330 /* put out enough spaces to get to column 15 */
331 i = digits(total);
332 while (i++ < 4)
334 putchar(' ');
336 /* cursor may end up right where we want it!!! */
339 /* save new total */
340 ltotal = total;
343 /* see if any of the state numbers has changed */
344 if (memcmp(lprocstates, brkdn, num_procstates * sizeof(int)) != 0)
346 /* format and update the line */
347 summary_format(new, brkdn, procstate_names);
348 line_update(procstates_buffer, new, x_brkdn, y_brkdn);
349 memcpy(lprocstates, brkdn, num_procstates * sizeof(int));
354 * *_cpustates(states, names) - print the cpu state percentages
356 * Assumptions: cursor is on the PREVIOUS line
359 void
360 i_cpustates(struct system_info *si)
362 int i;
363 int value;
364 const char **names;
365 const char *thisname;
366 int *states = si->cpustates;
367 int cpu;
369 /* print tag and bump lastline */
370 for (cpu = 0; cpu < n_cpus; ++cpu) {
371 if (n_cpus > 1)
372 printf("\nCPU%d states: ", cpu);
373 else
374 printf("\nCPU states: ");
375 lastline++;
377 /* now walk thru the names and print the line */
378 names = cpustate_names;
379 i = 0;
380 while ((thisname = *names++) != NULL)
382 if (*thisname != '\0')
384 /* retrieve the value and remember it */
385 value = *states++;
386 /* if percentage is >= 1000, print it as 100% */
387 printf((value >= 1000 ? "%s%4.0f%% %s" : "%s%4.1f%% %s"),
388 i++ == 0 ? "" : ", ",
389 ((float)value)/10.,
390 thisname);
396 void
397 z_cpustates(struct system_info *si __unused)
399 int i;
400 const char **names;
401 const char *thisname;
402 int cpu;
404 /* show tag and bump lastline */
405 for (cpu = 0; cpu < n_cpus; ++cpu) {
406 if (n_cpus > 1)
407 printf("\nCPU%d states: ", cpu);
408 else
409 printf("\nCPU states: ");
410 lastline++;
412 i = 0;
413 names = cpustate_names;
414 while ((thisname = *names++) != NULL)
416 if (*thisname != '\0')
418 printf("%s %% %s", i++ == 0 ? "" : ", ", thisname);
425 * *_memory(stats) - print "Memory: " followed by the memory summary string
427 * Assumptions: cursor is on "lastline"
428 * for i_memory ONLY: cursor is on the previous line
431 char memory_buffer[MAX_COLS];
433 void
434 i_memory(int *stats)
436 fputs("\nMem: ", stdout);
437 lastline++;
439 /* format and print the memory summary */
440 summary_format(memory_buffer, stats, memory_names);
441 fputs(memory_buffer, stdout);
444 void
445 u_memory(int *stats)
447 static char new[MAX_COLS];
449 /* format the new line */
450 summary_format(new, stats, memory_names);
451 line_update(memory_buffer, new, x_mem, y_mem);
455 * *_swap(stats) - print "Swap: " followed by the swap summary string
457 * Assumptions: cursor is on "lastline"
458 * for i_swap ONLY: cursor is on the previous line
461 char swap_buffer[MAX_COLS];
463 void
464 i_swap(int *stats)
466 fputs("\nSwap: ", stdout);
467 lastline++;
469 /* format and print the swap summary */
470 summary_format(swap_buffer, stats, swap_names);
471 fputs(swap_buffer, stdout);
474 void
475 u_swap(int *stats)
477 static char new[MAX_COLS];
479 /* format the new line */
480 summary_format(new, stats, swap_names);
481 line_update(swap_buffer, new, x_swap, y_swap);
485 * *_message() - print the next pending message line, or erase the one
486 * that is there.
488 * Note that u_message is (currently) the same as i_message.
490 * Assumptions: lastline is consistent
494 * i_message is funny because it gets its message asynchronously (with
495 * respect to screen updates).
498 static char next_msg[MAX_COLS + 5];
499 static int msglen = 0;
500 /* Invariant: msglen is always the length of the message currently displayed
501 on the screen (even when next_msg doesn't contain that message). */
503 void
504 i_message(void)
506 while (lastline < y_message)
508 fputc('\n', stdout);
509 lastline++;
511 if (next_msg[0] != '\0')
513 dostandout(next_msg);
514 msglen = strlen(next_msg);
515 next_msg[0] = '\0';
517 else if (msglen > 0)
519 (void) clear_eol(msglen);
520 msglen = 0;
524 void
525 u_message(void)
527 i_message();
530 static int header_length;
533 * *_header(text) - print the header for the process area
535 * Assumptions: cursor is on the previous line and lastline is consistent
538 void
539 i_header(char *text)
541 header_length = strlen(text);
542 if (header_status == ON)
544 putchar('\n');
545 fputs(text, stdout);
546 lastline++;
548 else if (header_status == ERASE)
550 header_status = OFF;
554 /*ARGSUSED*/
555 void
556 u_header(char *text __unused)
558 if (header_status == ERASE)
560 putchar('\n');
561 lastline++;
562 clear_eol(header_length);
563 header_status = OFF;
568 * *_process(line, thisline) - print one process line
570 * Assumptions: lastline is consistent
573 void
574 i_process(int line, char *thisline)
576 register char *p;
577 register char *base;
579 /* make sure we are on the correct line */
580 while (lastline < y_procs + line)
582 putchar('\n');
583 lastline++;
586 /* truncate the line to conform to our current screen width */
587 thisline[display_width] = '\0';
589 /* write the line out */
590 fputs(thisline, stdout);
592 /* copy it in to our buffer */
593 base = smart_terminal ? screenbuf + lineindex(line) : screenbuf;
594 p = strecpy(base, thisline);
596 /* zero fill the rest of it */
597 memzero(p, display_width - (p - base));
600 void
601 u_process(int xline, char *xnewline)
603 char *optr;
604 int screen_line = xline + Header_lines;
605 char *bufferline;
607 /* remember a pointer to the current line in the screen buffer */
608 bufferline = &screenbuf[lineindex(xline)];
610 /* truncate the line to conform to our current screen width */
611 newline[display_width] = '\0';
613 /* is line higher than we went on the last display? */
614 if (xline >= last_hi)
616 /* yes, just ignore screenbuf and write it out directly */
617 /* get positioned on the correct line */
618 if (screen_line - lastline == 1)
620 putchar('\n');
621 lastline++;
623 else
625 Move_to(0, screen_line);
626 lastline = screen_line;
629 /* now write the line */
630 fputs(xnewline, stdout);
632 /* copy it in to the buffer */
633 optr = strecpy(bufferline, xnewline);
635 /* zero fill the rest of it */
636 memzero(optr, display_width - (optr - bufferline));
638 else
640 line_update(bufferline, xnewline, 0, xline + Header_lines);
644 void
645 u_endscreen(int hi)
647 int screen_line = hi + Header_lines;
648 int i;
650 if (smart_terminal)
652 if (hi < last_hi)
654 /* need to blank the remainder of the screen */
655 /* but only if there is any screen left below this line */
656 if (lastline + 1 < screen_length)
658 /* efficiently move to the end of currently displayed info */
659 if (screen_line - lastline < 5)
661 while (lastline < screen_line)
663 putchar('\n');
664 lastline++;
667 else
669 Move_to(0, screen_line);
670 lastline = screen_line;
673 if (clear_to_end)
675 /* we can do this the easy way */
676 putcap(clear_to_end);
678 else
680 /* use clear_eol on each line */
681 i = hi;
682 while ((void) clear_eol(strlen(&screenbuf[lineindex(i++)])), i < last_hi)
684 putchar('\n');
689 last_hi = hi;
691 /* move the cursor to a pleasant place */
692 Move_to(x_idlecursor, y_idlecursor);
693 lastline = y_idlecursor;
695 else
697 /* separate this display from the next with some vertical room */
698 fputs("\n\n", stdout);
702 void
703 display_header(int t)
705 if (t)
707 header_status = ON;
709 else if (header_status == ON)
711 header_status = ERASE;
715 /*VARARGS2*/
716 void
717 new_message(int type, const char *msgfmt, ...)
719 va_list va;
720 int i;
722 /* first, format the message */
723 va_start(va, msgfmt);
724 vsnprintf(next_msg, sizeof(next_msg), msgfmt, va);
725 va_end(va);
727 if (msglen > 0)
729 /* message there already -- can we clear it? */
730 if (!overstrike)
732 /* yes -- write it and clear to end */
733 i = strlen(next_msg);
734 if ((type & MT_delayed) == 0)
736 if (type & MT_standout)
737 dostandout(next_msg);
738 else
739 fputs(next_msg, stdout);
740 (void) clear_eol(msglen - i);
741 msglen = i;
742 next_msg[0] = '\0';
746 else
748 if ((type & MT_delayed) == 0)
750 if (type & MT_standout)
751 dostandout(next_msg);
752 else
753 fputs(next_msg, stdout);
754 msglen = strlen(next_msg);
755 next_msg[0] = '\0';
760 void
761 clear_message(void)
763 if (clear_eol(msglen) == 1)
765 putchar('\r');
770 readline(char *buffer, int size, int numeric)
772 char *ptr = buffer;
773 char ch;
774 char cnt = 0;
775 char maxcnt = 0;
777 /* allow room for null terminator */
778 size -= 1;
780 /* read loop */
781 while ((fflush(stdout), read(0, ptr, 1) > 0))
783 /* newline means we are done */
784 if ((ch = *ptr) == '\n' || ch == '\r')
786 break;
789 /* handle special editing characters */
790 if (ch == ch_kill)
792 /* kill line -- account for overstriking */
793 if (overstrike)
795 msglen += maxcnt;
798 /* return null string */
799 *buffer = '\0';
800 putchar('\r');
801 return(-1);
803 else if (ch == ch_erase)
805 /* erase previous character */
806 if (cnt <= 0)
808 /* none to erase! */
809 putchar('\7');
811 else
813 fputs("\b \b", stdout);
814 ptr--;
815 cnt--;
818 /* check for character validity and buffer overflow */
819 else if (cnt == size || (numeric && !isdigit(ch)) ||
820 !isprint(ch))
822 /* not legal */
823 putchar('\7');
825 else
827 /* echo it and store it in the buffer */
828 putchar(ch);
829 ptr++;
830 cnt++;
831 if (cnt > maxcnt)
833 maxcnt = cnt;
838 /* all done -- null terminate the string */
839 *ptr = '\0';
841 /* account for the extra characters in the message area */
842 /* (if terminal overstrikes, remember the furthest they went) */
843 msglen += overstrike ? maxcnt : cnt;
845 /* return either inputted number or string length */
846 putchar('\r');
847 return(cnt == 0 ? -1 : numeric ? atoi(buffer) : cnt);
850 /* internal support routines */
852 static int
853 string_count(const char **pp)
855 int cnt;
857 cnt = 0;
858 while (*pp++ != NULL)
860 cnt++;
862 return(cnt);
865 static void
866 summary_format(char *str, int *numbers, const char **names)
868 char *p;
869 int num;
870 const char *thisname;
872 /* format each number followed by its string */
873 p = str;
874 while ((thisname = *names++) != NULL)
876 /* get the number to format */
877 num = *numbers++;
879 /* display only non-zero numbers */
880 if (num > 0)
882 /* is this number in kilobytes? */
883 if (thisname[0] == 'K')
885 /* yes: format it as a memory value */
886 p = strecpy(p, format_k(num));
888 /* skip over the K, since it was included by format_k */
889 p = strecpy(p, thisname+1);
891 else
893 p = strecpy(p, ltoa(num));
894 p = strecpy(p, thisname);
898 /* ignore negative numbers, but display corresponding string */
899 else if (num < 0)
901 p = strecpy(p, thisname);
905 /* if the last two characters in the string are ", ", delete them */
906 p -= 2;
907 if (p >= str && p[0] == ',' && p[1] == ' ')
909 *p = '\0';
913 static void
914 line_update(char *old, char *new, int start, int line)
916 register int ch;
917 register int diff;
918 register int newcol = start + 1;
919 register int lastcol = start;
920 char cursor_on_line = No;
921 char *current;
923 /* compare the two strings and only rewrite what has changed */
924 current = old;
925 #ifdef DEBUG
926 fprintf(debug, "line_update, starting at %d\n", start);
927 fputs(old, debug);
928 fputc('\n', debug);
929 fputs(new, debug);
930 fputs("\n-\n", debug);
931 #endif
933 /* start things off on the right foot */
934 /* this is to make sure the invariants get set up right */
935 if ((ch = *new++) != *old)
937 if (line - lastline == 1 && start == 0)
939 putchar('\n');
941 else
943 Move_to(start, line);
945 cursor_on_line = Yes;
946 putchar(ch);
947 *old = ch;
948 lastcol = 1;
950 old++;
953 * main loop -- check each character. If the old and new aren't the
954 * same, then update the display. When the distance from the
955 * current cursor position to the new change is small enough,
956 * the characters that belong there are written to move the
957 * cursor over.
959 * Invariants:
960 * lastcol is the column where the cursor currently is sitting
961 * (always one beyond the end of the last mismatch).
963 do /* yes, a do...while */
965 if ((ch = *new++) != *old)
967 /* new character is different from old */
968 /* make sure the cursor is on top of this character */
969 diff = newcol - lastcol;
970 if (diff > 0)
972 /* some motion is required--figure out which is shorter */
973 if (diff < 6 && cursor_on_line)
975 /* overwrite old stuff--get it out of the old buffer */
976 printf("%.*s", diff, &current[lastcol-start]);
978 else
980 /* use cursor addressing */
981 Move_to(newcol, line);
982 cursor_on_line = Yes;
984 /* remember where the cursor is */
985 lastcol = newcol + 1;
987 else
989 /* already there, update position */
990 lastcol++;
993 /* write what we need to */
994 if (ch == '\0')
996 /* at the end--terminate with a clear-to-end-of-line */
997 (void) clear_eol(strlen(old));
999 else
1001 /* write the new character */
1002 putchar(ch);
1004 /* put the new character in the screen buffer */
1005 *old = ch;
1008 /* update working column and screen buffer pointer */
1009 newcol++;
1010 old++;
1012 } while (ch != '\0');
1014 /* zero out the rest of the line buffer -- MUST BE DONE! */
1015 diff = display_width - newcol;
1016 if (diff > 0)
1018 memzero(old, diff);
1021 /* remember where the current line is */
1022 if (cursor_on_line)
1024 lastline = line;
1029 * printable(str) - make the string pointed to by "str" into one that is
1030 * printable (i.e.: all ascii), by converting all non-printable
1031 * characters into '?'. Replacements are done in place and a pointer
1032 * to the original buffer is returned.
1035 char *
1036 printable(char *str)
1038 char *ptr;
1039 char ch;
1041 ptr = str;
1042 while ((ch = *ptr) != '\0')
1044 if (!isprint(ch))
1046 *ptr = '?';
1048 ptr++;
1050 return(str);
1053 void
1054 i_uptime(struct timeval *bt, time_t *tod)
1056 time_t uptime;
1057 int days, hrs, mins, secs;
1059 if (bt->tv_sec != -1) {
1060 uptime = *tod - bt->tv_sec;
1061 uptime += 30;
1062 days = uptime / 86400;
1063 uptime %= 86400;
1064 hrs = uptime / 3600;
1065 uptime %= 3600;
1066 mins = uptime / 60;
1067 secs = uptime % 60;
1070 * Display the uptime.
1073 if (smart_terminal)
1075 Move_to((screen_width - 24) - (days > 9 ? 1 : 0), 0);
1077 else
1079 fputs(" ", stdout);
1081 printf(" up %d+%02d:%02d:%02d", days, hrs, mins, secs);