Debian Codegraph @

src/top/top.c

raw
1 /* top.c - Source file: show Linux processes */
2 /*
3 * Copyright © 2002-2023 Jim Warner <[email protected]
4 *
5 * This file may be used subject to the terms and conditions of the
6 * GNU Library General Public License Version 2, or any later version
7 * at your option, as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Library General Public License for more details.
12 */
13 /* For contributions to this program, the author wishes to thank:
14 * Craig Small, <[email protected]>
15 * Albert D. Cahalan, <[email protected]>
16 * Sami Kerola, <[email protected]>
17 */
18
19 #include <ctype.h>
20 #include <curses.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <float.h>
24 #include <getopt.h>
25 #include <limits.h>
26 #include <pwd.h>
27 #include <pthread.h>
28 #include <semaphore.h>
29 #include <signal.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <term.h> // foul sob, defines all sorts of stuff...
35 #undef raw
36 #undef tab
37 #undef TTY
38 #include <termios.h>
39 #include <time.h>
40 #include <unistd.h>
41 #include <wchar.h>
42
43 #include <sys/ioctl.h>
44 #include <sys/resource.h>
45 #include <sys/select.h> // also available via <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
48 #include <sys/types.h> // also available via <stdlib.h>
49
50 #include "fileutils.h"
51 #include "signals.h"
52 #include "nls.h"
53
54 #include "meminfo.h"
55 #include "misc.h"
56 #include "pids.h"
57 #include "stat.h"
58
59 #include "top.h"
60 #include "top_nls.h"
61
62 /*###### Miscellaneous global stuff ####################################*/
63
64 /* The original and new terminal definitions
65 (only set when not in 'Batch' mode) */
66 static struct termios Tty_original, // our inherited terminal definition
67 #ifdef TERMIOS_ONLY
68 Tty_tweaked, // for interactive 'line' input
69 #endif
70 Tty_raw; // for unsolicited input
71 static int Ttychanged = 0;
72
73 /* Last established cursor state/shape */
74 static const char *Cursor_state = "";
75
76 /* Program name used in error messages and local 'rc' file name */
77 static char *Myname;
78
79 /* Our constant sigset, so we need initialize it but once */
80 static sigset_t Sigwinch_set;
81
82 /* The 'local' config file support */
83 static char Rc_name [OURPATHSZ];
84 static RCF_t Rc = DEF_RCFILE;
85 static int Rc_questions;
86 static int Rc_compatibilty;
87
88 /* SMP, Irix/Solaris mode, Linux 2.5.xx support (and beyond) */
89 static long Hertz;
90 static int Cpu_cnt;
91 static float Cpu_pmax;
92 static const char *Cpu_States_fmts;
93
94 /* Specific process id monitoring support */
95 static int Monpids [MONPIDMAX+1] = { 0 };
96 static int Monpidsidx = 0;
97
98 /* Current screen dimensions.
99 note: the number of processes displayed is tracked on a per window
100 basis (see the WIN_t). Max_lines is the total number of
101 screen rows after deducting summary information overhead. */
102 /* Current terminal screen size. */
103 static int Screen_cols, Screen_rows, Max_lines;
104
105 /* These 'SCREEN_ROWS', 'BOT_ and 'Bot_' guys are used
106 in managing the special separate bottom 'window' ... */
107 #define SCREEN_ROWS ( Screen_rows - Bot_rsvd )
108 #define BOT_PRESENT ( Bot_what != 0 )
109 #define BOT_ITEMMAX 10 // Bot_item array's max size
110 #define BOT_MSGSMAX 10 // total entries for Msg_tab
111 #define BOT_UNFOCUS -1 // tab focus not established
112 // negative 'item' values won't be seen by build_headers() ...
113 #define BOT_DELIMIT -1 // fencepost with item array
114 #define BOT_ITEM_NS -2 // data for namespaces req'd
115 #define BOT_MSG_LOG -3 // show the most recent msgs
116 // next 4 are used when toggling window contents
117 #define BOT_SEP_CMA ','
118 #define BOT_SEP_SLS '/'
119 #define BOT_SEP_SMI ';'
120 #define BOT_SEP_SPC ' '
121 // 1 for horizontal separator
122 #define BOT_RSVD 1
123 #define BOT_KEEP Bot_show_func = NULL
124 #define BOT_TOSS do { Bot_show_func = NULL; Bot_item[0] = BOT_DELIMIT; \
125 Bot_task = Bot_rsvd = Bot_what = 0; \
126 Bot_indx = BOT_UNFOCUS; \
127 } while(0)
128 static int Bot_task,
129 Bot_what,
130 Bot_rsvd,
131 Bot_indx = BOT_UNFOCUS,
132 Bot_item[BOT_ITEMMAX] = { BOT_DELIMIT };
133 static char Bot_sep,
134 *Bot_head,
135 Bot_buf[BOTBUFSIZ]; // the 'environ' can be huge
136 typedef int(*BOT_f)(const void *, const void *);
137 static BOT_f Bot_focus_func;
138 static void(*Bot_show_func)(void);
139
140 /* This is really the number of lines needed to display the summary
141 information (0 - nn), but is used as the relative row where we
142 stick the cursor between frames. */
143 static int Msg_row;
144
145 /* Global/Non-windows mode stuff that is NOT persistent */
146 static int Batch = 0, // batch mode, collect no input, dumb output
147 Loops = -1, // number of iterations, -1 loops forever
148 Secure_mode = 0, // set if some functionality restricted
149 Width_mode = 0, // set w/ 'w' - potential output override
150 Thread_mode = 0; // set w/ 'H' - show threads vs. tasks
151
152 /* Unchangeable cap's stuff built just once (if at all) and
153 thus NOT saved in a WIN_t's RCW_t. To accommodate 'Batch'
154 mode, they begin life as empty strings so the overlying
155 logic need not change ! */
156 static char Cap_clr_eol [CAPBUFSIZ] = "", // global and/or static vars
157 Cap_nl_clreos [CAPBUFSIZ] = "", // are initialized to zeros!
158 Cap_clr_scr [CAPBUFSIZ] = "", // the assignments used here
159 Cap_curs_norm [CAPBUFSIZ] = "", // cost nothing but DO serve
160 Cap_curs_huge [CAPBUFSIZ] = "", // to remind people of those
161 Cap_curs_hide [CAPBUFSIZ] = "", // batch requirements!
162 Cap_clr_eos [CAPBUFSIZ] = "",
163 Cap_home [CAPBUFSIZ] = "",
164 Cap_norm [CAPBUFSIZ] = "",
165 Cap_reverse [CAPBUFSIZ] = "",
166 Caps_off [CAPBUFSIZ] = "",
167 Caps_endline [SMLBUFSIZ] = "";
168 #ifndef RMAN_IGNORED
169 static char Cap_rmam [CAPBUFSIZ] = "",
170 Cap_smam [CAPBUFSIZ] = "";
171 /* set to 1 if writing to the last column would be troublesome
172 (we don't distinguish the lowermost row from the other rows) */
173 static int Cap_avoid_eol = 0;
174 #endif
175 static int Cap_can_goto = 0;
176
177 /* Some optimization stuff, to reduce output demands...
178 The Pseudo_ guys are managed by adj_geometry and frame_make. They
179 are exploited in a macro and represent 90% of our optimization.
180 The Stdout_buf is transparent to our code and regardless of whose
181 buffer is used, stdout is flushed at frame end or if interactive. */
182 static char *Pseudo_screen;
183 static int Pseudo_row = PROC_XTRA;
184 static size_t Pseudo_size;
185 #ifndef OFF_STDIOLBF
186 // less than stdout's normal buffer but with luck mostly '\n' anyway
187 static char Stdout_buf[2048];
188 #endif
189
190 /* Our four WIN_t's, and which of those is considered the 'current'
191 window (ie. which window is associated with any summ info displayed
192 and to which window commands are directed) */
193 static WIN_t Winstk [GROUPSMAX];
194 static WIN_t *Curwin;
195
196 /* Frame oriented stuff that can't remain local to any 1 function
197 and/or that would be too cumbersome managed as parms,
198 and/or that are simply more efficiently handled as globals
199 [ 'Frames_...' (plural) stuff persists beyond 1 frame ]
200 [ or are used in response to async signals received ! ] */
201 static volatile int Frames_signal; // time to rebuild all column headers
202 static float Frame_etscale; // so we can '*' vs. '/' WHEN 'pcpu'
203
204 /* Support for automatically sized fixed-width column expansions.
205 * (hopefully, the macros help clarify/document our new 'feature') */
206 static int Autox_array [EU_MAXPFLGS],
207 Autox_found;
208 #define AUTOX_NO EU_MAXPFLGS
209 #define AUTOX_COL(f) if (EU_MAXPFLGS > f && f >= 0) Autox_array[f] = Autox_found = 1
210 #define AUTOX_MODE (0 > Rc.fixed_widest)
211
212 /* Support for scale_mem and scale_num (to avoid duplication. */
213 #ifdef CASEUP_SUFIX // nls_maybe
214 static char Scaled_sfxtab[] = { 'K', 'M', 'G', 'T', 'P', 'E', 0 };
215 #else // nls_maybe
216 static char Scaled_sfxtab[] = { 'k', 'm', 'g', 't', 'p', 'e', 0 };
217 #endif
218
219 /* Support for NUMA Node display plus node expansion and targeting */
220 #ifndef OFF_STDERROR
221 static int Stderr_save = -1;
222 #endif
223 static int Numa_node_tot;
224 static int Numa_node_sel = -1;
225
226 /* Support for Graphing of the View_STATES ('t') and View_MEMORY ('m')
227 commands -- which are now both 4-way toggles */
228 #define GRAPH_length_max 100 // the actual bars or blocks
229 #define GRAPH_length_min 10 // the actual bars or blocks
230 #define GRAPH_prefix_std 25 // '.......: 100.0/100.0 100['
231 #define GRAPH_prefix_abv 12 // '.......:100['
232 #define GRAPH_suffix 2 // '] ' (bracket + trailing space)
233 // first 3 more static (adj_geometry), last 3 volatile (sum_tics/do_memory)
234 struct graph_parms {
235 float adjust; // bars/blocks scaling factor
236 int length; // scaled length (<= GRAPH_length_max)
237 int style; // rc.graph_cpus or rc.graph_mems
238 long total, part1, part2; // elements to be graphed
239 };
240 static struct graph_parms *Graph_cpus, *Graph_mems;
241 static const char Graph_blks[] = " ";
242 static const char Graph_bars[] = "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||";
243
244 /* Support for 'Other Filters' in the configuration file */
245 static const char Osel_delim_1_txt[] = "begin: saved other filter data -------------------\n";
246 static const char Osel_delim_2_txt[] = "end : saved other filter data -------------------\n";
247 static const char Osel_window_fmts[] = "window #%d, osel_tot=%d\n";
248 #define OSEL_FILTER "filter="
249 static const char Osel_filterO_fmt[] = "\ttype=%d,\t" OSEL_FILTER "%s\n";
250 static const char Osel_filterI_fmt[] = "\ttype=%d,\t" OSEL_FILTER "%*s\n";
251
252 /* Support for adjoining display (if terminal is wide enough) */
253 #ifdef TOG4_SEP_OFF
254 static char Adjoin_sp[] = " ";
255 #define ADJOIN_space (sizeof(Adjoin_sp) - 1) // 1 for null
256 #else
257 #ifdef TOG4_SEP_STD
258 static char Adjoin_sp[] = "~1 ~6 ";
259 #else
260 static char Adjoin_sp[] = " ~6 ~1";
261 #endif
262 #define ADJOIN_space (sizeof(Adjoin_sp) - 5) // 1 for null + 4 unprintable
263 #endif
264 #define ADJOIN_limit 8
265
266 /* Support for the new library API -- acquired (if necessary)
267 at program startup and referenced throughout our lifetime. */
268 /*
269 * --- <proc/pids.h> -------------------------------------------------- */
270 static struct pids_info *Pids_ctx;
271 static int Pids_itms_tot; // same as MAXTBL(Fieldstab)
272 static enum pids_item *Pids_itms; // allocated as MAXTBL(Fieldstab)
273 static struct pids_fetch *Pids_reap; // for reap or select
274 #define PIDSmaxt Pids_reap->counts->total // just a little less wordy
275 // pid stack results extractor macro, where e=our EU enum, t=type, s=stack
276 // ( we'll exploit that <proc/pids.h> provided macro as much as possible )
277 // ( but many functions use their own unique tailored version for access )
278 #define PID_VAL(e,t,s) PIDS_VAL(e, t, s, Pids_ctx)
279 /*
280 * --- <proc/stat.h> -------------------------------------------------- */
281 static struct stat_info *Stat_ctx;
282 static struct stat_reaped *Stat_reap;
283 static enum stat_item Stat_items[] = {
284 STAT_TIC_ID, STAT_TIC_NUMA_NODE,
285 STAT_TIC_DELTA_USER, STAT_TIC_DELTA_SYSTEM,
286 STAT_TIC_DELTA_NICE, STAT_TIC_DELTA_IDLE,
287 STAT_TIC_DELTA_IOWAIT, STAT_TIC_DELTA_IRQ,
288 STAT_TIC_DELTA_SOFTIRQ, STAT_TIC_DELTA_STOLEN,
289 STAT_TIC_DELTA_GUEST, STAT_TIC_DELTA_GUEST_NICE,
290 STAT_TIC_SUM_DELTA_USER, STAT_TIC_SUM_DELTA_SYSTEM,
291 #ifdef CORE_TYPE_NO
292 STAT_TIC_SUM_DELTA_TOTAL };
293 #else
294 STAT_TIC_SUM_DELTA_TOTAL, STAT_TIC_TYPE_CORE };
295 #endif
296 enum Rel_statitems {
297 stat_ID, stat_NU,
298 stat_US, stat_SY,
299 stat_NI, stat_IL,
300 stat_IO, stat_IR,
301 stat_SI, stat_ST,
302 stat_GU, stat_GN,
303 stat_SUM_USR, stat_SUM_SYS,
304 #ifdef CORE_TYPE_NO
305 stat_SUM_TOT };
306 #else
307 stat_SUM_TOT, stat_COR_TYP };
308 #endif
309 // cpu/node stack results extractor macros, where e=rel enum, x=index
310 #define CPU_VAL(e,x) STAT_VAL(e, s_int, Stat_reap->cpus->stacks[x], Stat_ctx)
311 #define NOD_VAL(e,x) STAT_VAL(e, s_int, Stat_reap->numa->stacks[x], Stat_ctx)
312 #define TIC_VAL(e,s) STAT_VAL(e, sl_int, s, Stat_ctx)
313 #define E_CORE 1 // values for stat_COR_TYP itself
314 #define P_CORE 2 // ( 0 = unsure/unknown )
315 #define P_CORES_ONLY 2 // values of rc.core_types toggle, for filtering
316 #define E_CORES_ONLY 3 // ( 0 = Cpu shown, 1 = both CpP & CpE shown )
317 /*
318 * --- <proc/meminfo.h> ----------------------------------------------- */
319 static struct meminfo_info *Mem_ctx;
320 static struct meminfo_stack *Mem_stack;
321 static enum meminfo_item Mem_items[] = {
322 MEMINFO_MEM_FREE, MEMINFO_MEM_USED, MEMINFO_MEM_TOTAL,
323 MEMINFO_MEM_CACHED_ALL, MEMINFO_MEM_BUFFERS, MEMINFO_MEM_AVAILABLE,
324 MEMINFO_SWAP_TOTAL, MEMINFO_SWAP_FREE, MEMINFO_SWAP_USED };
325 enum Rel_memitems {
326 mem_FRE, mem_USE, mem_TOT,
327 mem_QUE, mem_BUF, mem_AVL,
328 swp_TOT, swp_FRE, swp_USE };
329 // mem stack results extractor macro, where e=rel enum
330 #define MEM_VAL(e) MEMINFO_VAL(e, ul_int, Mem_stack, Mem_ctx)
331
332 /* Support for concurrent library updates via
333 multithreaded background processes */
334 #ifdef THREADED_CPU
335 static pthread_t Thread_id_cpus;
336 static sem_t Semaphore_cpus_beg, Semaphore_cpus_end;
337 #endif
338 #ifdef THREADED_MEM
339 static pthread_t Thread_id_memory;
340 static sem_t Semaphore_memory_beg, Semaphore_memory_end;
341 #endif
342 #ifdef THREADED_TSK
343 static pthread_t Thread_id_tasks;
344 static sem_t Semaphore_tasks_beg, Semaphore_tasks_end;
345 #endif
346 #if defined THREADED_CPU || defined THREADED_MEM || defined THREADED_TSK
347 static pthread_t Thread_id_main;
348 #endif
349
350 /* Support for a namespace with proc mounted subset=pid,
351 ( we'll limit our display to task information only ). */
352 static int Restrict_some = 0;
353
354 /*###### Tiny useful routine(s) ########################################*/
355
356 /*
357 * This routine simply formats whatever the caller wants and
358 * returns a pointer to the resulting 'const char' string... */
359 static const char *fmtmk (const char *fmts, ...) __attribute__((format(printf,1,2)));
360 static const char *fmtmk (const char *fmts, ...) {
361 static char buf[BIGBUFSIZ]; // with help stuff, our buffer
362 va_list va; // requirements now exceed 1k
363
364 va_start(va, fmts);
365 vsnprintf(buf, sizeof(buf), fmts, va);
366 va_end(va);
367 return (const char *)buf;
368 } // end: fmtmk
369
370
371 /*
372 * Integer based fieldscur version of 'strlen' */
373 static inline int mlen (const int *mem) {
374 int i;
375
376 for (i = 0; mem[i]; i++)
377 ;
378 return i;
379 } // end: mlen
380
381
382 /*
383 * Integer based fieldscur version of 'strchr' */
384 static inline int *msch (const int *mem, int obj, int max) {
385 int i;
386
387 for (i = 0; i < max; i++)
388 if (*(mem + i) == obj) return (int *)mem + i;
389 return NULL;
390 } // end: msch
391
392
393 /*
394 * This guy is just our way of avoiding the overhead of the standard
395 * strcat function (should the caller choose to participate) */
396 static inline char *scat (char *dst, const char *src) {
397 while (*dst) dst++;
398 while ((*(dst++) = *(src++)));
399 return --dst;
400 } // end: scat
401
402
403 /*
404 * This guy just facilitates Batch and protects against dumb ttys
405 * -- we'd 'inline' him but he's only called twice per frame,
406 * yet used in many other locations. */
407 static const char *tg2 (int x, int y) {
408 // it's entirely possible we're trying for an invalid row...
409 return Cap_can_goto ? tgoto(cursor_address, x, y) : "";
410 } // end: tg2
411
412 /*###### Exit/Interrupt routines #######################################*/
413
414 /*
415 * Reset the tty, if necessary */
416 static void at_eoj (void) {
417 if (Ttychanged) {
418 tcsetattr(STDIN_FILENO, TCSAFLUSH, &Tty_original);
419 if (keypad_local) putp(keypad_local);
420 putp(tg2(0, Screen_rows));
421 putp("\n");
422 #ifdef OFF_SCROLLBK
423 if (exit_ca_mode) {
424 // this next will also replace top's most recent screen with the
425 // original display contents that were visible at our invocation
426 putp(exit_ca_mode);
427 }
428 #endif
429 putp(Cap_curs_norm);
430 putp(Cap_clr_eol);
431 #ifndef RMAN_IGNORED
432 putp(Cap_smam);
433 #endif
434 }
435 fflush(stdout);
436 #ifndef OFF_STDERROR
437 /* we gotta reverse the stderr redirect which was employed during start up
438 and needed because the two libnuma 'weak' functions were useless to us! */
439 if (-1 < Stderr_save) {
440 dup2(Stderr_save, fileno(stderr));
441 close(Stderr_save);
442 Stderr_save = -1; // we'll be ending soon anyway but what the heck
443 }
444 #endif
445 } // end: at_eoj
446
447
448 /*
449 * The real program end */
450 static void bye_bye (const char *str) __attribute__((__noreturn__));
451 static void bye_bye (const char *str) {
452 sigset_t ss;
453
454 // POSIX.1 async-signal-safe: sigfillset, sigprocmask, pthread_sigmask
455 sigfillset(&ss);
456 #if defined THREADED_CPU || defined THREADED_MEM || defined THREADED_TSK
457 pthread_sigmask(SIG_BLOCK, &ss, NULL);
458 #else
459 sigprocmask(SIG_BLOCK, &ss, NULL);
460 #endif
461 at_eoj(); // restore tty in preparation for exit
462 #ifdef ATEOJ_RPTSTD
463 {
464 if (!str && !Frames_signal && Ttychanged) { fprintf(stderr,
465 "\n%s's Summary report:"
466 "\n\tProgram"
467 "\n\t %s"
468 "\n\t Hertz = %u (%u bytes, %u-bit time)"
469 "\n\t Stat_reap->cpus->total = %d, Stat_reap->numa->total = %d"
470 "\n\t Pids_itms_tot = %d, sizeof(struct pids_result) = %d, pids stack size = %d"
471 "\n\t SCREENMAX = %d, ROWMINSIZ = %d, ROWMAXSIZ = %d"
472 "\n\t PACKAGE = '%s', LOCALEDIR = '%s'"
473 "\n\tTerminal: %s"
474 "\n\t device = %s, ncurses = v%s"
475 "\n\t max_colors = %d, max_pairs = %d"
476 "\n\t Cap_can_goto = %s"
477 "\n\t Screen_cols = %d, Screen_rows = %d"
478 "\n\t Max_lines = %d, most recent Pseudo_size = %u"
479 #ifndef OFF_STDIOLBF
480 "\n\t Stdout_buf = %u, BUFSIZ = %u"
481 #endif
482 "\n\tWindows and Curwin->"
483 "\n\t sizeof(WIN_t) = %u, GROUPSMAX = %d"
484 "\n\t winname = %s, grpname = %s"
485 #ifdef CASEUP_HEXES
486 "\n\t winflags = %08X, maxpflgs = %d"
487 #else
488 "\n\t winflags = x%08x, maxpflgs = %d"
489 #endif
490 "\n\t sortindx = %d, maxtasks = %d"
491 "\n\t varcolsz = %d, winlines = %d"
492 "\n\t strlen(columnhdr) = %d"
493 "\n\t current fieldscur = %d, maximum fieldscur = %d"
494 "\n"
495 , __func__
496 , PACKAGE_STRING
497 , (unsigned)Hertz, (unsigned)sizeof(Hertz), (unsigned)sizeof(Hertz) * 8
498 , Stat_reap->cpus->total, Stat_reap->numa->total
499 , Pids_itms_tot, (int)sizeof(struct pids_result), (int)(sizeof(struct pids_result) * Pids_itms_tot)
500 , (int)SCREENMAX, (int)ROWMINSIZ, (int)ROWMAXSIZ
501 , PACKAGE, LOCALEDIR
502 #ifdef PRETENDNOCAP
503 , "dumb"
504 #else
505 , termname()
506 #endif
507 , ttyname(STDOUT_FILENO), NCURSES_VERSION
508 , max_colors, max_pairs
509 , Cap_can_goto ? "yes" : "No!"
510 , Screen_cols, Screen_rows
511 , Max_lines, (unsigned)Pseudo_size
512 #ifndef OFF_STDIOLBF
513 , (unsigned)sizeof(Stdout_buf), (unsigned)BUFSIZ
514 #endif
515 , (unsigned)sizeof(WIN_t), GROUPSMAX
516 , Curwin->rc.winname, Curwin->grpname
517 , Curwin->rc.winflags, Curwin->maxpflgs
518 , Curwin->rc.sortindx, Curwin->rc.maxtasks
519 , Curwin->varcolsz, Curwin->winlines
520 , (int)strlen(Curwin->columnhdr)
521 , EU_MAXPFLGS, mlen(Curwin->rc.fieldscur)
522 );
523 }
524 }
525 #endif // end: ATEOJ_RPTSTD
526
527 // there's lots of signal-unsafe stuff in the following ...
528 if (Frames_signal != BREAK_sig) {
529 #if defined THREADED_CPU || defined THREADED_MEM || defined THREADED_TSK
530 /* can not execute any cleanup from a sibling thread and
531 we will violate proper indentation to minimize impact */
532 if (pthread_equal(Thread_id_main, pthread_self())) {
533 #endif
534 #ifdef THREADED_CPU
535 pthread_cancel(Thread_id_cpus);
536 pthread_join(Thread_id_cpus, NULL);
537 sem_destroy(&Semaphore_cpus_end);
538 sem_destroy(&Semaphore_cpus_beg);
539 #endif
540 #ifdef THREADED_MEM
541 pthread_cancel(Thread_id_memory);
542 pthread_join(Thread_id_memory, NULL);
543 sem_destroy(&Semaphore_memory_end);
544 sem_destroy(&Semaphore_memory_beg);
545 #endif
546 #ifdef THREADED_TSK
547 pthread_cancel(Thread_id_tasks);
548 pthread_join(Thread_id_tasks, NULL);
549 sem_destroy(&Semaphore_tasks_end);
550 sem_destroy(&Semaphore_tasks_beg);
551 #endif
552 procps_pids_unref(&Pids_ctx);
553 procps_stat_unref(&Stat_ctx);
554 procps_meminfo_unref(&Mem_ctx);
555 #if defined THREADED_CPU || defined THREADED_MEM || defined THREADED_TSK
556 }
557 #endif
558 }
559
560 /* we'll only have a 'str' if called by error_exit() |
561 and parse_args(), never from a signal handler ... | */
562 if (str) {
563 fputs(str, stderr);
564 exit(EXIT_FAILURE);
565 }
566 /* this could happen when called from several places |
567 including that sig_endpgm(). thus we must use an |
568 async-signal-safe write function just in case ... |
569 (thanks: Shaohua Zhan [email protected]) | */
570 if (Batch)
571 write(fileno(stdout), "\n", sizeof("\n") - 1);
572
573 exit(EXIT_SUCCESS);
574 } // end: bye_bye
575
576
577 /*
578 * Standard error handler to normalize the look of all err output */
579 static void error_exit (const char *str) __attribute__((__noreturn__));
580 static void error_exit (const char *str) {
581 static char buf[MEDBUFSIZ];
582
583 Frames_signal = BREAK_off;
584 /* we'll use our own buffer so callers can still use fmtmk() and, after
585 twelve long years, 2013 was the year we finally eliminated the leading
586 tab character -- now our message can get lost in screen clutter too! */
587 snprintf(buf, sizeof(buf), "%s: %s\n", Myname, str);
588 bye_bye(buf);
589 } // end: error_exit
590
591
592 /*
593 * Catches all remaining signals not otherwise handled */
594 static void sig_abexit (int sig) __attribute__((__noreturn__));
595 static void sig_abexit (int sig) {
596 sigset_t ss;
597
598 // POSIX.1 async-signal-safe: sigfillset, signal, sigemptyset, sigaddset, sigprocmask, pthread_sigmask, raise
599 sigfillset(&ss);
600 #if defined THREADED_CPU || defined THREADED_MEM || defined THREADED_TSK
601 pthread_sigmask(SIG_BLOCK, &ss, NULL);
602 #else
603 sigprocmask(SIG_BLOCK, &ss, NULL);
604 #endif
605 at_eoj(); // restore tty in preparation for exit
606 fprintf(stderr, N_fmt(EXIT_signals_fmt)
607 , sig, signal_number_to_name(sig), Myname);
608 signal(sig, SIG_DFL); // allow core dumps, if applicable
609 sigemptyset(&ss);
610 sigaddset(&ss, sig);
611 #if defined THREADED_CPU || defined THREADED_MEM || defined THREADED_TSK
612 pthread_sigmask(SIG_UNBLOCK, &ss, NULL);
613 #else
614 sigprocmask(SIG_UNBLOCK, &ss, NULL);
615 #endif
616 raise(sig); // ( plus set proper return code )
617 _exit(EXIT_FAILURE); // if default sig action is ignore
618 } // end: sig_abexit
619
620
621 /*
622 * Catches:
623 * SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
624 * SIGUSR1 and SIGUSR2 */
625 static void sig_endpgm (int dont_care_sig) __attribute__((__noreturn__));
626 static void sig_endpgm (int dont_care_sig) {
627 Frames_signal = BREAK_sig;
628 bye_bye(NULL);
629 (void)dont_care_sig;
630 } // end: sig_endpgm
631
632
633 /*
634 * Catches:
635 * SIGTSTP, SIGTTIN and SIGTTOU */
636 static void sig_paused (int dont_care_sig) {
637 // POSIX.1 async-signal-safe: tcsetattr, tcdrain, raise
638 if (-1 == tcsetattr(STDIN_FILENO, TCSAFLUSH, &Tty_original))
639 error_exit(fmtmk(N_fmt(FAIL_tty_set_fmt), strerror(errno)));
640 if (keypad_local) putp(keypad_local);
641 putp(tg2(0, Screen_rows));
642 putp(Cap_curs_norm);
643 #ifndef RMAN_IGNORED
644 putp(Cap_smam);
645 #endif
646 // tcdrain(STDOUT_FILENO) was not reliable prior to ncurses-5.9.20121017,
647 // so we'll risk POSIX's wrath with good ol' fflush, lest 'Stopped' gets
648 // co-mingled with our most recent output...
649 fflush(stdout);
650 raise(SIGSTOP);
651 // later, after SIGCONT...
652 if (-1 == tcsetattr(STDIN_FILENO, TCSAFLUSH, &Tty_raw))
653 error_exit(fmtmk(N_fmt(FAIL_tty_set_fmt), strerror(errno)));
654 #ifndef RMAN_IGNORED
655 putp(Cap_rmam);
656 #endif
657 if (keypad_xmit) putp(keypad_xmit);
658 putp(Cursor_state);
659 Frames_signal = BREAK_sig;
660 (void)dont_care_sig;
661 } // end: sig_paused
662
663
664 /*
665 * Catches:
666 * SIGCONT and SIGWINCH */
667 static void sig_resize (int dont_care_sig) {
668 // POSIX.1 async-signal-safe: tcdrain
669 tcdrain(STDOUT_FILENO);
670 Frames_signal = BREAK_sig;
671 (void)dont_care_sig;
672 } // end: sig_resize
673
674 /*###### Special UTF-8 Multi-Byte support ##############################*/
675
676 /* Support for NLS translated multi-byte strings */
677 static char UTF8_tab[] = {
678 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 - 0x0F
679 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 - 0x1F
680 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 - 0x2F
681 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 - 0x3F
682 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 - 0x4F
683 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 - 0x5F
684 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 - 0x6F
685 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 - 0x7F
686 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 0x80 - 0x8F
687 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 0x90 - 0x9F
688 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 0xA0 - 0xAF
689 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 0xB0 - 0xBF
690 -1,-1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xC0 - 0xCF, 0xC2 = begins 2
691 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xD0 - 0xDF
692 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xE0 - 0xEF, 0xE0 = begins 3
693 4, 4, 4, 4, 4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 0xF0 - 0xFF, 0xF0 = begins 4
694 }; // ( 0xF5 & beyond invalid )
695
696
697 /*
698 * Accommodate any potential differences between some multibyte
699 * character sequence and the screen columns needed to print it */
700 static inline int utf8_cols (const unsigned char *p, int n) {
701 #ifndef OFF_XTRAWIDE
702 wchar_t wc;
703
704 if (n > 1) {
705 (void)mbtowc(&wc, (const char *)p, n);
706 // allow a zero as valid, as with a 'combining acute accent'
707 if ((n = wcwidth(wc)) < 0) n = 1;
708 }
709 return n;
710 #else
711 (void)p; (void)n;
712 return 1;
713 #endif
714 } // end: utf8_cols
715
716
717 /*
718 * Determine difference between total bytes versus printable
719 * characters in that passed, potentially multi-byte, string */
720 static int utf8_delta (const char *str) {
721 const unsigned char *p = (const unsigned char *)str;
722 int clen, cnum = 0;
723
724 while (*p) {
725 // -1 represents a decoding error, pretend it's untranslated ...
726 if (0 > (clen = UTF8_tab[*p])) return 0;
727 cnum += utf8_cols(p, clen);
728 p += clen;
729 }
730 return (int)((const char *)p - str) - cnum;
731 } // end: utf8_delta
732
733
734 /*
735 * Determine a physical end within a potential multi-byte string
736 * where maximum printable chars could be accommodated in width */
737 static int utf8_embody (const char *str, int width) {
738 const unsigned char *p = (const unsigned char *)str;
739 int clen, cnum = 0;
740
741 if (width > 0) {
742 while (*p) {
743 // -1 represents a decoding error, pretend it's untranslated ...
744 if (0 > (clen = UTF8_tab[*p])) return width;
745 if (width < (cnum += utf8_cols(p, clen))) break;
746 p += clen;
747 }
748 }
749 return (int)((const char *)p - str);
750 } // end: utf8_embody
751
752
753 /*
754 * Like the regular justify_pad routine but this guy
755 * can accommodate the multi-byte translated strings */
756 static const char *utf8_justify (const char *str, int width, int justr) {
757 static char l_fmt[] = "%-*.*s%s", r_fmt[] = "%*.*s%s";
758 static char buf[SCREENMAX];
759 char tmp[SCREENMAX];
760
761 snprintf(tmp, sizeof(tmp), "%.*s", utf8_embody(str, width), str);
762 width += utf8_delta(tmp);
763 snprintf(buf, sizeof(buf), justr ? r_fmt : l_fmt, width, width, tmp, COLPADSTR);
764 return buf;
765 } // end: utf8_justify
766
767
768 /*
769 * Returns a physical or logical column number given a
770 * multi-byte string and a target column value */
771 static int utf8_proper_col (const char *str, int col, int tophysical) {
772 const unsigned char *p = (const unsigned char *)str;
773 int clen, tlen = 0, cnum = 0;
774
775 while (*p) {
776 // -1 represents a decoding error, don't encourage repositioning ...
777 if (0 > (clen = UTF8_tab[*p])) return col;
778 if (cnum + 1 > col && tophysical) break;
779 p += clen;
780 tlen += clen;
781 if (tlen > col && !tophysical) break;
782 ++cnum;
783 }
784 return tophysical ? tlen : cnum;
785 } // end: utf8_proper_col
786
787 /*###### Misc Color/Display support ####################################*/
788
789 /*
790 * Make the appropriate caps/color strings for a window/field group.
791 * note: we avoid the use of background color so as to maximize
792 * compatibility with the user's xterm settings */
793 static void capsmk (WIN_t *q) {
794 /* macro to test if a basic (non-color) capability is valid
795 thanks: Floyd Davidson <[email protected]> */
796 #define tIF(s) s ? s : ""
797 /* macro to make compatible with netbsd-curses too
798 thanks: rofl0r <[email protected]> */
799 #define tPM(a,b) tparm(a, b, 0, 0, 0, 0, 0, 0, 0, 0)
800 static int capsdone = 0;
801
802 // we must NOT disturb our 'empty' terminfo strings!
803 if (Batch) return;
804
805 // these are the unchangeable puppies, so we only do 'em once
806 if (!capsdone) {
807 STRLCPY(Cap_clr_eol, tIF(clr_eol))
808 STRLCPY(Cap_clr_eos, tIF(clr_eos))
809 STRLCPY(Cap_clr_scr, tIF(clear_screen))
810 // due to the leading newline, the following must be used with care
811 snprintf(Cap_nl_clreos, sizeof(Cap_nl_clreos), "\n%s", tIF(clr_eos));
812 STRLCPY(Cap_curs_huge, tIF(cursor_visible))
813 STRLCPY(Cap_curs_norm, tIF(cursor_normal))
814 STRLCPY(Cap_curs_hide, tIF(cursor_invisible))
815 STRLCPY(Cap_home, tIF(cursor_home))
816 STRLCPY(Cap_norm, tIF(exit_attribute_mode))
817 STRLCPY(Cap_reverse, tIF(enter_reverse_mode))
818 #ifndef RMAN_IGNORED
819 if (!eat_newline_glitch) {
820 STRLCPY(Cap_rmam, tIF(exit_am_mode))
821 STRLCPY(Cap_smam, tIF(enter_am_mode))
822 if (!*Cap_rmam || !*Cap_smam) {
823 *Cap_rmam = '\0';
824 *Cap_smam = '\0';
825 if (auto_right_margin)
826 Cap_avoid_eol = 1;
827 }
828 putp(Cap_rmam);
829 }
830 #endif
831 snprintf(Caps_off, sizeof(Caps_off), "%s%s", Cap_norm, tIF(orig_pair));
832 snprintf(Caps_endline, sizeof(Caps_endline), "%s%s", Caps_off, Cap_clr_eol);
833 if (tgoto(cursor_address, 1, 1)) Cap_can_goto = 1;
834 capsdone = 1;
835 }
836
837 /* the key to NO run-time costs for configurable colors -- we spend a
838 little time with the user now setting up our terminfo strings, and
839 the job's done until he/she/it has a change-of-heart */
840 STRLCPY(q->cap_bold, CHKw(q, View_NOBOLD) ? Cap_norm : tIF(enter_bold_mode))
841 if (CHKw(q, Show_COLORS) && max_colors > 0) {
842 STRLCPY(q->capclr_sum, tPM(set_a_foreground, q->rc.summclr))
843 snprintf(q->capclr_msg, sizeof(q->capclr_msg), "%s%s"
844 , tPM(set_a_foreground, q->rc.msgsclr), Cap_reverse);
845 snprintf(q->capclr_pmt, sizeof(q->capclr_pmt), "%s%s"
846 , tPM(set_a_foreground, q->rc.msgsclr), q->cap_bold);
847 snprintf(q->capclr_hdr, sizeof(q->capclr_hdr), "%s%s"
848 , tPM(set_a_foreground, q->rc.headclr), Cap_reverse);
849 snprintf(q->capclr_rownorm, sizeof(q->capclr_rownorm), "%s%s"
850 , Caps_off, tPM(set_a_foreground, q->rc.taskclr));
851 } else {
852 q->capclr_sum[0] = '\0';
853 #ifdef USE_X_COLHDR
854 snprintf(q->capclr_msg, sizeof(q->capclr_msg), "%s%s"
855 , Cap_reverse, q->cap_bold);
856 #else
857 STRLCPY(q->capclr_msg, Cap_reverse)
858 #endif
859 STRLCPY(q->capclr_pmt, q->cap_bold)
860 STRLCPY(q->capclr_hdr, Cap_reverse)
861 STRLCPY(q->capclr_rownorm, Cap_norm)
862 }
863
864 // composite(s), so we do 'em outside and after the if
865 snprintf(q->capclr_rowhigh, sizeof(q->capclr_rowhigh), "%s%s"
866 , q->capclr_rownorm, CHKw(q, Show_HIBOLD) ? q->cap_bold : Cap_reverse);
867 #undef tIF
868 #undef tPM
869 } // end: capsmk
870
871
872 static struct msg_node {
873 char msg[SMLBUFSIZ];
874 struct msg_node *prev;
875 } Msg_tab[BOT_MSGSMAX];
876
877 static struct msg_node *Msg_this = Msg_tab;
878
879 /*
880 * Show an error message (caller may include '\a' for sound) */
881 static void show_msg (const char *str) {
882 STRLCPY(Msg_this->msg, str);
883 if (++Msg_this > &Msg_tab[BOT_MSGSMAX - 1]) Msg_this = Msg_tab;
884
885 PUTT("%s%s %.*s %s%s%s"
886 , tg2(0, Msg_row)
887 , Curwin->capclr_msg
888 , utf8_embody(str, Screen_cols - 2)
889 , str
890 , Cap_curs_hide
891 , Caps_off
892 , Cap_clr_eol);
893 fflush(stdout);
894 usleep(MSG_USLEEP);
895 } // end: show_msg
896
897
898 /*
899 * Show an input prompt + larger cursor (if possible) */
900 static int show_pmt (const char *str) {
901 char buf[MEDBUFSIZ];
902 int len;
903
904 snprintf(buf, sizeof(buf), "%.*s", utf8_embody(str, Screen_cols - 2), str);
905 len = utf8_delta(buf);
906 #ifdef PRETENDNOCAP
907 PUTT("\n%s%s%.*s %s%s%s"
908 #else
909 PUTT("%s%s%.*s %s%s%s"
910 #endif
911 , tg2(0, Msg_row)
912 , Curwin->capclr_pmt
913 , (Screen_cols - 2) + len
914 , buf
915 , Cap_curs_huge
916 , Caps_off
917 , Cap_clr_eol);
918 fflush(stdout);
919 len = strlen(buf) - len;
920 // +1 for the space we added or -1 for the cursor...
921 return (len + 1 < Screen_cols) ? len + 1 : Screen_cols - 1;
922 } // end: show_pmt
923
924
925 /*
926 * Create and print the optional scroll coordinates message */
927 static void show_scroll (void) {
928 char tmp1[SMLBUFSIZ];
929 #ifndef SCROLLVAR_NO
930 char tmp2[SMLBUFSIZ];
931 #endif
932 int totpflgs = Curwin->totpflgs;
933 int begpflgs = Curwin->begpflg + 1;
934
935 #ifndef USE_X_COLHDR
936 if (CHKw(Curwin, Show_HICOLS)) {
937 totpflgs -= 2;
938 if (ENUpos(Curwin, Curwin->rc.sortindx) < Curwin->begpflg) begpflgs -= 2;
939 }
940 #endif
941 if (1 > totpflgs) totpflgs = 1;
942 if (1 > begpflgs) begpflgs = 1;
943 snprintf(tmp1, sizeof(tmp1), N_fmt(SCROLL_coord_fmt), Curwin->begtask + 1, PIDSmaxt, begpflgs, totpflgs);
944 #ifndef SCROLLVAR_NO
945 if (Curwin->varcolbeg) {
946 snprintf(tmp2, sizeof(tmp2), " + %d", Curwin->varcolbeg);
947 scat(tmp1, tmp2);
948 }
949 #endif
950 PUTT("%s%s %.*s%s", tg2(0, Msg_row), Caps_off, Screen_cols - 3, tmp1, Cap_clr_eol);
951 } // end: show_scroll
952
953
954 /*
955 * Show lines with specially formatted elements, but only output
956 * what will fit within the current screen width.
957 * Our special formatting consists of:
958 * "some text <_delimiter_> some more text <_delimiter_>...\n"
959 * Where <_delimiter_> is a two byte combination consisting of a
960 * tilde followed by an ascii digit in the range of 1 - 8.
961 * examples: ~1, ~5, ~8, etc.
962 * The tilde is effectively stripped and the next digit
963 * converted to an index which is then used to select an
964 * 'attribute' from a capabilities table. That attribute
965 * is then applied to the *preceding* substring.
966 * Once recognized, the delimiter is replaced with a null character
967 * and viola, we've got a substring ready to output! Strings or
968 * substrings without delimiters will receive the Cap_norm attribute.
969 *
970 * Caution:
971 * This routine treats all non-delimiter bytes as displayable
972 * data subject to our screen width marching orders. If callers
973 * embed non-display data like tabs or terminfo strings in our
974 * glob, a line will truncate incorrectly at best. Worse case
975 * would be truncation of an embedded tty escape sequence.
976 *
977 * Tabs must always be avoided or our efforts are wasted and
978 * lines will wrap. To lessen but not eliminate the risk of
979 * terminfo string truncation, such non-display stuff should
980 * be placed at the beginning of a "short" line. */
981 static void show_special (int interact, const char *glob) {
982 /* note: the following is for documentation only,
983 the real captab is now found in a group's WIN_t !
984 +------------------------------------------------------+
985 | char *captab[] = { : Cap's = Index |
986 | Cap_norm, Cap_norm, = \000, \001, |
987 | cap_bold, capclr_sum, = \002, \003, |
988 | capclr_msg, capclr_pmt, = \004, \005, |
989 | capclr_hdr, = \006, |
990 | capclr_rowhigh, = \007, |
991 | capclr_rownorm }; = \010 [octal!] |
992 +------------------------------------------------------+ */
993 /* ( Pssst, after adding the termcap transitions, row may )
994 ( exceed 300+ bytes, even in an 80x24 terminal window! )
995 ( Shown here are the former buffer size specifications )
996 ( char tmp[SMLBUFSIZ], lin[MEDBUFSIZ], row[LRGBUFSIZ]. )
997 ( So now we use larger buffers and a little protection )
998 ( against overrunning them with this 'lin_end - glob'. )
999
1000 ( That was uncovered during 'Inspect' development when )
1001 ( this guy was being considered for a supporting role. )
1002 ( However, such an approach was abandoned. As a result )
1003 ( this function is called only with a glob under top's )
1004 ( control and never containing any 'raw/binary' chars! ) */
1005 char tmp[LRGBUFSIZ], lin[LRGBUFSIZ], row[ROWMINSIZ];
1006 char *rp, *lin_end, *sub_beg, *sub_end;
1007 int room;
1008
1009 // handle multiple lines passed in a bunch
1010 while ((lin_end = strchr(glob, '\n'))) {
1011 #define myMIN(a,b) (((a) < (b)) ? (a) : (b))
1012 size_t lessor = myMIN((size_t)(lin_end - glob), sizeof(lin) -3);
1013
1014 // create a local copy we can extend and otherwise abuse
1015 memcpy(lin, glob, lessor);
1016 // zero terminate this part and prepare to parse substrings
1017 lin[lessor] = '\0';
1018 room = Screen_cols;
1019 sub_beg = sub_end = lin;
1020 *(rp = row) = '\0';
1021
1022 while (*sub_beg) {
1023 int ch = *sub_end;
1024 if ('~' == ch) ch = *(sub_end + 1) - '0';
1025 switch (ch) {
1026 case 0: // no end delim, captab makes normal
1027 // only possible when '\n' was NOT preceded with a '~#' sequence
1028 // ( '~1' thru '~8' is valid range, '~0' is never actually used )
1029 *(sub_end + 1) = '\0'; // extend str end, then fall through
1030 *(sub_end + 2) = '\0'; // ( +1 optimization for usual path )
1031 // fall through
1032 case 1: case 2: case 3: case 4:
1033 case 5: case 6: case 7: case 8:
1034 *sub_end = '\0';
1035 snprintf(tmp, sizeof(tmp), "%s%.*s%s"
1036 , Curwin->captab[ch], utf8_embody(sub_beg, room), sub_beg, Caps_off);
1037 rp = scat(rp, tmp);
1038 room -= (sub_end - sub_beg);
1039 room += utf8_delta(sub_beg);
1040 sub_beg = (sub_end += 2);
1041 break;
1042 default: // nothin' special, just text
1043 ++sub_end;
1044 }
1045 if (0 >= room) break; // skip substrings that won't fit
1046 }
1047
1048 if (interact) PUTT("%s%s\n", row, Cap_clr_eol);
1049 else PUFF("%s%s\n", row, Caps_endline);
1050 glob = ++lin_end; // point to next line (maybe)
1051
1052 #undef myMIN
1053 } // end: while 'lines'
1054
1055 /* If there's anything left in the glob (by virtue of no trailing '\n'),
1056 it probably means caller wants to retain cursor position on this final
1057 line. That, in turn, means we're interactive and so we'll just do our
1058 'fit-to-screen' thingy while also leaving room for the cursor... */
1059 if (*glob) PUTT("%.*s", utf8_embody(glob, Screen_cols - 1), glob);
1060 } // end: show_special
1061
1062 /*###### Low Level Memory/Keyboard/File I/O support ####################*/
1063
1064 /*
1065 * Handle our own memory stuff without the risk of leaving the
1066 * user's terminal in an ugly state should things go sour. */
1067
1068 static void *alloc_c (size_t num) {
1069 void *pv;
1070
1071 if (!num) ++num;
1072 if (!(pv = calloc(1, num)))
1073 error_exit(N_txt(FAIL_alloc_c_txt));
1074 return pv;
1075 } // end: alloc_c
1076
1077
1078 static void *alloc_r (void *ptr, size_t num) {
1079 void *pv;
1080
1081 if (!num) ++num;
1082 if (!(pv = realloc(ptr, num)))
1083 error_exit(N_txt(FAIL_alloc_r_txt));
1084 return pv;
1085 } // end: alloc_r
1086
1087
1088 static char *alloc_s (const char *str) {
1089 return strcpy(alloc_c(strlen(str) +1), str);
1090 } // end: alloc_s
1091
1092
1093 /*
1094 * An 'I/O available' routine which will detect raw single byte |
1095 * unsolicited keyboard input which was susceptible to SIGWINCH |
1096 * interrupt (or any other signal). He'll also support timeout |
1097 * in the absence of any user keystrokes or a signal interrupt. | */
1098 static inline int ioa (struct timespec *ts) {
1099 fd_set fs;
1100 int rc;
1101
1102 FD_ZERO(&fs);
1103 FD_SET(STDIN_FILENO, &fs);
1104
1105 #ifdef SIGNALS_LESS // conditional comments are silly, but help in documenting
1106 // hold here until we've got keyboard input, any signal except SIGWINCH
1107 // or (optionally) we timeout with nanosecond granularity
1108 #else
1109 // hold here until we've got keyboard input, any signal (including SIGWINCH)
1110 // or (optionally) we timeout with nanosecond granularity
1111 #endif
1112 rc = pselect(STDIN_FILENO + 1, &fs, NULL, NULL, ts, &Sigwinch_set);
1113
1114 if (rc < 0) rc = 0;
1115 return rc;
1116 } // end: ioa
1117
1118
1119 /*
1120 * This routine isolates ALL user INPUT and ensures that we
1121 * won't be mixing I/O from stdio and low-level read() requests */
1122 static int ioch (int ech, char *buf, unsigned cnt) {
1123 int rc = -1;
1124
1125 #ifdef TERMIOS_ONLY
1126 if (ech) {
1127 tcsetattr(STDIN_FILENO, TCSAFLUSH, &Tty_tweaked);
1128 rc = read(STDIN_FILENO, buf, cnt);
1129 tcsetattr(STDIN_FILENO, TCSAFLUSH, &Tty_raw);
1130 } else {
1131 if (ioa(NULL))
1132 rc = read(STDIN_FILENO, buf, cnt);
1133 }
1134 #else
1135 (void)ech;
1136 if (ioa(NULL))
1137 rc = read(STDIN_FILENO, buf, cnt);
1138 #endif
1139
1140 // zero means EOF, might happen if we erroneously get detached from terminal
1141 if (0 == rc) bye_bye(NULL);
1142
1143 // it may have been the beginning of a lengthy escape sequence
1144 tcflush(STDIN_FILENO, TCIFLUSH);
1145
1146 // note: we do NOT produce a valid 'string'
1147 return rc;
1148 } // end: ioch
1149
1150
1151 #define IOKEY_INIT 0
1152 #define IOKEY_ONCE 1
1153 #define IOKEY_NEXT 2
1154
1155 /*
1156 * Support for single or multiple keystroke input AND
1157 * escaped cursor motion keys.
1158 * note: we support more keys than we currently need, in case
1159 * we attract new consumers in the future */
1160 static int iokey (int action) {
1161 static struct {
1162 const char *str;
1163 int key;
1164 } tinfo_tab[] = {
1165 { NULL, kbd_BKSP }, { NULL, kbd_INS }, { NULL, kbd_DEL }, { NULL, kbd_LEFT },
1166 { NULL, kbd_DOWN }, { NULL, kbd_UP }, { NULL, kbd_RIGHT }, { NULL, kbd_HOME },
1167 { NULL, kbd_PGDN }, { NULL, kbd_PGUP }, { NULL, kbd_END }, { NULL, kbd_BTAB },
1168 // remainder are alternatives for above, just in case...
1169 // ( the h,j,k,l entries are the vim cursor motion keys )
1170 { "\b", kbd_BKSP }, { "\177", kbd_BKSP }, /* backspace */
1171 { "\033h", kbd_LEFT }, { "\033j", kbd_DOWN }, /* meta+ h,j */
1172 { "\033k", kbd_UP }, { "\033l", kbd_RIGHT }, /* meta+ k,l */
1173 { "\033\010", kbd_HOME }, { "\033\012", kbd_PGDN }, /* ctrl+meta+ h,j */
1174 { "\033\013", kbd_PGUP }, { "\033\014", kbd_END }, /* ctrl+meta+ k,l */
1175 { "\xC3\xA8", kbd_LEFT }, { "\xC3\xAA", kbd_DOWN }, /* meta+ h,j (some xterms) */
1176 { "\xC3\xAB", kbd_UP }, { "\xC3\xAC", kbd_RIGHT }, /* meta+ k,l (some xterms) */
1177 { "\xC2\x88", kbd_HOME }, { "\xC2\x8A", kbd_PGDN }, /* ctrl+meta+ h,j (some xterms) */
1178 { "\xC2\x8B", kbd_PGUP }, { "\xC2\x8C", kbd_END }, /* ctrl+meta+ k,l (some xterms) */
1179 { "\033\011", kbd_BTAB }
1180 };
1181 static char erase[2];
1182 #ifdef TERMIOS_ONLY
1183 char buf[SMLBUFSIZ], *pb;
1184 #else
1185 static char buf[MEDBUFSIZ];
1186 static int pos, len;
1187 char *pb;
1188 #endif
1189 int i;
1190
1191 if (action == IOKEY_INIT) {
1192 #ifndef _POSIX_VDISABLE
1193 #define _POSIX_VDISABLE fpathconf(STDIN_FILENO, _PC_VDISABLE)
1194 #endif
1195 if (Tty_original.c_cc[VERASE] == _POSIX_VDISABLE)
1196 tinfo_tab[0].str = key_backspace;
1197 else {
1198 *erase = Tty_original.c_cc[VERASE];
1199 tinfo_tab[0].str = erase;
1200 }
1201 tinfo_tab[1].str = key_ic;
1202 tinfo_tab[2].str = key_dc;
1203 tinfo_tab[3].str = key_left;
1204 tinfo_tab[4].str = key_down;
1205 tinfo_tab[5].str = key_up;
1206 tinfo_tab[6].str = key_right;
1207 tinfo_tab[7].str = key_home;
1208 tinfo_tab[8].str = key_npage;
1209 tinfo_tab[9].str = key_ppage;
1210 tinfo_tab[10].str = key_end;
1211 tinfo_tab[11].str = back_tab;
1212 // next is critical so returned results match bound terminfo keys
1213 if (keypad_xmit)
1214 putp(keypad_xmit);
1215 // ( converse keypad_local issued at pause/pgm end, just in case )
1216 return 0;
1217 }
1218
1219 if (action == IOKEY_ONCE) {
1220 memset(buf, '\0', sizeof(buf));
1221 if (1 > ioch(0, buf, sizeof(buf)-1)) return 0;
1222 }
1223
1224 #ifndef TERMIOS_ONLY
1225 if (action == IOKEY_NEXT) {
1226 if (pos < len)
1227 return buf[pos++]; // exhaust prior keystrokes
1228 pos = len = 0;
1229 memset(buf, '\0', sizeof(buf));
1230 if (1 > ioch(0, buf, sizeof(buf)-1)) return 0;
1231 if (!iscntrl(buf[0])) { // no need for translation
1232 len = strlen(buf);
1233 pos = 1;
1234 return buf[0];
1235 }
1236 }
1237 #endif
1238
1239 /* some emulators implement 'key repeat' too well and we get duplicate
1240 key sequences -- so we'll focus on the last escaped sequence, while
1241 also allowing use of the meta key... */
1242 if (!(pb = strrchr(buf, '\033'))) pb = buf;
1243 else if (pb > buf && '\033' == *(pb - 1)) --pb;
1244
1245 for (i = 0; i < MAXTBL(tinfo_tab); i++)
1246 if (tinfo_tab[i].str && !strcmp(tinfo_tab[i].str, pb))
1247 return tinfo_tab[i].key;
1248
1249 // no match, so we'll return single non-escaped keystrokes only
1250 if (buf[0] == '\033' && buf[1]) return -1;
1251 return buf[0];
1252 } // end: iokey
1253
1254
1255 #ifdef TERMIOS_ONLY
1256 /*
1257 * Get line oriented interactive input from the user,
1258 * using native tty support */
1259 static char *ioline (const char *prompt) {
1260 static const char ws[] = "\b\f\n\r\t\v\x1b\x9b"; // 0x1b + 0x9b are escape
1261 static char buf[MEDBUFSIZ];
1262 char *p;
1263
1264 show_pmt(prompt);
1265 memset(buf, '\0', sizeof(buf));
1266 ioch(1, buf, sizeof(buf)-1);
1267
1268 if ((p = strpbrk(buf, ws))) *p = '\0';
1269 // note: we DO produce a valid 'string'
1270 return buf;
1271 } // end: ioline
1272
1273 #else
1274 /*
1275 * Get some line oriented interactive input from the ol' user,
1276 * going way, way beyond that native tty support by providing:
1277 * . true input line editing, not just a destructive backspace
1278 * . an input limit sensitive to the current screen dimensions
1279 * . an ability to recall prior strings for editing & re-input */
1280 static char *ioline (const char *prompt) {
1281 #define setLEN ( len = strlen(buf) - utf8_delta(buf) )
1282 #define setPOS(X) ( pos = utf8_embody(buf, X) )
1283 #define utfCHR(X) ( (unsigned char *)&buf[X] )
1284 #define utfTOT(X) ( UTF8_tab[(unsigned char)buf[X]] )
1285 #define utfCOL(X) ( utf8_cols(utfCHR(X), utfTOT(X)) )
1286 #define movBKW { setPOS(cur - 1); while (utfTOT(pos) < 0) --pos; }
1287 #define chkCUR { if (cur < 0) cur = 0; if (cur > len) cur = len; }
1288 // thank goodness ol' memmove will safely allow strings to overlap
1289 #define sqzSTR { i = utfTOT(pos); while (i < 0) i = utfTOT(--pos); \
1290 if (!utfCOL(pos + i)) i += utfTOT(pos + i); \
1291 memmove(&buf[pos], &buf[pos + i], bufMAX-(pos + i)); \
1292 memset(&buf[bufMAX - i], '\0', i); }
1293 #define expSTR(X) if (bufNXT < bufMAX && scrNXT < Screen_cols) { \
1294 memmove(&buf[pos + X], &buf[pos], bufMAX - pos); }
1295 #define savMAX 50
1296 #define bufNXT ( pos + 4 ) // four equals longest utf8 str
1297 #define scrNXT ( beg + len + 2 ) // two due to multi-column char
1298 #define bufMAX ((int)sizeof(buf)-2) // -1 for '\0' string delimiter
1299 static char buf[MEDBUFSIZ+1]; // +1 for '\0' string delimiter
1300 static int ovt;
1301 int beg, // the physical column where input began, buf[0]
1302 cur, // the logical current column/insertion position
1303 len, // the logical input length, thus the end column
1304 pos, // the physical position in the buffer currently
1305 key, i;
1306 struct lin_s {
1307 struct lin_s *bkw; // pointer for older saved strs
1308 struct lin_s *fwd; // pointer for newer saved strs
1309 char *str; // an actual saved input string
1310 };
1311 static struct lin_s *anchor, *plin;
1312
1313 if (!anchor) {
1314 anchor = alloc_c(sizeof(struct lin_s));
1315 anchor->str = alloc_s(""); // the top-of-stack (empty str)
1316 }
1317 plin = anchor;
1318 cur = len = pos = 0;
1319 beg = show_pmt(prompt);
1320 memset(buf, '\0', sizeof(buf));
1321 // this may not work under a gui emulator (but linux console is ok)
1322 putp(ovt ? Cap_curs_huge : Cap_curs_norm);
1323
1324 do {
1325 fflush(stdout);
1326 key = iokey(IOKEY_NEXT);
1327 switch (key) {
1328 case 0:
1329 buf[0] = '\0';
1330 return buf;
1331 case kbd_ESC:
1332 buf[0] = kbd_ESC;
1333 return buf;
1334 case kbd_ENTER:
1335 case kbd_BTAB: case kbd_PGUP: case kbd_PGDN:
1336 continue;
1337 case kbd_INS:
1338 ovt = !ovt;
1339 putp(ovt ? Cap_curs_huge : Cap_curs_norm);
1340 break;
1341 case kbd_DEL:
1342 sqzSTR
1343 break;
1344 case kbd_BKSP:
1345 if (0 < cur) { movBKW; cur -= utfCOL(pos); setPOS(cur); sqzSTR; }
1346 break;
1347 case kbd_LEFT:
1348 if (0 < cur) { movBKW; cur -= utfCOL(pos); }
1349 break;
1350 case kbd_RIGHT:
1351 if (cur < len) cur += utfCOL(pos);
1352 break;
1353 case kbd_HOME:
1354 cur = pos = 0;
1355 break;
1356 case kbd_END:
1357 cur = len;
1358 pos = strlen(buf);
1359 break;
1360 case kbd_UP:
1361 if (plin->bkw) {
1362 plin = plin->bkw;
1363 memset(buf, '\0', sizeof(buf));
1364 memccpy(buf, plin->str, '\0', bufMAX);
1365 cur = setLEN;
1366 pos = strlen(buf);
1367 }
1368 break;
1369 case kbd_DOWN:
1370 if (plin->fwd) plin = plin->fwd;
1371 memset(buf, '\0', sizeof(buf));
1372 memccpy(buf, plin->str, '\0', bufMAX);
1373 cur = setLEN;
1374 pos = strlen(buf);
1375 break;
1376 default: // what we REALLY wanted (maybe)
1377 if (bufNXT < bufMAX && scrNXT < Screen_cols && strlen(buf) < bufMAX) {
1378 int tot = UTF8_tab[(unsigned char)key],
1379 sav = pos;
1380 if (tot < 1) tot = 1;
1381 if (!ovt) { expSTR(tot); }
1382 else { pos = utf8_embody(buf, cur); sqzSTR; expSTR(tot); }
1383 buf[pos++] = key;
1384 while (tot > 1) {
1385 key = iokey(IOKEY_NEXT);
1386 buf[pos++] = key;
1387 --tot;
1388 }
1389 cur += utfCOL(sav);
1390 }
1391 break;
1392 }
1393 setLEN;
1394 chkCUR;
1395 setPOS(cur);
1396 putp(fmtmk("%s%s%s", tg2(beg, Msg_row), Cap_clr_eol, buf));
1397 #ifdef OVERTYPE_SEE
1398 putp(fmtmk("%s%c", tg2(beg - 1, Msg_row), ovt ? '^' : ' '));
1399 #endif
1400 putp(tg2(beg + cur, Msg_row));
1401 } while (key != kbd_ENTER);
1402
1403 // weed out duplicates, including empty strings (top-of-stack)...
1404 for (i = 0, plin = anchor; ; i++) {
1405 #ifdef RECALL_FIXED
1406 if (!STRCMP(plin->str, buf)) // if matched, retain original order
1407 return buf;
1408 #else
1409 if (!STRCMP(plin->str, buf)) { // if matched, rearrange stack order
1410 if (i > 1) { // but not null str or if already #2
1411 if (plin->bkw) // splice around this matched string
1412 plin->bkw->fwd = plin->fwd; // if older exists link to newer
1413 plin->fwd->bkw = plin->bkw; // newer linked to older or NULL
1414 anchor->bkw->fwd = plin; // stick matched on top of former #2
1415 plin->bkw = anchor->bkw; // keep empty string at top-of-stack
1416 plin->fwd = anchor; // then prepare to be the 2nd banana
1417 anchor->bkw = plin; // by sliding us in below the anchor
1418 }
1419 return buf;
1420 }
1421 #endif
1422 if (!plin->bkw) break; // let i equal total stacked strings
1423 plin = plin->bkw; // ( with plin representing bottom )
1424 }
1425 if (i < savMAX)
1426 plin = alloc_c(sizeof(struct lin_s));
1427 else { // when a new string causes overflow
1428 plin->fwd->bkw = NULL; // make next-to-last string new last
1429 free(plin->str); // and toss copy but keep the struct
1430 }
1431 plin->str = alloc_s(buf); // copy user's new unique input line
1432 plin->bkw = anchor->bkw; // keep empty string as top-of-stack
1433 if (plin->bkw) // did we have some already stacked?
1434 plin->bkw->fwd = plin; // yep, so point prior to new string
1435 plin->fwd = anchor; // and prepare to be a second banana
1436 anchor->bkw = plin; // by sliding it in as new number 2!
1437
1438 return buf; // protect our copy, return original
1439 #undef setLEN
1440 #undef setPOS
1441 #undef utfCHR
1442 #undef utfTOT
1443 #undef utfCOL
1444 #undef movBKW
1445 #undef chkCUR
1446 #undef sqzSTR
1447 #undef expSTR
1448 #undef savMAX
1449 #undef bufNXT
1450 #undef scrNXT
1451 #undef bufMAX
1452 } // end: ioline
1453 #endif
1454
1455
1456 /*
1457 * Make locale unaware float (but maybe restrict to whole numbers). */
1458 static int mkfloat (const char *str, float *num, int whole) {
1459 char tmp[SMLBUFSIZ], *ep;
1460
1461 if (whole) {
1462 *num = (float)strtol(str, &ep, 0);
1463 if (ep != str && *ep == '\0' && *num < INT_MAX)
1464 return 1;
1465 return 0;
1466 }
1467 snprintf(tmp, sizeof(tmp), "%s", str);
1468 *num = strtof(tmp, &ep);
1469 if (*ep != '\0') {
1470 // fallback - try to swap the floating point separator
1471 if (*ep == '.') *ep = ',';
1472 else if (*ep == ',') *ep = '.';
1473 *num = strtof(tmp, &ep);
1474 }
1475 if (ep != tmp && *ep == '\0' && *num < INT_MAX)
1476 return 1;
1477 return 0;
1478 } // end: mkfloat
1479
1480
1481 /*
1482 * This routine provides the i/o in support of files whose size
1483 * cannot be determined in advance. Given a stream pointer, he'll
1484 * try to slurp in the whole thing and return a dynamically acquired
1485 * buffer supporting that single string glob.
1486 *
1487 * He always creates a buffer at least READMINSZ big, possibly
1488 * all zeros (an empty string), even if the file wasn't read. */
1489 static int readfile (FILE *fp, char **baddr, size_t *bsize, size_t *bread) {
1490 char chunk[4096*16];
1491 size_t num;
1492
1493 *bread = 0;
1494 *bsize = READMINSZ;
1495 *baddr = alloc_c(READMINSZ);
1496 if (fp) {
1497 while (0 < (num = fread(chunk, 1, sizeof(chunk), fp))) {
1498 *baddr = alloc_r(*baddr, num + *bsize);
1499 memcpy(*baddr + *bread, chunk, num);
1500 *bread += num;
1501 *bsize += num;
1502 };
1503 *(*baddr + *bread) = '\0';
1504 return ferror(fp);
1505 }
1506 return ENOENT;
1507 } // end: readfile
1508
1509 /*###### Small Utility routines ########################################*/
1510
1511 #define GET_NUM_BAD INT_MIN
1512 #define GET_NUM_ESC (INT_MIN + 1)
1513 #define GET_NUM_NOT (INT_MIN + 2)
1514
1515 /*
1516 * Get a float from the user */
1517 static float get_float (const char *prompt) {
1518 char *line;
1519 float f;
1520
1521 line = ioline(prompt);
1522 if (line[0] == kbd_ESC || Frames_signal) return GET_NUM_ESC;
1523 if (!line[0]) return GET_NUM_NOT;
1524 // note: we're not allowing negative floats
1525 if (!mkfloat(line, &f, 0) || f < 0) {
1526 show_msg(N_txt(BAD_numfloat_txt));
1527 return GET_NUM_BAD;
1528 }
1529 return f;
1530 } // end: get_float
1531
1532
1533 /*
1534 * Get an integer from the user, returning INT_MIN for error */
1535 static int get_int (const char *prompt) {
1536 char *line;
1537 float f;
1538
1539 line = ioline(prompt);
1540 if (line[0] == kbd_ESC || Frames_signal) return GET_NUM_ESC;
1541 if (!line[0]) return GET_NUM_NOT;
1542 // note: we've got to allow negative ints (renice)
1543 if (!mkfloat(line, &f, 1)) {
1544 show_msg(N_txt(BAD_integers_txt));
1545 return GET_NUM_BAD;
1546 }
1547 return (int)f;
1548 } // end: get_int
1549
1550
1551 /*
1552 * Make a hex value, and maybe suppress zeroes. */
1553 static inline const char *hex_make (long num, int noz) {
1554 static char buf[SMLBUFSIZ];
1555 int i;
1556
1557 #ifdef CASEUP_HEXES
1558 snprintf(buf, sizeof(buf), "%08lX", num);
1559 #else
1560 snprintf(buf, sizeof(buf), "%08lx", num);
1561 #endif
1562 if (noz)
1563 for (i = 0; buf[i]; i++)
1564 if ('0' == buf[i])
1565 buf[i] = '.';
1566 return buf;
1567 } // end: hex_make
1568
1569
1570 /*
1571 * Validate the passed string as a user name or number,
1572 * and/or update the window's 'u/U' selection stuff. */
1573 static const char *user_certify (WIN_t *q, const char *str, char typ) {
1574 struct passwd *pwd;
1575 char *endp;
1576 uid_t num;
1577
1578 Monpidsidx = 0;
1579 q->usrseltyp = 0;
1580 q->usrselflg = 1;
1581 if (*str) {
1582 if ('!' == *str) { ++str; q->usrselflg = 0; }
1583 num = (uid_t)strtoul(str, &endp, 0);
1584 if ('\0' == *endp) {
1585 pwd = getpwuid(num);
1586 if (!pwd) {
1587 /* allow foreign users, from e.g within chroot
1588 ( thanks Dr. Werner Fink <[email protected]> ) */
1589 q->usrseluid = num;
1590 q->usrseltyp = typ;
1591 return NULL;
1592 }
1593 } else
1594 pwd = getpwnam(str);
1595 if (!pwd) return N_txt(BAD_username_txt);
1596 q->usrseluid = pwd->pw_uid;
1597 q->usrseltyp = typ;
1598 }
1599 return NULL;
1600 } // end: user_certify
1601
1602 /*###### Basic Formatting support ######################################*/
1603
1604 /*
1605 * Just do some justify stuff, then add post column padding. */
1606 static inline const char *justify_pad (const char *str, int width, int justr) {
1607 static char l_fmt[] = "%-*.*s%s", r_fmt[] = "%*.*s%s";
1608 static char buf[SCREENMAX];
1609
1610 snprintf(buf, sizeof(buf), justr ? r_fmt : l_fmt, width, width, str, COLPADSTR);
1611 return buf;
1612 } // end: justify_pad
1613
1614
1615 /*
1616 * Make and then justify a single character. */
1617 static inline const char *make_chr (const char ch, int width, int justr) {
1618 static char buf[SMLBUFSIZ];
1619
1620 snprintf(buf, sizeof(buf), "%c", ch);
1621 return justify_pad(buf, width, justr);
1622 } // end: make_chr
1623
1624
1625 /*
1626 * Make and then justify an integer NOT subject to scaling,
1627 * and include a visual clue should tuncation be necessary. */
1628 static inline const char *make_num (long num, int width, int justr, int col, int noz) {
1629 static char buf[SMLBUFSIZ];
1630
1631 buf[0] = '\0';
1632 if (noz && Rc.zero_suppress && 0 == num)
1633 goto end_justifies;
1634
1635 if (width < snprintf(buf, sizeof(buf), "%ld", num)) {
1636 if (width <= 0 || (size_t)width >= sizeof(buf))
1637 width = sizeof(buf)-1;
1638 buf[width-1] = COLPLUSCH;
1639 buf[width] = '\0';
1640 AUTOX_COL(col);
1641 }
1642 end_justifies:
1643 return justify_pad(buf, width, justr);
1644 } // end: make_num
1645
1646
1647 /*
1648 * Make and then justify a character string,
1649 * and include a visual clue should tuncation be necessary. */
1650 static inline const char *make_str (const char *str, int width, int justr, int col) {
1651 static char buf[SCREENMAX];
1652
1653 if (width < snprintf(buf, sizeof(buf), "%s", str)) {
1654 if (width <= 0 || (size_t)width >= sizeof(buf))
1655 width = sizeof(buf)-1;
1656 buf[width-1] = COLPLUSCH;
1657 buf[width] = '\0';
1658 AUTOX_COL(col);
1659 }
1660 return justify_pad(buf, width, justr);
1661 } // end: make_str
1662
1663
1664 /*
1665 * Make and then justify a potentially multi-byte character string,
1666 * and include a visual clue should tuncation be necessary. */
1667 static inline const char *make_str_utf8 (const char *str, int width, int justr, int col) {
1668 static char buf[SCREENMAX];
1669 int delta = utf8_delta(str);
1670
1671 if (width + delta < snprintf(buf, sizeof(buf), "%s", str)) {
1672 snprintf(buf, sizeof(buf), "%.*s%c", utf8_embody(str, width-1), str, COLPLUSCH);
1673 delta = utf8_delta(buf);
1674 AUTOX_COL(col);
1675 }
1676 return justify_pad(buf, width + delta, justr);
1677 } // end: make_str_utf8
1678
1679
1680 /*
1681 * Do some scaling then justify stuff.
1682 * We'll interpret 'num' as a kibibytes quantity and try to
1683 * format it to reach 'target' while also fitting 'width'. */
1684 static const char *scale_mem (int target, float num, int width, int justr) {
1685 // SK_Kb SK_Mb SK_Gb SK_Tb SK_Pb SK_Eb
1686 #ifdef BOOST_MEMORY
1687 static const char *fmttab[] = { "%.0f", "%#.1f%c", "%#.3f%c", "%#.3f%c", "%#.3f%c", NULL };
1688 #else
1689 static const char *fmttab[] = { "%.0f", "%.1f%c", "%.1f%c", "%.1f%c", "%.1f%c", NULL };
1690 #endif
1691 static char buf[SMLBUFSIZ];
1692 char *psfx;
1693 int i;
1694
1695 buf[0] = '\0';
1696 if (Rc.zero_suppress && 0 >= num)
1697 goto end_justifies;
1698
1699 for (i = SK_Kb, psfx = Scaled_sfxtab; i < SK_Eb; psfx++, i++) {
1700 if (i >= target
1701 && (width >= snprintf(buf, sizeof(buf), fmttab[i], num, *psfx)))
1702 goto end_justifies;
1703 num /= 1024.0;
1704 }
1705
1706 // well shoot, this outta' fit...
1707 snprintf(buf, sizeof(buf), "?");
1708 end_justifies:
1709 return justify_pad(buf, width, justr);
1710 } // end: scale_mem
1711
1712
1713 /*
1714 * Do some scaling then justify stuff. */
1715 static const char *scale_num (float num, int width, int justr) {
1716 static char buf[SMLBUFSIZ];
1717 char *psfx;
1718
1719 buf[0] = '\0';
1720 if (Rc.zero_suppress && 0 >= num)
1721 goto end_justifies;
1722 if (width >= snprintf(buf, sizeof(buf), "%.0f", num))
1723 goto end_justifies;
1724
1725 for (psfx = Scaled_sfxtab; 0 < *psfx; psfx++) {
1726 num /= 1024.0;
1727 if (width >= snprintf(buf, sizeof(buf), "%.1f%c", num, *psfx))
1728 goto end_justifies;
1729 if (width >= snprintf(buf, sizeof(buf), "%.0f%c", num, *psfx))
1730 goto end_justifies;
1731 }
1732
1733 // well shoot, this outta' fit...
1734 snprintf(buf, sizeof(buf), "?");
1735 end_justifies:
1736 return justify_pad(buf, width, justr);
1737 } // end: scale_num
1738
1739
1740 /*
1741 * Make and then justify a percentage, with decreasing precision. */
1742 static const char *scale_pcnt (float num, int width, int justr, int xtra) {
1743 static char buf[SMLBUFSIZ];
1744
1745 buf[0] = '\0';
1746 if (Rc.zero_suppress && 0 >= num)
1747 goto end_justifies;
1748 if (xtra) {
1749 if (width >= snprintf(buf, sizeof(buf), "%#.3f", num))
1750 goto end_justifies;
1751 if (width >= snprintf(buf, sizeof(buf), "%#.2f", num))
1752 goto end_justifies;
1753 goto carry_on;
1754 }
1755 #ifdef BOOST_PERCNT
1756 if (width >= snprintf(buf, sizeof(buf), "%#.3f", num))
1757 goto end_justifies;
1758 if (width >= snprintf(buf, sizeof(buf), "%#.2f", num))
1759 goto end_justifies;
1760 (void)xtra;
1761 #endif
1762 carry_on:
1763 if (width >= snprintf(buf, sizeof(buf), "%#.1f", num))
1764 goto end_justifies;
1765 if (width >= snprintf(buf, sizeof(buf), "%*.0f", width, num))
1766 goto end_justifies;
1767
1768 // well shoot, this outta' fit...
1769 snprintf(buf, sizeof(buf), "?");
1770 end_justifies:
1771 return justify_pad(buf, width, justr);
1772 } // end: scale_pcnt
1773
1774
1775 #define TICS_AS_SECS 0
1776 #define TICS_AS_MINS 1
1777 #define TICS_AS_HOUR 2
1778 #define TICS_AS_DAY1 3
1779 #define TICS_AS_DAY2 4
1780 #define TICS_AS_WEEK 5
1781 #define TICS_AS_LAST 6
1782
1783 /*
1784 * Do some scaling stuff.
1785 * Try to format 'tics' to reach 'target' while also
1786 * fitting in 'width', then justify it. */
1787 static const char *scale_tics (TIC_t tics, int width, int justr, int target) {
1788 #ifdef CASEUP_SUFIX
1789 #define HH "%luH" // nls_maybe
1790 #define DD "%luD"
1791 #define WW "%luW"
1792 #else
1793 #define HH "%luh" // nls_maybe
1794 #define DD "%lud"
1795 #define WW "%luw"
1796 #endif
1797 static char buf[SMLBUFSIZ];
1798 TIC_t nt; // for speed on 64-bit
1799 #ifdef SCALE_FORMER
1800 unsigned long cc; // centiseconds
1801 unsigned long nn; // multi-purpose whatever
1802 #else
1803 unsigned long cent, secs, mins, hour, days, week;
1804 #endif
1805
1806 buf[0] = '\0';
1807 nt = (tics * 100ull) / Hertz; // lots of room for any time
1808 if (Rc.zero_suppress && 0 >= nt)
1809 goto end_justifies;
1810
1811 #ifdef SCALE_FORMER
1812 cc = nt % 100; // centiseconds past second
1813 nt /= 100; // total seconds
1814 nn = nt % 60; // seconds past the minute
1815 nt /= 60; // total minutes
1816 if (target < TICS_AS_MINS
1817 && (width >= snprintf(buf, sizeof(buf), "%llu:%02lu.%02lu", nt, nn, cc)))
1818 goto end_justifies;
1819 if (target < TICS_AS_HOUR
1820 && (width >= snprintf(buf, sizeof(buf), "%llu:%02lu", nt, nn)))
1821 goto end_justifies;
1822 nn = nt % 60; // minutes past the hour
1823 nt /= 60; // total hours
1824 if (width >= snprintf(buf, sizeof(buf), "%llu,%02lu", nt, nn))
1825 goto end_justifies;
1826 nn = nt; // now also hours
1827 if (width >= snprintf(buf, sizeof(buf), HH, nn))
1828 goto end_justifies;
1829 nn /= 24; // now days
1830 if (width >= snprintf(buf, sizeof(buf), DD, nn))
1831 goto end_justifies;
1832 nn /= 7; // now weeks
1833 if (width >= snprintf(buf, sizeof(buf), WW, nn))
1834 goto end_justifies;
1835 #else
1836 #define mmLIMIT 360 // arbitrary 6 hours
1837 #define hhLIMIT 96 // arbitrary 4 days
1838 #define ddLIMIT 14 // arbitrary 2 weeks
1839
1840 cent = (nt % 100); // cent past secs
1841 secs = (nt /= 100); // total secs
1842 mins = (nt /= 60); // total mins
1843 hour = (nt /= 60); // total hour
1844 days = (nt /= 24); // total days
1845 week = (nt / 7); // total week
1846
1847 if (Rc.tics_scaled > target)
1848 target += Rc.tics_scaled - target;
1849
1850 switch (target) {
1851 case TICS_AS_SECS:
1852 if (mins < mmLIMIT + 1) {
1853 if (width >= snprintf(buf, sizeof(buf), "%lu:%02lu.%02lu", mins, secs % 60, cent))
1854 goto end_justifies;
1855 }
1856 case TICS_AS_MINS: // fall through
1857 if (mins < mmLIMIT + 1) {
1858 if (width >= snprintf(buf, sizeof(buf), "%lu:%02lu", mins, secs % 60))
1859 goto end_justifies;
1860 }
1861 case TICS_AS_HOUR: // fall through
1862 if (hour < hhLIMIT + 1) {
1863 if (width >= snprintf(buf, sizeof(buf), "%lu,%02lu", hour, mins % 60))
1864 goto end_justifies;
1865 }
1866 case TICS_AS_DAY1: // fall through
1867 if (days < ddLIMIT + 1) {
1868 if (width >= snprintf(buf, sizeof(buf), DD "+" HH, days, hour % 24))
1869 goto end_justifies;
1870 #ifdef SCALE_POSTFX
1871 if (width >= snprintf(buf, sizeof(buf), DD "+%lu", days, hour % 24))
1872 goto end_justifies;
1873 #endif
1874 case TICS_AS_DAY2: // fall through
1875 if (width >= snprintf(buf, sizeof(buf), DD, days))
1876 goto end_justifies;
1877 }
1878 case TICS_AS_WEEK: // fall through
1879 if (width >= snprintf(buf, sizeof(buf), WW "+" DD, week, days % 7))
1880 goto end_justifies;
1881 #ifdef SCALE_POSTFX
1882 if (width >= snprintf(buf, sizeof(buf), WW "+%lu", week, days % 7))
1883 goto end_justifies;
1884 #endif
1885 case TICS_AS_LAST: // fall through
1886 if (width >= snprintf(buf, sizeof(buf), WW, week))
1887 goto end_justifies;
1888 default: // fall through
1889 break;
1890 }
1891 #undef mmLIMIT
1892 #undef hhLIMIT
1893 #undef ddLIMIT
1894 #endif
1895
1896 // well shoot, this outta' fit...
1897 snprintf(buf, sizeof(buf), "?");
1898
1899 end_justifies:
1900 return justify_pad(buf, width, justr);
1901 #undef HH
1902 #undef DD
1903 #undef WW
1904 } // end: scale_tics
1905
1906 /*###### Fields Management support #####################################*/
1907
1908 /* These are our gosh darn 'Fields' !
1909 They MUST be kept in sync with pflags !! */
1910 static struct {
1911 int width; // field width, if applicable
1912 int scale; // scaled target, if applicable
1913 const int align; // the default column alignment flag
1914 enum pids_item item; // the new libproc item enum identifier
1915 } Fieldstab[] = {
1916 // these identifiers reflect the default column alignment but they really
1917 // contain the WIN_t flag used to check/change justification at run-time!
1918 #define A_left Show_JRSTRS /* toggled with lower case 'j' */
1919 #define A_right Show_JRNUMS /* toggled with upper case 'J' */
1920
1921 /* .width anomalies:
1922 a -1 width represents variable width columns
1923 a 0 width represents columns set once at startup (see zap_fieldstab)
1924
1925 .width .scale .align .item
1926 ------ ------ -------- ------------------- */
1927 { 0, -1, A_right, PIDS_ID_PID }, // s_int EU_PID
1928 { 0, -1, A_right, PIDS_ID_PPID }, // s_int EU_PPD
1929 { 5, -1, A_right, PIDS_ID_EUID }, // u_int EU_UED
1930 { 8, -1, A_left, PIDS_ID_EUSER }, // str EU_UEN
1931 { 5, -1, A_right, PIDS_ID_RUID }, // u_int EU_URD
1932 { 8, -1, A_left, PIDS_ID_RUSER }, // str EU_URN
1933 { 5, -1, A_right, PIDS_ID_SUID }, // u_int EU_USD
1934 { 8, -1, A_left, PIDS_ID_SUSER }, // str EU_USN
1935 { 5, -1, A_right, PIDS_ID_EGID }, // u_int EU_GID
1936 { 8, -1, A_left, PIDS_ID_EGROUP }, // str EU_GRP
1937 { 0, -1, A_right, PIDS_ID_PGRP }, // s_int EU_PGD
1938 { 8, -1, A_left, PIDS_TTY_NAME }, // str EU_TTY
1939 { 0, -1, A_right, PIDS_ID_TPGID }, // s_int EU_TPG
1940 { 0, -1, A_right, PIDS_ID_SESSION }, // s_int EU_SID
1941 { 3, -1, A_right, PIDS_PRIORITY }, // s_int EU_PRI
1942 { 3, -1, A_right, PIDS_NICE }, // s_int EU_NCE
1943 { 3, -1, A_right, PIDS_NLWP }, // s_int EU_THD
1944 { 0, -1, A_right, PIDS_PROCESSOR }, // s_int EU_CPN
1945 { 5, -1, A_right, PIDS_TICS_ALL_DELTA }, // u_int EU_CPU
1946 { 6, -1, A_right, PIDS_TICS_ALL }, // ull_int EU_TME
1947 { 9, -1, A_right, PIDS_TICS_ALL }, // ull_int EU_TM2
1948 { 5, -1, A_right, PIDS_MEM_RES }, // ul_int EU_MEM
1949 { 7, SK_Kb, A_right, PIDS_MEM_VIRT }, // ul_int EU_VRT
1950 { 6, SK_Kb, A_right, PIDS_VM_SWAP }, // ul_int EU_SWP
1951 { 6, SK_Kb, A_right, PIDS_MEM_RES }, // ul_int EU_RES
1952 { 6, SK_Kb, A_right, PIDS_MEM_CODE }, // ul_int EU_COD
1953 { 7, SK_Kb, A_right, PIDS_MEM_DATA }, // ul_int EU_DAT
1954 { 6, SK_Kb, A_right, PIDS_MEM_SHR }, // ul_int EU_SHR
1955 { 4, -1, A_right, PIDS_FLT_MAJ }, // ul_int EU_FL1
1956 { 4, -1, A_right, PIDS_FLT_MIN }, // ul_int EU_FL2
1957 { 4, -1, A_right, PIDS_noop }, // ul_int EU_DRT ( always 0 w/ since 2.6 )
1958 { 1, -1, A_right, PIDS_STATE }, // s_ch EU_STA
1959 { -1, -1, A_left, PIDS_CMD }, // str EU_CMD
1960 { 10, -1, A_left, PIDS_WCHAN_NAME }, // str EU_WCH
1961 { 8, -1, A_left, PIDS_FLAGS }, // ul_int EU_FLG
1962 { -1, -1, A_left, PIDS_CGROUP }, // str EU_CGR
1963 { -1, -1, A_left, PIDS_SUPGIDS }, // str EU_SGD
1964 { -1, -1, A_left, PIDS_SUPGROUPS }, // str EU_SGN
1965 { 0, -1, A_right, PIDS_ID_TGID }, // s_int EU_TGD
1966 { 5, -1, A_right, PIDS_OOM_ADJ }, // s_int EU_OOA
1967 { 4, -1, A_right, PIDS_OOM_SCORE }, // s_int EU_OOM
1968 { -1, -1, A_left, PIDS_ENVIRON }, // str EU_ENV
1969 { 3, -1, A_right, PIDS_FLT_MAJ_DELTA }, // s_int EU_FV1
1970 { 3, -1, A_right, PIDS_FLT_MIN_DELTA }, // s_int EU_FV2
1971 { 6, SK_Kb, A_right, PIDS_VM_USED }, // ul_int EU_USE
1972 { 10, -1, A_right, PIDS_NS_IPC }, // ul_int EU_NS1
1973 { 10, -1, A_right, PIDS_NS_MNT }, // ul_int EU_NS2
1974 { 10, -1, A_right, PIDS_NS_NET }, // ul_int EU_NS3
1975 { 10, -1, A_right, PIDS_NS_PID }, // ul_int EU_NS4
1976 { 10, -1, A_right, PIDS_NS_USER }, // ul_int EU_NS5
1977 { 10, -1, A_right, PIDS_NS_UTS }, // ul_int EU_NS6
1978 { 8, -1, A_left, PIDS_LXCNAME }, // str EU_LXC
1979 { 6, SK_Kb, A_right, PIDS_VM_RSS_ANON }, // ul_int EU_RZA
1980 { 6, SK_Kb, A_right, PIDS_VM_RSS_FILE }, // ul_int EU_RZF
1981 { 6, SK_Kb, A_right, PIDS_VM_RSS_LOCKED }, // ul_int EU_RZL
1982 { 6, SK_Kb, A_right, PIDS_VM_RSS_SHARED }, // ul_int EU_RZS
1983 { -1, -1, A_left, PIDS_CGNAME }, // str EU_CGN
1984 { 0, -1, A_right, PIDS_PROCESSOR_NODE }, // s_int EU_NMA
1985 { 5, -1, A_right, PIDS_ID_LOGIN }, // s_int EU_LID
1986 { -1, -1, A_left, PIDS_EXE }, // str EU_EXE
1987 { 6, SK_Kb, A_right, PIDS_SMAP_RSS }, // ul_int EU_RSS
1988 { 6, SK_Kb, A_right, PIDS_SMAP_PSS }, // ul_int EU_PSS
1989 { 6, SK_Kb, A_right, PIDS_SMAP_PSS_ANON }, // ul_int EU_PZA
1990 { 6, SK_Kb, A_right, PIDS_SMAP_PSS_FILE }, // ul_int EU_PZF
1991 { 6, SK_Kb, A_right, PIDS_SMAP_PSS_SHMEM }, // ul_int EU_PZS
1992 { 6, SK_Kb, A_right, PIDS_SMAP_PRV_TOTAL }, // ul_int EU_USS
1993 { 6, -1, A_right, PIDS_IO_READ_BYTES }, // ul_int EU_IRB
1994 { 5, -1, A_right, PIDS_IO_READ_OPS }, // ul_int EU_IRO
1995 { 6, -1, A_right, PIDS_IO_WRITE_BYTES }, // ul_int EU_IWB
1996 { 5, -1, A_right, PIDS_IO_WRITE_OPS }, // ul_int EU_IWO
1997 { 5, -1, A_right, PIDS_AUTOGRP_ID }, // s_int EU_AGI
1998 { 4, -1, A_right, PIDS_AUTOGRP_NICE }, // s_int EU_AGN
1999 { 7, -1, A_right, PIDS_TICS_BEGAN }, // ull_int EU_TM3
2000 { 7, -1, A_right, PIDS_TIME_ELAPSED }, // real EU_TM4
2001 { 6, -1, A_right, PIDS_UTILIZATION }, // real EU_CUU
2002 { 7, -1, A_right, PIDS_UTILIZATION_C }, // real EU_CUC
2003 { 10, -1, A_right, PIDS_NS_CGROUP }, // ul_int EU_NS7
2004 { 10, -1, A_right, PIDS_NS_TIME } // ul_int EU_NS8
2005 #define eu_LAST EU_NS8
2006 // xtra Fieldstab 'pseudo pflag' entries for the newlib interface . . . . . . .
2007 #define eu_CMDLINE eu_LAST +1
2008 #define eu_TICS_ALL_C eu_LAST +2
2009 #define eu_ID_FUID eu_LAST +3
2010 #define eu_CMDLINE_V eu_LAST +4
2011 #define eu_ENVIRON_V eu_LAST +5
2012 #define eu_TREE_HID eu_LAST +6
2013 #define eu_TREE_LVL eu_LAST +7
2014 #define eu_TREE_ADD eu_LAST +8
2015 #define eu_RESET eu_TREE_HID // demarcation for reset to zero (PIDS_extra)
2016 , { -1, -1, -1, PIDS_CMDLINE } // str ( if Show_CMDLIN, eu_CMDLINE )
2017 , { -1, -1, -1, PIDS_TICS_ALL_C } // ull_int ( if Show_CTIMES, eu_TICS_ALL_C )
2018 , { -1, -1, -1, PIDS_ID_FUID } // u_int ( if a usrseltyp, eu_ID_FUID )
2019 , { -1, -1, -1, PIDS_CMDLINE_V } // strv ( if Ctrlk, eu_CMDLINE_V )
2020 , { -1, -1, -1, PIDS_ENVIRON_V } // strv ( if CtrlN, eu_ENVIRON_V )
2021 , { -1, -1, -1, PIDS_extra } // s_ch ( if Show_FOREST, eu_TREE_HID )
2022 , { -1, -1, -1, PIDS_extra } // s_int ( if Show_FOREST, eu_TREE_LVL )
2023 , { -1, -1, -1, PIDS_extra } // s_int ( if Show_FOREST, eu_TREE_ADD )
2024 #undef A_left
2025 #undef A_right
2026 };
2027
2028
2029 /*
2030 * A calibrate_fields() *Helper* function which refreshes
2031 * all that cached screen geometry plus related variables */
2032 static void adj_geometry (void) {
2033 static size_t pseudo_max = 0;
2034 static int w_set = 0, w_cols = 0, w_rows = 0;
2035 struct winsize wz;
2036
2037 Screen_cols = columns; // <term.h>
2038 Screen_rows = lines; // <term.h>
2039
2040 if (-1 != ioctl(STDOUT_FILENO, TIOCGWINSZ, &wz)
2041 && 0 < wz.ws_col && 0 < wz.ws_row) {
2042 Screen_cols = wz.ws_col;
2043 Screen_rows = wz.ws_row;
2044 }
2045
2046 #ifndef RMAN_IGNORED
2047 // be crudely tolerant of crude tty emulators
2048 if (Cap_avoid_eol) Screen_cols--;
2049 #endif
2050
2051 // we might disappoint some folks (but they'll deserve it)
2052 if (Screen_cols > SCREENMAX) Screen_cols = SCREENMAX;
2053 if (Screen_cols < W_MIN_COL) Screen_cols = W_MIN_COL;
2054
2055 if (!w_set) {
2056 if (Width_mode > 0) // -w with arg, we'll try to honor
2057 w_cols = Width_mode;
2058 else
2059 if (Width_mode < 0) { // -w without arg, try environment
2060 char *env_columns = getenv("COLUMNS"),
2061 *env_lines = getenv("LINES"),
2062 *ep;
2063 if (env_columns && *env_columns) {
2064 long t, tc = 0;
2065 t = strtol(env_columns, &ep, 0);
2066 if (!*ep && (t > 0) && (t <= 0x7fffffffL)) tc = t;
2067 if (0 < tc) w_cols = (int)tc;
2068 }
2069 if (env_lines && *env_lines) {
2070 long t, tr = 0;
2071 t = strtol(env_lines, &ep, 0);
2072 if (!*ep && (t > 0) && (t <= 0x7fffffffL)) tr = t;
2073 if (0 < tr) w_rows = (int)tr;
2074 }
2075 if (!w_cols) w_cols = SCREENMAX;
2076 if (w_cols && w_cols < W_MIN_COL) w_cols = W_MIN_COL;
2077 if (w_rows && w_rows < W_MIN_ROW) w_rows = W_MIN_ROW;
2078 }
2079 if (w_cols > SCREENMAX) w_cols = SCREENMAX;
2080 w_set = 1;
2081 }
2082
2083 /* keep our support for output optimization in sync with current reality
2084 note: when we're in Batch mode, we don't really need a Pseudo_screen
2085 and when not Batch, our buffer will contain 1 extra 'line' since
2086 Msg_row is never represented -- but it's nice to have some space
2087 between us and the great-beyond... */
2088 if (Batch) {
2089 if (w_cols) Screen_cols = w_cols;
2090 Screen_rows = w_rows ? w_rows : INT_MAX;
2091 Pseudo_size = (sizeof(*Pseudo_screen) * ROWMAXSIZ);
2092 } else {
2093 const int max_rows = INT_MAX / (sizeof(*Pseudo_screen) * ROWMAXSIZ);
2094 if (w_cols && w_cols < Screen_cols) Screen_cols = w_cols;
2095 if (w_rows && w_rows < Screen_rows) Screen_rows = w_rows;
2096 if (Screen_rows < 0 || Screen_rows > max_rows) Screen_rows = max_rows;
2097 Pseudo_size = (sizeof(*Pseudo_screen) * ROWMAXSIZ) * Screen_rows;
2098 }
2099 // we'll only grow our Pseudo_screen, never shrink it
2100 if (pseudo_max < Pseudo_size) {
2101 pseudo_max = Pseudo_size;
2102 Pseudo_screen = alloc_r(Pseudo_screen, pseudo_max);
2103 }
2104 // ensure each row is repainted (just in case)
2105 PSU_CLREOS(0);
2106
2107 // prepare to customize potential cpu/memory graphs
2108 if (Curwin->rc.double_up) {
2109 int num = (Curwin->rc.double_up + 1);
2110 int pfx = (Curwin->rc.double_up < 2) ? GRAPH_prefix_std : GRAPH_prefix_abv;
2111
2112 Graph_cpus->length = (Screen_cols - (ADJOIN_space * Curwin->rc.double_up) - (num * (pfx + GRAPH_suffix))) / num;
2113 if (Graph_cpus->length > GRAPH_length_max) Graph_cpus->length = GRAPH_length_max;
2114 if (Graph_cpus->length < GRAPH_length_min) Graph_cpus->length = GRAPH_length_min;
2115
2116 #ifdef TOG4_MEM_1UP
2117 Graph_mems->length = (Screen_cols - (GRAPH_prefix_std + GRAPH_suffix));
2118 #else
2119 Graph_mems->length = (Screen_cols - ADJOIN_space - (2 * (pfx + GRAPH_suffix))) / 2;
2120 #endif
2121 if (Graph_mems->length > GRAPH_length_max) Graph_mems->length = GRAPH_length_max;
2122 if (Graph_mems->length < GRAPH_length_min) Graph_mems->length = GRAPH_length_min;
2123
2124 #if !defined(TOG4_MEM_FIX) && !defined(TOG4_MEM_1UP)
2125 if (num > 2) {
2126 #define cpuGRAPH ( GRAPH_prefix_abv + Graph_cpus->length + GRAPH_suffix )
2127 #define nxtGRAPH ( cpuGRAPH + ADJOIN_space )
2128 int len = cpuGRAPH;
2129 for (;;) {
2130 if (len + nxtGRAPH > GRAPH_length_max) break;
2131 len += nxtGRAPH;
2132 }
2133 len -= (GRAPH_prefix_abv + ADJOIN_space);
2134 Graph_mems->length = len;
2135 #undef cpuGRAPH
2136 #undef nxtGRAPH
2137 }
2138 #endif
2139 } else {
2140 Graph_cpus->length = Screen_cols - (GRAPH_prefix_std + GRAPH_length_max + GRAPH_suffix);
2141 if (Graph_cpus->length >= 0) Graph_cpus->length = GRAPH_length_max;
2142 else Graph_cpus->length = Screen_cols - GRAPH_prefix_std - GRAPH_suffix;
2143 if (Graph_cpus->length < GRAPH_length_min) Graph_cpus->length = GRAPH_length_min;
2144 #ifdef TOG4_MEM_1UP
2145 Graph_mems->length = (Screen_cols - (GRAPH_prefix_std + GRAPH_suffix));
2146 if (Graph_mems->length > GRAPH_length_max) Graph_mems->length = GRAPH_length_max;
2147 if (Graph_mems->length < GRAPH_length_min) Graph_mems->length = GRAPH_length_min;
2148 #else
2149 Graph_mems->length = Graph_cpus->length;
2150 #endif
2151 }
2152 Graph_cpus->adjust = (float)Graph_cpus->length / 100.0;
2153 Graph_cpus->style = Curwin->rc.graph_cpus;
2154
2155 Graph_mems->adjust = (float)Graph_mems->length / 100.0;
2156 Graph_mems->style = Curwin->rc.graph_mems;
2157
2158 fflush(stdout);
2159 Frames_signal = BREAK_off;
2160 } // end: adj_geometry
2161
2162
2163 /*
2164 * A calibrate_fields() *Helper* function to build the actual
2165 * column headers & ensure necessary item enumerators support */
2166 static void build_headers (void) {
2167 #define ckITEM(f) do { Pids_itms[f] = Fieldstab[f].item; } while (0)
2168 #define ckCMDS(w) do { if (CHKw(w, Show_CMDLIN)) ckITEM(eu_CMDLINE); } while (0)
2169 FLG_t f;
2170 char *s;
2171 WIN_t *w = Curwin;
2172 #ifdef EQUCOLHDRYES
2173 int x, hdrmax = 0;
2174 #endif
2175 int i;
2176
2177 // ensure fields not visible incur no significant library costs
2178 for (i = 0; i < eu_RESET; i++)
2179 Pids_itms[i] = PIDS_noop;
2180 for ( ; i < MAXTBL(Fieldstab); i++)
2181 Pids_itms[i] = PIDS_extra;
2182
2183 ckITEM(EU_PID); // these 2 fields may not display,
2184 ckITEM(EU_STA); // yet we'll always need them both
2185 ckITEM(EU_CMD); // this is used with 'Y' (inspect)
2186
2187 do {
2188 if (VIZISw(w)) {
2189 memset((s = w->columnhdr), 0, sizeof(w->columnhdr));
2190 if (Rc.mode_altscr) s = scat(s, fmtmk("%d", w->winnum));
2191
2192 for (i = 0; i < w->maxpflgs; i++) {
2193 f = w->procflgs[i];
2194 #ifdef USE_X_COLHDR
2195 if (CHKw(w, Show_HICOLS) && f == w->rc.sortindx) {
2196 s = scat(s, fmtmk("%s%s", Caps_off, w->capclr_msg));
2197 w->hdrcaplen += strlen(Caps_off) + strlen(w->capclr_msg);
2198 }
2199 #else
2200 if (EU_MAXPFLGS <= f) continue;
2201 #endif
2202 ckITEM(f);
2203 switch (f) {
2204 case EU_CMD:
2205 ckCMDS(w);
2206 break;
2207 case EU_CPU:
2208 // cpu calculations depend on number of threads
2209 ckITEM(EU_THD);
2210 break;
2211 case EU_TME:
2212 case EU_TM2:
2213 // for 'cumulative' times, we'll need equivalent of cutime & cstime
2214 if (CHKw(w, Show_CTIMES)) ckITEM(eu_TICS_ALL_C);
2215 break;
2216 default:
2217 break;
2218 }
2219 s = scat(s, utf8_justify(N_col(f)
2220 , VARcol(f) ? w->varcolsz : Fieldstab[f].width
2221 , CHKw(w, Fieldstab[f].align)));
2222 #ifdef USE_X_COLHDR
2223 if (CHKw(w, Show_HICOLS) && f == w->rc.sortindx) {
2224 s = scat(s, fmtmk("%s%s", Caps_off, w->capclr_hdr));
2225 w->hdrcaplen += strlen(Caps_off) + strlen(w->capclr_hdr);
2226 }
2227 #endif
2228 }
2229 #ifdef EQUCOLHDRYES
2230 // prepare to even out column header lengths...
2231 if (hdrmax + w->hdrcaplen < (x = strlen(w->columnhdr))) hdrmax = x - w->hdrcaplen;
2232 #endif
2233 // for 'busy' only processes, we'll need elapsed tics
2234 if (!CHKw(w, Show_IDLEPS)) ckITEM(EU_CPU);
2235 // with forest view mode, we'll need pid, tgid, ppid & start_time...
2236 #ifndef TREE_VCPUOFF
2237 if (CHKw(w, Show_FOREST)) { ckITEM(EU_PPD); ckITEM(EU_TGD); ckITEM(EU_TM3); ckITEM(eu_TREE_HID); ckITEM(eu_TREE_LVL); ckITEM(eu_TREE_ADD); }
2238 #else
2239 if (CHKw(w, Show_FOREST)) { ckITEM(EU_PPD); ckITEM(EU_TGD); ckITEM(EU_TM3); ckITEM(eu_TREE_HID); ckITEM(eu_TREE_LVL); }
2240 #endif
2241 // for 'u/U' filtering we need these too (old top forgot that, oops)
2242 if (w->usrseltyp) { ckITEM(EU_UED); ckITEM(EU_URD); ckITEM(EU_USD); ckITEM(eu_ID_FUID); }
2243
2244 // we must also accommodate an out of view sort field...
2245 f = w->rc.sortindx;
2246 if (EU_CMD == f) ckCMDS(w);
2247 else ckITEM(f);
2248
2249 // lastly, accommodate any special non-display 'tagged' needs...
2250 i = 0;
2251 while (Bot_item[i] > BOT_DELIMIT) {
2252 ckITEM(Bot_item[i]);
2253 ++i;
2254 }
2255 } // end: VIZISw(w)
2256
2257 if (Rc.mode_altscr) w = w->next;
2258 } while (w != Curwin);
2259
2260 #ifdef EQUCOLHDRYES
2261 /* now we can finally even out column header lengths
2262 (we're assuming entire columnhdr was memset to '\0') */
2263 if (Rc.mode_altscr && SCREENMAX > Screen_cols)
2264 for (i = 0; i < GROUPSMAX; i++) {
2265 w = &Winstk[i];
2266 if (CHKw(w, Show_TASKON))
2267 if (hdrmax + w->hdrcaplen > (x = strlen(w->columnhdr)))
2268 memset(&w->columnhdr[x], ' ', hdrmax + w->hdrcaplen - x);
2269 }
2270 #endif
2271
2272 #undef ckITEM
2273 #undef ckCMDS
2274 } // end: build_headers
2275
2276
2277 /*
2278 * This guy coordinates the activities surrounding the maintenance of
2279 * each visible window's columns headers plus item enumerators needed */
2280 static void calibrate_fields (void) {
2281 FLG_t f;
2282 char *s;
2283 const char *h;
2284 WIN_t *w = Curwin;
2285 int i, varcolcnt, len, rc;
2286
2287 adj_geometry();
2288
2289 do {
2290 if (VIZISw(w)) {
2291 w->hdrcaplen = 0; // really only used with USE_X_COLHDR
2292 // build window's pflgsall array, establish upper bounds for maxpflgs
2293 for (i = 0, w->totpflgs = 0; i < EU_MAXPFLGS; i++) {
2294 if (FLDviz(w, i)) {
2295 f = FLDget(w, i);
2296 #ifdef USE_X_COLHDR
2297 w->pflgsall[w->totpflgs++] = f;
2298 #else
2299 if (CHKw(w, Show_HICOLS) && f == w->rc.sortindx) {
2300 w->pflgsall[w->totpflgs++] = EU_XON;
2301 w->pflgsall[w->totpflgs++] = f;
2302 w->pflgsall[w->totpflgs++] = EU_XOF;
2303 } else
2304 w->pflgsall[w->totpflgs++] = f;
2305 #endif
2306 }
2307 }
2308 if (!w->totpflgs) w->pflgsall[w->totpflgs++] = EU_PID;
2309
2310 /* build a preliminary columns header not to exceed screen width
2311 while accounting for a possible leading window number */
2312 w->varcolsz = varcolcnt = 0;
2313 *(s = w->columnhdr) = '\0';
2314 if (Rc.mode_altscr) s = scat(s, " ");
2315 for (i = 0; i + w->begpflg < w->totpflgs; i++) {
2316 f = w->pflgsall[i + w->begpflg];
2317 w->procflgs[i] = f;
2318 #ifndef USE_X_COLHDR
2319 if (EU_MAXPFLGS <= f) continue;
2320 #endif
2321 h = N_col(f);
2322 len = (VARcol(f) ? (int)strlen(h) : Fieldstab[f].width) + COLPADSIZ;
2323 // oops, won't fit -- we're outta here...
2324 if (Screen_cols < ((int)(s - w->columnhdr) + len)) break;
2325 if (VARcol(f)) { ++varcolcnt; w->varcolsz += strlen(h); }
2326 s = scat(s, fmtmk("%*.*s", len, len, h));
2327 }
2328 #ifndef USE_X_COLHDR
2329 if (i >= 1 && EU_XON == w->procflgs[i - 1]) --i;
2330 #endif
2331
2332 /* establish the final maxpflgs and prepare to grow the variable column
2333 heading(s) via varcolsz - it may be a fib if their pflags weren't
2334 encountered, but that's ok because they won't be displayed anyway */
2335 w->maxpflgs = i;
2336 w->varcolsz += Screen_cols - strlen(w->columnhdr);
2337 if (varcolcnt) w->varcolsz /= varcolcnt;
2338
2339 /* establish the field where all remaining fields would still
2340 fit within screen width, including a leading window number */
2341 *(s = w->columnhdr) = '\0';
2342 if (Rc.mode_altscr) s = scat(s, " ");
2343 w->endpflg = 0;
2344 for (i = w->totpflgs - 1; -1 < i; i--) {
2345 f = w->pflgsall[i];
2346 #ifndef USE_X_COLHDR
2347 if (EU_MAXPFLGS <= f) { w->endpflg = i; continue; }
2348 #endif
2349 h = N_col(f);
2350 len = (VARcol(f) ? (int)strlen(h) : Fieldstab[f].width) + COLPADSIZ;
2351 if (Screen_cols < ((int)(s - w->columnhdr) + len)) break;
2352 s = scat(s, fmtmk("%*.*s", len, len, h));
2353 w->endpflg = i;
2354 }
2355 #ifndef USE_X_COLHDR
2356 if (EU_XOF == w->pflgsall[w->endpflg]) ++w->endpflg;
2357 #endif
2358 } // end: if (VIZISw(w))
2359
2360 if (Rc.mode_altscr) w = w->next;
2361 } while (w != Curwin);
2362
2363 build_headers();
2364
2365 if ((rc = procps_pids_reset(Pids_ctx, Pids_itms, Pids_itms_tot)))
2366 error_exit(fmtmk(N_fmt(LIB_errorpid_fmt), __LINE__, strerror(-rc)));
2367 } // end: calibrate_fields
2368
2369
2370 /*
2371 * Display each field represented in the current window's fieldscur
2372 * array along with its description. Mark with bold and a leading
2373 * asterisk those fields associated with the "on" or "active" state.
2374 *
2375 * Special highlighting will be accorded the "focus" field with such
2376 * highlighting potentially extended to include the description.
2377 *
2378 * Below is the current Fieldstab space requirement and how
2379 * we apportion it. The xSUFX is considered sacrificial,
2380 * something we can reduce or do without.
2381 * 0 1 2 3
2382 * 12345678901234567890123456789012
2383 * * HEADING = Longest Description!
2384 * xPRFX ----------______________________ xSUFX
2385 * ( xPRFX has pos 2 & 10 for 'extending' when at minimums )
2386 *
2387 * The first 4 screen rows are reserved for explanatory text, and
2388 * the maximum number of columns is Screen_cols / xPRFX + 1 space
2389 * between columns. Thus, for example, with 42 fields a tty will
2390 * still remain usable under these extremes:
2391 * rows columns what's
2392 * tty top tty top displayed
2393 * --- --- --- --- ------------------
2394 * 46 42 10 1 xPRFX only
2395 * 46 42 32 1 full xPRFX + xSUFX
2396 * 6 2 231 21 xPRFX only
2397 * 10 6 231 7 full xPRFX + xSUFX
2398 */
2399 static void display_fields (int focus, int extend) {
2400 #define mkERR { putp("\n"); putp(N_txt(XTRA_winsize_txt)); return; }
2401 #define mxCOL ( (Screen_cols / 11) > 0 ? (Screen_cols / 11) : 1 )
2402 #define yRSVD 4
2403 #define xEQUS 2 // length of suffix beginning '= '
2404 #define xSUFX 22 // total suffix length, incl xEQUS
2405 #define xPRFX (10 + xadd)
2406 #define xTOTL (xPRFX + xSUFX)
2407 static int col_sav, row_sav;
2408 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
2409 int i; // utility int (a row, tot cols, ix)
2410 int smax; // printable width of xSUFX
2411 int xadd = 0; // spacing between data columns
2412 int cmax = Screen_cols; // total data column width
2413 int rmax = Screen_rows - yRSVD; // total usable rows
2414
2415 i = (EU_MAXPFLGS % mxCOL) ? 1 : 0;
2416 if (rmax < i + (EU_MAXPFLGS / mxCOL)) mkERR;
2417 i = EU_MAXPFLGS / rmax;
2418 if (EU_MAXPFLGS % rmax) ++i;
2419 if (i > 1) { cmax /= i; xadd = 1; }
2420 if (cmax > xTOTL) cmax = xTOTL;
2421 smax = cmax - xPRFX;
2422 if (smax < 0) mkERR;
2423
2424 /* we'll go the extra distance to avoid any potential screen flicker
2425 which occurs under some terminal emulators (but it was our fault) */
2426 if (col_sav != Screen_cols || row_sav != Screen_rows) {
2427 col_sav = Screen_cols;
2428 row_sav = Screen_rows;
2429 putp(Cap_clr_eos);
2430 }
2431 fflush(stdout);
2432
2433 for (i = 0; i < EU_MAXPFLGS; ++i) {
2434 int b = FLDviz(w, i), x = (i / rmax) * cmax, y = (i % rmax) + yRSVD;
2435 const char *e = (i == focus && extend) ? w->capclr_hdr : "";
2436 FLG_t f = FLDget(w, i);
2437 char sbuf[xSUFX*4]; // 4 = max multi-byte
2438 int xcol, xfld;
2439
2440 /* prep sacrificial suffix (allowing for beginning '= ')
2441 note: width passed to 'utf8_embody' may go negative, but he'll be just fine */
2442 snprintf(sbuf, sizeof(sbuf), "= %.*s", utf8_embody(N_fld(f), smax - xEQUS), N_fld(f));
2443 // obtain translated deltas (if any) ...
2444 xcol = utf8_delta(fmtmk("%.*s", utf8_embody(N_col(f), 8), N_col(f)));
2445 xfld = utf8_delta(sbuf + xEQUS); // ignore beginning '= '
2446
2447 PUTT("%s%c%s%s %s%-*.*s%s%s%s %-*.*s%s"
2448 , tg2(x, y)
2449 , b ? '*' : ' '
2450 , b ? w->cap_bold : Cap_norm
2451 , e
2452 , i == focus ? w->capclr_hdr : ""
2453 , 8 + xcol, 8 + xcol
2454 , N_col(f)
2455 , Cap_norm
2456 , b ? w->cap_bold : ""
2457 , e
2458 , smax + xfld, smax + xfld
2459 , sbuf
2460 , Cap_norm);
2461 }
2462
2463 putp(Caps_off);
2464 #undef mkERR
2465 #undef mxCOL
2466 #undef yRSVD
2467 #undef xEQUS
2468 #undef xSUFX
2469 #undef xPRFX
2470 #undef xTOTL
2471 } // end: display_fields
2472
2473
2474 /*
2475 * Manage all fields aspects (order/toggle/sort), for all windows. */
2476 static void fields_utility (void) {
2477 #ifndef SCROLLVAR_NO
2478 #define unSCRL { w->begpflg = w->varcolbeg = 0; OFFw(w, Show_HICOLS); }
2479 #else
2480 #define unSCRL { w->begpflg = 0; OFFw(w, Show_HICOLS); }
2481 #endif
2482 #define swapEM { int c; unSCRL; c = w->rc.fieldscur[i]; \
2483 w->rc.fieldscur[i] = *p; *p = c; p = &w->rc.fieldscur[i]; }
2484 #define spewFI { int *t; f = w->rc.sortindx; t = msch(w->rc.fieldscur, ENUcvt(f, FLDon), EU_MAXPFLGS); \
2485 if (!t) t = msch(w->rc.fieldscur, ENUcvt(f, FLDoff), EU_MAXPFLGS); \
2486 i = (t) ? (int)(t - w->rc.fieldscur) : 0; }
2487 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
2488 const char *h = NULL;
2489 int *p = NULL;
2490 int i, key;
2491 FLG_t f;
2492
2493 spewFI
2494 signify_that:
2495 putp(Cap_clr_scr);
2496 adj_geometry();
2497
2498 do {
2499 if (!h) h = N_col(f);
2500 putp(Cap_home);
2501 show_special(1, fmtmk(N_unq(FIELD_header_fmt)
2502 , w->grpname, CHKw(w, Show_FOREST) ? N_txt(FOREST_views_txt) : h));
2503 display_fields(i, (p != NULL));
2504 fflush(stdout);
2505
2506 if (Frames_signal) goto signify_that;
2507 key = iokey(IOKEY_ONCE);
2508 if (key < 1) goto signify_that;
2509
2510 switch (key) {
2511 case kbd_UP:
2512 if (i > 0) { --i; if (p) swapEM }
2513 break;
2514 case kbd_DOWN:
2515 if (i + 1 < EU_MAXPFLGS) { ++i; if (p) swapEM }
2516 break;
2517 case kbd_LEFT:
2518 case kbd_ENTER:
2519 p = NULL;
2520 break;
2521 case kbd_RIGHT:
2522 p = &w->rc.fieldscur[i];
2523 break;
2524 case kbd_HOME:
2525 case kbd_PGUP:
2526 if (!p) i = 0;
2527 break;
2528 case kbd_END:
2529 case kbd_PGDN:
2530 if (!p) i = EU_MAXPFLGS - 1;
2531 break;
2532 case kbd_SPACE:
2533 case 'd':
2534 if (!p) { FLDtog(w, i); unSCRL }
2535 break;
2536 case 's':
2537 #ifdef TREE_NORESET
2538 if (!p && !CHKw(w, Show_FOREST)) { w->rc.sortindx = f = FLDget(w, i); h = NULL; unSCRL }
2539 #else
2540 if (!p) { w->rc.sortindx = f = FLDget(w, i); h = NULL; unSCRL; OFFw(w, Show_FOREST); }
2541 #endif
2542 break;
2543 case 'a':
2544 case 'w':
2545 Curwin = w = ('a' == key) ? w->next : w->prev;
2546 spewFI
2547 h = NULL;
2548 p = NULL;
2549 break;
2550 default: // keep gcc happy
2551 break;
2552 }
2553 } while (key != 'q' && key != kbd_ESC);
2554
2555 // signal that we just corrupted entire screen
2556 Frames_signal = BREAK_screen;
2557 #undef unSCRL
2558 #undef swapEM
2559 #undef spewFI
2560 } // end: fields_utility
2561
2562
2563 /*
2564 * This routine takes care of auto sizing field widths
2565 * if/when the user sets Rc.fixed_widest to -1. Along the
2566 * way he reinitializes some things for the next frame. */
2567 static inline void widths_resize (void) {
2568 int i;
2569
2570 // next var may also be set by the guys that actually truncate stuff
2571 Autox_found = 0;
2572 for (i = 0; i < EU_MAXPFLGS; i++) {
2573 if (Autox_array[i]) {
2574 Fieldstab[i].width++;
2575 Autox_array[i] = 0;
2576 Autox_found = 1;
2577 }
2578 }
2579 // trigger a call to calibrate_fields (via zap_fieldstab)
2580 if (Autox_found) Frames_signal = BREAK_autox;
2581 } // end: widths_resize
2582
2583
2584 /*
2585 * This routine exists just to consolidate most of the messin'
2586 * around with the Fieldstab array and some related stuff. */
2587 static void zap_fieldstab (void) {
2588 #ifdef WIDEN_COLUMN
2589 #define maX(E) ( (wtab[E].wnls > wtab[E].wmin) \
2590 ? wtab[E].wnls : wtab[E].wmin )
2591 static struct {
2592 int wmin; // minimum field width (-1 == variable width)
2593 int wnls; // translated header column requirements
2594 int watx; // +1 == non-scalable auto sized columns
2595 } wtab[EU_MAXPFLGS];
2596 #endif
2597 static int once;
2598 int i, digits;
2599 char buf[8];
2600
2601 if (!once) {
2602 Fieldstab[EU_CPN].width = 1;
2603 Fieldstab[EU_NMA].width = 2;
2604 Fieldstab[EU_PID].width = Fieldstab[EU_PPD].width
2605 = Fieldstab[EU_PGD].width = Fieldstab[EU_SID].width
2606 = Fieldstab[EU_TGD].width = Fieldstab[EU_TPG].width = 5;
2607 if (5 < (digits = (int)procps_pid_length())) {
2608 if (10 < digits) error_exit(N_txt(FAIL_widepid_txt));
2609 Fieldstab[EU_PID].width = Fieldstab[EU_PPD].width
2610 = Fieldstab[EU_PGD].width = Fieldstab[EU_SID].width
2611 = Fieldstab[EU_TGD].width = Fieldstab[EU_TPG].width = digits;
2612 }
2613 #ifdef WIDEN_COLUMN
2614 // identify our non-scalable auto sized columns
2615 wtab[EU_UED].watx = wtab[EU_UEN].watx = wtab[EU_URD].watx
2616 = wtab[EU_URN].watx = wtab[EU_USD].watx = wtab[EU_USN].watx
2617 = wtab[EU_GID].watx = wtab[EU_GRP].watx = wtab[EU_TTY].watx
2618 = wtab[EU_WCH].watx = wtab[EU_NS1].watx = wtab[EU_NS2].watx
2619 = wtab[EU_NS3].watx = wtab[EU_NS4].watx = wtab[EU_NS5].watx
2620 = wtab[EU_NS6].watx = wtab[EU_NS7].watx = wtab[EU_NS8].watx
2621 = wtab[EU_LXC].watx = wtab[EU_LID].watx
2622 = +1;
2623 /* establish translatable header 'column' requirements
2624 and ensure .width reflects the widest value */
2625 for (i = 0; i < EU_MAXPFLGS; i++) {
2626 wtab[i].wmin = Fieldstab[i].width;
2627 wtab[i].wnls = (int)strlen(N_col(i)) - utf8_delta(N_col(i));
2628 if (wtab[i].wmin != -1)
2629 Fieldstab[i].width = maX(i);
2630 }
2631 #endif
2632 once = 1;
2633 }
2634
2635 Cpu_pmax = 99.9;
2636 if (Rc.mode_irixps && Cpu_cnt > 1 && !Thread_mode) {
2637 Cpu_pmax = 100.0 * Cpu_cnt;
2638 if (Cpu_cnt > 1000) {
2639 if (Cpu_pmax > 9999999.0) Cpu_pmax = 9999999.0;
2640 } else if (Cpu_cnt > 100) {
2641 if (Cpu_cnt > 999999.0) Cpu_pmax = 999999.0;
2642 } else if (Cpu_cnt > 10) {
2643 if (Cpu_pmax > 99999.0) Cpu_pmax = 99999.0;
2644 } else {
2645 if (Cpu_pmax > 999.9) Cpu_pmax = 999.9;
2646 }
2647 }
2648
2649 #ifdef WIDEN_COLUMN
2650 digits = snprintf(buf, sizeof(buf), "%d", Cpu_cnt);
2651 if (wtab[EU_CPN].wmin < digits) {
2652 if (5 < digits) error_exit(N_txt(FAIL_widecpu_txt));
2653 wtab[EU_CPN].wmin = digits;
2654 Fieldstab[EU_CPN].width = maX(EU_CPN);
2655 }
2656 digits = snprintf(buf, sizeof(buf), "%d", Numa_node_tot);
2657 if (wtab[EU_NMA].wmin < digits) {
2658 wtab[EU_NMA].wmin = digits;
2659 Fieldstab[EU_NMA].width = maX(EU_NMA);
2660 }
2661
2662 // and accommodate optional wider non-scalable columns (maybe)
2663 if (!AUTOX_MODE) {
2664 for (i = 0; i < EU_MAXPFLGS; i++) {
2665 if (wtab[i].watx)
2666 Fieldstab[i].width = Rc.fixed_widest ? Rc.fixed_widest + maX(i) : maX(i);
2667 }
2668 }
2669 #else
2670 digits = snprintf(buf, sizeof(buf), "%d", Cpu_cnt);
2671 if (1 < digits) {
2672 if (5 < digits) error_exit(N_txt(FAIL_widecpu_txt));
2673 Fieldstab[EU_CPN].width = digits;
2674 }
2675 digits = snprintf(buf, sizeof(buf), "%d", Numa_node_tot);
2676 if (2 < digits)
2677 Fieldstab[EU_NMA].width = digits;
2678
2679 // and accommodate optional wider non-scalable columns (maybe)
2680 if (!AUTOX_MODE) {
2681 Fieldstab[EU_UED].width = Fieldstab[EU_URD].width
2682 = Fieldstab[EU_USD].width = Fieldstab[EU_GID].width
2683 = Rc.fixed_widest ? 5 + Rc.fixed_widest : 5;
2684 Fieldstab[EU_UEN].width = Fieldstab[EU_URN].width
2685 = Fieldstab[EU_USN].width = Fieldstab[EU_GRP].width
2686 = Rc.fixed_widest ? 8 + Rc.fixed_widest : 8;
2687 Fieldstab[EU_TTY].width = Fieldstab[EU_LXC].width
2688 = Rc.fixed_widest ? 8 + Rc.fixed_widest : 8;
2689 Fieldstab[EU_WCH].width
2690 = Rc.fixed_widest ? 10 + Rc.fixed_widest : 10;
2691 // the initial namespace fields
2692 for (i = EU_NS1; i <= EU_NS6; i++)
2693 Fieldstab[i].width
2694 = Rc.fixed_widest ? 10 + Rc.fixed_widest : 10;
2695 // the later namespace additions
2696 for (i = EU_NS7; i <= EU_NS8; i++)
2697 Fieldstab[i].width
2698 = Rc.fixed_widest ? 10 + Rc.fixed_widest : 10;
2699 }
2700 #endif
2701
2702 /* plus user selectable scaling */
2703 Fieldstab[EU_VRT].scale = Fieldstab[EU_SWP].scale
2704 = Fieldstab[EU_RES].scale = Fieldstab[EU_COD].scale
2705 = Fieldstab[EU_DAT].scale = Fieldstab[EU_SHR].scale
2706 = Fieldstab[EU_USE].scale = Fieldstab[EU_RZA].scale
2707 = Fieldstab[EU_RZF].scale = Fieldstab[EU_RZL].scale
2708 = Fieldstab[EU_RZS].scale = Fieldstab[EU_RSS].scale
2709 = Fieldstab[EU_PSS].scale = Fieldstab[EU_PZA].scale
2710 = Fieldstab[EU_PZF].scale = Fieldstab[EU_PZS].scale
2711 = Fieldstab[EU_USS].scale = Rc.task_mscale;
2712
2713 // lastly, ensure we've got proper column headers...
2714 calibrate_fields();
2715 #undef maX
2716 } // end: zap_fieldstab
2717
2718 /*###### Library Interface (as separate threads) #######################*/
2719
2720 /*
2721 * This guy's responsible for interfacing with the library <stat> API
2722 * and reaping all cpu or numa node tics.
2723 * ( his task is now embarassingly small under the new api ) */
2724 static void *cpus_refresh (void *unused) {
2725 enum stat_reap_type which;
2726
2727 do {
2728 #ifdef THREADED_CPU
2729 sem_wait(&Semaphore_cpus_beg);
2730 #endif
2731 which = STAT_REAP_CPUS_ONLY;
2732 if (CHKw(Curwin, View_CPUNOD))
2733 which = STAT_REAP_NUMA_NODES_TOO;
2734
2735 Stat_reap = procps_stat_reap(Stat_ctx, which, Stat_items, MAXTBL(Stat_items));
2736 if (!Stat_reap)
2737 error_exit(fmtmk(N_fmt(LIB_errorcpu_fmt), __LINE__, strerror(errno)));
2738 #ifndef PRETEND0NUMA
2739 // adapt to changes in total numa nodes (assuming it's even possible)
2740 if (Stat_reap->numa->total && Stat_reap->numa->total != Numa_node_tot) {
2741 Numa_node_tot = Stat_reap->numa->total;
2742 Numa_node_sel = -1;
2743 }
2744 #endif
2745 if (Stat_reap->cpus->total && Stat_reap->cpus->total != Cpu_cnt) {
2746 Cpu_cnt = Stat_reap->cpus->total;
2747 #ifdef PRETEND48CPU
2748 Cpu_cnt = 48;
2749 #endif
2750 }
2751 #ifdef PRETENDECORE
2752 { int i, x;
2753 x = Cpu_cnt - (Cpu_cnt / 4);
2754 for (i = 0; i < Cpu_cnt; i++)
2755 Stat_reap->cpus->stacks[i]->head[stat_COR_TYP].result.s_int = (i < x) ? P_CORE : E_CORE;
2756 }
2757 #endif
2758 #ifdef THREADED_CPU
2759 sem_post(&Semaphore_cpus_end);
2760 } while (1);
2761 #else
2762 } while (0);
2763 #endif
2764 return NULL;
2765 (void)unused;
2766 } // end: cpus_refresh
2767
2768
2769 /*
2770 * This serves as our interface to the memory portion of libprocps.
2771 * The sampling frequency is reduced in order to minimize overhead. */
2772 static void *memory_refresh (void *unused) {
2773 static time_t sav_secs;
2774 time_t cur_secs;
2775
2776 do {
2777 #ifdef THREADED_MEM
2778 sem_wait(&Semaphore_memory_beg);
2779 #endif
2780 if (Frames_signal)
2781 sav_secs = 0;
2782 cur_secs = time(NULL);
2783
2784 if (3 <= cur_secs - sav_secs) {
2785 if (!(Mem_stack = procps_meminfo_select(Mem_ctx, Mem_items, MAXTBL(Mem_items))))
2786 error_exit(fmtmk(N_fmt(LIB_errormem_fmt), __LINE__, strerror(errno)));
2787 sav_secs = cur_secs;
2788 }
2789 #ifdef THREADED_MEM
2790 sem_post(&Semaphore_memory_end);
2791 } while (1);
2792 #else
2793 } while (0);
2794 #endif
2795 return NULL;
2796 (void)unused;
2797 } // end: memory_refresh
2798
2799
2800 /*
2801 * This guy's responsible for interfacing with the library <pids> API
2802 * then refreshing the WIN_t ptr arrays, growing them as appropirate. */
2803 static void *tasks_refresh (void *unused) {
2804 #define nALIGN(n,m) (((n + m - 1) / m) * m) // unconditionally align
2805 #define nALGN2(n,m) ((n + m - 1) & ~(m - 1)) // with power of 2 align
2806 #define n_reap Pids_reap->counts->total
2807 static double uptime_sav;
2808 static int n_alloc = -1; // size of windows stacks arrays
2809 double uptime_cur;
2810 float et;
2811 int i, what;
2812
2813 do {
2814 #ifdef THREADED_TSK
2815 sem_wait(&Semaphore_tasks_beg);
2816 #endif
2817 procps_uptime(&uptime_cur, NULL);
2818 et = uptime_cur - uptime_sav;
2819 if (et < 0.01) et = 0.005;
2820 uptime_sav = uptime_cur;
2821 // if in Solaris mode, adjust our scaling for all cpus
2822 Frame_etscale = 100.0f / ((float)Hertz * (float)et * (Rc.mode_irixps ? 1 : Cpu_cnt));
2823
2824 what = Thread_mode ? PIDS_FETCH_THREADS_TOO : PIDS_FETCH_TASKS_ONLY;
2825 if (Monpidsidx) {
2826 what |= PIDS_SELECT_PID;
2827 Pids_reap = procps_pids_select(Pids_ctx, (unsigned *)Monpids, Monpidsidx, what);
2828 } else
2829 Pids_reap = procps_pids_reap(Pids_ctx, what);
2830 if (!Pids_reap)
2831 error_exit(fmtmk(N_fmt(LIB_errorpid_fmt), __LINE__, strerror(errno)));
2832
2833 // now refresh each window's stacks pointer array...
2834 if (n_alloc < n_reap) {
2835 // n_alloc = nALIGN(n_reap, 100);
2836 n_alloc = nALGN2(n_reap, 128);
2837 for (i = 0; i < GROUPSMAX; i++) {
2838 Winstk[i].ppt = alloc_r(Winstk[i].ppt, sizeof(void *) * n_alloc);
2839 memcpy(Winstk[i].ppt, Pids_reap->stacks, sizeof(void *) * PIDSmaxt);
2840 }
2841 } else {
2842 for (i = 0; i < GROUPSMAX; i++)
2843 memcpy(Winstk[i].ppt, Pids_reap->stacks, sizeof(void *) * PIDSmaxt);
2844 }
2845 #ifdef THREADED_TSK
2846 sem_post(&Semaphore_tasks_end);
2847 } while (1);
2848 #else
2849 } while (0);
2850 #endif
2851 return NULL;
2852 (void)unused;
2853 #undef nALIGN
2854 #undef nALGN2
2855 #undef n_reap
2856 } // end: tasks_refresh
2857
2858 /*###### Inspect Other Output ##########################################*/
2859
2860 /*
2861 * HOWTO Extend the top 'inspect' functionality:
2862 *
2863 * To exploit the 'Y' interactive command, one must add entries to
2864 * the top personal configuration file. Such entries simply reflect
2865 * a file to be read or command/pipeline to be executed whose results
2866 * will then be displayed in a separate scrollable window.
2867 *
2868 * Entries beginning with a '#' character are ignored, regardless of
2869 * content. Otherwise they consist of the following 3 elements, each
2870 * of which must be separated by a tab character (thus 2 '\t' total):
2871 * type: literal 'file' or 'pipe'
2872 * name: selection shown on the Inspect screen
2873 * fmts: string representing a path or command
2874 *
2875 * The two types of Inspect entries are not interchangeable.
2876 * Those designated 'file' will be accessed using fopen/fread and must
2877 * reference a single file in the 'fmts' element. Entries specifying
2878 * 'pipe' will employ popen/fread, their 'fmts' element could contain
2879 * many pipelined commands and, none can be interactive.
2880 *
2881 * Here are some examples of both types of inspection entries.
2882 * The first entry will be ignored due to the initial '#' character.
2883 * For clarity, the pseudo tab depictions (^I) are surrounded by an
2884 * extra space but the actual tabs would not be.
2885 *
2886 * # pipe ^I Sockets ^I lsof -n -P -i 2>&1
2887 * pipe ^I Open Files ^I lsof -P -p %d 2>&1
2888 * file ^I NUMA Info ^I /proc/%d/numa_maps
2889 * pipe ^I Log ^I tail -n100 /var/log/syslog | sort -Mr
2890 *
2891 * Caution: If the output contains unprintable characters they will
2892 * be displayed in either the ^I notation or hexadecimal <FF> form.
2893 * This applies to tab characters as well. So if one wants a more
2894 * accurate display, any tabs should be expanded within the 'fmts'.
2895 *
2896 * The following example takes what could have been a 'file' entry
2897 * but employs a 'pipe' instead so as to expand the tabs.
2898 *
2899 * # next would have contained '\t' ...
2900 * # file ^I <your_name> ^I /proc/%d/status
2901 * # but this will eliminate embedded '\t' ...
2902 * pipe ^I <your_name> ^I cat /proc/%d/status | expand -
2903 *
2904 * Note: If a pipe such as the following was established, one must
2905 * use Ctrl-C to terminate that pipe in order to review the results.
2906 * This is the single occasion where a '^C' will not terminate top.
2907 *
2908 * pipe ^I Trace ^I /usr/bin/strace -p %d 2>&1
2909 */
2910
2911 /*
2912 * Our driving table support, the basis for generalized inspection,
2913 * built at startup (if at all) from rcfile or demo entries. */
2914 struct I_ent {
2915 void (*func)(char *, int); // a pointer to file/pipe/demo function
2916 char *type; // the type of entry ('file' or 'pipe')
2917 char *name; // the selection label for display
2918 char *fmts; // format string to build path or command
2919 int farg; // 1 = '%d' in fmts, 0 = not (future use)
2920 const char *caps; // not really caps, show_special() delim's
2921 char *fstr; // entry's current/active search string
2922 int flen; // above's strlen, without call overhead
2923 };
2924 struct I_struc {
2925 int demo; // do NOT save table entries in rcfile
2926 int total; // total I_ent table entries
2927 char *raw; // all entries for 'W', incl '#' & blank
2928 struct I_ent *tab;
2929 };
2930 static struct I_struc Inspect;
2931
2932 static char **Insp_p; // pointers to each line start
2933 static int Insp_nl; // total lines, total Insp_p entries
2934 static int Insp_utf8; // treat Insp_buf as translatable, else raw
2935 static char *Insp_buf; // the results from insp_do_file/pipe
2936 static size_t Insp_bufsz; // allocated size of Insp_buf
2937 static size_t Insp_bufrd; // bytes actually in Insp_buf
2938 static struct I_ent *Insp_sel; // currently selected Inspect entry
2939
2940 // Our 'make status line' macro
2941 #define INSP_MKSL(big,txt) { int _sz = big ? Screen_cols : 80; \
2942 const char *_p; \
2943 _sz += utf8_delta(txt); \
2944 _p = fmtmk("%-*.*s", _sz, _sz, txt); \
2945 PUTT("%s%s%.*s%s", tg2(0, (Msg_row = 3)), Curwin->capclr_hdr \
2946 , utf8_embody(_p, Screen_cols), _p, Cap_clr_eol); \
2947 putp(Caps_off); fflush(stdout); }
2948
2949 // Our 'row length' macro, equivalent to a strlen() call
2950 #define INSP_RLEN(idx) (int)(Insp_p[idx +1] - Insp_p[idx] -1)
2951
2952 // Our 'busy/working' macro
2953 #define INSP_BUSY(enu) { INSP_MKSL(0, N_txt(enu)) }
2954
2955
2956 /*
2957 * Establish the number of lines present in the Insp_buf glob plus
2958 * build the all important row start array. It is that array that
2959 * others will rely on since we dare not try to use strlen() on what
2960 * is potentially raw binary data. Who knows what some user might
2961 * name as a file or include in a pipeline (scary, ain't it?). */
2962 static void insp_cnt_nl (void) {
2963 char *beg = Insp_buf;
2964 char *cur = Insp_buf;
2965 char *end = Insp_buf + Insp_bufrd + 1;
2966
2967 #ifdef INSP_SAVEBUF
2968 {
2969 static int n = 1;
2970 char fn[SMLBUFSIZ];
2971 FILE *fd;
2972 snprintf(fn, sizeof(fn), "%s.Insp_buf.%02d.txt", Myname, n++);
2973 fd = fopen(fn, "w");
2974 if (fd) {
2975 fwrite(Insp_buf, 1, Insp_bufrd, fd);
2976 fclose(fd);
2977 }
2978 }
2979 #endif
2980 Insp_p = alloc_c(sizeof(char *) * 2);
2981
2982 for (Insp_nl = 0; beg < end; beg++) {
2983 if (*beg == '\n') {
2984 Insp_p[Insp_nl++] = cur;
2985 // keep our array ahead of next potential need (plus the 2 above)
2986 Insp_p = alloc_r(Insp_p, (sizeof(char *) * (Insp_nl +3)));
2987 cur = beg +1;
2988 }
2989 }
2990 Insp_p[0] = Insp_buf;
2991 Insp_p[Insp_nl++] = cur;
2992 Insp_p[Insp_nl] = end;
2993 if ((end - cur) == 1) // if there's an eof null delimiter,
2994 --Insp_nl; // don't count it as a new line
2995 } // end: insp_cnt_nl
2996
2997
2998 #ifndef INSP_OFFDEMO
2999 /*
3000 * The pseudo output DEMO utility. */
3001 static void insp_do_demo (char *fmts, int pid) {
3002 (void)fmts; (void)pid;
3003 /* next will put us on a par with the real file/pipe read buffers
3004 ( and also avoid a harmless, but evil sounding, valgrind warning ) */
3005 Insp_bufsz = READMINSZ + strlen(N_txt(YINSP_dstory_txt));
3006 Insp_buf = alloc_c(Insp_bufsz);
3007 Insp_bufrd = snprintf(Insp_buf, Insp_bufsz, "%s", N_txt(YINSP_dstory_txt));
3008 insp_cnt_nl();
3009 } // end: insp_do_demo
3010 #endif
3011
3012
3013 /*
3014 * The generalized FILE utility. */
3015 static void insp_do_file (char *fmts, int pid) {
3016 char buf[LRGBUFSIZ];
3017 FILE *fp;
3018 int rc;
3019
3020 snprintf(buf, sizeof(buf), fmts, pid);
3021 fp = fopen(buf, "r");
3022 rc = readfile(fp, &Insp_buf, &Insp_bufsz, &Insp_bufrd);
3023 if (fp) fclose(fp);
3024 if (rc) Insp_bufrd = snprintf(Insp_buf, Insp_bufsz, "%s"
3025 , fmtmk(N_fmt(YINSP_failed_fmt), strerror(errno)));
3026 insp_cnt_nl();
3027 } // end: insp_do_file
3028
3029
3030 /*
3031 * The generalized PIPE utility. */
3032 static void insp_do_pipe (char *fmts, int pid) {
3033 char buf[LRGBUFSIZ];
3034 struct sigaction sa;
3035 FILE *fp;
3036 int rc;
3037
3038 memset(&sa, 0, sizeof(sa));
3039 sigemptyset(&sa.sa_mask);
3040 sa.sa_handler = SIG_IGN;
3041 sigaction(SIGINT, &sa, NULL);
3042
3043 snprintf(buf, sizeof(buf), fmts, pid);
3044 fp = popen(buf, "r");
3045 rc = readfile(fp, &Insp_buf, &Insp_bufsz, &Insp_bufrd);
3046 if (fp) pclose(fp);
3047 if (rc) Insp_bufrd = snprintf(Insp_buf, Insp_bufsz, "%s"
3048 , fmtmk(N_fmt(YINSP_failed_fmt), strerror(errno)));
3049 insp_cnt_nl();
3050
3051 sa.sa_handler = sig_endpgm;
3052 sigaction(SIGINT, &sa, NULL);
3053 } // end: insp_do_pipe
3054
3055
3056 /*
3057 * This guy is a *Helper* function serving the following two masters:
3058 * insp_find_str() - find the next Insp_sel->fstr match
3059 * insp_mkrow_... - highlight any Insp_sel->fstr matches in-view
3060 * If Insp_sel->fstr is found in the designated row, he returns the
3061 * offset from the start of the row, otherwise he returns a huge
3062 * integer so traditional fencepost usage can be employed. */
3063 static inline int insp_find_ofs (int col, int row) {
3064 #define begFS (int)(fnd - Insp_p[row])
3065 char *p, *fnd = NULL;
3066
3067 if (Insp_sel->fstr[0]) {
3068 // skip this row, if there's no chance of a match
3069 if (memchr(Insp_p[row], Insp_sel->fstr[0], INSP_RLEN(row))) {
3070 for ( ; col < INSP_RLEN(row); col++) {
3071 if (!*(p = Insp_p[row] + col)) // skip any empty strings
3072 continue;
3073 fnd = STRSTR(p, Insp_sel->fstr); // with binary data, each
3074 if (fnd) // row may have '\0'. so
3075 break; // our scans must be done
3076 col += strlen(p); // as individual strings.
3077 }
3078 if (fnd && fnd < Insp_p[row + 1]) // and, we must watch out
3079 return begFS; // for potential overrun!
3080 }
3081 }
3082 return INT_MAX;
3083 #undef begFS
3084 } // end: insp_find_ofs
3085
3086
3087 /*
3088 * This guy supports the inspect 'L' and '&' search provisions
3089 * and returns the row and *optimal* column for viewing any match
3090 * ( we'll always opt for left column justification since any )
3091 * ( preceding ctrl chars appropriate an unpredictable amount ) */
3092 static void insp_find_str (int ch, int *col, int *row) {
3093 #define reDUX (found) ? N_txt(WORD_another_txt) : ""
3094 static int found;
3095
3096 if ((ch == '&' || ch == 'n') && !Insp_sel->fstr[0]) {
3097 show_msg(N_txt(FIND_no_next_txt));
3098 return;
3099 }
3100 if (ch == 'L' || ch == '/') {
3101 char *str = ioline(N_txt(GET_find_str_txt));
3102 if (*str == kbd_ESC) return;
3103 snprintf(Insp_sel->fstr, FNDBUFSIZ, "%s", str);
3104 Insp_sel->flen = strlen(Insp_sel->fstr);
3105 found = 0;
3106 }
3107 if (Insp_sel->fstr[0]) {
3108 int xx, yy;
3109
3110 INSP_BUSY(YINSP_waitin_txt);
3111 for (xx = *col, yy = *row; yy < Insp_nl; ) {
3112 xx = insp_find_ofs(xx, yy);
3113 if (xx < INSP_RLEN(yy)) {
3114 found = 1;
3115 if (xx == *col && yy == *row) { // matched where we were!
3116 ++xx; // ( was the user maybe )
3117 continue; // ( trying to fool us? )
3118 }
3119 *col = xx;
3120 *row = yy;
3121 return;
3122 }
3123 xx = 0;
3124 ++yy;
3125 }
3126 show_msg(fmtmk(N_fmt(FIND_no_find_fmt), reDUX, Insp_sel->fstr));
3127 }
3128 #undef reDUX
3129 } // end: insp_find_str
3130
3131
3132 /*
3133 * This guy is a *Helper* function responsible for positioning a
3134 * single row in the current 'X axis', then displaying the results.
3135 * Along the way, he makes sure control characters and/or unprintable
3136 * characters display in a less-like fashion:
3137 * '^A' for control chars
3138 * '<BC>' for other unprintable stuff
3139 * Those will be highlighted with the current windows's capclr_msg,
3140 * while visible search matches display with capclr_hdr for emphasis.
3141 * ( we hide ugly plumbing in macros to concentrate on the algorithm ) */
3142 static void insp_mkrow_raw (int col, int row) {
3143 #define maxSZ ( Screen_cols - to )
3144 #define capNO { if (hicap) { putp(Caps_off); hicap = 0; } }
3145 #define mkFND { PUTT("%s%.*s%s", Curwin->capclr_hdr, maxSZ, Insp_sel->fstr, Caps_off); \
3146 fr += Insp_sel->flen -1; to += Insp_sel->flen; hicap = 0; }
3147 #ifndef INSP_JUSTNOT
3148 #define mkCTL { const char *p = fmtmk("^%c", uch + '@'); \
3149 PUTT("%s%.*s", (!hicap) ? Curwin->capclr_msg : "", maxSZ, p); to += 2; hicap = 1; }
3150 #define mkUNP { const char *p = fmtmk("<%02X>", uch); \
3151 PUTT("%s%.*s", (!hicap) ? Curwin->capclr_msg : "", maxSZ, p); to += 4; hicap = 1; }
3152 #else
3153 #define mkCTL { if ((to += 2) <= Screen_cols) \
3154 PUTT("%s^%c", (!hicap) ? Curwin->capclr_msg : "", uch + '@'); hicap = 1; }
3155 #define mkUNP { if ((to += 4) <= Screen_cols) \
3156 PUTT("%s<%02X>", (!hicap) ? Curwin->capclr_msg : "", uch); hicap = 1; }
3157 #endif
3158 #define mkSTD { capNO; if (++to <= Screen_cols) { static char _str[2]; \
3159 _str[0] = uch; putp(_str); } }
3160 unsigned char tline[SCREENMAX];
3161 int fr, to, ofs;
3162 int hicap = 0;
3163
3164 if (col < INSP_RLEN(row))
3165 memcpy(tline, Insp_p[row] + col, sizeof(tline));
3166 else tline[0] = '\n';
3167
3168 for (fr = 0, to = 0, ofs = 0; to < Screen_cols; fr++) {
3169 if (!ofs)
3170 ofs = insp_find_ofs(col + fr, row);
3171 if (col + fr < ofs) {
3172 unsigned char uch = tline[fr];
3173 if (uch == '\n') break; // a no show (he,he)
3174 if (uch > 126) mkUNP // show as: '<AB>'
3175 else if (uch < 32) mkCTL // show as: '^C'
3176 else mkSTD // a show off (he,he)
3177 } else { mkFND // a big show (he,he)
3178 ofs = 0;
3179 }
3180 if (col + fr >= INSP_RLEN(row)) break;
3181 }
3182 capNO;
3183 putp(Cap_clr_eol);
3184
3185 #undef maxSZ
3186 #undef capNO
3187 #undef mkFND
3188 #undef mkCTL
3189 #undef mkUNP
3190 #undef mkSTD
3191 } // end: insp_mkrow_raw
3192
3193
3194 /*
3195 * This guy is a *Helper* function responsible for positioning a
3196 * single row in the current 'X axis' within a multi-byte string
3197 * then displaying the results. Along the way he ensures control
3198 * characters will then be displayed in two positions like '^A'.
3199 * ( assuming they can even get past those 'gettext' utilities ) */
3200 static void insp_mkrow_utf8 (int col, int row) {
3201 #define maxSZ ( Screen_cols - to )
3202 #define mkFND { PUTT("%s%.*s%s", Curwin->capclr_hdr, maxSZ, Insp_sel->fstr, Caps_off); \
3203 fr += Insp_sel->flen; to += Insp_sel->flen; }
3204 #ifndef INSP_JUSTNOT
3205 #define mkCTL { const char *p = fmtmk("^%c", uch + '@'); \
3206 PUTT("%s%.*s%s", Curwin->capclr_msg, maxSZ, p, Caps_off); to += 2; }
3207 #else
3208 #define mkCTL { if ((to += 2) <= Screen_cols) \
3209 PUTT("%s^%c%s", Curwin->capclr_msg, uch + '@', Caps_off); }
3210 #endif
3211 #define mkNUL { buf1[0] = ' '; doPUT(buf1) }
3212 #define doPUT(buf) if ((to += cno) <= Screen_cols) putp(buf);
3213 static char buf1[2], buf2[3], buf3[4], buf4[5];
3214 unsigned char tline[BIGBUFSIZ];
3215 int fr, to, ofs;
3216
3217 col = utf8_proper_col(Insp_p[row], col, 1);
3218 if (col < INSP_RLEN(row))
3219 memcpy(tline, Insp_p[row] + col, sizeof(tline));
3220 else tline[0] = '\n';
3221
3222 for (fr = 0, to = 0, ofs = 0; to < Screen_cols; ) {
3223 if (!ofs)
3224 ofs = insp_find_ofs(col + fr, row);
3225 if (col + fr < ofs) {
3226 unsigned char uch = tline[fr];
3227 int bno = UTF8_tab[uch];
3228 int cno = utf8_cols(&tline[fr++], bno);
3229 switch (bno) {
3230 case 1:
3231 if (uch == '\n') break;
3232 if (uch < 32) mkCTL
3233 else if (uch == 127) mkNUL
3234 else { buf1[0] = uch; doPUT(buf1) }
3235 break;
3236 case 2:
3237 buf2[0] = uch; buf2[1] = tline[fr++];
3238 doPUT(buf2)
3239 break;
3240 case 3:
3241 buf3[0] = uch; buf3[1] = tline[fr++]; buf3[2] = tline[fr++];
3242 doPUT(buf3)
3243 break;
3244 case 4:
3245 buf4[0] = uch; buf4[1] = tline[fr++]; buf4[2] = tline[fr++]; buf4[3] = tline[fr++];
3246 doPUT(buf4)
3247 break;
3248 default:
3249 mkNUL
3250 break;
3251 }
3252 } else {
3253 mkFND
3254 ofs = 0;
3255 }
3256 if (col + fr >= INSP_RLEN(row)) break;
3257 }
3258 putp(Cap_clr_eol);
3259
3260 #undef maxSZ
3261 #undef mkFND
3262 #undef mkCTL
3263 #undef mkNUL
3264 #undef doPUT
3265 } // end: insp_mkrow_utf8
3266
3267
3268 /*
3269 * This guy is an insp_view_choice() *Helper* function who displays
3270 * a page worth of of the user's damages. He also creates a status
3271 * line based on maximum digits for the current selection's lines and
3272 * hozizontal position (so it serves to inform, not distract, by
3273 * otherwise being jumpy). */
3274 static inline void insp_show_pgs (int col, int row, int max) {
3275 char buf[SMLBUFSIZ];
3276 void (*mkrow_func)(int, int);
3277 int r = snprintf(buf, sizeof(buf), "%d", Insp_nl);
3278 int c = snprintf(buf, sizeof(buf), "%d", col +Screen_cols);
3279 int l = row +1, ls = Insp_nl;
3280
3281 if (!Insp_bufrd)
3282 l = ls = 0;
3283 snprintf(buf, sizeof(buf), N_fmt(YINSP_status_fmt)
3284 , Insp_sel->name
3285 , r, l, r, ls
3286 , c, col + 1, c, col + Screen_cols
3287 , (unsigned long)Insp_bufrd);
3288 INSP_MKSL(0, buf);
3289
3290 mkrow_func = Insp_utf8 ? insp_mkrow_utf8 : insp_mkrow_raw;
3291
3292 for ( ; max && row < Insp_nl; row++) {
3293 putp("\n");
3294 mkrow_func(col, row);
3295 --max;
3296 }
3297
3298 if (max)
3299 putp(Cap_nl_clreos);
3300 } // end: insp_show_pgs
3301
3302
3303 /*
3304 * This guy is responsible for displaying the Insp_buf contents and
3305 * managing all scrolling/locate requests until the user gives up. */
3306 static int insp_view_choice (struct pids_stack *p) {
3307 #ifdef INSP_SLIDE_1
3308 #define hzAMT 1
3309 #else
3310 #define hzAMT 8
3311 #endif
3312 #define maxLN (Screen_rows - (Msg_row +1))
3313 #define makHD(b1,b2) { \
3314 snprintf(b1, sizeof(b1), "%d", PID_VAL(EU_PID, s_int, p)); \
3315 snprintf(b2, sizeof(b2), "%s", PID_VAL(EU_CMD, str, p)); }
3316 #define makFS(dst) { if (Insp_sel->flen < 22) \
3317 snprintf(dst, sizeof(dst), "%s", Insp_sel->fstr); \
3318 else snprintf(dst, sizeof(dst), "%.19s...", Insp_sel->fstr); }
3319 char buf[LRGBUFSIZ];
3320 int key, curlin = 0, curcol = 0;
3321
3322 signify_that:
3323 putp(Cap_clr_scr);
3324 adj_geometry();
3325
3326 for (;;) {
3327 char pid[6], cmd[64];
3328
3329 if (curcol < 0) curcol = 0;
3330 if (curlin >= Insp_nl) curlin = Insp_nl -1;
3331 if (curlin < 0) curlin = 0;
3332
3333 makFS(buf)
3334 makHD(pid,cmd)
3335 putp(Cap_home);
3336 show_special(1, fmtmk(N_unq(YINSP_hdview_fmt)
3337 , pid, cmd, (Insp_sel->fstr[0]) ? buf : " N/A ")); // nls_maybe
3338 insp_show_pgs(curcol, curlin, maxLN);
3339 fflush(stdout);
3340 /* fflush(stdin) didn't do the trick, so we'll just dip a little deeper
3341 lest repeated <Enter> keys produce immediate re-selection in caller */
3342 tcflush(STDIN_FILENO, TCIFLUSH);
3343
3344 if (Frames_signal) goto signify_that;
3345 key = iokey(IOKEY_ONCE);
3346 if (key < 1) goto signify_that;
3347
3348 switch (key) {
3349 case kbd_ENTER: // must force new iokey()
3350 key = INT_MAX; // fall through !
3351 case kbd_ESC:
3352 case 'q':
3353 putp(Cap_clr_scr);
3354 return key;
3355 case kbd_LEFT:
3356 curcol -= hzAMT;
3357 break;
3358 case kbd_RIGHT:
3359 curcol += hzAMT;
3360 break;
3361 case kbd_UP:
3362 --curlin;
3363 break;
3364 case kbd_DOWN:
3365 ++curlin;
3366 break;
3367 case kbd_PGUP:
3368 case 'b':
3369 curlin -= maxLN -1; // keep 1 line for reference
3370 break;
3371 case kbd_PGDN:
3372 case kbd_SPACE:
3373 curlin += maxLN -1; // ditto
3374 break;
3375 case kbd_HOME:
3376 case 'g':
3377 curcol = curlin = 0;
3378 break;
3379 case kbd_END:
3380 case 'G':
3381 curcol = 0;
3382 curlin = Insp_nl - maxLN;
3383 break;
3384 case 'L':
3385 case '&':
3386 case '/':
3387 case 'n':
3388 if (!Insp_utf8)
3389 insp_find_str(key, &curcol, &curlin);
3390 else {
3391 int tmpcol = utf8_proper_col(Insp_p[curlin], curcol, 1);
3392 insp_find_str(key, &tmpcol, &curlin);
3393 curcol = utf8_proper_col(Insp_p[curlin], tmpcol, 0);
3394 }
3395 // must re-hide cursor in case a prompt for a string makes it huge
3396 putp((Cursor_state = Cap_curs_hide));
3397 break;
3398 case '=':
3399 snprintf(buf, sizeof(buf), "%s: %s", Insp_sel->type, Insp_sel->fmts);
3400 INSP_MKSL(1, buf); // show an extended SL
3401 if (iokey(IOKEY_ONCE) < 1)
3402 goto signify_that;
3403 break;
3404 default: // keep gcc happy
3405 break;
3406 }
3407 }
3408 #undef hzAMT
3409 #undef maxLN
3410 #undef makHD
3411 #undef makFS
3412 } // end: insp_view_choice
3413
3414
3415 /*
3416 * This is the main Inspect routine, responsible for:
3417 * 1) validating the passed pid (required, but not always used)
3418 * 2) presenting/establishing the target selection
3419 * 3) arranging to fill Insp_buf (via the Inspect.tab[?].func)
3420 * 4) invoking insp_view_choice for viewing/scrolling/searching
3421 * 5) cleaning up the dynamically acquired memory afterwards */
3422 static void inspection_utility (int pid) {
3423 #define mkSEL(dst) { for (i = 0; i < Inspect.total; i++) Inspect.tab[i].caps = "~1"; \
3424 Inspect.tab[sel].caps = "~4"; dst[0] = '\0'; \
3425 for (i = 0; i < Inspect.total; i++) { char _s[SMLBUFSIZ]; \
3426 snprintf(_s, sizeof(_s), " %s %s", Inspect.tab[i].name, Inspect.tab[i].caps); \
3427 strncat(dst, _s, (sizeof(dst) - 1) - strlen(dst)); } }
3428 char sels[SCREENMAX];
3429 static int sel;
3430 int i, key;
3431 struct pids_stack *p;
3432
3433 for (i = 0, p = NULL; i < PIDSmaxt; i++)
3434 if (pid == PID_VAL(EU_PID, s_int, Curwin->ppt[i])) {
3435 p = Curwin->ppt[i];
3436 break;
3437 }
3438 if (!p) {
3439 show_msg(fmtmk(N_fmt(YINSP_pidbad_fmt), pid));
3440 return;
3441 }
3442 // must re-hide cursor since the prompt for a pid made it huge
3443 putp((Cursor_state = Cap_curs_hide));
3444 signify_that:
3445 putp(Cap_clr_scr);
3446 adj_geometry();
3447
3448 key = INT_MAX;
3449 do {
3450 mkSEL(sels);
3451 putp(Cap_home);
3452 show_special(1, fmtmk(N_unq(YINSP_hdsels_fmt)
3453 , pid, PID_VAL(EU_CMD, str, Curwin->ppt[i]), sels));
3454 INSP_MKSL(0, " ");
3455
3456 if (Frames_signal) goto signify_that;
3457 if (key == INT_MAX) key = iokey(IOKEY_ONCE);
3458 if (key < 1) goto signify_that;
3459
3460 switch (key) {
3461 case 'q':
3462 case kbd_ESC:
3463 break;
3464 case kbd_END:
3465 sel = 0; // fall through !
3466 case kbd_LEFT:
3467 if (--sel < 0) sel = Inspect.total -1;
3468 key = INT_MAX;
3469 break;
3470 case kbd_HOME:
3471 sel = Inspect.total; // fall through !
3472 case kbd_RIGHT:
3473 if (++sel >= Inspect.total) sel = 0;
3474 key = INT_MAX;
3475 break;
3476 case kbd_ENTER:
3477 INSP_BUSY(!strcmp("file", Inspect.tab[sel].type)
3478 ? YINSP_waitin_txt : YINSP_workin_txt);
3479 Insp_sel = &Inspect.tab[sel];
3480 Inspect.tab[sel].func(Inspect.tab[sel].fmts, pid);
3481 Insp_utf8 = utf8_delta(Insp_buf);
3482 key = insp_view_choice(p);
3483 free(Insp_buf);
3484 free(Insp_p);
3485 break;
3486 default:
3487 goto signify_that;
3488 }
3489 } while (key != 'q' && key != kbd_ESC);
3490
3491 // signal that we just corrupted entire screen
3492 Frames_signal = BREAK_screen;
3493 #undef mkSEL
3494 } // end: inspection_utility
3495
3496 #undef INSP_MKSL
3497 #undef INSP_RLEN
3498 #undef INSP_BUSY
3499
3500 /*###### Other Filtering ###############################################*/
3501
3502 /*
3503 * This structure is hung from a WIN_t when other filtering is active */
3504 struct osel_s {
3505 struct osel_s *nxt; // the next criteria or NULL.
3506 int (*rel)(const char *, const char *); // relational strings compare
3507 char *(*sel)(const char *, const char *); // for selection str compares
3508 char *raw; // raw user input (dup check)
3509 char *val; // value included or excluded
3510 int ops; // filter delimiter/operation
3511 int inc; // include == 1, exclude == 0
3512 int enu; // field (procflag) to filter
3513 int typ; // typ used to set: rel & sel
3514 };
3515
3516 /*
3517 * A function to parse, validate and build a single 'other filter' */
3518 static const char *osel_add (WIN_t *q, int ch, char *glob, int push) {
3519 int (*rel)(const char *, const char *);
3520 char *(*sel)(const char *, const char *);
3521 char raw[MEDBUFSIZ], ops, *pval;
3522 struct osel_s *osel;
3523 int inc, enu;
3524
3525 if (ch == 'o') {
3526 rel = strcasecmp;
3527 sel = strcasestr;
3528 } else {
3529 rel = strcmp;
3530 sel = strstr;
3531 }
3532
3533 if (!snprintf(raw, sizeof(raw), "%s", glob))
3534 return NULL;
3535 for (osel = q->osel_1st; osel; ) {
3536 if (!strcmp(osel->raw, raw)) // #1: is criteria duplicate?
3537 return N_txt(OSEL_errdups_txt);
3538 osel = osel->nxt;
3539 }
3540 if (*glob != '!') inc = 1; // #2: is it include/exclude?
3541 else { ++glob; inc = 0; }
3542
3543 if (!(pval = strpbrk(glob, "<=>"))) // #3: do we see a delimiter?
3544 return fmtmk(N_fmt(OSEL_errdelm_fmt)
3545 , inc ? N_txt(WORD_include_txt) : N_txt(WORD_exclude_txt));
3546 ops = *(pval);
3547 *(pval++) = '\0';
3548
3549 for (enu = 0; enu < EU_MAXPFLGS; enu++) // #4: is this a valid field?
3550 if (!STRCMP(N_col(enu), glob)) break;
3551 if (enu == EU_MAXPFLGS)
3552 return fmtmk(N_fmt(XTRA_badflds_fmt), glob);
3553
3554 if (!(*pval)) // #5: did we get some value?
3555 return fmtmk(N_fmt(OSEL_errvalu_fmt)
3556 , inc ? N_txt(WORD_include_txt) : N_txt(WORD_exclude_txt));
3557
3558 osel = alloc_c(sizeof(struct osel_s));
3559 osel->typ = ch;
3560 osel->inc = inc;
3561 osel->enu = enu;
3562 osel->ops = ops;
3563 if (ops == '=') osel->val = alloc_s(pval);
3564 else osel->val = alloc_s(justify_pad(pval, Fieldstab[enu].width, Fieldstab[enu].align));
3565 osel->rel = rel;
3566 osel->sel = sel;
3567 osel->raw = alloc_s(raw);
3568
3569 if (push) {
3570 // a LIFO queue was used when we're interactive
3571 osel->nxt = q->osel_1st;
3572 q->osel_1st = osel;
3573 } else {
3574 // a FIFO queue must be employed for the rcfile
3575 if (!q->osel_1st)
3576 q->osel_1st = osel;
3577 else {
3578 struct osel_s *prev, *walk = q->osel_1st;
3579 do {
3580 prev = walk;
3581 walk = walk->nxt;
3582 } while (walk);
3583 prev->nxt = osel;
3584 }
3585 }
3586 q->osel_tot += 1;
3587
3588 return NULL;
3589 } // end: osel_add
3590
3591
3592 /*
3593 * A function to turn off entire other filtering in the given window */
3594 static void osel_clear (WIN_t *q) {
3595 struct osel_s *osel = q->osel_1st;
3596
3597 while (osel) {
3598 struct osel_s *nxt = osel->nxt;
3599 free(osel->val);
3600 free(osel->raw);
3601 free(osel);
3602 osel = nxt;
3603 }
3604 q->osel_tot = 0;
3605 q->osel_1st = NULL;
3606 } // end: osel_clear
3607
3608
3609 /*
3610 * Determine if there are matching values or relationships among the
3611 * other criteria in this passed window -- it's called from only one
3612 * place, and likely inlined even without the directive */
3613 static inline int osel_matched (const WIN_t *q, FLG_t enu, const char *str) {
3614 struct osel_s *osel = q->osel_1st;
3615
3616 while (osel) {
3617 if (osel->enu == enu) {
3618 int r;
3619 switch (osel->ops) {
3620 case '<': // '<' needs the r < 0 unless
3621 r = osel->rel(str, osel->val); // '!' which needs an inverse
3622 if ((r >= 0 && osel->inc) || (r < 0 && !osel->inc)) return 0;
3623 break;
3624 case '>': // '>' needs the r > 0 unless
3625 r = osel->rel(str, osel->val); // '!' which needs an inverse
3626 if ((r <= 0 && osel->inc) || (r > 0 && !osel->inc)) return 0;
3627 break;
3628 default:
3629 { char *p = osel->sel(str, osel->val);
3630 if ((!p && osel->inc) || (p && !osel->inc)) return 0;
3631 }
3632 break;
3633 }
3634 }
3635 osel = osel->nxt;
3636 }
3637 return 1;
3638 } // end: osel_matched
3639
3640 /*###### Startup routines ##############################################*/
3641
3642 /*
3643 * No matter what *they* say, we handle the really really BIG and
3644 * IMPORTANT stuff upon which all those lessor functions depend! */
3645 static void before (char *me) {
3646 #define doALL STAT_REAP_NUMA_NODES_TOO
3647 int i, rc;
3648 int linux_version_code = procps_linux_version();
3649
3650 atexit(close_stdout);
3651
3652 // setup our program name
3653 Myname = strrchr(me, '/');
3654 if (Myname) ++Myname; else Myname = me;
3655
3656 // accommodate nls/gettext potential translations
3657 // ( must 'setlocale' before our libproc called )
3658 initialize_nls();
3659
3660 // is /proc mounted?
3661 fatal_proc_unmounted(NULL, 0);
3662
3663 #ifndef OFF_STDERROR
3664 /* there's a chance that damn libnuma may spew to stderr so we gotta
3665 make sure he does not corrupt poor ol' top's first output screen!
3666 Yes, he provides some overridable 'weak' functions to change such
3667 behavior but we can't exploit that since we don't follow a normal
3668 ld route to symbol resolution (we use that dlopen() guy instead)! */
3669 Stderr_save = dup(fileno(stderr));
3670 if (-1 < Stderr_save && freopen("/dev/null", "w", stderr))
3671 ; // avoid -Wunused-result
3672 #endif
3673
3674 // establish some cpu particulars
3675 Hertz = procps_hertz_get();
3676 Cpu_States_fmts = N_unq(STATE_lin2x6_fmt);
3677 if (linux_version_code >= LINUX_VERSION(2, 6, 11))
3678 Cpu_States_fmts = N_unq(STATE_lin2x7_fmt);
3679
3680 // get the total cpus (and, if possible, numa node total)
3681 if ((rc = procps_stat_new(&Stat_ctx)))
3682 Restrict_some = Cpu_cnt = 1;
3683 else {
3684 if (!(Stat_reap = procps_stat_reap(Stat_ctx, doALL, Stat_items, MAXTBL(Stat_items))))
3685 error_exit(fmtmk(N_fmt(LIB_errorcpu_fmt), __LINE__, strerror(errno)));
3686 #ifndef PRETEND0NUMA
3687 Numa_node_tot = Stat_reap->numa->total;
3688 #endif
3689 Cpu_cnt = Stat_reap->cpus->total;
3690 #ifdef PRETEND48CPU
3691 Cpu_cnt = 48;
3692 #endif
3693 }
3694
3695 // prepare for memory stats from new library API ...
3696 if ((rc = procps_meminfo_new(&Mem_ctx)))
3697 Restrict_some = 1;
3698
3699 // establish max depth for newlib pids stack (# of result structs)
3700 Pids_itms = alloc_c(sizeof(enum pids_item) * MAXTBL(Fieldstab));
3701 if (PIDS_noop != 0)
3702 for (i = 0; i < MAXTBL(Fieldstab); i++)
3703 Pids_itms[i] = PIDS_noop;
3704 Pids_itms_tot = MAXTBL(Fieldstab);
3705 // we will identify specific items in the build_headers() function
3706 if ((rc = procps_pids_new(&Pids_ctx, Pids_itms, Pids_itms_tot)))
3707 error_exit(fmtmk(N_fmt(LIB_errorpid_fmt), __LINE__, strerror(-rc)));
3708
3709 #if defined THREADED_CPU || defined THREADED_MEM || defined THREADED_TSK
3710 { struct sigaction sa;
3711 Thread_id_main = pthread_self();
3712 /* in case any of our threads have been enabled, they'll inherit this mask
3713 with everything blocked. therefore, signals go to the main thread (us). */
3714 sigfillset(&sa.sa_mask);
3715 pthread_sigmask(SIG_BLOCK, &sa.sa_mask, NULL);
3716 }
3717 #endif
3718
3719 #ifdef THREADED_CPU
3720 if (0 != sem_init(&Semaphore_cpus_beg, 0, 0)
3721 || (0 != sem_init(&Semaphore_cpus_end, 0, 0)))
3722 error_exit(fmtmk(N_fmt(X_SEMAPHORES_fmt), __LINE__, strerror(errno)));
3723 if (0 != pthread_create(&Thread_id_cpus, NULL, cpus_refresh, NULL))
3724 error_exit(fmtmk(N_fmt(X_THREADINGS_fmt), __LINE__, strerror(errno)));
3725 pthread_setname_np(Thread_id_cpus, "update cpus");
3726 #endif
3727 #ifdef THREADED_MEM
3728 if (0 != sem_init(&Semaphore_memory_beg, 0, 0)
3729 || (0 != sem_init(&Semaphore_memory_end, 0, 0)))
3730 error_exit(fmtmk(N_fmt(X_SEMAPHORES_fmt), __LINE__, strerror(errno)));
3731 if (0 != pthread_create(&Thread_id_memory, NULL, memory_refresh, NULL))
3732 error_exit(fmtmk(N_fmt(X_THREADINGS_fmt), __LINE__, strerror(errno)));
3733 pthread_setname_np(Thread_id_memory, "update memory");
3734 #endif
3735 #ifdef THREADED_TSK
3736 if (0 != sem_init(&Semaphore_tasks_beg, 0, 0)
3737 || (0 != sem_init(&Semaphore_tasks_end, 0, 0)))
3738 error_exit(fmtmk(N_fmt(X_SEMAPHORES_fmt), __LINE__, strerror(errno)));
3739 if (0 != pthread_create(&Thread_id_tasks, NULL, tasks_refresh, NULL))
3740 error_exit(fmtmk(N_fmt(X_THREADINGS_fmt), __LINE__, strerror(errno)));
3741 pthread_setname_np(Thread_id_tasks, "update tasks");
3742 #endif
3743 // lastly, establish support for graphing cpus & memory
3744 Graph_cpus = alloc_c(sizeof(struct graph_parms));
3745 Graph_mems = alloc_c(sizeof(struct graph_parms));
3746 #undef doALL
3747
3748 // don't distort startup cpu(s) display ...
3749 usleep(LIB_USLEEP);
3750 } // end: before
3751
3752
3753 /*
3754 * A configs_file *Helper* function responsible for transforming
3755 * a 3.2.8 - 3.3.17 format 'fieldscur' into our integer based format */
3756 static int cfg_xform (WIN_t *q, char *flds, const char *defs) {
3757 #define CVTon(c) ((c) |= 0x80)
3758 static struct {
3759 int old, new;
3760 } flags_tab[] = {
3761 #define old_View_NOBOLD 0x000001
3762 #define old_VISIBLE_tsk 0x000008
3763 #define old_Qsrt_NORMAL 0x000010
3764 #define old_Show_HICOLS 0x000200
3765 #define old_Show_THREAD 0x010000
3766 { old_View_NOBOLD, View_NOBOLD },
3767 { old_VISIBLE_tsk, Show_TASKON },
3768 { old_Qsrt_NORMAL, Qsrt_NORMAL },
3769 { old_Show_HICOLS, Show_HICOLS },
3770 { old_Show_THREAD, 0 }
3771 #undef old_View_NOBOLD
3772 #undef old_VISIBLE_tsk
3773 #undef old_Qsrt_NORMAL
3774 #undef old_Show_HICOLS
3775 #undef old_Show_THREAD
3776 };
3777 static char null_flds[] = "abcdefghijklmnopqrstuvwxyz";
3778 static const char fields_src[] = CVT_FORMER;
3779 char fields_dst[PFLAGSSIZ], *p1, *p2;
3780 int c, f, i, x, *pn;
3781
3782 if (Rc.id == 'a') {
3783 // first we'll touch up this window's winflags ...
3784 x = q->rc.winflags;
3785 q->rc.winflags = 0;
3786 for (i = 0; i < MAXTBL(flags_tab); i++) {
3787 if (x & flags_tab[i].old) {
3788 x &= ~flags_tab[i].old;
3789 q->rc.winflags |= flags_tab[i].new;
3790 }
3791 }
3792 q->rc.winflags |= x;
3793
3794 // now let's convert old top's more limited fields ...
3795 f = strlen(flds);
3796 if (f >= CVT_FLDMAX)
3797 return 1;
3798 strcpy(fields_dst, fields_src);
3799 /* all other fields represent the 'on' state with a capitalized version
3800 of a particular qwerty key. for the 2 additional suse out-of-memory
3801 fields it makes perfect sense to do the exact opposite, doesn't it?
3802 in any case, we must turn them 'off' temporarily ... */
3803 if ((p1 = strchr(flds, '['))) *p1 = '{';
3804 if ((p2 = strchr(flds, '\\'))) *p2 = '|';
3805 for (i = 0; i < f; i++) {
3806 c = flds[i];
3807 x = tolower(c) - 'a';
3808 if (x < 0 || x >= CVT_FLDMAX)
3809 return 1;
3810 fields_dst[i] = fields_src[x];
3811 if (isupper(c))
3812 CVTon(fields_dst[i]);
3813 }
3814 // if we turned any suse only fields off, turn 'em back on OUR way ...
3815 if (p1) CVTon(fields_dst[p1 - flds]);
3816 if (p2) CVTon(fields_dst[p2 - flds]);
3817
3818 // next, we must adjust the old sort field enum ...
3819 x = q->rc.sortindx;
3820 c = null_flds[x];
3821 q->rc.sortindx = 0;
3822 if ((p1 = memchr(flds, c, CVT_FLDMAX))
3823 || ((p1 = memchr(flds, toupper(c), CVT_FLDMAX)))) {
3824 x = p1 - flds;
3825 q->rc.sortindx = (fields_dst[x] & 0x7f) - FLD_OFFSET;
3826 }
3827 // now we're in a 3.3.0 format (soon to be transformed) ...
3828 strcpy(flds, fields_dst);
3829 }
3830
3831 // lastly, let's attend to the 3.3.0 - 3.3.17 fieldcurs format ...
3832 pn = &q->rc.fieldscur[0];
3833 x = strlen(defs);
3834 for (i = 0; i < x; i++) {
3835 f = ((unsigned char)flds[i] & 0x7f);
3836 f = f << 1;
3837 if ((unsigned char)flds[i] & 0x80) f |= FLDon;
3838 *(pn + i) = f;
3839 }
3840
3841 return 0;
3842 #undef CVTon
3843 } // end: cfg_xform
3844
3845
3846 /*
3847 * A configs_file *Helper* function responsible for reading
3848 * and validating a configuration file's 'Inspection' entries */
3849 static int config_insp (FILE *fp, char *buf, size_t size) {
3850 int i;
3851
3852 // we'll start off with a 'potential' blank or empty line
3853 // ( only realized if we end up with Inspect.total > 0 )
3854 if (!buf[0] || buf[0] != '\n') Inspect.raw = alloc_s("\n");
3855 else Inspect.raw = alloc_c(1);
3856
3857 for (i = 0;;) {
3858 #define iT(element) Inspect.tab[i].element
3859 #define nxtLINE { buf[0] = '\0'; continue; }
3860 size_t lraw = strlen(Inspect.raw) +1;
3861 int n, x;
3862 char *s1, *s2, *s3;
3863
3864 if (i < 0 || (size_t)i >= INT_MAX / sizeof(struct I_ent)) break;
3865 if (lraw >= INT_MAX - size) break;
3866
3867 if (!buf[0] && !fgets(buf, size, fp)) break;
3868 lraw += strlen(buf) +1;
3869 Inspect.raw = alloc_r(Inspect.raw, lraw);
3870 strcat(Inspect.raw, buf);
3871
3872 if (buf[0] == '#' || buf[0] == '\n') nxtLINE;
3873 Inspect.tab = alloc_r(Inspect.tab, sizeof(struct I_ent) * (i + 1));
3874
3875 // part of this is used in a show_special() call, so let's sanitize it
3876 for (n = 0, x = strlen(buf); n < x; n++) {
3877 if ((buf[n] != '\t' && buf[n] != '\n')
3878 && (buf[n] < ' ')) {
3879 buf[n] = '.';
3880 Rc_questions = 1;
3881 }
3882 }
3883 if (!(s1 = strtok(buf, "\t\n"))) { Rc_questions = 1; nxtLINE; }
3884 if (!(s2 = strtok(NULL, "\t\n"))) { Rc_questions = 1; nxtLINE; }
3885 if (!(s3 = strtok(NULL, "\t\n"))) { Rc_questions = 1; nxtLINE; }
3886
3887 switch (toupper(buf[0])) {
3888 case 'F':
3889 iT(func) = insp_do_file;
3890 break;
3891 case 'P':
3892 iT(func) = insp_do_pipe;
3893 break;
3894 default:
3895 Rc_questions = 1;
3896 nxtLINE;
3897 }
3898 iT(type) = alloc_s(s1);
3899 iT(name) = alloc_s(s2);
3900 iT(fmts) = alloc_s(s3);
3901 iT(farg) = (strstr(iT(fmts), "%d")) ? 1 : 0;
3902 iT(fstr) = alloc_c(FNDBUFSIZ);
3903 iT(flen) = 0;
3904
3905 buf[0] = '\0';
3906 ++i;
3907 #undef iT
3908 #undef nxtLINE
3909 } // end: for ('inspect' entries)
3910
3911 Inspect.total = i;
3912 #ifndef INSP_OFFDEMO
3913 if (!Inspect.total) {
3914 #define mkS(n) N_txt(YINSP_demo ## n ## _txt)
3915 const char *sels[] = { mkS(01), mkS(02), mkS(03) };
3916 Inspect.total = Inspect.demo = MAXTBL(sels);
3917 Inspect.tab = alloc_c(sizeof(struct I_ent) * Inspect.total);
3918 for (i = 0; i < Inspect.total; i++) {
3919 Inspect.tab[i].type = alloc_s(N_txt(YINSP_deqtyp_txt));
3920 Inspect.tab[i].name = alloc_s(sels[i]);
3921 Inspect.tab[i].func = insp_do_demo;
3922 Inspect.tab[i].fmts = alloc_s(N_txt(YINSP_deqfmt_txt));
3923 Inspect.tab[i].fstr = alloc_c(FNDBUFSIZ);
3924 }
3925 #undef mkS
3926 }
3927 #endif
3928 return 0;
3929 } // end: config_insp
3930
3931
3932 /*
3933 * A configs_file *Helper* function responsible for reading
3934 * and validating a configuration file's 'Other Filter' entries */
3935 static int config_osel (FILE *fp, char *buf, size_t size) {
3936 int i, ch, tot, wno, begun;
3937 char *p;
3938
3939 for (begun = 0;;) {
3940 if (!fgets(buf, size, fp)) return 0;
3941 if (buf[0] == '\n') continue;
3942 // whoa, must be an 'inspect' entry
3943 if (!begun && !strstr(buf, Osel_delim_1_txt))
3944 return 0;
3945 // ok, we're now beginning
3946 if (!begun && strstr(buf, Osel_delim_1_txt)) {
3947 begun = 1;
3948 continue;
3949 }
3950 // this marks the end of our stuff
3951 if (begun && strstr(buf, Osel_delim_2_txt))
3952 break;
3953
3954 if (2 != sscanf(buf, Osel_window_fmts, &wno, &tot))
3955 goto end_oops;
3956 if (wno < 0 || wno >= GROUPSMAX) goto end_oops;
3957 if (tot < 0) goto end_oops;
3958
3959 for (i = 0; i < tot; i++) {
3960 if (!fgets(buf, size, fp)) return 1;
3961 if (1 > sscanf(buf, Osel_filterI_fmt, &ch)) goto end_oops;
3962 if ((p = strchr(buf, '\n'))) *p = '\0';
3963 if (!(p = strstr(buf, OSEL_FILTER))) goto end_oops;
3964 p += sizeof(OSEL_FILTER) - 1;
3965 if (osel_add(&Winstk[wno], ch, p, 0)) goto end_oops;
3966 }
3967 }
3968 // let's prime that buf for the next guy...
3969 fgets(buf, size, fp);
3970 return 0;
3971
3972 end_oops:
3973 Rc_questions = 1;
3974 return 1;
3975 } // end: config_osel
3976
3977
3978 /*
3979 * A configs_reads *Helper* function responsible for processing
3980 * a configuration file (personal or system-wide default) */
3981 static const char *configs_file (FILE *fp, const char *name, float *delay) {
3982 char fbuf[LRGBUFSIZ];
3983 int i, n, tmp_whole, tmp_fract;
3984 const char *p = NULL;
3985
3986 p = fmtmk(N_fmt(RC_bad_files_fmt), name);
3987 (void)fgets(fbuf, sizeof(fbuf), fp); // ignore eyecatcher
3988 if (6 != fscanf(fp
3989 , "Id:%c, Mode_altscr=%d, Mode_irixps=%d, Delay_time=%d.%d, Curwin=%d\n"
3990 , &Rc.id, &Rc.mode_altscr, &Rc.mode_irixps, &tmp_whole, &tmp_fract, &i)) {
3991 return p;
3992 }
3993 if (Rc.id < 'a' || Rc.id > RCF_VERSION_ID)
3994 return p;
3995 if (strchr("bcde", Rc.id))
3996 return p;
3997 if (Rc.mode_altscr < 0 || Rc.mode_altscr > 1)
3998 return p;
3999 if (Rc.mode_irixps < 0 || Rc.mode_irixps > 1)
4000 return p;
4001 if (tmp_whole < 0)
4002 return p;
4003 // you saw that, right? (fscanf stickin' it to 'i')
4004 if (i < 0 || i >= GROUPSMAX)
4005 return p;
4006 Curwin = &Winstk[i];
4007 // this may be ugly, but it keeps us locale independent...
4008 *delay = (float)tmp_whole + (float)tmp_fract / 1000;
4009
4010 for (i = 0 ; i < GROUPSMAX; i++) {
4011 static const char *def_flds[] = { DEF_FORMER, JOB_FORMER, MEM_FORMER, USR_FORMER };
4012 int j, x;
4013 WIN_t *w = &Winstk[i];
4014 p = fmtmk(N_fmt(RC_bad_entry_fmt), i+1, name);
4015
4016 if (1 != fscanf(fp, "%3s\tfieldscur=", w->rc.winname))
4017 return p;
4018 if (Rc.id < RCF_XFORMED_ID)
4019 fscanf(fp, "%s\n", fbuf);
4020 else {
4021 for (j = 0; ; j++)
4022 if (1 != fscanf(fp, "%d", &w->rc.fieldscur[j]))
4023 break;
4024 }
4025
4026 // be tolerant of missing release 3.3.10 graph modes additions
4027 if (3 > fscanf(fp, "\twinflags=%d, sortindx=%d, maxtasks=%d, graph_cpus=%d, graph_mems=%d"
4028 ", double_up=%d, combine_cpus=%d, core_types=%d\n"
4029 , &w->rc.winflags, &w->rc.sortindx, &w->rc.maxtasks, &w->rc.graph_cpus, &w->rc.graph_mems
4030 , &w->rc.double_up, &w->rc.combine_cpus, &w->rc.core_types))
4031 return p;
4032 if (w->rc.sortindx < 0 || w->rc.sortindx >= EU_MAXPFLGS)
4033 return p;
4034 if (w->rc.maxtasks < 0)
4035 return p;
4036 if (w->rc.graph_cpus < 0 || w->rc.graph_cpus > 2)
4037 return p;
4038 if (w->rc.graph_mems < 0 || w->rc.graph_mems > 2)
4039 return p;
4040 if (w->rc.double_up < 0 || w->rc.double_up >= ADJOIN_limit)
4041 return p;
4042 // can't check upper bounds until Cpu_cnt is known
4043 if (w->rc.combine_cpus < 0)
4044 return p;
4045 if (w->rc.core_types < 0 || w->rc.core_types > E_CORES_ONLY)
4046 return p;
4047
4048 if (4 != fscanf(fp, "\tsummclr=%d, msgsclr=%d, headclr=%d, taskclr=%d\n"
4049 , &w->rc.summclr, &w->rc.msgsclr, &w->rc.headclr, &w->rc.taskclr))
4050 return p;
4051 // would prefer to use 'max_colors', but it isn't available yet...
4052 if (w->rc.summclr < 0 || w->rc.summclr > 255) return p;
4053 if (w->rc.msgsclr < 0 || w->rc.msgsclr > 255) return p;
4054 if (w->rc.headclr < 0 || w->rc.headclr > 255) return p;
4055 if (w->rc.taskclr < 0 || w->rc.taskclr > 255) return p;
4056
4057 switch (Rc.id) {
4058 case 'a': // 3.2.8 (former procps)
4059 // fall through
4060 case 'f': // 3.3.0 thru 3.3.3 (ng)
4061 SETw(w, Show_JRNUMS);
4062 // fall through
4063 case 'g': // from 3.3.4 thru 3.3.8
4064 if (Rc.id > 'a') scat(fbuf, RCF_PLUS_H);
4065 // fall through
4066 case 'h': // this is release 3.3.9
4067 w->rc.graph_cpus = w->rc.graph_mems = 0;
4068 // these next 2 are really global, but best documented here
4069 Rc.summ_mscale = Rc.task_mscale = SK_Kb;
4070 // fall through
4071 case 'i': // from 3.3.10 thru 3.3.16
4072 if (Rc.id > 'a') scat(fbuf, RCF_PLUS_J);
4073 w->rc.double_up = w->rc.combine_cpus = 0;
4074 // fall through
4075 case 'j': // this is release 3.3.17
4076 if (cfg_xform(w, fbuf, def_flds[i]))
4077 return p;
4078 Rc.tics_scaled = 0;
4079 // fall through
4080 case 'k': // current RCF_VERSION_ID
4081 // fall through
4082 default:
4083 if (mlen(w->rc.fieldscur) < EU_MAXPFLGS)
4084 return p;
4085 for (x = 0; x < EU_MAXPFLGS; x++) {
4086 FLG_t f = FLDget(w, x);
4087 if (f >= EU_MAXPFLGS || f < 0)
4088 return p;
4089 }
4090 break;
4091 }
4092 // ensure there's been no manual alteration of fieldscur
4093 for (n = 0 ; n < EU_MAXPFLGS; n++) {
4094 if (&w->rc.fieldscur[n] != msch(w->rc.fieldscur, w->rc.fieldscur[n], EU_MAXPFLGS))
4095 return p;
4096 }
4097 } // end: for (GROUPSMAX)
4098
4099 // any new addition(s) last, for older rcfiles compatibility...
4100 (void)fscanf(fp, "Fixed_widest=%d, Summ_mscale=%d, Task_mscale=%d, Zero_suppress=%d, Tics_scaled=%d\n"
4101 , &Rc.fixed_widest, &Rc.summ_mscale, &Rc.task_mscale, &Rc.zero_suppress, &Rc.tics_scaled);
4102 if (Rc.fixed_widest < -1 || Rc.fixed_widest > SCREENMAX)
4103 Rc.fixed_widest = 0;
4104 if (Rc.summ_mscale < 0 || Rc.summ_mscale > SK_Eb)
4105 Rc.summ_mscale = 0;
4106 if (Rc.task_mscale < 0 || Rc.task_mscale > SK_Pb)
4107 Rc.task_mscale = 0;
4108 if (Rc.zero_suppress < 0 || Rc.zero_suppress > 1)
4109 Rc.zero_suppress = 0;
4110 if (Rc.tics_scaled < 0 || Rc.tics_scaled > TICS_AS_LAST)
4111 Rc.tics_scaled = 0;
4112
4113 // prepare to warn that older top can no longer read rcfile ...
4114 if (Rc.id != RCF_VERSION_ID)
4115 Rc_compatibilty = 1;
4116
4117 // lastly, let's process any optional glob(s) ...
4118 // (darn, must do osel 1st even though alphabetically 2nd)
4119 fbuf[0] = '\0';
4120 config_osel(fp, fbuf, sizeof(fbuf));
4121 config_insp(fp, fbuf, sizeof(fbuf));
4122
4123 return NULL;
4124 } // end: configs_file
4125
4126
4127 /*
4128 * A configs_reads *Helper* function responsible for ensuring the
4129 * complete path was established, otherwise force the 'W' to fail */
4130 static int configs_path (const char *const fmts, ...) __attribute__((format(printf,1,2)));
4131 static int configs_path (const char *const fmts, ...) {
4132 int len;
4133 va_list ap;
4134
4135 va_start(ap, fmts);
4136 len = vsnprintf(Rc_name, sizeof(Rc_name), fmts, ap);
4137 va_end(ap);
4138 if (len <= 0 || (size_t)len >= sizeof(Rc_name)) {
4139 Rc_name[0] = '\0';
4140 len = 0;
4141 }
4142 return len;
4143 } // end: configs_path
4144
4145
4146 /*
4147 * Try reading up to 3 rcfiles
4148 * 1. 'SYS_RCRESTRICT' contains two lines consisting of the secure
4149 * mode switch and an update interval. Its presence limits what
4150 * ordinary users are allowed to do.
4151 * 2. 'Rc_name' contains multiple lines - both global & per window.
4152 * line 1 : an eyecatcher and creating program/alias name
4153 * line 2 : an id, Mode_altcsr, Mode_irixps, Delay_time, Curwin.
4154 * For each of the 4 windows:
4155 * lines a: contains w->winname, fieldscur
4156 * line b: contains w->winflags, sortindx, maxtasks, etc
4157 * line c: contains w->summclr, msgsclr, headclr, taskclr
4158 * global : miscellaneous additional settings
4159 * Any remaining lines are devoted to the optional entries
4160 * supporting the 'Other Filter' and 'Inspect' provisions.
4161 * 3. 'SYS_RCDEFAULTS' system-wide defaults if 'Rc_name' absent
4162 * format is identical to #2 above */
4163 static void configs_reads (void) {
4164 float tmp_delay = DEF_DELAY;
4165 const char *p, *p_home;
4166 FILE *fp;
4167
4168 fp = fopen(SYS_RCRESTRICT, "r");
4169 if (fp) {
4170 char fbuf[SMLBUFSIZ];
4171 if (fgets(fbuf, sizeof(fbuf), fp)) { // sys rc file, line 1
4172 Secure_mode = 1;
4173 if (fgets(fbuf, sizeof(fbuf), fp)) // sys rc file, line 2
4174 sscanf(fbuf, "%f", &Rc.delay_time);
4175 }
4176 fclose(fp);
4177 }
4178
4179 Rc_name[0] = '\0'; // "fopen() shall fail if pathname is an empty string."
4180 // attempt to use the legacy file first, if we cannot access that file, use
4181 // the new XDG basedir locations (XDG_CONFIG_HOME or HOME/.config) instead.
4182 p_home = getenv("HOME");
4183 if (!p_home || p_home[0] != '/') {
4184 const struct passwd *const pwd = getpwuid(getuid());
4185 if (!pwd || !(p_home = pwd->pw_dir) || p_home[0] != '/') {
4186 p_home = NULL;
4187 }
4188 }
4189 if (p_home)
4190 configs_path("%s/.%src", p_home, Myname);
4191
4192 if (!(fp = fopen(Rc_name, "r"))) {
4193 p = getenv("XDG_CONFIG_HOME");
4194 // ensure the path we get is absolute, fallback otherwise.
4195 if (!p || p[0] != '/') {
4196 if (!p_home) goto system_default;
4197 p = fmtmk("%s/.config", p_home);
4198 (void)mkdir(p, 0700);
4199 }
4200 if (!configs_path("%s/procps", p)) goto system_default;
4201 (void)mkdir(Rc_name, 0700);
4202 if (!configs_path("%s/procps/%src", p, Myname)) goto system_default;
4203 fp = fopen(Rc_name, "r");
4204 }
4205
4206 if (fp) {
4207 p = configs_file(fp, Rc_name, &tmp_delay);
4208 fclose(fp);
4209 if (p) goto default_or_error;
4210 } else {
4211 system_default:
4212 fp = fopen(SYS_RCDEFAULTS, "r");
4213 if (fp) {
4214 p = configs_file(fp, SYS_RCDEFAULTS, &tmp_delay);
4215 fclose(fp);
4216 if (p) goto default_or_error;
4217 }
4218 }
4219
4220 // lastly, establish the true runtime secure mode and delay time
4221 if (!getuid()) Secure_mode = 0;
4222 if (!Secure_mode) Rc.delay_time = tmp_delay;
4223 return;
4224
4225 default_or_error:
4226 #ifdef RCFILE_NOERR
4227 { RCF_t rcdef = DEF_RCFILE;
4228 int i;
4229 Rc = rcdef;
4230 for (i = 0 ; i < GROUPSMAX; i++)
4231 Winstk[i].rc = Rc.win[i];
4232 }
4233 #else
4234 error_exit(p);
4235 #endif
4236 } // end: configs_reads
4237
4238
4239 /*
4240 * Parse command line arguments.
4241 * Note: it's assumed that the rc file(s) have already been read
4242 * and our job is to see if any of those options are to be
4243 * overridden -- we'll force some on and negate others in our
4244 * best effort to honor the loser's (oops, user's) wishes... */
4245 static void parse_args (int argc, char **argv) {
4246 static const char sopts[] = "bcd:E:e:Hhin:Oo:p:SsU:u:Vw::1";
4247 static const struct option lopts[] = {
4248 { "batch-mode", no_argument, NULL, 'b' },
4249 { "cmdline-toggle", no_argument, NULL, 'c' },
4250 { "delay", required_argument, NULL, 'd' },
4251 { "scale-summary-mem", required_argument, NULL, 'E' },
4252 { "scale-task-mem", required_argument, NULL, 'e' },
4253 { "threads-show", no_argument, NULL, 'H' },
4254 { "help", no_argument, NULL, 'h' },
4255 { "idle-toggle", no_argument, NULL, 'i' },
4256 { "iterations", required_argument, NULL, 'n' },
4257 { "list-fields", no_argument, NULL, 'O' },
4258 { "sort-override", required_argument, NULL, 'o' },
4259 { "pid", required_argument, NULL, 'p' },
4260 { "accum-time-toggle", no_argument, NULL, 'S' },
4261 { "secure-mode", no_argument, NULL, 's' },
4262 { "filter-any-user", required_argument, NULL, 'U' },
4263 { "filter-only-euser", required_argument, NULL, 'u' },
4264 { "version", no_argument, NULL, 'V' },
4265 { "width", optional_argument, NULL, 'w' },
4266 { "single-cpu-toggle", no_argument, NULL, '1' },
4267 { NULL, 0, NULL, 0 }
4268 };
4269 float tmp_delay = FLT_MAX;
4270 int ch;
4271
4272 while (-1 != (ch = getopt_long(argc, argv, sopts, lopts, NULL))) {
4273 int i;
4274 float tmp;
4275 char *cp = optarg;
4276
4277 #ifndef GETOPTFIX_NO
4278 /* first, let's plug some awful gaps in the getopt implementation,
4279 especially relating to short options with (optional) arguments! */
4280 if (!cp && optind < argc && argv[optind][0] != '-')
4281 cp = argv[optind++];
4282 if (cp) {
4283 if (*cp == '=') ++cp;
4284 /* here, if we're actually accessing argv[argc], we'll rely on
4285 the required NULL delimiter which yields an error_exit next */
4286 if (*cp == '\0') cp = argv[optind++];
4287 if (!cp) error_exit(fmtmk(N_fmt(MISSING_args_fmt), ch));
4288 }
4289 #endif
4290 switch (ch) {
4291 case '1': // ensure behavior identical to run-time toggle
4292 if (CHKw(Curwin, View_CPUNOD)) OFFw(Curwin, View_CPUSUM);
4293 else TOGw(Curwin, View_CPUSUM);
4294 OFFw(Curwin, View_CPUNOD);
4295 SETw(Curwin, View_STATES);
4296 break;
4297 case 'b':
4298 Batch = 1;
4299 break;
4300 case 'c':
4301 TOGw(Curwin, Show_CMDLIN);
4302 break;
4303 case 'd':
4304 if (!mkfloat(cp, &tmp_delay, 0))
4305 error_exit(fmtmk(N_fmt(BAD_delayint_fmt), cp));
4306 if (0 > tmp_delay)
4307 error_exit(N_txt(DELAY_badarg_txt));
4308 continue;
4309 case 'E':
4310 { const char *get = "kmgtpe", *got;
4311 if (!(got = strchr(get, tolower(*cp))) || strlen(cp) > 1)
4312 error_exit(fmtmk(N_fmt(BAD_memscale_fmt), cp));
4313 Rc.summ_mscale = (int)(got - get);
4314 } continue;
4315 case 'e':
4316 { const char *get = "kmgtp", *got;
4317 if (!(got = strchr(get, tolower(*cp))) || strlen(cp) > 1)
4318 error_exit(fmtmk(N_fmt(BAD_memscale_fmt), cp));
4319 Rc.task_mscale = (int)(got - get);
4320 } continue;
4321 case 'H':
4322 Thread_mode = 1;
4323 break;
4324 case 'h':
4325 puts(fmtmk(N_fmt(HELP_cmdline_fmt), Myname));
4326 bye_bye(NULL);
4327 case 'i':
4328 TOGw(Curwin, Show_IDLEPS);
4329 Curwin->rc.maxtasks = 0;
4330 break;
4331 case 'n':
4332 if (!mkfloat(cp, &tmp, 1) || 1.0 > tmp)
4333 error_exit(fmtmk(N_fmt(BAD_niterate_fmt), cp));
4334 Loops = (int)tmp;
4335 continue;
4336 case 'O':
4337 for (i = 0; i < EU_MAXPFLGS; i++)
4338 puts(N_col(i));
4339 bye_bye(NULL);
4340 case 'o':
4341 if (*cp == '+') { SETw(Curwin, Qsrt_NORMAL); ++cp; }
4342 else if (*cp == '-') { OFFw(Curwin, Qsrt_NORMAL); ++cp; }
4343 for (i = 0; i < EU_MAXPFLGS; i++)
4344 if (!STRCMP(cp, N_col(i))) break;
4345 if (i == EU_MAXPFLGS)
4346 error_exit(fmtmk(N_fmt(XTRA_badflds_fmt), cp));
4347 OFFw(Curwin, Show_FOREST);
4348 Curwin->rc.sortindx = i;
4349 continue;
4350 case 'p':
4351 { int pid; char *p;
4352 if (Curwin->usrseltyp) error_exit(N_txt(SELECT_clash_txt));
4353 do {
4354 if (Monpidsidx >= MONPIDMAX)
4355 error_exit(fmtmk(N_fmt(LIMIT_exceed_fmt), MONPIDMAX));
4356 if (1 != sscanf(cp, "%d", &pid)
4357 || strpbrk(cp, "+-."))
4358 error_exit(fmtmk(N_fmt(BAD_mon_pids_fmt), cp));
4359 if (!pid) pid = getpid();
4360 for (i = 0; i < Monpidsidx; i++)
4361 if (Monpids[i] == pid) goto next_pid;
4362 Monpids[Monpidsidx++] = pid;
4363 next_pid:
4364 if (!(p = strchr(cp, ','))) break;
4365 cp = p + 1;
4366 } while (*cp);
4367 } continue;
4368 case 'S':
4369 TOGw(Curwin, Show_CTIMES);
4370 break;
4371 case 's':
4372 Secure_mode = 1;
4373 break;
4374 case 'U':
4375 case 'u':
4376 { const char *errmsg;
4377 if (Monpidsidx || Curwin->usrseltyp) error_exit(N_txt(SELECT_clash_txt));
4378 if ((errmsg = user_certify(Curwin, cp, ch))) error_exit(errmsg);
4379 } continue;
4380 case 'V':
4381 puts(fmtmk(N_fmt(VERSION_opts_fmt), Myname, PACKAGE_STRING));
4382 bye_bye(NULL);
4383 case 'w':
4384 tmp = -1;
4385 if (cp && (!mkfloat(cp, &tmp, 1) || tmp < W_MIN_COL || tmp > SCREENMAX))
4386 error_exit(fmtmk(N_fmt(BAD_widtharg_fmt), cp));
4387 Width_mode = (int)tmp;
4388 continue;
4389 default:
4390 /* we'll rely on getopt for any error message while
4391 forcing an EXIT_FAILURE with an empty string ... */
4392 bye_bye("");
4393 } // end: switch (ch)
4394 #ifndef GETOPTFIX_NO
4395 if (cp) error_exit(fmtmk(N_fmt(UNKNOWN_opts_fmt), cp));
4396 #endif
4397 } // end: while getopt_long
4398
4399 if (optind < argc)
4400 error_exit(fmtmk(N_fmt(UNKNOWN_opts_fmt), argv[optind]));
4401
4402 // fixup delay time, maybe...
4403 if (FLT_MAX > tmp_delay) {
4404 if (Secure_mode)
4405 error_exit(N_txt(DELAY_secure_txt));
4406 Rc.delay_time = tmp_delay;
4407 }
4408 } // end: parse_args
4409
4410
4411 /*
4412 * Establish a robust signals environment */
4413 static void signals_set (void) {
4414 #ifndef SIGRTMAX // not available on hurd, maybe others too
4415 #define SIGRTMAX 32
4416 #endif
4417 int i;
4418 struct sigaction sa;
4419
4420 memset(&sa, 0, sizeof(sa));
4421 sigemptyset(&sa.sa_mask);
4422 // with user position preserved through SIGWINCH, we must avoid SA_RESTART
4423 sa.sa_flags = 0;
4424 for (i = SIGRTMAX; i; i--) {
4425 switch (i) {
4426 case SIGHUP:
4427 if (Batch)
4428 sa.sa_handler = SIG_IGN;
4429 else
4430 sa.sa_handler = sig_endpgm;
4431 break;
4432 case SIGALRM: case SIGINT: case SIGPIPE:
4433 case SIGQUIT: case SIGTERM: case SIGUSR1:
4434 case SIGUSR2:
4435 sa.sa_handler = sig_endpgm;
4436 break;
4437 case SIGTSTP: case SIGTTIN: case SIGTTOU:
4438 sa.sa_handler = sig_paused;
4439 break;
4440 case SIGCONT: case SIGWINCH:
4441 sa.sa_handler = sig_resize;
4442 break;
4443 default:
4444 sa.sa_handler = sig_abexit;
4445 break;
4446 case SIGKILL: case SIGSTOP:
4447 // because uncatchable, fall through
4448 case SIGCHLD: // we can't catch this
4449 continue; // when opening a pipe
4450 }
4451 sigaction(i, &sa, NULL);
4452 }
4453 } // end: signals_set
4454
4455
4456 /*
4457 * Set up the terminal attributes */
4458 static void whack_terminal (void) {
4459 static char dummy[] = "dumb";
4460 struct termios tmptty;
4461
4462 // the curses part...
4463 if (Batch) {
4464 setupterm(dummy, STDOUT_FILENO, NULL);
4465 return;
4466 }
4467 #ifdef PRETENDNOCAP
4468 setupterm(dummy, STDOUT_FILENO, NULL);
4469 #else
4470 setupterm(NULL, STDOUT_FILENO, NULL);
4471 #endif
4472 // our part...
4473 if (-1 == tcgetattr(STDIN_FILENO, &Tty_original))
4474 error_exit(N_txt(FAIL_tty_get_txt));
4475 // ok, haven't really changed anything but we do have our snapshot
4476 Ttychanged = 1;
4477
4478 // first, a consistent canonical mode for interactive line input
4479 tmptty = Tty_original;
4480 tmptty.c_lflag |= (ECHO | ECHOCTL | ECHOE | ICANON | ISIG);
4481 tmptty.c_lflag &= ~NOFLSH;
4482 tmptty.c_oflag &= ~TAB3;
4483 tmptty.c_iflag |= BRKINT;
4484 tmptty.c_iflag &= ~IGNBRK;
4485 #ifdef TERMIOS_ONLY
4486 if (-1 == tcsetattr(STDIN_FILENO, TCSAFLUSH, &tmptty))
4487 error_exit(fmtmk(N_fmt(FAIL_tty_set_fmt), strerror(errno)));
4488 tcgetattr(STDIN_FILENO, &Tty_tweaked);
4489 #endif
4490 // lastly, a nearly raw mode for unsolicited single keystrokes
4491 tmptty.c_lflag &= ~(ECHO | ECHOCTL | ECHOE | ICANON);
4492 tmptty.c_cc[VMIN] = 1;
4493 tmptty.c_cc[VTIME] = 0;
4494 if (-1 == tcsetattr(STDIN_FILENO, TCSAFLUSH, &tmptty))
4495 error_exit(fmtmk(N_fmt(FAIL_tty_set_fmt), strerror(errno)));
4496 tcgetattr(STDIN_FILENO, &Tty_raw);
4497
4498 #ifndef OFF_STDIOLBF
4499 // thanks anyway stdio, but we'll manage buffering at the frame level...
4500 setbuffer(stdout, Stdout_buf, sizeof(Stdout_buf));
4501 #endif
4502 #ifdef OFF_SCROLLBK
4503 // this has the effect of disabling any troublesome scrollback buffer...
4504 if (enter_ca_mode) putp(enter_ca_mode);
4505 #endif
4506 // and don't forget to ask iokey to initialize his tinfo_tab
4507 iokey(IOKEY_INIT);
4508 } // end: whack_terminal
4509
4510 /*###### Windows/Field Groups support #################################*/
4511
4512 /*
4513 * Value a window's name and make the associated group name. */
4514 static void win_names (WIN_t *q, const char *name) {
4515 /* note: sprintf/snprintf results are "undefined" when src==dst,
4516 according to C99 & POSIX.1-2001 (thanks adc) */
4517 if (q->rc.winname != name)
4518 snprintf(q->rc.winname, sizeof(q->rc.winname), "%s", name);
4519 snprintf(q->grpname, sizeof(q->grpname), "%d:%s", q->winnum, name);
4520 } // end: win_names
4521
4522
4523 /*
4524 * This guy just resets (normalizes) a single window
4525 * and he ensures pid monitoring is no longer active. */
4526 static void win_reset (WIN_t *q) {
4527 SETw(q, Show_IDLEPS | Show_TASKON);
4528 #ifndef SCROLLVAR_NO
4529 q->rc.maxtasks = q->usrseltyp = q->begpflg = q->begtask = q->varcolbeg = q->focus_pid = 0;
4530 #else
4531 q->rc.maxtasks = q->usrseltyp = q->begpflg = q->begtask = q->focus_pid = 0;
4532 #endif
4533 mkVIZoff(q)
4534 osel_clear(q);
4535 q->findstr[0] = '\0';
4536 q->rc.combine_cpus = 0;
4537 q->rc.core_types = 0;
4538
4539 // these next guys are global, not really windows based
4540 Monpidsidx = 0;
4541 Rc.tics_scaled = 0;
4542 BOT_TOSS;
4543 } // end: win_reset
4544
4545
4546 /*
4547 * Display a window/field group (ie. make it "current"). */
4548 static WIN_t *win_select (int ch) {
4549 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
4550
4551 /* if there's no ch, it means we're supporting the external interface,
4552 so we must try to get our own darn ch by begging the user... */
4553 if (!ch) {
4554 show_pmt(N_txt(CHOOSE_group_txt));
4555 if (1 > (ch = iokey(IOKEY_ONCE))) return w;
4556 }
4557 switch (ch) {
4558 case 'a': // we don't carry 'a' / 'w' in our
4559 w = w->next; // pmt - they're here for a good
4560 break; // friend of ours -- wins_colors.
4561 case 'w': // (however those letters work via
4562 w = w->prev; // the pmt too but gee, end-loser
4563 break; // should just press the darn key)
4564 case '1': case '2' : case '3': case '4':
4565 w = &Winstk[ch - '1'];
4566 break;
4567 default: // keep gcc happy
4568 break;
4569 }
4570 Curwin = w;
4571 return Curwin;
4572 } // end: win_select
4573
4574
4575 /*
4576 * Just warn the user when a command can't be honored. */
4577 static int win_warn (int what) {
4578 switch (what) {
4579 case Warn_ALT:
4580 show_msg(N_txt(DISABLED_cmd_txt));
4581 break;
4582 case Warn_VIZ:
4583 show_msg(fmtmk(N_fmt(DISABLED_win_fmt), Curwin->grpname));
4584 break;
4585 default: // keep gcc happy
4586 break;
4587 }
4588 /* we gotta' return false 'cause we're somewhat well known within
4589 macro society, by way of that sassy little tertiary operator... */
4590 return 0;
4591 } // end: win_warn
4592
4593
4594 /*
4595 * Change colors *Helper* function to save/restore settings;
4596 * ensure colors will show; and rebuild the terminfo strings. */
4597 static void wins_clrhlp (WIN_t *q, int save) {
4598 static int flgssav, summsav, msgssav, headsav, tasksav;
4599
4600 if (save) {
4601 flgssav = q->rc.winflags; summsav = q->rc.summclr;
4602 msgssav = q->rc.msgsclr; headsav = q->rc.headclr; tasksav = q->rc.taskclr;
4603 SETw(q, Show_COLORS);
4604 } else {
4605 q->rc.winflags = flgssav; q->rc.summclr = summsav;
4606 q->rc.msgsclr = msgssav; q->rc.headclr = headsav; q->rc.taskclr = tasksav;
4607 }
4608 capsmk(q);
4609 } // end: wins_clrhlp
4610
4611
4612 /*
4613 * Change colors used in display */
4614 static void wins_colors (void) {
4615 #define kbdABORT 'q'
4616 #define kbdAPPLY kbd_ENTER
4617 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
4618 int clr = w->rc.taskclr, *pclr = &w->rc.taskclr;
4619 char tgt = 'T';
4620 int key;
4621
4622 if (0 >= max_colors) {
4623 show_msg(N_txt(COLORS_nomap_txt));
4624 return;
4625 }
4626 wins_clrhlp(w, 1);
4627 putp((Cursor_state = Cap_curs_huge));
4628 signify_that:
4629 putp(Cap_clr_scr);
4630 adj_geometry();
4631
4632 do {
4633 putp(Cap_home);
4634 // this string is well above ISO C89's minimum requirements!
4635 show_special(1, fmtmk(N_unq(COLOR_custom_fmt)
4636 , w->grpname
4637 , CHKw(w, View_NOBOLD) ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)
4638 , CHKw(w, Show_COLORS) ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)
4639 , CHKw(w, Show_HIBOLD) ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)
4640 , tgt, max_colors, clr, w->grpname));
4641 putp(Cap_clr_eos);
4642 fflush(stdout);
4643
4644 if (Frames_signal) goto signify_that;
4645 key = iokey(IOKEY_ONCE);
4646 if (key < 1) goto signify_that;
4647 if (key == kbd_ESC) break;
4648
4649 switch (key) {
4650 case 'S':
4651 pclr = &w->rc.summclr;
4652 clr = *pclr;
4653 tgt = key;
4654 break;
4655 case 'M':
4656 pclr = &w->rc.msgsclr;
4657 clr = *pclr;
4658 tgt = key;
4659 break;
4660 case 'H':
4661 pclr = &w->rc.headclr;
4662 clr = *pclr;
4663 tgt = key;
4664 break;
4665 case 'T':
4666 pclr = &w->rc.taskclr;
4667 clr = *pclr;
4668 tgt = key;
4669 break;
4670 case '0': case '1': case '2': case '3':
4671 case '4': case '5': case '6': case '7':
4672 clr = key - '0';
4673 *pclr = clr;
4674 break;
4675 case kbd_UP:
4676 ++clr;
4677 if (clr >= max_colors) clr = 0;
4678 *pclr = clr;
4679 break;
4680 case kbd_DOWN:
4681 --clr;
4682 if (clr < 0) clr = max_colors - 1;
4683 *pclr = clr;
4684 break;
4685 case 'B':
4686 TOGw(w, View_NOBOLD);
4687 break;
4688 case 'b':
4689 TOGw(w, Show_HIBOLD);
4690 break;
4691 case 'z':
4692 TOGw(w, Show_COLORS);
4693 break;
4694 case 'a':
4695 case 'w':
4696 wins_clrhlp((w = win_select(key)), 1);
4697 clr = w->rc.taskclr, pclr = &w->rc.taskclr;
4698 tgt = 'T';
4699 break;
4700 default:
4701 break; // keep gcc happy
4702 }
4703 capsmk(w);
4704 } while (key != kbdAPPLY && key != kbdABORT);
4705
4706 if (key == kbdABORT || key == kbd_ESC) wins_clrhlp(w, 0);
4707 // signal that we just corrupted entire screen
4708 Frames_signal = BREAK_screen;
4709 #undef kbdABORT
4710 #undef kbdAPPLY
4711 } // end: wins_colors
4712
4713
4714 /*
4715 * Manipulate flag(s) for all our windows. */
4716 static void wins_reflag (int what, int flg) {
4717 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
4718
4719 do {
4720 switch (what) {
4721 case Flags_TOG:
4722 TOGw(w, flg);
4723 break;
4724 case Flags_SET: // Ummmm, i can't find anybody
4725 SETw(w, flg); // who uses Flags_set ...
4726 break;
4727 case Flags_OFF:
4728 OFFw(w, flg);
4729 break;
4730 default: // keep gcc happy
4731 break;
4732 }
4733 /* a flag with special significance -- user wants to rebalance
4734 display so we gotta' off some stuff then force on two flags... */
4735 if (EQUWINS_xxx == flg)
4736 win_reset(w);
4737
4738 w = w->next;
4739 } while (w != Curwin);
4740 } // end: wins_reflag
4741
4742
4743 /*
4744 * Set up the raw/incomplete field group windows --
4745 * they'll be finished off after startup completes.
4746 * [ and very likely that will override most/all of our efforts ]
4747 * [ --- life-is-NOT-fair --- ] */
4748 static void wins_stage_1 (void) {
4749 WIN_t *w;
4750 int i;
4751
4752 for (i = 0; i < GROUPSMAX; i++) {
4753 w = &Winstk[i];
4754 w->winnum = i + 1;
4755 w->rc = Rc.win[i];
4756 w->captab[0] = Cap_norm;
4757 w->captab[1] = Cap_norm;
4758 w->captab[2] = w->cap_bold;
4759 w->captab[3] = w->capclr_sum;
4760 w->captab[4] = w->capclr_msg;
4761 w->captab[5] = w->capclr_pmt;
4762 w->captab[6] = w->capclr_hdr;
4763 w->captab[7] = w->capclr_rowhigh;
4764 w->captab[8] = w->capclr_rownorm;
4765 w->next = w + 1;
4766 w->prev = w - 1;
4767 }
4768
4769 // fixup the circular chains...
4770 Winstk[GROUPSMAX - 1].next = &Winstk[0];
4771 Winstk[0].prev = &Winstk[GROUPSMAX - 1];
4772 Curwin = Winstk;
4773
4774 for (i = 1; i < BOT_MSGSMAX; i++)
4775 Msg_tab[i].prev = &Msg_tab[i - 1];
4776 Msg_tab[0].prev = &Msg_tab[BOT_MSGSMAX -1];
4777 } // end: wins_stage_1
4778
4779
4780 /*
4781 * This guy just completes the field group windows after the
4782 * rcfiles have been read and command line arguments parsed.
4783 * And since he's the cabose of startup, he'll also tidy up
4784 * a few final things... */
4785 static void wins_stage_2 (void) {
4786 int i;
4787
4788 for (i = 0; i < GROUPSMAX; i++) {
4789 win_names(&Winstk[i], Winstk[i].rc.winname);
4790 capsmk(&Winstk[i]);
4791 Winstk[i].findstr = alloc_c(FNDBUFSIZ);
4792 Winstk[i].findlen = 0;
4793 if (Winstk[i].rc.combine_cpus >= Cpu_cnt)
4794 Winstk[i].rc.combine_cpus = 0;
4795 if (CHKw(&Winstk[i], (View_CPUSUM | View_CPUNOD)))
4796 Winstk[i].rc.double_up = 0;
4797 }
4798 if (!Batch)
4799 putp((Cursor_state = Cap_curs_hide));
4800 else {
4801 OFFw(Curwin, View_SCROLL);
4802 signal(SIGHUP, SIG_IGN); // allow running under nohup
4803 }
4804 // fill in missing Fieldstab members and build each window's columnhdr
4805 zap_fieldstab();
4806
4807 // with preserved 'other filters' & command line 'user filters',
4808 // we must ensure that we always have a visible task on row one.
4809 mkVIZrow1
4810
4811 // lastly, initialize a signal set used to throttle one troublesome signal
4812 sigemptyset(&Sigwinch_set);
4813 #ifdef SIGNALS_LESS
4814 sigaddset(&Sigwinch_set, SIGWINCH);
4815 #endif
4816 } // end: wins_stage_2
4817
4818
4819 /*
4820 * Determine if this task matches the 'u/U' selection
4821 * criteria for a given window */
4822 static inline int wins_usrselect (const WIN_t *q, int idx) {
4823 // a tailored 'results stack value' extractor macro
4824 #define rSv(E) PID_VAL(E, u_int, p)
4825 struct pids_stack *p = q->ppt[idx];
4826
4827 switch (q->usrseltyp) {
4828 case 0: // uid selection inactive
4829 return 1;
4830 case 'U': // match any uid
4831 if (rSv(EU_URD) == (unsigned)q->usrseluid) return q->usrselflg;
4832 if (rSv(EU_USD) == (unsigned)q->usrseluid) return q->usrselflg;
4833 if (rSv(eu_ID_FUID) == (unsigned)q->usrseluid) return q->usrselflg;
4834 // fall through...
4835 case 'u': // match effective uid
4836 if (rSv(EU_UED) == (unsigned)q->usrseluid) return q->usrselflg;
4837 // fall through...
4838 default: // no match...
4839 ;
4840 }
4841 return !q->usrselflg;
4842 #undef rSv
4843 } // end: wins_usrselect
4844
4845 /*###### Forest View support ###########################################*/
4846
4847 /*
4848 * We try keeping most existing code unaware of these activities |
4849 * ( plus, maintain alphabetical order within carefully chosen ) |
4850 * ( names beginning forest_a, forest_b, forest_c and forest_d ) |
4851 * ( with each name exactly 1 letter more than its predecessor ) | */
4852 static struct pids_stack **Seed_ppt; // temporary win ppt pointer |
4853 static struct pids_stack **Tree_ppt; // forest_begin resizes this |
4854 static int Tree_idx; // frame_make resets to zero |
4855 /* those next two support collapse/expand children. the Hide_pid |
4856 array holds parent pids whose children have been manipulated. |
4857 positive pid values represent parents with collapsed children |
4858 while a negative pid value means children have been expanded. |
4859 ( both of these are managed under the 'keys_task()' routine ) | */
4860 static int *Hide_pid; // collapsible process array |
4861 static int Hide_tot; // total used in above array |
4862
4863 /*
4864 * This little recursive guy was the real forest view workhorse. |
4865 * He fills in the Tree_ppt array and also sets the child indent |
4866 * level which is stored in an 'extra' result struct as a u_int. | */
4867 static void forest_adds (const int self, int level) {
4868 // tailored 'results stack value' extractor macros
4869 #define rSv(E,X) PID_VAL(E, s_int, Seed_ppt[X])
4870 // if xtra-procps-debug.h active, can't use PID_VAL with assignment
4871 #define rSv_Lvl Tree_ppt[Tree_idx]->head[eu_TREE_LVL].result.s_int
4872 int i;
4873
4874 if (Tree_idx < PIDSmaxt) { // immunize against insanity |
4875 if (level > 100) level = 101; // our arbitrary nests limit |
4876 Tree_ppt[Tree_idx] = Seed_ppt[self]; // add this as root or child |
4877 rSv_Lvl = level; // while recording its level |
4878 ++Tree_idx;
4879 #ifdef TREE_SCANALL
4880 for (i = 0; i < PIDSmaxt; i++) {
4881 if (i == self) continue;
4882 #else
4883 for (i = self + 1; i < PIDSmaxt; i++) {
4884 #endif
4885 if (rSv(EU_PID, self) == rSv(EU_TGD, i)
4886 || (rSv(EU_PID, self) == rSv(EU_PPD, i) && rSv(EU_PID, i) == rSv(EU_TGD, i)))
4887 forest_adds(i, level + 1); // got one child any others?
4888 }
4889 }
4890 #undef rSv
4891 #undef rSv_Lvl
4892 } // end: forest_adds
4893
4894
4895 /*
4896 * This function is responsible for making that stacks ptr array |
4897 * a forest display in that designated window. After completion, |
4898 * he'll replace that original window ppt array with a specially |
4899 * ordered forest view version. He'll also mark hidden children! | */
4900 static void forest_begin (WIN_t *q) {
4901 static int hwmsav;
4902 int i, j;
4903
4904 Seed_ppt = q->ppt; // avoid passing pointers |
4905 if (!Tree_idx) { // do just once per frame |
4906 if (hwmsav < PIDSmaxt) { // grow, but never shrink |
4907 hwmsav = PIDSmaxt;
4908 Tree_ppt = alloc_r(Tree_ppt, sizeof(void *) * hwmsav);
4909 }
4910
4911 #ifndef TREE_SCANALL
4912 if (!(procps_pids_sort(Pids_ctx, Seed_ppt, PIDSmaxt
4913 , PIDS_TICS_BEGAN, PIDS_SORT_ASCEND)))
4914 error_exit(fmtmk(N_fmt(LIB_errorpid_fmt), __LINE__, strerror(errno)));
4915 #endif
4916 for (i = 0; i < PIDSmaxt; i++) { // avoid hidepid distorts |
4917 if (!PID_VAL(eu_TREE_LVL, s_int, Seed_ppt[i])) // parents lvl 0 |
4918 forest_adds(i, 0); // add parents + children |
4919 }
4920
4921 /* we use up to three additional 'PIDS_extra' results in our stack |
4922 eu_TREE_HID (s_ch) : where 'x' == collapsed & 'z' == unseen |
4923 eu_TREE_LVL (s_int): where level number is stored (0 - 100) |
4924 eu_TREE_ADD (u_int): where a children's tics stored (maybe) | */
4925 for (i = 0; i < Hide_tot; i++) {
4926
4927 // if have xtra-procps-debug.h, cannot use PID_VAL w/ assignment |
4928 #define rSv(E,T,X) Tree_ppt[X]->head[E].result.T
4929 #define rSv_Pid(X) rSv(EU_PID, s_int, X)
4930 #define rSv_Lvl(X) rSv(eu_TREE_LVL, s_int, X)
4931 #define rSv_Hid(X) rSv(eu_TREE_HID, s_ch, X)
4932 /* next 2 aren't needed if TREE_VCPUOFF but they cost us nothing |
4933 & the EU_CPU slot will now always be present (even if it's 0) | */
4934 #define rSv_Add(X) rSv(eu_TREE_ADD, u_int, X)
4935 #define rSv_Cpu(X) rSv(EU_CPU, u_int, X)
4936
4937 if (Hide_pid[i] > 0) {
4938 for (j = 0; j < PIDSmaxt; j++) {
4939 if (rSv_Pid(j) == Hide_pid[i]) {
4940 int parent = j;
4941 int children = 0;
4942 int level = rSv_Lvl(parent);
4943 while (j+1 < PIDSmaxt && rSv_Lvl(j+1) > level) {
4944 ++j;
4945 rSv_Hid(j) = 'z';
4946 #ifndef TREE_VCPUOFF
4947 rSv_Add(parent) += rSv_Cpu(j);
4948 #endif
4949 children = 1;
4950 }
4951 /* if any children found (& collapsed) mark the parent |
4952 ( when children aren't found don't negate the pid ) |
4953 ( to prevent future scans since who's to say such ) |
4954 ( tasks will not fork more children in the future ) | */
4955 if (children) rSv_Hid(parent) = 'x';
4956 // this will force a check of next Hide_pid[i], if any |
4957 j = PIDSmaxt + 1;
4958 }
4959 }
4960 // if a target task disappeared prevent any further scanning |
4961 if (j == PIDSmaxt) Hide_pid[i] = -Hide_pid[i];
4962 }
4963 #undef rSv
4964 #undef rSv_Pid
4965 #undef rSv_Lvl
4966 #undef rSv_Hid
4967 #undef rSv_Add
4968 #undef rSv_Cpu
4969 }
4970 } // end: !Tree_idx
4971 memcpy(Seed_ppt, Tree_ppt, sizeof(void *) * PIDSmaxt);
4972 } // end: forest_begin
4973
4974
4975 /*
4976 * When there's a 'focus_pid' established for a window, this guy |
4977 * determines that window's 'focus_beg' plus 'focus_end' values. |
4978 * But, if the pid can no longer be found, he'll turn off focus! | */
4979 static void forest_config (WIN_t *q) {
4980 // tailored 'results stack value' extractor macro
4981 #define rSv(x) PID_VAL(eu_TREE_LVL, s_int, q->ppt[(x)])
4982 int i, level = 0;
4983
4984 for (i = 0; i < PIDSmaxt; i++) {
4985 if (q->focus_pid == PID_VAL(EU_PID, s_int, q->ppt[i])) {
4986 level = rSv(i);
4987 q->focus_beg = i;
4988 break;
4989 }
4990 }
4991 if (i == PIDSmaxt)
4992 q->focus_pid = q->begtask = 0;
4993 else {
4994 #ifdef FOCUS_TREE_X
4995 q->focus_lvl = rSv(i);
4996 #endif
4997 while (i+1 < PIDSmaxt && rSv(i+1) > level)
4998 ++i;
4999 q->focus_end = i + 1; // make 'focus_end' a proper fencpost
5000 // watch out for newly forked/cloned tasks 'above' us ...
5001 if (q->begtask < q->focus_beg) {
5002 q->begtask = q->focus_beg;
5003 mkVIZoff(q)
5004 }
5005 #ifdef FOCUS_HARD_Y
5006 // if some task 'above' us ended, try to maintain focus
5007 // ( but allow scrolling when there are many children )
5008 if (q->begtask > q->focus_beg
5009 && (SCREEN_ROWS > (q->focus_end - q->focus_beg))) {
5010 q->begtask = q->focus_beg;
5011 mkVIZoff(q)
5012 }
5013 #endif
5014 }
5015 #undef rSv
5016 } // end: forest_config
5017
5018
5019 /*
5020 * This guy adds the artwork to either 'cmd' or 'cmdline' values |
5021 * if we are in forest view mode otherwise he just returns them. | */
5022 static inline const char *forest_display (const WIN_t *q, int idx) {
5023 // tailored 'results stack value' extractor macros
5024 #define rSv(E) PID_VAL(E, str, p)
5025 #define rSv_Lvl PID_VAL(eu_TREE_LVL, s_int, p)
5026 #define rSv_Hid PID_VAL(eu_TREE_HID, s_ch, p)
5027 #ifndef SCROLLVAR_NO
5028 static char buf[MAXBUFSIZ];
5029 #else
5030 static char buf[ROWMINSIZ];
5031 #endif
5032 struct pids_stack *p = q->ppt[idx];
5033 const char *which = (CHKw(q, Show_CMDLIN)) ? rSv(eu_CMDLINE) : rSv(EU_CMD);
5034 int level = rSv_Lvl;
5035
5036 #ifdef FOCUS_TREE_X
5037 if (q->focus_pid) {
5038 if (idx >= q->focus_beg && idx < q->focus_end)
5039 level -= q->focus_lvl;
5040 }
5041 #endif
5042 if (!CHKw(q, Show_FOREST) || level == 0) return which;
5043 #ifndef TREE_VWINALL
5044 if (q == Curwin) // note: the following is NOT indented
5045 #endif
5046 if (rSv_Hid == 'x') {
5047 #ifdef TREE_VALTMRK
5048 snprintf(buf, sizeof(buf), "%*s%s", (4 * level), "`+ ", which);
5049 #else
5050 snprintf(buf, sizeof(buf), "+%*s%s", ((4 * level) - 1), "`- ", which);
5051 #endif
5052 return buf;
5053 }
5054 if (level > 100) {
5055 snprintf(buf, sizeof(buf), "%400s%s", " + ", which);
5056 return buf;
5057 }
5058 #ifndef FOCUS_VIZOFF
5059 if (q->focus_pid) snprintf(buf, sizeof(buf), "|%*s%s", ((4 * level) - 1), "`- ", which);
5060 else snprintf(buf, sizeof(buf), "%*s%s", (4 * level), " `- ", which);
5061 #else
5062 snprintf(buf, sizeof(buf), "%*s%s", (4 * level), " `- ", which);
5063 #endif
5064 return buf;
5065 #undef rSv
5066 #undef rSv_Lvl
5067 #undef rSv_Hid
5068 } // end: forest_display
5069
5070 /*###### Special Separate Bottom Window support ########################*/
5071
5072 /*
5073 * This guy actually draws the parsed strings |
5074 * including adding a highlight if necessary. | */
5075 static void bot_do (const char *str, int focus) {
5076 char *cap = Cap_norm;
5077
5078 while (*str == ' ') putchar(*(str++));
5079 if (focus)
5080 #ifdef BOT_STRV_OFF
5081 cap = Cap_reverse;
5082 #else
5083 cap = strchr(str, Bot_sep) ? Curwin->capclr_msg : Cap_reverse;
5084 #endif
5085 putp(fmtmk("%s%s%s", cap, str, Cap_norm));
5086 } // end: bot_do
5087
5088
5089 /*
5090 * This guy draws that bottom window's header |
5091 * then parses/arranges to show the contents. |
5092 * ( returns relative # of elements printed ) | */
5093 static int bot_focus_str (const char *hdr, const char *str) {
5094 #define maxRSVD ( Screen_rows - 1 )
5095 char *beg, *end;
5096 char tmp[BIGBUFSIZ];
5097 int n, x;
5098
5099 if (str) {
5100 // we're a little careless with overhead here (it's a one time cost)
5101 memset(Bot_buf, '\0', sizeof(Bot_buf));
5102 n = strlen(str);
5103 if (n >= sizeof(Bot_buf)) n = sizeof(Bot_buf) - 1;
5104 if (!*str || !strcmp(str, "-")) strcpy(Bot_buf, N_txt(X_BOT_nodata_txt));
5105 else memccpy(Bot_buf, str, '\0', n);
5106 Bot_rsvd = 1 + BOT_RSVD + ((strlen(Bot_buf) - utf8_delta(Bot_buf)) / Screen_cols);
5107 if (Bot_rsvd > maxRSVD) Bot_rsvd = maxRSVD;
5108 // somewhere down call chain fmtmk() may be used, so we'll old school it
5109 snprintf(tmp, sizeof(tmp), "%s%s%-*s"
5110 , tg2(0, SCREEN_ROWS)
5111 , Curwin->capclr_hdr
5112 , Screen_cols + utf8_delta(hdr)
5113 , hdr);
5114 putp(tmp);
5115 }
5116 // now fmtmk is safe to use ...
5117 putp(fmtmk("%s%s%s", tg2(0, SCREEN_ROWS + 1), Cap_clr_eos, Cap_norm));
5118
5119 beg = &Bot_buf[0];
5120 x = BOT_UNFOCUS;
5121
5122 while (*beg) {
5123 if (!(end = strchr(beg, Bot_sep)))
5124 end = beg + strlen(beg);
5125 if ((n = end - beg) >= sizeof(tmp))
5126 n = sizeof(tmp) - 1;
5127 memccpy(tmp, beg, '\0', n);
5128 tmp[n] = '\0';
5129 bot_do(tmp, (++x == Bot_indx));
5130 if (*(beg += n))
5131 putchar(*(beg++));
5132 while (*beg == ' ') putchar(*(beg++));
5133 }
5134 return x;
5135 #undef maxRSVD
5136 } // end: bot_focus_str
5137
5138
5139 /*
5140 * This guy draws that bottom window's header |
5141 * & parses/arranges to show vector contents. |
5142 * ( returns relative # of elements printed ) | */
5143 static int bot_focus_strv (const char *hdr, const char **strv) {
5144 #define maxRSVD ( Screen_rows - 1 )
5145 static int nsav;
5146 char tmp[SCREENMAX], *p;
5147 int i, n, x;
5148
5149 if (strv) {
5150 // we're a little careless with overhead here (it's a one time cost)
5151 memset(Bot_buf, '\0', sizeof(Bot_buf));
5152 n = (char *)&strv[0] - strv[0];
5153 if (n >= sizeof(Bot_buf)) n = sizeof(Bot_buf) - 1;
5154 memcpy(Bot_buf, strv[0], n);
5155 if ((!Bot_buf[0] || !strcmp(Bot_buf, "-")) && n <= sizeof(char *))
5156 strcpy(Bot_buf, N_txt(X_BOT_nodata_txt));
5157 for (nsav= 0, p = Bot_buf, x = 0; strv[nsav] != NULL; nsav++) {
5158 p += strlen(strv[nsav]) + 1;
5159 if ((p - Bot_buf) >= sizeof(Bot_buf))
5160 break;
5161 x += utf8_delta(strv[nsav]);
5162 }
5163 n = (p - Bot_buf) - (x + 1);
5164 Bot_rsvd = 1 + BOT_RSVD + (n / Screen_cols);
5165 if (Bot_rsvd > maxRSVD) Bot_rsvd = maxRSVD;
5166 // somewhere down call chain fmtmk() may be used, so we'll old school it
5167 snprintf(tmp, sizeof(tmp), "%s%s%-*s"
5168 , tg2(0, SCREEN_ROWS)
5169 , Curwin->capclr_hdr
5170 , Screen_cols + utf8_delta(hdr)
5171 , hdr);
5172 putp(tmp);
5173 }
5174 // now fmtmk is safe to use ...
5175 putp(fmtmk("%s%s%s", tg2(0, SCREEN_ROWS + 1), Cap_clr_eos, Cap_norm));
5176
5177 p = Bot_buf;
5178 x = BOT_UNFOCUS;
5179
5180 for (i = 0; i < nsav; i++) {
5181 bot_do(p, (++x == Bot_indx));
5182 p += strlen(p) + 1;
5183 putchar(' ');
5184 }
5185 return x;
5186 #undef maxRSVD
5187 } // end: bot_focus_strv
5188
5189
5190 static struct {
5191 enum pflag this;
5192 enum namespace_type that;
5193 } ns_tab[] = {
5194 // careful, cgroup & time were late additions ...
5195 { EU_NS7, PROCPS_NS_CGROUP }, { EU_NS1, PROCPS_NS_IPC },
5196 { EU_NS2, PROCPS_NS_MNT }, { EU_NS3, PROCPS_NS_NET },
5197 { EU_NS4, PROCPS_NS_PID }, { EU_NS8, PROCPS_NS_TIME },
5198 { EU_NS5, PROCPS_NS_USER }, { EU_NS6, PROCPS_NS_UTS }
5199 };
5200
5201
5202 /*
5203 * A helper function that will gather various |
5204 * stuff for display by the bot_item_show guy. | */
5205 static void *bot_item_hlp (struct pids_stack *p) {
5206 static char buf[BIGBUFSIZ];
5207 char tmp[SMLBUFSIZ], *b;
5208 struct msg_node *m;
5209 int i;
5210
5211 switch (Bot_what) {
5212 case BOT_MSG_LOG:
5213 *(b = &buf[0]) = '\0';
5214 m = Msg_this->prev;
5215 do {
5216 if (m->msg[0]) {
5217 b = scat(b, m->msg);
5218 if (m != Msg_this && m->prev->msg[0]) {
5219 // caller itself may have used fmtmk, so we'll old school it ...
5220 snprintf(tmp, sizeof(tmp), "%c ", BOT_SEP_SMI);
5221 b = scat(b, tmp);
5222 }
5223 }
5224 m = m->prev;
5225 } while (m != Msg_this->prev);
5226 return buf;
5227 case BOT_ITEM_NS:
5228 *(b = &buf[0]) = '\0';
5229 for (i = 0; i < MAXTBL(ns_tab); i++) {
5230 // caller itself may have used fmtmk, so we'll old school it ...
5231 snprintf(tmp, sizeof(tmp), "%s: %-10lu"
5232 , procps_ns_get_name(ns_tab[i].that)
5233 , PID_VAL(ns_tab[i].this, ul_int, p));
5234 b = scat(b, tmp);
5235 if (i < (MAXTBL(ns_tab) - 1)) b = scat(b, ", ");
5236 }
5237 return buf;
5238 case eu_CMDLINE_V:
5239 case eu_ENVIRON_V:
5240 return p->head[Bot_item[0]].result.strv;
5241 default:
5242 return p->head[Bot_item[0]].result.str;
5243 }
5244 } // end: bot_item_hlp
5245
5246
5247 /*
5248 * This guy manages that bottom margin window |
5249 * which shows various process related stuff. | */
5250 static void bot_item_show (void) {
5251 #define mkHDR fmtmk(Bot_head, Bot_task, PID_VAL(EU_CMD, str, p))
5252 struct pids_stack *p;
5253 int i;
5254
5255 for (i = 0; i < PIDSmaxt; i++) {
5256 p = Curwin->ppt[i];
5257 if (Bot_task == PID_VAL(EU_PID, s_int, p))
5258 break;
5259 }
5260 if (i < PIDSmaxt) {
5261 Bot_focus_func(mkHDR, bot_item_hlp(p));
5262 }
5263 #ifdef BOT_DEAD_ZAP
5264 else
5265 BOT_TOSS;
5266 #else
5267 BOT_KEEP;
5268 #endif
5269 #undef mkHDR
5270 } // end: bot_item_show
5271
5272
5273 /*
5274 * This guy can toggle between displaying the |
5275 * bottom window or arranging to turn it off. | */
5276 static void bot_item_toggle (int what, const char *head, char sep) {
5277 int i;
5278
5279 // if already targeted, assume user wants to turn it off ...
5280 if (Bot_what == what) {
5281 BOT_TOSS;
5282 } else {
5283 // accommodate transition from larger to smaller window
5284 Bot_rsvd = 0;
5285 switch (what) {
5286 case BOT_ITEM_NS:
5287 for (i = 0; i < MAXTBL(ns_tab); i++)
5288 Bot_item[i] = ns_tab[i].this;
5289 Bot_item[i] = BOT_DELIMIT;
5290 Bot_focus_func = (BOT_f)bot_focus_str;
5291 break;
5292 case eu_CMDLINE_V:
5293 case eu_ENVIRON_V:
5294 Bot_item[0] = what;
5295 Bot_item[1] = BOT_DELIMIT;
5296 Bot_focus_func = (BOT_f)bot_focus_strv;
5297 break;
5298 default:
5299 Bot_item[0] = what;
5300 Bot_item[1] = BOT_DELIMIT;
5301 Bot_focus_func = (BOT_f)bot_focus_str;
5302 break;
5303 }
5304 Bot_sep = sep;
5305 Bot_what = what;
5306 Bot_indx = BOT_UNFOCUS;
5307 Bot_head = (char *)head;
5308 Bot_show_func = bot_item_show;
5309 Bot_task = PID_VAL(EU_PID, s_int, Curwin->ppt[Curwin->begtask]);
5310 }
5311 } // end: bot_item_toggle
5312
5313 /*###### Interactive Input Tertiary support ############################*/
5314
5315 /*
5316 * This section exists so as to offer some function naming freedom
5317 * while also maintaining the strict alphabetical order protocol
5318 * within each section. */
5319
5320 /*
5321 * This guy is a *Helper* function serving the following two masters:
5322 * find_string() - find the next match in a given window
5323 * task_show() - highlight all matches currently in-view
5324 * If q->findstr is found in the designated buffer, he returns the
5325 * offset from the start of the buffer, otherwise he returns -1. */
5326 static inline int find_ofs (const WIN_t *q, const char *buf) {
5327 char *fnd;
5328
5329 if (q->findstr[0] && (fnd = STRSTR(buf, q->findstr)))
5330 return (int)(fnd - buf);
5331 return -1;
5332 } // end: find_ofs
5333
5334
5335
5336 /* This is currently the only true prototype required by top.
5337 It is placed here, instead of top.h, to avoid one compiler
5338 warning when the top_nls.c source was compiled separately. */
5339 static const char *task_show (const WIN_t *q, int idx);
5340
5341 static void find_string (int ch) {
5342 #define reDUX (found) ? N_txt(WORD_another_txt) : ""
5343 static int found;
5344 int i;
5345
5346 if ('&' == ch && !Curwin->findstr[0]) {
5347 show_msg(N_txt(FIND_no_next_txt));
5348 return;
5349 }
5350 if ('L' == ch) {
5351 char *str = ioline(N_txt(GET_find_str_txt));
5352 if (*str == kbd_ESC) return;
5353 snprintf(Curwin->findstr, FNDBUFSIZ, "%s", str);
5354 Curwin->findlen = strlen(Curwin->findstr);
5355 found = 0;
5356 }
5357 if (Curwin->findstr[0]) {
5358 SETw(Curwin, NOPRINT_xxx);
5359 for (i = Curwin->begtask; i < PIDSmaxt; i++) {
5360 const char *row = task_show(Curwin, i);
5361 if (*row && -1 < find_ofs(Curwin, row)) {
5362 found = 1;
5363 if (i == Curwin->begtask) continue;
5364 Curwin->begtask = i;
5365 return;
5366 }
5367 }
5368 show_msg(fmtmk(N_fmt(FIND_no_find_fmt), reDUX, Curwin->findstr));
5369 }
5370 #undef reDUX
5371 } // end: find_string
5372
5373
5374 static void help_view (void) {
5375 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
5376 char key = 1;
5377
5378 putp((Cursor_state = Cap_curs_huge));
5379 signify_that:
5380 putp(Cap_clr_scr);
5381 adj_geometry();
5382
5383 show_special(1, fmtmk(N_unq(KEYS_helpbas_fmt)
5384 , PACKAGE_STRING
5385 , w->grpname
5386 , CHKw(w, Show_CTIMES) ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)
5387 , Rc.delay_time
5388 , Secure_mode ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)
5389 , Secure_mode ? "" : N_unq(KEYS_helpext_fmt)));
5390 putp(Cap_clr_eos);
5391 fflush(stdout);
5392
5393 if (Frames_signal) goto signify_that;
5394 key = iokey(IOKEY_ONCE);
5395 if (key < 1) goto signify_that;
5396
5397 switch (key) {
5398 // these keys serve the primary help screen
5399 case kbd_ESC: case 'q':
5400 break;
5401 case '?': case 'h': case 'H':
5402 do {
5403 signify_this:
5404 putp(Cap_clr_scr);
5405 adj_geometry();
5406 show_special(1, fmtmk(N_unq(WINDOWS_help_fmt)
5407 , w->grpname
5408 , Winstk[0].rc.winname, Winstk[1].rc.winname
5409 , Winstk[2].rc.winname, Winstk[3].rc.winname));
5410 putp(Cap_clr_eos);
5411 fflush(stdout);
5412 if (Frames_signal || (key = iokey(IOKEY_ONCE)) < 1)
5413 goto signify_this;
5414 else w = win_select(key);
5415 // these keys serve the secondary help screen
5416 } while (key != kbd_ENTER && key != kbd_ESC && key != 'q');
5417 break;
5418 default:
5419 goto signify_that;
5420 }
5421 // signal that we just corrupted entire screen
5422 Frames_signal = BREAK_screen;
5423 } // end: help_view
5424
5425
5426 static void other_filters (int ch) {
5427 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
5428 const char *txt, *p;
5429 char *glob;
5430
5431 switch (ch) {
5432 case 'o':
5433 case 'O':
5434 if (ch == 'o') txt = N_txt(OSEL_casenot_txt);
5435 else txt = N_txt(OSEL_caseyes_txt);
5436 glob = ioline(fmtmk(N_fmt(OSEL_prompts_fmt), w->osel_tot + 1, txt));
5437 if (*glob == kbd_ESC || *glob == '\0')
5438 return;
5439 if ((p = osel_add(w, ch, glob, 1))) {
5440 show_msg(p);
5441 return;
5442 }
5443 break;
5444 case kbd_CtrlO:
5445 if (VIZCHKw(w)) {
5446 char buf[SCREENMAX], **pp;
5447 struct osel_s *osel;
5448 int i;
5449
5450 i = 0;
5451 osel = w->osel_1st;
5452 pp = alloc_c((w->osel_tot + 1) * sizeof(char *));
5453 while (osel && i < w->osel_tot) {
5454 pp[i++] = osel->raw;
5455 osel = osel->nxt;
5456 }
5457 buf[0] = '\0';
5458 for ( ; i > 0; )
5459 strncat(buf, fmtmk("%s'%s'", " + " , pp[--i]), sizeof(buf) - (strlen(buf) + 1));
5460 if (buf[0]) p = buf + strspn(buf, " + ");
5461 else p = N_txt(WORD_noneone_txt);
5462 ioline(fmtmk(N_fmt(OSEL_statlin_fmt), p));
5463 free(pp);
5464 }
5465 break;
5466 default: // keep gcc happy
5467 break;
5468 }
5469 } // end: other_filters
5470
5471
5472 static void write_rcfile (void) {
5473 FILE *fp;
5474 int i, j, n;
5475
5476 if (Rc_questions) {
5477 show_pmt(N_txt(XTRA_warncfg_txt));
5478 if ('y' != tolower(iokey(IOKEY_ONCE)))
5479 return;
5480 Rc_questions = 0;
5481 }
5482 if (Rc_compatibilty) {
5483 show_pmt(N_txt(XTRA_warnold_txt));
5484 if ('y' != tolower(iokey(IOKEY_ONCE)))
5485 return;
5486 Rc_compatibilty = 0;
5487 }
5488 if (!(fp = fopen(Rc_name, "w"))) {
5489 show_msg(fmtmk(N_fmt(FAIL_rc_open_fmt), Rc_name, strerror(errno)));
5490 return;
5491 }
5492 fprintf(fp, "%s's " RCF_EYECATCHER, Myname);
5493 fprintf(fp, "Id:%c, Mode_altscr=%d, Mode_irixps=%d, Delay_time=%d.%d, Curwin=%d\n"
5494 , RCF_VERSION_ID
5495 , Rc.mode_altscr, Rc.mode_irixps
5496 // this may be ugly, but it keeps us locale independent...
5497 , (int)Rc.delay_time, (int)((Rc.delay_time - (int)Rc.delay_time) * 1000)
5498 , (int)(Curwin - Winstk));
5499
5500 for (i = 0 ; i < GROUPSMAX; i++) {
5501 n = mlen(Winstk[i].rc.fieldscur);
5502 fprintf(fp, "%s\tfieldscur=", Winstk[i].rc.winname);
5503 for (j = 0; j < n; j++) {
5504 if (j && !(j % FLD_ROWMAX) && j < n)
5505 fprintf(fp, "\n\t\t ");
5506 fprintf(fp, "%4d ", (int)Winstk[i].rc.fieldscur[j]);
5507 }
5508 fprintf(fp, "\n");
5509 fprintf(fp, "\twinflags=%d, sortindx=%d, maxtasks=%d, graph_cpus=%d, graph_mems=%d"
5510 ", double_up=%d, combine_cpus=%d, core_types=%d\n"
5511 , Winstk[i].rc.winflags, Winstk[i].rc.sortindx, Winstk[i].rc.maxtasks
5512 , Winstk[i].rc.graph_cpus, Winstk[i].rc.graph_mems, Winstk[i].rc.double_up
5513 , Winstk[i].rc.combine_cpus, Winstk[i].rc.core_types);
5514 fprintf(fp, "\tsummclr=%d, msgsclr=%d, headclr=%d, taskclr=%d\n"
5515 , Winstk[i].rc.summclr, Winstk[i].rc.msgsclr
5516 , Winstk[i].rc.headclr, Winstk[i].rc.taskclr);
5517 }
5518
5519 // any new addition(s) last, for older rcfiles compatibility...
5520 fprintf(fp, "Fixed_widest=%d, Summ_mscale=%d, Task_mscale=%d, Zero_suppress=%d, Tics_scaled=%d\n"
5521 , Rc.fixed_widest, Rc.summ_mscale, Rc.task_mscale, Rc.zero_suppress, Rc.tics_scaled);
5522
5523 if (Winstk[0].osel_tot + Winstk[1].osel_tot
5524 + Winstk[2].osel_tot + Winstk[3].osel_tot) {
5525 fprintf(fp, "\n");
5526 fprintf(fp, Osel_delim_1_txt);
5527 for (i = 0 ; i < GROUPSMAX; i++) {
5528 struct osel_s *osel = Winstk[i].osel_1st;
5529 if (osel) {
5530 fprintf(fp, Osel_window_fmts, i, Winstk[i].osel_tot);
5531 do {
5532 fprintf(fp, Osel_filterO_fmt, osel->typ, osel->raw);
5533 osel = osel->nxt;
5534 } while (osel);
5535 }
5536 }
5537 fprintf(fp, Osel_delim_2_txt);
5538 }
5539
5540 if (Inspect.raw && strcmp(Inspect.raw, "\n"))
5541 fputs(Inspect.raw, fp);
5542
5543 fclose(fp);
5544 show_msg(fmtmk(N_fmt(WRITE_rcfile_fmt), Rc_name));
5545 } // end: write_rcfile
5546
5547 /*###### Interactive Input Secondary support (do_key helpers) ##########*/
5548
5549 /*
5550 * These routines exist just to keep the do_key() function
5551 * a reasonably modest size. */
5552
5553 static void keys_global (int ch) {
5554 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
5555 int i, num, def, pid;
5556
5557 switch (ch) {
5558 case '?':
5559 case 'h':
5560 help_view();
5561 break;
5562 case 'B':
5563 TOGw(w, View_NOBOLD);
5564 capsmk(w);
5565 break;
5566 case 'd':
5567 case 's':
5568 if (Secure_mode)
5569 show_msg(N_txt(NOT_onsecure_txt));
5570 else {
5571 float tmp =
5572 get_float(fmtmk(N_fmt(DELAY_change_fmt), Rc.delay_time));
5573 if (tmp > -1) Rc.delay_time = tmp;
5574 }
5575 break;
5576 case 'E':
5577 if (++Rc.summ_mscale > SK_Eb) Rc.summ_mscale = SK_Kb;
5578 break;
5579 case 'e':
5580 if (++Rc.task_mscale > SK_Pb) Rc.task_mscale = SK_Kb;
5581 break;
5582 case 'f':
5583 fields_utility();
5584 break;
5585 case 'g':
5586 win_select(0);
5587 break;
5588 case 'H':
5589 Thread_mode = !Thread_mode;
5590 if (!CHKw(w, View_STATES))
5591 show_msg(fmtmk(N_fmt(THREADS_show_fmt)
5592 , Thread_mode ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)));
5593 for (i = 0 ; i < GROUPSMAX; i++)
5594 Winstk[i].begtask = Winstk[i].focus_pid = 0;
5595 // force an extra procs refresh to avoid %cpu distortions...
5596 Pseudo_row = PROC_XTRA;
5597 // signal that we just corrupted entire screen
5598 Frames_signal = BREAK_screen;
5599 break;
5600 case 'I':
5601 if (Cpu_cnt > 1) {
5602 Rc.mode_irixps = !Rc.mode_irixps;
5603 show_msg(fmtmk(N_fmt(IRIX_curmode_fmt)
5604 , Rc.mode_irixps ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)));
5605 } else
5606 show_msg(N_txt(NOT_smp_cpus_txt));
5607 break;
5608 case 'k':
5609 if (Secure_mode)
5610 show_msg(N_txt(NOT_onsecure_txt));
5611 else {
5612 num = SIGTERM;
5613 def = PID_VAL(EU_PID, s_int, w->ppt[w->begtask]);
5614 pid = get_int(fmtmk(N_txt(GET_pid2kill_fmt), def));
5615 if (pid > GET_NUM_ESC) {
5616 char *str;
5617 if (pid == GET_NUM_NOT) pid = def;
5618 str = ioline(fmtmk(N_fmt(GET_sigs_num_fmt), pid, SIGTERM));
5619 if (*str != kbd_ESC) {
5620 if (*str) num = signal_name_to_number(str);
5621 if (Frames_signal) break;
5622 if (0 < num && kill(pid, num))
5623 show_msg(fmtmk(N_fmt(FAIL_signals_fmt)
5624 , pid, num, strerror(errno)));
5625 else if (0 > num) show_msg(N_txt(BAD_signalid_txt));
5626 }
5627 }
5628 }
5629 break;
5630 case 'r':
5631 if (Secure_mode)
5632 show_msg(N_txt(NOT_onsecure_txt));
5633 else {
5634 def = PID_VAL(EU_PID, s_int, w->ppt[w->begtask]);
5635 pid = get_int(fmtmk(N_fmt(GET_pid2nice_fmt), def));
5636 if (pid > GET_NUM_ESC) {
5637 if (pid == GET_NUM_NOT) pid = def;
5638 num = get_int(fmtmk(N_fmt(GET_nice_num_fmt), pid));
5639 if (num > GET_NUM_NOT
5640 && setpriority(PRIO_PROCESS, (unsigned)pid, num))
5641 show_msg(fmtmk(N_fmt(FAIL_re_nice_fmt)
5642 , pid, num, strerror(errno)));
5643 }
5644 }
5645 break;
5646 case 'X':
5647 num = get_int(fmtmk(N_fmt(XTRA_fixwide_fmt), Rc.fixed_widest));
5648 if (num > GET_NUM_NOT) {
5649 if (num >= 0 && num <= SCREENMAX) Rc.fixed_widest = num;
5650 else Rc.fixed_widest = -1;
5651 }
5652 break;
5653 case 'Y':
5654 if (!Inspect.total)
5655 #ifndef INSP_OFFDEMO
5656 ioline(N_txt(YINSP_noent1_txt));
5657 #else
5658 ioline(N_txt(YINSP_noent2_txt));
5659 #endif
5660 else {
5661 def = PID_VAL(EU_PID, s_int, w->ppt[w->begtask]);
5662 pid = get_int(fmtmk(N_fmt(YINSP_pidsee_fmt), def));
5663 if (pid > GET_NUM_ESC) {
5664 if (pid == GET_NUM_NOT) pid = def;
5665 if (pid) inspection_utility(pid);
5666 }
5667 }
5668 break;
5669 case 'Z':
5670 wins_colors();
5671 break;
5672 case '0':
5673 Rc.zero_suppress = !Rc.zero_suppress;
5674 break;
5675 case kbd_CtrlE:
5676 #ifndef SCALE_FORMER
5677 Rc.tics_scaled++;
5678 if (Rc.tics_scaled > TICS_AS_LAST)
5679 Rc.tics_scaled = 0;
5680 #endif
5681 break;
5682 case kbd_CtrlG:
5683 bot_item_toggle(EU_CGR, N_fmt(X_BOT_ctlgrp_fmt), BOT_SEP_SLS);
5684 break;
5685 case kbd_CtrlI:
5686 if (BOT_PRESENT) {
5687 ++Bot_indx;
5688 if (Bot_indx > Bot_focus_func(NULL, NULL))
5689 Bot_indx = BOT_UNFOCUS;
5690 }
5691 break;
5692 case kbd_CtrlK:
5693 // with string vectors, the 'separator' may serve a different purpose
5694 bot_item_toggle(eu_CMDLINE_V, N_fmt(X_BOT_cmdlin_fmt), BOT_SEP_SPC);
5695 break;
5696 case kbd_CtrlL:
5697 bot_item_toggle(BOT_MSG_LOG, N_txt(X_BOT_msglog_txt), BOT_SEP_SMI);
5698 break;
5699 case kbd_CtrlN:
5700 // with string vectors, the 'separator' may serve a different purpose
5701 bot_item_toggle(eu_ENVIRON_V, N_fmt(X_BOT_envirn_fmt), BOT_SEP_SPC);
5702 break;
5703 case kbd_CtrlP:
5704 bot_item_toggle(BOT_ITEM_NS, N_fmt(X_BOT_namesp_fmt), BOT_SEP_CMA);
5705 break;
5706 case kbd_CtrlR:
5707 if (Secure_mode)
5708 show_msg(N_txt(NOT_onsecure_txt));
5709 else {
5710 def = PID_VAL(EU_PID, s_int, w->ppt[w->begtask]);
5711 pid = get_int(fmtmk(N_fmt(GET_pid2nice_fmt), def));
5712 if (pid > GET_NUM_ESC) {
5713 int fd;
5714 if (pid == GET_NUM_NOT) pid = def;
5715 num = get_int(fmtmk(N_fmt(AGNI_valueof_fmt), pid));
5716 if (num > GET_NUM_NOT) {
5717 if (num < -20 || num > +19)
5718 show_msg(N_txt(AGNI_invalid_txt));
5719 else if (0 > (fd = open(fmtmk("/proc/%d/autogroup", pid), O_WRONLY)))
5720 show_msg(fmtmk(N_fmt(AGNI_notopen_fmt), strerror(errno)));
5721 else {
5722 char buf[TNYBUFSIZ];
5723 snprintf(buf, sizeof(buf), "%d", num);
5724 if (0 >= write(fd, buf, strlen(buf)))
5725 show_msg(fmtmk(N_fmt(AGNI_nowrite_fmt), strerror(errno)));
5726 close(fd);
5727 }
5728 }
5729 }
5730 }
5731 break;
5732 case kbd_CtrlU:
5733 bot_item_toggle(EU_SGN, N_fmt(X_BOT_supgrp_fmt), BOT_SEP_CMA);
5734 break;
5735 case kbd_BTAB:
5736 if (BOT_PRESENT) {
5737 --Bot_indx;
5738 num = Bot_focus_func(NULL, NULL);
5739 if (Bot_indx <= BOT_UNFOCUS)
5740 Bot_indx = num + 1;
5741 }
5742 break;
5743 case kbd_ENTER: // these two have the effect of waking us
5744 case kbd_SPACE: // from 'pselect', refreshing the display
5745 break; // and updating any hot-plugged resources
5746 default: // keep gcc happy
5747 break;
5748 }
5749 } // end: keys_global
5750
5751
5752 static void keys_summary (int ch) {
5753 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
5754
5755 if (Restrict_some && ch != 'C') {
5756 show_msg(N_txt(X_RESTRICTED_txt));
5757 return;
5758 }
5759 switch (ch) {
5760 case '!':
5761 if (CHKw(w, View_CPUSUM) || CHKw(w, View_CPUNOD))
5762 show_msg(N_txt(XTRA_modebad_txt));
5763 else {
5764 if (!w->rc.combine_cpus) w->rc.combine_cpus = 2;
5765 else w->rc.combine_cpus *= 2;
5766 if (w->rc.combine_cpus >= Cpu_cnt) w->rc.combine_cpus = 0;
5767 w->rc.core_types = 0;
5768 }
5769 break;
5770 case '1':
5771 if (CHKw(w, View_CPUNOD)) OFFw(w, View_CPUSUM);
5772 else TOGw(w, View_CPUSUM);
5773 OFFw(w, View_CPUNOD);
5774 SETw(w, View_STATES);
5775 w->rc.double_up = 0;
5776 w->rc.core_types = 0;
5777 break;
5778 case '2':
5779 if (!Numa_node_tot)
5780 show_msg(N_txt(NUMA_nodenot_txt));
5781 else {
5782 if (Numa_node_sel < 0) TOGw(w, View_CPUNOD);
5783 if (!CHKw(w, View_CPUNOD)) SETw(w, View_CPUSUM);
5784 SETw(w, View_STATES);
5785 Numa_node_sel = -1;
5786 w->rc.double_up = 0;
5787 w->rc.core_types = 0;
5788 }
5789 break;
5790 case '3':
5791 if (!Numa_node_tot)
5792 show_msg(N_txt(NUMA_nodenot_txt));
5793 else {
5794 int num = get_int(fmtmk(N_fmt(NUMA_nodeget_fmt), Numa_node_tot -1));
5795 if (num > GET_NUM_NOT) {
5796 if (num >= 0 && num < Numa_node_tot) {
5797 Numa_node_sel = num;
5798 SETw(w, View_CPUNOD | View_STATES);
5799 OFFw(w, View_CPUSUM);
5800 w->rc.double_up = 0;
5801 w->rc.core_types = 0;
5802 } else
5803 show_msg(N_txt(NUMA_nodebad_txt));
5804 }
5805 }
5806 break;
5807 case '4':
5808 w->rc.double_up += 1;
5809 if ((w->rc.double_up >= ADJOIN_limit)
5810 || ((w->rc.double_up >= Cpu_cnt)))
5811 w->rc.double_up = 0;
5812 if ((w->rc.double_up > 1)
5813 && (!w->rc.graph_cpus))
5814 w->rc.double_up = 0;
5815 OFFw(w, (View_CPUSUM | View_CPUNOD));
5816 break;
5817 #ifndef CORE_TYPE_NO
5818 case '5':
5819 if (!CHKw(w, View_STATES)
5820 || ((CHKw(w, View_CPUSUM | View_CPUNOD))
5821 || ((w->rc.combine_cpus))))
5822 show_msg(N_txt(XTRA_modebad_txt));
5823 else {
5824 int scanned;
5825 for (scanned = 0; scanned < Cpu_cnt; scanned++)
5826 if (CPU_VAL(stat_COR_TYP, scanned) == E_CORE)
5827 break;
5828 if (scanned < Cpu_cnt) {
5829 w->rc.core_types += 1;
5830 if (w->rc.core_types > E_CORES_ONLY)
5831 w->rc.core_types = 0;
5832 } else w->rc.core_types = 0;
5833 }
5834 break;
5835 #endif
5836 case 'C':
5837 VIZTOGw(w, View_SCROLL);
5838 break;
5839 case 'l':
5840 TOGw(w, View_LOADAV);
5841 break;
5842 case 'm':
5843 if (!CHKw(w, View_MEMORY))
5844 SETw(w, View_MEMORY);
5845 else if (++w->rc.graph_mems > 2) {
5846 w->rc.graph_mems = 0;
5847 OFFw(w, View_MEMORY);
5848 }
5849 break;
5850 case 't':
5851 if (!CHKw(w, View_STATES))
5852 SETw(w, View_STATES);
5853 else if (++w->rc.graph_cpus > 2) {
5854 w->rc.graph_cpus = 0;
5855 OFFw(w, View_STATES);
5856 }
5857 if ((w->rc.double_up > 1)
5858 && (!w->rc.graph_cpus))
5859 w->rc.double_up = 0;
5860 break;
5861 default: // keep gcc happy
5862 break;
5863 }
5864 } // end: keys_summary
5865
5866
5867 static void keys_task (int ch) {
5868 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
5869
5870 switch (ch) {
5871 case '#':
5872 case 'n':
5873 if (VIZCHKw(w)) {
5874 int num = get_int(fmtmk(N_fmt(GET_max_task_fmt), w->rc.maxtasks));
5875 if (num > GET_NUM_NOT) {
5876 if (-1 < num ) w->rc.maxtasks = num;
5877 else show_msg(N_txt(BAD_max_task_txt));
5878 }
5879 }
5880 break;
5881 case '<':
5882 #ifdef TREE_NORESET
5883 if (CHKw(w, Show_FOREST)) break;
5884 #endif
5885 if (VIZCHKw(w)) {
5886 FLG_t *p = w->procflgs + w->maxpflgs - 1;
5887 while (p > w->procflgs && *p != w->rc.sortindx) --p;
5888 if (*p == w->rc.sortindx) {
5889 --p;
5890 #ifndef USE_X_COLHDR
5891 if (EU_MAXPFLGS < *p) --p;
5892 #endif
5893 if (p >= w->procflgs) {
5894 w->rc.sortindx = *p;
5895 #ifndef TREE_NORESET
5896 OFFw(w, Show_FOREST);
5897 #endif
5898 }
5899 }
5900 }
5901 break;
5902 case '>':
5903 #ifdef TREE_NORESET
5904 if (CHKw(w, Show_FOREST)) break;
5905 #endif
5906 if (VIZCHKw(w)) {
5907 FLG_t *p = w->procflgs + w->maxpflgs - 1;
5908 while (p > w->procflgs && *p != w->rc.sortindx) --p;
5909 if (*p == w->rc.sortindx) {
5910 ++p;
5911 #ifndef USE_X_COLHDR
5912 if (EU_MAXPFLGS < *p) ++p;
5913 #endif
5914 if (p < w->procflgs + w->maxpflgs) {
5915 w->rc.sortindx = *p;
5916 #ifndef TREE_NORESET
5917 OFFw(w, Show_FOREST);
5918 #endif
5919 }
5920 }
5921 }
5922 break;
5923 case 'b':
5924 TOGw(w, Show_HIBOLD);
5925 capsmk(w);
5926 break;
5927 case 'c':
5928 VIZTOGw(w, Show_CMDLIN);
5929 break;
5930 case 'F':
5931 if (VIZCHKw(w)) {
5932 if (CHKw(w, Show_FOREST)) {
5933 int n = PID_VAL(EU_PID, s_int, w->ppt[w->begtask]);
5934 if (w->focus_pid == n) w->focus_pid = 0;
5935 else w->focus_pid = n;
5936 }
5937 }
5938 break;
5939 case 'i':
5940 { static WIN_t *w_sav;
5941 static int beg_sav;
5942 if (w_sav != w) { beg_sav = 0; w_sav = w; }
5943 if (CHKw(w, Show_IDLEPS)) { beg_sav = w->begtask; w->begtask = 0; }
5944 else { w->begtask = beg_sav; beg_sav = 0; }
5945 }
5946 VIZTOGw(w, Show_IDLEPS);
5947 break;
5948 case 'J':
5949 VIZTOGw(w, Show_JRNUMS);
5950 break;
5951 case 'j':
5952 VIZTOGw(w, Show_JRSTRS);
5953 break;
5954 case 'R':
5955 #ifdef TREE_NORESET
5956 if (!CHKw(w, Show_FOREST)) VIZTOGw(w, Qsrt_NORMAL);
5957 #else
5958 if (VIZCHKw(w)) {
5959 TOGw(w, Qsrt_NORMAL);
5960 OFFw(w, Show_FOREST);
5961 }
5962 #endif
5963 break;
5964 case 'S':
5965 if (VIZCHKw(w)) {
5966 TOGw(w, Show_CTIMES);
5967 show_msg(fmtmk(N_fmt(TIME_accumed_fmt) , CHKw(w, Show_CTIMES)
5968 ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)));
5969 }
5970 break;
5971 case 'O':
5972 case 'o':
5973 case kbd_CtrlO:
5974 if (VIZCHKw(w)) other_filters(ch);
5975 break;
5976 case 'U':
5977 case 'u':
5978 if (VIZCHKw(w)) {
5979 const char *errmsg, *str = ioline(N_txt(GET_user_ids_txt));
5980 if (*str != kbd_ESC
5981 && (errmsg = user_certify(w, str, ch)))
5982 show_msg(errmsg);
5983 }
5984 break;
5985 case 'V':
5986 if (VIZCHKw(w)) {
5987 TOGw(w, Show_FOREST);
5988 if (!ENUviz(w, EU_CMD))
5989 show_msg(fmtmk(N_fmt(FOREST_modes_fmt) , CHKw(w, Show_FOREST)
5990 ? N_txt(ON_word_only_txt) : N_txt(OFF_one_word_txt)));
5991 if (!CHKw(w, Show_FOREST)) w->focus_pid = 0;
5992 }
5993 break;
5994 case 'v':
5995 if (VIZCHKw(w)) {
5996 if (CHKw(w, Show_FOREST)) {
5997 int i, pid = PID_VAL(EU_PID, s_int, w->ppt[w->begtask]);
5998 #ifdef TREE_VPROMPT
5999 int got = get_int(fmtmk(N_txt(XTRA_vforest_fmt), pid));
6000 if (got < GET_NUM_NOT) break;
6001 if (got > GET_NUM_NOT) pid = got;
6002 #endif
6003 for (i = 0; i < Hide_tot; i++) {
6004 if (Hide_pid[i] == pid || Hide_pid[i] == -pid) {
6005 Hide_pid[i] = -Hide_pid[i];
6006 break;
6007 }
6008 }
6009 if (i == Hide_tot) {
6010 static int totsav;
6011 if (Hide_tot >= totsav) {
6012 totsav += 128;
6013 Hide_pid = alloc_r(Hide_pid, sizeof(int) * totsav);
6014 }
6015 Hide_pid[Hide_tot++] = pid;
6016 } else {
6017 // if everything's expanded, let's empty the array ...
6018 for (i = 0; i < Hide_tot; i++)
6019 if (Hide_pid[i] > 0) break;
6020 if (i == Hide_tot) Hide_tot = 0;
6021 }
6022 }
6023 }
6024 break;
6025 case 'x':
6026 if (VIZCHKw(w)) {
6027 #ifdef USE_X_COLHDR
6028 TOGw(w, Show_HICOLS);
6029 capsmk(w);
6030 #else
6031 if (ENUviz(w, w->rc.sortindx)) {
6032 TOGw(w, Show_HICOLS);
6033 if (ENUpos(w, w->rc.sortindx) < w->begpflg) {
6034 if (CHKw(w, Show_HICOLS)) w->begpflg += 2;
6035 else w->begpflg -= 2;
6036 if (0 > w->begpflg) w->begpflg = 0;
6037 }
6038 capsmk(w);
6039 }
6040 #endif
6041 }
6042 break;
6043 case 'y':
6044 if (VIZCHKw(w)) {
6045 TOGw(w, Show_HIROWS);
6046 capsmk(w);
6047 }
6048 break;
6049 case 'z':
6050 if (VIZCHKw(w)) {
6051 TOGw(w, Show_COLORS);
6052 capsmk(w);
6053 }
6054 break;
6055 default: // keep gcc happy
6056 break;
6057 }
6058 } // end: keys_task
6059
6060
6061 static void keys_window (int ch) {
6062 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
6063
6064 switch (ch) {
6065 case '+':
6066 if (ALTCHKw) wins_reflag(Flags_OFF, EQUWINS_xxx);
6067 Hide_tot = 0;
6068 break;
6069 case '-':
6070 if (ALTCHKw) TOGw(w, Show_TASKON);
6071 break;
6072 case '=':
6073 win_reset(w);
6074 Hide_tot = 0;
6075 break;
6076 case '_':
6077 if (ALTCHKw) wins_reflag(Flags_TOG, Show_TASKON);
6078 break;
6079 case '&':
6080 case 'L':
6081 if (VIZCHKw(w)) find_string(ch);
6082 break;
6083 case 'A':
6084 Rc.mode_altscr = !Rc.mode_altscr;
6085 break;
6086 case 'a':
6087 case 'w':
6088 if (ALTCHKw) win_select(ch);
6089 break;
6090 case 'G':
6091 if (ALTCHKw) {
6092 char tmp[SMLBUFSIZ];
6093 STRLCPY(tmp, ioline(fmtmk(N_fmt(NAME_windows_fmt), w->rc.winname)));
6094 if (tmp[0] && tmp[0] != kbd_ESC) win_names(w, tmp);
6095 }
6096 break;
6097 case kbd_UP:
6098 if (VIZCHKw(w)) if (CHKw(w, Show_IDLEPS)) mkVIZrowX(-1)
6099 break;
6100 case kbd_DOWN:
6101 if (VIZCHKw(w)) if (CHKw(w, Show_IDLEPS)) mkVIZrowX(+1)
6102 break;
6103 #ifdef USE_X_COLHDR // ------------------------------------
6104 case kbd_LEFT:
6105 #ifndef SCROLLVAR_NO
6106 if (VIZCHKw(w)) {
6107 if (VARleft(w))
6108 w->varcolbeg -= SCROLLAMT;
6109 else if (0 < w->begpflg)
6110 w->begpflg -= 1;
6111 }
6112 #else
6113 if (VIZCHKw(w)) if (0 < w->begpflg) w->begpflg -= 1;
6114 #endif
6115 break;
6116 case kbd_RIGHT:
6117 #ifndef SCROLLVAR_NO
6118 if (VIZCHKw(w)) {
6119 if (VARright(w)) {
6120 w->varcolbeg += SCROLLAMT;
6121 if (0 > w->varcolbeg) w->varcolbeg = 0;
6122 } else if (w->begpflg + 1 < w->totpflgs)
6123 w->begpflg += 1;
6124 }
6125 #else
6126 if (VIZCHKw(w)) if (w->begpflg + 1 < w->totpflgs) w->begpflg += 1;
6127 #endif
6128 break;
6129 #else // USE_X_COLHDR ------------------------------------
6130 case kbd_LEFT:
6131 #ifndef SCROLLVAR_NO
6132 if (VIZCHKw(w)) {
6133 if (VARleft(w))
6134 w->varcolbeg -= SCROLLAMT;
6135 else if (0 < w->begpflg) {
6136 w->begpflg -= 1;
6137 if (EU_MAXPFLGS < w->pflgsall[w->begpflg]) w->begpflg -= 2;
6138 }
6139 }
6140 #else
6141 if (VIZCHKw(w)) if (0 < w->begpflg) {
6142 w->begpflg -= 1;
6143 if (EU_MAXPFLGS < w->pflgsall[w->begpflg]) w->begpflg -= 2;
6144 }
6145 #endif
6146 break;
6147 case kbd_RIGHT:
6148 #ifndef SCROLLVAR_NO
6149 if (VIZCHKw(w)) {
6150 if (VARright(w)) {
6151 w->varcolbeg += SCROLLAMT;
6152 if (0 > w->varcolbeg) w->varcolbeg = 0;
6153 } else if (w->begpflg + 1 < w->totpflgs) {
6154 if (EU_MAXPFLGS < w->pflgsall[w->begpflg])
6155 w->begpflg += (w->begpflg + 3 < w->totpflgs) ? 3 : 0;
6156 else w->begpflg += 1;
6157 }
6158 }
6159 #else
6160 if (VIZCHKw(w)) if (w->begpflg + 1 < w->totpflgs) {
6161 if (EU_MAXPFLGS < w->pflgsall[w->begpflg])
6162 w->begpflg += (w->begpflg + 3 < w->totpflgs) ? 3 : 0;
6163 else w->begpflg += 1;
6164 }
6165 #endif
6166 break;
6167 #endif // USE_X_COLHDR ------------------------------------
6168 case kbd_PGUP:
6169 if (VIZCHKw(w)) {
6170 if (CHKw(w, Show_IDLEPS) && 0 < w->begtask) {
6171 mkVIZrowX(-(w->winlines - (Rc.mode_altscr ? 1 : 2)))
6172 }
6173 }
6174 break;
6175 case kbd_PGDN:
6176 if (VIZCHKw(w)) {
6177 if (CHKw(w, Show_IDLEPS) && w->begtask < PIDSmaxt - 1) {
6178 mkVIZrowX(+(w->winlines - (Rc.mode_altscr ? 1 : 2)))
6179 }
6180 }
6181 break;
6182 case kbd_HOME:
6183 #ifndef SCROLLVAR_NO
6184 if (VIZCHKw(w)) if (CHKw(w, Show_IDLEPS)) w->begtask = w->begpflg = w->varcolbeg = 0;
6185 #else
6186 if (VIZCHKw(w)) if (CHKw(w, Show_IDLEPS)) w->begtask = w->begpflg = 0;
6187 #endif
6188 break;
6189 case kbd_END:
6190 if (VIZCHKw(w)) {
6191 if (CHKw(w, Show_IDLEPS)) {
6192 mkVIZrowX((PIDSmaxt - w->winlines) + 1)
6193 w->begpflg = w->endpflg;
6194 #ifndef SCROLLVAR_NO
6195 w->varcolbeg = 0;
6196 #endif
6197 }
6198 }
6199 break;
6200 default: // keep gcc happy
6201 break;
6202 }
6203 } // end: keys_window
6204
6205
6206 static void keys_xtra (int ch) {
6207 // const char *xmsg;
6208 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
6209
6210 #ifdef TREE_NORESET
6211 if (CHKw(w, Show_FOREST)) return;
6212 #else
6213 OFFw(w, Show_FOREST);
6214 #endif
6215 /* these keys represent old-top compatibility --
6216 they're grouped here so that if users could ever be weaned,
6217 we would just whack do_key's key_tab entry and this function... */
6218 switch (ch) {
6219 case 'M':
6220 w->rc.sortindx = EU_MEM;
6221 // xmsg = "Memory";
6222 break;
6223 case 'N':
6224 w->rc.sortindx = EU_PID;
6225 // xmsg = "Numerical";
6226 break;
6227 case 'P':
6228 w->rc.sortindx = EU_CPU;
6229 // xmsg = "CPU";
6230 break;
6231 case 'T':
6232 w->rc.sortindx = EU_TM2;
6233 // xmsg = "Time";
6234 break;
6235 default: // keep gcc happy
6236 break;
6237 }
6238 // some have objected to this message, so we'll just keep silent...
6239 // show_msg(fmtmk("%s sort compatibility key honored", xmsg));
6240 } // end: keys_xtra
6241
6242 /*###### Tertiary summary display support (summary_show helpers) #######*/
6243
6244 /*
6245 * note how alphabetical order is maintained within carefully chosen |
6246 * function names such as: (s)sum_see, (t)sum_tics, and (u)sum_unify |
6247 * with every name exactly 1 letter more than the preceding function |
6248 * ( surely, this must make us run much more efficiently. amirite? ) | */
6249
6250 struct rx_st {
6251 float pcnt_one, pcnt_two, pcnt_tot;
6252 char graph[MEDBUFSIZ];
6253 };
6254
6255 /*
6256 * A *Helper* function to produce the actual cpu & memory graphs for |
6257 * these functions -- sum_tics (tertiary) and do_memory (secondary). |
6258 * (sorry about the name, but it keeps the above comment commitment) | */
6259 static struct rx_st *sum_rx (struct graph_parms *these) {
6260 static struct {
6261 const char *part1, *part2, *style;
6262 } gtab[] = {
6263 { "%-.*s~7", "%-.*s~8", Graph_bars },
6264 { "%-.*s~4", "%-.*s~6", Graph_blks }
6265 };
6266 static __thread struct rx_st rx;
6267 char buf1[SMLBUFSIZ], buf2[SMLBUFSIZ], buf3[MEDBUFSIZ];
6268 int ix, num1, num2, width;
6269 float scale = 0.0;
6270
6271 if (these->total > 0)
6272 scale = 100.0 / these->total;
6273 rx.pcnt_one = scale * these->part1;
6274 rx.pcnt_two = scale * these->part2;
6275 if (rx.pcnt_one + rx.pcnt_two > 100.0 || rx.pcnt_two < 0)
6276 rx.pcnt_two = 0;
6277 rx.pcnt_tot = rx.pcnt_one + rx.pcnt_two;
6278
6279 num1 = (int)((rx.pcnt_one * these->adjust) + .5);
6280 num2 = (int)((rx.pcnt_two * these->adjust) + .5);
6281 if (num1 + num2 > these->length) {
6282 if (num1 > these->length) num1 = these->length;
6283 num2 = these->length - num1;
6284 }
6285
6286 width = these->length;
6287 buf1[0] = buf2[0] = buf3[0] = '\0';
6288 ix = these->style - 1; // now relative to zero
6289 if (num1) {
6290 snprintf(buf1, sizeof(buf1), gtab[ix].part1, num1, gtab[ix].style);
6291 width += 2;
6292 }
6293 if (num2) {
6294 snprintf(buf2, sizeof(buf2), gtab[ix].part2, num2, gtab[ix].style);
6295 width += 2;
6296 }
6297 snprintf(buf3, sizeof(buf3), "%s%s", buf1, buf2);
6298 // 'width' has accounted for any show_special directives embedded above
6299 snprintf(rx.graph, sizeof(rx.graph), "[~1%-*.*s] ~1", width, width, buf3);
6300
6301 return &rx;
6302 } // end: sum_rx
6303
6304
6305 /*
6306 * A *Helper* function to show multiple lines of summary information |
6307 * as a single line. We return the number of lines actually printed. | */
6308 static inline int sum_see (const char *str, int nobuf) {
6309 static char row[ROWMAXSIZ];
6310 static int tog;
6311 char *p;
6312
6313 p = scat(row, str);
6314 if (!str[0]) goto flush_it;
6315 if (Curwin->rc.double_up
6316 && (!nobuf)) {
6317 if (++tog <= Curwin->rc.double_up) {
6318 scat(p, Adjoin_sp);
6319 return 0;
6320 }
6321 }
6322 flush_it:
6323 if (!row[0]) return 0;
6324 scat(p, "\n");
6325 show_special(0, row);
6326 row[0] = '\0';
6327 tog = 0;
6328 return 1;
6329 } // end: sum_see
6330
6331
6332 /*
6333 * State display *Helper* function to calculate plus display (maybe) |
6334 * the percentages for a single cpu. In this way, we'll support the |
6335 * following environments without (hopefully) that usual code bloat: |
6336 * 1) single cpu platforms (no matter the paucity of these types) |
6337 * 2) modest smp boxes with ample room for each cpu's percentages |
6338 * 3) massive smp guys leaving little or no room for that process |
6339 * display and thus requiring the '1', '4', or '!' cpu toggles |
6340 * ( we return the number of lines printed, as reported by sum_see ) | */
6341 static int sum_tics (struct stat_stack *this, const char *pfx, int nobuf) {
6342 // tailored 'results stack value' extractor macros
6343 #define qSv(E) STAT_VAL(E, s_int, this, Stat_ctx)
6344 #define rSv(E) TIC_VAL(E, this)
6345 SIC_t idl_frme, tot_frme;
6346 struct rx_st *rx;
6347 float scale;
6348
6349 #ifndef CORE_TYPE_NO
6350 if (Curwin->rc.core_types == P_CORES_ONLY && qSv(stat_COR_TYP) != P_CORE) return 0;
6351 if (Curwin->rc.core_types == E_CORES_ONLY && qSv(stat_COR_TYP) != E_CORE) return 0;
6352 #endif
6353 idl_frme = rSv(stat_IL);
6354 tot_frme = rSv(stat_SUM_TOT);
6355 if (1 > tot_frme) idl_frme = tot_frme = 1;
6356 scale = 100.0 / (float)tot_frme;
6357
6358 /* account for VM tics not otherwise provided for ...
6359 ( with xtra-procps-debug.h, can't use PID_VAL w/ assignment ) */
6360 this->head[stat_SY].result.sl_int += rSv(stat_GU) + rSv(stat_GN);
6361 this->head[stat_SUM_SYS].result.sl_int += rSv(stat_GU) + rSv(stat_GN);
6362
6363 /* display some kinda' cpu state percentages
6364 (who or what is explained by the passed prefix) */
6365 if (Curwin->rc.graph_cpus) {
6366 Graph_cpus->total = tot_frme;
6367 Graph_cpus->part1 = rSv(stat_SUM_USR);
6368 Graph_cpus->part2 = rSv(stat_SUM_SYS);
6369 rx = sum_rx(Graph_cpus);
6370 if (Curwin->rc.double_up > 1)
6371 return sum_see(fmtmk("%s~3%3.0f%s", pfx, rx->pcnt_tot, rx->graph), nobuf);
6372 else {
6373 return sum_see(fmtmk("%s ~3%#5.1f~2/%-#5.1f~3 %3.0f%s"
6374 , pfx, rx->pcnt_one, rx->pcnt_two, rx->pcnt_tot
6375 , rx->graph)
6376 , nobuf);
6377 }
6378 } else {
6379 return sum_see(fmtmk(Cpu_States_fmts, pfx
6380 , (float)rSv(stat_US) * scale, (float)rSv(stat_SY) * scale
6381 , (float)rSv(stat_NI) * scale, (float)idl_frme * scale
6382 , (float)rSv(stat_IO) * scale, (float)rSv(stat_IR) * scale
6383 , (float)rSv(stat_SI) * scale, (float)rSv(stat_ST) * scale), nobuf);
6384 }
6385 #undef qSv
6386 #undef rSv
6387 } // end: sum_tics
6388
6389
6390 /*
6391 * Cpu *Helper* function to combine additional cpu statistics in our |
6392 * efforts to reduce the total number of processors that'll be shown |
6393 * ( we return the number of lines printed, as reported by sum_see ) | */
6394 static int sum_unify (struct stat_stack *this, int nobuf) {
6395 // a tailored 'results stack value' extractor macro
6396 #define rSv(E,T) STAT_VAL(E, T, this, Stat_ctx)
6397 static struct stat_result stack[MAXTBL(Stat_items)];
6398 static struct stat_stack accum = { &stack[0] };
6399 static int ix, beg;
6400 char pfx[16];
6401 int n;
6402
6403 // entries for stat_ID & stat_NU are unused
6404 stack[stat_US].result.sl_int += rSv(stat_US, sl_int);
6405 stack[stat_SY].result.sl_int += rSv(stat_SY, sl_int);
6406 stack[stat_NI].result.sl_int += rSv(stat_NI, sl_int);
6407 stack[stat_IL].result.sl_int += rSv(stat_IL, sl_int);
6408 stack[stat_IO].result.sl_int += rSv(stat_IO, sl_int);
6409 stack[stat_IR].result.sl_int += rSv(stat_IR, sl_int);
6410 stack[stat_SI].result.sl_int += rSv(stat_SI, sl_int);
6411 stack[stat_ST].result.sl_int += rSv(stat_ST, sl_int);
6412 stack[stat_GU].result.sl_int += rSv(stat_GU, sl_int);
6413 stack[stat_GN].result.sl_int += rSv(stat_GN, sl_int);
6414 stack[stat_SUM_USR].result.sl_int += rSv(stat_SUM_USR, sl_int);
6415 stack[stat_SUM_SYS].result.sl_int += rSv(stat_SUM_SYS, sl_int);
6416 stack[stat_SUM_TOT].result.sl_int += rSv(stat_SUM_TOT, sl_int);
6417
6418 if (!ix) beg = rSv(stat_ID, s_int);
6419 if (nobuf || ix >= (Curwin->rc.combine_cpus - 1)) {
6420 snprintf(pfx, sizeof(pfx), "%-7.7s:", fmtmk("%d-%d", beg, rSv(stat_ID, s_int)));
6421 n = sum_tics(&accum, pfx, nobuf);
6422 memset(&stack, 0, sizeof(stack));
6423 ix = 0;
6424 return n;
6425 }
6426 ++ix;
6427 return 0;
6428 #undef rSv
6429 } // end: sum_unify
6430
6431 /*###### Secondary summary display support (summary_show helpers) ######*/
6432
6433 /*
6434 * A helper function that displays cpu and/or numa node stuff |
6435 * ( so as to keep the 'summary_show' guy a reasonable size ) | */
6436 static void do_cpus (void) {
6437 #define noMAS (Msg_row + 1 >= SCREEN_ROWS - 1)
6438 #define eachCPU(x) N_fmt(WORD_eachcpu_fmt), 'u', x
6439 char tmp[MEDBUFSIZ];
6440 int i;
6441
6442 if (CHKw(Curwin, View_CPUNOD)) {
6443 if (Numa_node_sel < 0) {
6444 numa_oops:
6445 /*
6446 * display the 1st /proc/stat line, then the nodes (if room) ... */
6447 Msg_row += sum_tics(Stat_reap->summary, N_txt(WORD_allcpus_txt), 1);
6448 // display each cpu node's states
6449 for (i = 0; i < Numa_node_tot; i++) {
6450 struct stat_stack *nod_ptr = Stat_reap->numa->stacks[i];
6451 if (NOD_VAL(stat_NU, i) == STAT_NODE_INVALID) continue;
6452 if (noMAS) break;
6453 snprintf(tmp, sizeof(tmp), N_fmt(NUMA_nodenam_fmt), NOD_VAL(stat_ID, i));
6454 Msg_row += sum_tics(nod_ptr, tmp, 1);
6455 }
6456 } else {
6457 /*
6458 * display the node summary, then the associated cpus (if room) ... */
6459 for (i = 0; i < Numa_node_tot; i++) {
6460 if (Numa_node_sel == NOD_VAL(stat_ID, i)
6461 && (NOD_VAL(stat_NU, i) != STAT_NODE_INVALID)) break;
6462 }
6463 if (i == Numa_node_tot) {
6464 Numa_node_sel = -1;
6465 goto numa_oops;
6466 }
6467 snprintf(tmp, sizeof(tmp), N_fmt(NUMA_nodenam_fmt), Numa_node_sel);
6468 Msg_row += sum_tics(Stat_reap->numa->stacks[Numa_node_sel], tmp, 1);
6469 #ifdef PRETEND48CPU
6470 #define deLIMIT Stat_reap->cpus->total
6471 #else
6472 #define deLIMIT Cpu_cnt
6473 #endif
6474 for (i = 0; i < deLIMIT; i++) {
6475 if (Numa_node_sel == CPU_VAL(stat_NU, i)) {
6476 if (noMAS) break;
6477 snprintf(tmp, sizeof(tmp), eachCPU(CPU_VAL(stat_ID, i)));
6478 Msg_row += sum_tics(Stat_reap->cpus->stacks[i], tmp, 1);
6479 }
6480 }
6481 #undef deLIMIT
6482 }
6483
6484 } else if (!CHKw(Curwin, View_CPUSUM)) {
6485 /*
6486 * display each cpu's states separately, screen height permitting ... */
6487 #ifdef PRETEND48CPU
6488 int j;
6489 if (Curwin->rc.combine_cpus) {
6490 for (i = 0, j = 0; i < Cpu_cnt; i++) {
6491 Stat_reap->cpus->stacks[j]->head[stat_ID].result.s_int = i;
6492 Msg_row += sum_unify(Stat_reap->cpus->stacks[j], (i+1 >= Cpu_cnt));
6493 if (++j >= Stat_reap->cpus->total) j = 0;
6494 if (noMAS) break;
6495 }
6496 } else {
6497 for (i = 0, j = 0; i < Cpu_cnt; i++) {
6498 snprintf(tmp, sizeof(tmp), eachCPU(i));
6499 Msg_row += sum_tics(Stat_reap->cpus->stacks[j], tmp, (i+1 >= Cpu_cnt));
6500 if (++j >= Stat_reap->cpus->total) j = 0;
6501 if (noMAS) break;
6502 }
6503 }
6504 #else
6505 if (Curwin->rc.combine_cpus) {
6506 for (i = 0; i < Cpu_cnt; i++) {
6507 Msg_row += sum_unify(Stat_reap->cpus->stacks[i], (i+1 >= Cpu_cnt));
6508 if (noMAS) break;
6509 }
6510 } else {
6511 for (i = 0; i < Cpu_cnt; i++) {
6512 #ifndef CORE_TYPE_NO
6513 #ifdef CORE_TYPE_LO
6514 char ctab[] = { 'u', 'e', 'p' };
6515 #else
6516 char ctab[] = { 'u', 'E', 'P' };
6517 #endif
6518 int cid = CPU_VAL(stat_ID, i), typ = CPU_VAL(stat_COR_TYP, i);
6519 char chr = Curwin->rc.core_types ? ctab[typ] : 'u' ;
6520 snprintf(tmp, sizeof(tmp), N_fmt(WORD_eachcpu_fmt), chr, cid);
6521 #else
6522 snprintf(tmp, sizeof(tmp), eachCPU(CPU_VAL(stat_ID, i)));
6523 #endif
6524 Msg_row += sum_tics(Stat_reap->cpus->stacks[i], tmp, (i+1 >= Cpu_cnt));
6525 if (noMAS) break;
6526 }
6527 }
6528 #endif
6529
6530 } else {
6531 /*
6532 * display just the 1st /proc/stat line ... */
6533 Msg_row += sum_tics(Stat_reap->summary, N_txt(WORD_allcpus_txt), 1);
6534 }
6535
6536 // coax this guy into flushing any pending cpu stuff ...
6537 Msg_row += sum_see("", 1);
6538 #undef noMAS
6539 #undef eachCPU
6540 } // end: do_cpus
6541
6542
6543 /*
6544 * A helper function which will display the memory/swap stuff |
6545 * ( so as to keep the 'summary_show' guy a reasonable size ) | */
6546 static void do_memory (void) {
6547 #define bfT(n) buftab[n].buf
6548 #define scT(e) scaletab[Rc.summ_mscale]. e
6549 #define mkM(x) (float) x / scT(div)
6550 #define prT(b,z) { if (9 < snprintf(b, 10, scT(fmts), z)) b[8] = '+'; }
6551 #ifdef TOG4_MEM_1UP
6552 #define mem2UP 1
6553 #else
6554 #define mem2UP 0
6555 #endif
6556 static struct {
6557 float div;
6558 const char *fmts;
6559 const char *label;
6560 } scaletab[] = {
6561 { 1, "%.0f ", NULL }, // kibibytes
6562 #ifdef BOOST_MEMORY
6563 { 1024.0, "%#.3f ", NULL }, // mebibytes
6564 { 1024.0*1024, "%#.3f ", NULL }, // gibibytes
6565 { 1024.0*1024*1024, "%#.3f ", NULL }, // tebibytes
6566 { 1024.0*1024*1024*1024, "%#.3f ", NULL }, // pebibytes
6567 { 1024.0*1024*1024*1024*1024, "%#.3f ", NULL } // exbibytes
6568 #else
6569 { 1024.0, "%#.1f ", NULL }, // mebibytes
6570 { 1024.0*1024, "%#.1f ", NULL }, // gibibytes
6571 { 1024.0*1024*1024, "%#.1f ", NULL }, // tebibytes
6572 { 1024.0*1024*1024*1024, "%#.1f ", NULL }, // pebibytes
6573 { 1024.0*1024*1024*1024*1024, "%#.1f ", NULL } // exbibytes
6574 #endif
6575 };
6576 struct { // 0123456789
6577 // snprintf contents of each buf (after SK_Kb): 'nnnn.nnn 0'
6578 // & prT macro might replace space at buf[8] with: -------> +
6579 char buf[10]; // MEMORY_lines_fmt provides for 8+1 bytes
6580 } buftab[8];
6581 char row[ROWMINSIZ];
6582 long my_qued, my_misc, my_used;
6583 struct rx_st *rx;
6584
6585 if (!scaletab[0].label) {
6586 scaletab[0].label = N_txt(AMT_kilobyte_txt);
6587 scaletab[1].label = N_txt(AMT_megabyte_txt);
6588 scaletab[2].label = N_txt(AMT_gigabyte_txt);
6589 scaletab[3].label = N_txt(AMT_terabyte_txt);
6590 scaletab[4].label = N_txt(AMT_petabyte_txt);
6591 scaletab[5].label = N_txt(AMT_exxabyte_txt);
6592 }
6593 my_qued = MEM_VAL(mem_BUF) + MEM_VAL(mem_QUE);
6594
6595 if (Curwin->rc.graph_mems) {
6596 my_used = MEM_VAL(mem_TOT) - MEM_VAL(mem_FRE) - my_qued;
6597 #ifdef MEMGRAPH_OLD
6598 my_misc = my_qued;
6599 #else
6600 my_misc = MEM_VAL(mem_TOT) - MEM_VAL(mem_AVL) - my_used;
6601 #endif
6602 Graph_mems->total = MEM_VAL(mem_TOT);
6603 Graph_mems->part1 = my_used;
6604 Graph_mems->part2 = my_misc;
6605 rx = sum_rx(Graph_mems);
6606 #ifdef TOG4_MEM_1UP
6607 prT(bfT(0), mkM(MEM_VAL(mem_TOT)));
6608 snprintf(row, sizeof(row), "%s %s:~3%#5.1f~2/%-9.9s~3%s"
6609 , scT(label), N_txt(WORD_abv_mem_txt), rx->pcnt_tot, bfT(0), rx->graph);
6610 #else
6611 if (Curwin->rc.double_up > 1)
6612 snprintf(row, sizeof(row), "%s %s~3%3.0f%s"
6613 , scT(label), N_txt(WORD_abv_mem_txt), rx->pcnt_tot, rx->graph);
6614 else {
6615 prT(bfT(0), mkM(MEM_VAL(mem_TOT)));
6616 snprintf(row, sizeof(row), "%s %s:~3%#5.1f~2/%-9.9s~3%s"
6617 , scT(label), N_txt(WORD_abv_mem_txt), rx->pcnt_tot, bfT(0), rx->graph);
6618 }
6619 #endif
6620 Msg_row += sum_see(row, mem2UP);
6621
6622 Graph_mems->total = MEM_VAL(swp_TOT);
6623 Graph_mems->part1 = 0;
6624 Graph_mems->part2 = MEM_VAL(swp_USE);
6625 rx = sum_rx(Graph_mems);
6626 #ifdef TOG4_MEM_1UP
6627 prT(bfT(1), mkM(MEM_VAL(swp_TOT)));
6628 snprintf(row, sizeof(row), "%s %s:~3%#5.1f~2/%-9.9s~3%s"
6629 , scT(label), N_txt(WORD_abv_swp_txt), rx->pcnt_two, bfT(1), rx->graph);
6630 #else
6631 if (Curwin->rc.double_up > 1)
6632 snprintf(row, sizeof(row), "%s %s~3%3.0f%s"
6633 , scT(label), N_txt(WORD_abv_swp_txt), rx->pcnt_two, rx->graph);
6634 else {
6635 prT(bfT(1), mkM(MEM_VAL(swp_TOT)));
6636 snprintf(row, sizeof(row), "%s %s:~3%#5.1f~2/%-9.9s~3%s"
6637 , scT(label), N_txt(WORD_abv_swp_txt), rx->pcnt_two, bfT(1), rx->graph);
6638 }
6639 #endif
6640 Msg_row += sum_see(row, 1);
6641
6642 } else {
6643 prT(bfT(0), mkM(MEM_VAL(mem_TOT))); prT(bfT(1), mkM(MEM_VAL(mem_FRE)));
6644 prT(bfT(2), mkM(MEM_VAL(mem_USE))); prT(bfT(3), mkM(my_qued));
6645 prT(bfT(4), mkM(MEM_VAL(swp_TOT))); prT(bfT(5), mkM(MEM_VAL(swp_FRE)));
6646 prT(bfT(6), mkM(MEM_VAL(swp_USE))); prT(bfT(7), mkM(MEM_VAL(mem_AVL)));
6647
6648 snprintf(row, sizeof(row), N_unq(MEMORY_line1_fmt)
6649 , scT(label), N_txt(WORD_abv_mem_txt), bfT(0), bfT(1), bfT(2), bfT(3));
6650 Msg_row += sum_see(row, mem2UP);
6651
6652 snprintf(row, sizeof(row), N_unq(MEMORY_line2_fmt)
6653 , scT(label), N_txt(WORD_abv_swp_txt), bfT(4), bfT(5), bfT(6), bfT(7)
6654 , N_txt(WORD_abv_mem_txt));
6655 Msg_row += sum_see(row, 1);
6656 }
6657 #undef bfT
6658 #undef scT
6659 #undef mkM
6660 #undef prT
6661 #undef mem2UP
6662 } // end: do_memory
6663
6664 /*###### Main Screen routines ##########################################*/
6665
6666 /*
6667 * Process keyboard input during the main loop */
6668 static void do_key (int ch) {
6669 static struct {
6670 void (*func)(int ch);
6671 char keys[SMLBUFSIZ];
6672 } key_tab[] = {
6673 { keys_global,
6674 { '?', 'B', 'd', 'E', 'e', 'f', 'g', 'H', 'h'
6675 , 'I', 'k', 'r', 's', 'X', 'Y', 'Z', '0'
6676 , kbd_CtrlE, kbd_CtrlG, kbd_CtrlI, kbd_CtrlK, kbd_CtrlL
6677 , kbd_CtrlN, kbd_CtrlP, kbd_CtrlR, kbd_CtrlU
6678 , kbd_ENTER, kbd_SPACE, kbd_BTAB, '\0' } },
6679 { keys_summary,
6680 #ifdef CORE_TYPE_NO
6681 { '!', '1', '2', '3', '4', 'C', 'l', 'm', 't', '\0' } },
6682 #else
6683 { '!', '1', '2', '3', '4', '5', 'C', 'l', 'm', 't', '\0' } },
6684 #endif
6685 { keys_task,
6686 { '#', '<', '>', 'b', 'c', 'F', 'i', 'J', 'j', 'n', 'O', 'o'
6687 , 'R', 'S', 'U', 'u', 'V', 'v', 'x', 'y', 'z'
6688 , kbd_CtrlO, '\0' } },
6689 { keys_window,
6690 { '+', '-', '=', '_', '&', 'A', 'a', 'G', 'L', 'w'
6691 , kbd_UP, kbd_DOWN, kbd_LEFT, kbd_RIGHT, kbd_PGUP, kbd_PGDN
6692 , kbd_HOME, kbd_END, '\0' } },
6693 { keys_xtra,
6694 { 'M', 'N', 'P', 'T', '\0'} }
6695 };
6696 int i;
6697
6698 Frames_signal = BREAK_off;
6699 switch (ch) {
6700 case 0: // ignored (always)
6701 case kbd_ESC: // ignored (sometimes)
6702 goto all_done;
6703 case 'q': // no return from this guy
6704 bye_bye(NULL);
6705 case 'W': // no need for rebuilds
6706 write_rcfile();
6707 goto all_done;
6708 default: // and now, the real work...
6709 // and just in case 'Monpids' is active but matched no processes ...
6710 if (!PIDSmaxt && ch != '=') goto all_done;
6711 for (i = 0; i < MAXTBL(key_tab); ++i)
6712 if (strchr(key_tab[i].keys, ch)) {
6713 key_tab[i].func(ch);
6714 if (Frames_signal == BREAK_off)
6715 Frames_signal = BREAK_kbd;
6716 /* due to the proliferation of the need for 'mkVIZrow1', |
6717 aside from 'wins_stage_2' use, we'll now issue it one |
6718 time here. there will remain several places where the |
6719 companion 'mkVIZrowX' macro is issued, thus the check |
6720 for a value already in 'begnext' in this conditional. | */
6721 if (CHKw(Curwin, Show_TASKON) && !mkVIZyes)
6722 mkVIZrow1
6723 goto all_done;
6724 }
6725 };
6726 /* The Frames_signal above will force a rebuild of column headers.
6727 It's NOT simply lazy programming. Below are some keys that may
6728 require new column headers and/or new library item enumerators:
6729 'A' - likely
6730 'c' - likely when !Mode_altscr, maybe when Mode_altscr
6731 'F' - likely
6732 'f' - likely
6733 'g' - likely
6734 'H' - likely
6735 'I' - likely
6736 'J' - always
6737 'j' - always
6738 'Z' - likely, if 'Curwin' changed when !Mode_altscr
6739 '-' - likely (restricted to Mode_altscr)
6740 '_' - likely (restricted to Mode_altscr)
6741 '=' - maybe, but only when Mode_altscr
6742 '+' - likely (restricted to Mode_altscr)
6743 PLUS, likely for FOUR of the EIGHT cursor motion keys (scrolled)
6744 ( At this point we have a human being involved and so have all the time )
6745 ( in the world. We can afford a few extra cpu cycles every now & then! )
6746 */
6747
6748 show_msg(N_txt(UNKNOWN_cmds_txt));
6749 all_done:
6750 putp((Cursor_state = Cap_curs_hide));
6751 } // end: do_key
6752
6753
6754 /*
6755 * In support of a new frame:
6756 * 1) Display uptime and load average (maybe)
6757 * 2) Display task/cpu states (maybe)
6758 * 3) Display memory & swap usage (maybe) */
6759 static void summary_show (void) {
6760 #define isROOM(f,n) (CHKw(Curwin, f) && Msg_row + (n) < SCREEN_ROWS - 1)
6761
6762 if (Restrict_some) {
6763 #ifdef THREADED_TSK
6764 sem_wait(&Semaphore_tasks_end);
6765 #endif
6766 // Display Task States only
6767 if (isROOM(View_STATES, 1)) {
6768 show_special(0, fmtmk(N_unq(STATE_line_1_fmt)
6769 , Thread_mode ? N_txt(WORD_threads_txt) : N_txt(WORD_process_txt)
6770 , PIDSmaxt, Pids_reap->counts->running
6771 , Pids_reap->counts->sleeping + Pids_reap->counts->other
6772 , Pids_reap->counts->stopped, Pids_reap->counts->zombied));
6773 Msg_row += 1;
6774 }
6775 return;
6776 }
6777
6778 // Display Uptime and Loadavg
6779 if (isROOM(View_LOADAV, 1)) {
6780 if (!Rc.mode_altscr)
6781 show_special(0, fmtmk(LOADAV_line, Myname, procps_uptime_sprint()));
6782 else
6783 show_special(0, fmtmk(CHKw(Curwin, Show_TASKON)? LOADAV_line_alt : LOADAV_line
6784 , Curwin->grpname, procps_uptime_sprint()));
6785 Msg_row += 1;
6786 } // end: View_LOADAV
6787
6788 #ifdef THREADED_CPU
6789 sem_wait(&Semaphore_cpus_end);
6790 #endif
6791 #ifdef THREADED_TSK
6792 sem_wait(&Semaphore_tasks_end);
6793 #endif
6794 // Display Task and Cpu(s) States
6795 if (isROOM(View_STATES, 2)) {
6796 show_special(0, fmtmk(N_unq(STATE_line_1_fmt)
6797 , Thread_mode ? N_txt(WORD_threads_txt) : N_txt(WORD_process_txt)
6798 , PIDSmaxt, Pids_reap->counts->running
6799 , Pids_reap->counts->sleeping + Pids_reap->counts->other
6800 , Pids_reap->counts->stopped, Pids_reap->counts->zombied));
6801 Msg_row += 1;
6802
6803 do_cpus();
6804 }
6805
6806 #ifdef THREADED_MEM
6807 sem_wait(&Semaphore_memory_end);
6808 #endif
6809 // Display Memory and Swap stats
6810 if (isROOM(View_MEMORY, 2)) {
6811 do_memory();
6812 }
6813
6814 #undef isROOM
6815 } // end: summary_show
6816
6817
6818 /*
6819 * Build the information for a single task row and
6820 * display the results or return them to the caller. */
6821 static const char *task_show (const WIN_t *q, int idx) {
6822 // a tailored 'results stack value' extractor macro
6823 #define rSv(E,T) PID_VAL(E, T, p)
6824 #ifndef SCROLLVAR_NO
6825 #define makeVAR(S) { const char *pv = S; \
6826 if (!q->varcolbeg) cp = make_str(pv, q->varcolsz, Js, AUTOX_NO); \
6827 else cp = make_str(q->varcolbeg < (int)strlen(pv) ? pv + q->varcolbeg : "", q->varcolsz, Js, AUTOX_NO); }
6828 #define varUTF8(S) { const char *pv = S; \
6829 if (!q->varcolbeg) cp = make_str_utf8(pv, q->varcolsz, Js, AUTOX_NO); \
6830 else cp = make_str_utf8((q->varcolbeg < ((int)strlen(pv) - utf8_delta(pv))) \
6831 ? pv + utf8_embody(pv, q->varcolbeg) : "", q->varcolsz, Js, AUTOX_NO); }
6832 #else
6833 #define makeVAR(S) { cp = make_str(S, q->varcolsz, Js, AUTOX_NO); }
6834 #define varUTF8(S) { cp = make_str_utf8(S, q->varcolsz, Js, AUTOX_NO); }
6835 #endif
6836 struct pids_stack *p = q->ppt[idx];
6837 static char rbuf[ROWMINSIZ];
6838 char *rp;
6839 int x;
6840
6841 /* we use up to three additional 'PIDS_extra' results in our stacks
6842 eu_TREE_HID (s_ch) : where 'x' == collapsed and 'z' == unseen
6843 eu_TREE_LVL (s_int): where a level number is stored (0 - 100)
6844 eu_TREE_ADD (u_int): where children's tics are stored (maybe) */
6845 #ifndef TREE_VWINALL
6846 if (q == Curwin) // note: the following is NOT indented
6847 #endif
6848 if (CHKw(q, Show_FOREST) && rSv(eu_TREE_HID, s_ch) == 'z')
6849 return "";
6850
6851 // we must begin a row with a possible window number in mind...
6852 *(rp = rbuf) = '\0';
6853 if (Rc.mode_altscr) rp = scat(rp, " ");
6854
6855 for (x = 0; x < q->maxpflgs; x++) {
6856 const char *cp = NULL;
6857 FLG_t i = q->procflgs[x];
6858 #define S Fieldstab[i].scale // these used to be variables
6859 #define W Fieldstab[i].width // but it's much better if we
6860 #define Js CHKw(q, Show_JRSTRS) // represent them as #defines
6861 #define Jn CHKw(q, Show_JRNUMS) // and only exec code if used
6862
6863 /* except for the XOF/XON pseudo flags the following case labels are grouped
6864 by result type according to capacity (small -> large) and then ordered by
6865 additional processing requirements (as in plain, scaled, decorated, etc.) */
6866
6867 switch (i) {
6868 #ifndef USE_X_COLHDR
6869 // these 2 aren't real procflgs, they're used in column highlighting!
6870 case EU_XOF:
6871 case EU_XON:
6872 cp = NULL;
6873 if (!CHKw(q, NOPRINT_xxx)) {
6874 /* treat running tasks specially - entire row may get highlighted
6875 so we needn't turn it on and we MUST NOT turn it off */
6876 if (!('R' == rSv(EU_STA, s_ch) && CHKw(q, Show_HIROWS)))
6877 cp = (EU_XON == i ? q->capclr_rowhigh : q->capclr_rownorm);
6878 }
6879 break;
6880 #endif
6881 /* s_ch, make_chr */
6882 case EU_STA: // PIDS_STATE
6883 cp = make_chr(rSv(EU_STA, s_ch), W, Js);
6884 break;
6885 /* s_int, make_num with auto width */
6886 case EU_LID: // PIDS_ID_LOGIN
6887 cp = make_num(rSv(EU_LID, s_int), W, Jn, EU_LID, 0);
6888 break;
6889 /* s_int, make_num without auto width */
6890 case EU_AGI: // PIDS_AUTOGRP_ID
6891 case EU_CPN: // PIDS_PROCESSOR
6892 case EU_NMA: // PIDS_PROCESSOR_NODE
6893 case EU_PGD: // PIDS_ID_PGRP
6894 case EU_PID: // PIDS_ID_PID
6895 case EU_PPD: // PIDS_ID_PPID
6896 case EU_SID: // PIDS_ID_SESSION
6897 case EU_TGD: // PIDS_ID_TGID
6898 case EU_THD: // PIDS_NLWP
6899 case EU_TPG: // PIDS_ID_TPGID
6900 cp = make_num(rSv(i, s_int), W, Jn, AUTOX_NO, 0);
6901 break;
6902 /* s_int, make_num without auto width, but with zero suppression */
6903 case EU_AGN: // PIDS_AUTOGRP_NICE
6904 case EU_NCE: // PIDS_NICE
6905 case EU_OOA: // PIDS_OOM_ADJ
6906 case EU_OOM: // PIDS_OOM_SCORE
6907 cp = make_num(rSv(i, s_int), W, Jn, AUTOX_NO, 1);
6908 break;
6909 /* s_int, scale_num */
6910 case EU_FV1: // PIDS_FLT_MAJ_DELTA
6911 case EU_FV2: // PIDS_FLT_MIN_DELTA
6912 cp = scale_num(rSv(i, s_int), W, Jn);
6913 break;
6914 /* s_int, make_num or make_str */
6915 case EU_PRI: // PIDS_PRIORITY
6916 if (-99 > rSv(EU_PRI, s_int) || 999 < rSv(EU_PRI, s_int))
6917 cp = make_str("rt", W, Jn, AUTOX_NO);
6918 else
6919 cp = make_num(rSv(EU_PRI, s_int), W, Jn, AUTOX_NO, 0);
6920 break;
6921 /* s_int, scale_pcnt with special handling */
6922 case EU_CPU: // PIDS_TICS_ALL_DELTA
6923 { float u = (float)rSv(EU_CPU, u_int);
6924 int n = rSv(EU_THD, s_int);
6925 if (Restrict_some) {
6926 cp = justify_pad("?", W, Jn);
6927 break;
6928 }
6929 #ifndef TREE_VCPUOFF
6930 #ifndef TREE_VWINALL
6931 if (q == Curwin) // note: the following is NOT indented
6932 #endif
6933 if (CHKw(q, Show_FOREST)) u += rSv(eu_TREE_ADD, u_int);
6934 u *= Frame_etscale;
6935 /* technically, eu_TREE_HID is only valid if Show_FOREST is active
6936 but its zeroed out slot will always be present now */
6937 if (rSv(eu_TREE_HID, s_ch) != 'x' && u > 100.0 * n) u = 100.0 * n;
6938 #else
6939 u *= Frame_etscale;
6940 /* process can't use more %cpu than number of threads it has
6941 ( thanks Jaromir Capik <[email protected]> ) */
6942 if (u > 100.0 * n) u = 100.0 * n;
6943 #endif
6944 if (u > Cpu_pmax) u = Cpu_pmax;
6945 cp = scale_pcnt(u, W, Jn, 0);
6946 }
6947 break;
6948 /* ull_int, scale_pcnt for 'utilization' */
6949 case EU_CUU: // PIDS_UTILIZATION
6950 case EU_CUC: // PIDS_UTILIZATION_C
6951 if (Restrict_some) {
6952 cp = justify_pad("?", W, Jn);
6953 break;
6954 }
6955 cp = scale_pcnt(rSv(i, real), W, Jn, 1);
6956 break;
6957 /* u_int, make_num with auto width */
6958 case EU_GID: // PIDS_ID_EGID
6959 case EU_UED: // PIDS_ID_EUID
6960 case EU_URD: // PIDS_ID_RUID
6961 case EU_USD: // PIDS_ID_SUID
6962 cp = make_num(rSv(i, u_int), W, Jn, i, 0);
6963 break;
6964 /* ul_int, make_num with auto width and zero suppression */
6965 case EU_NS1: // PIDS_NS_IPC
6966 case EU_NS2: // PIDS_NS_MNT
6967 case EU_NS3: // PIDS_NS_NET
6968 case EU_NS4: // PIDS_NS_PID
6969 case EU_NS5: // PIDS_NS_USER
6970 case EU_NS6: // PIDS_NS_UTS
6971 case EU_NS7: // PIDS_NS_CGROUP
6972 case EU_NS8: // PIDS_NS_TIME
6973 cp = make_num(rSv(i, ul_int), W, Jn, i, 1);
6974 break;
6975 /* ul_int, scale_mem */
6976 case EU_COD: // PIDS_MEM_CODE
6977 case EU_DAT: // PIDS_MEM_DATA
6978 case EU_DRT: // PIDS_noop, really # pgs, but always 0 since 2.6
6979 case EU_PZA: // PIDS_SMAP_PSS_ANON
6980 case EU_PZF: // PIDS_SMAP_PSS_FILE
6981 case EU_PZS: // PIDS_SMAP_PSS_SHMEM
6982 case EU_PSS: // PIDS_SMAP_PSS
6983 case EU_RES: // PIDS_MEM_RES
6984 case EU_RSS: // PIDS_SMAP_RSS
6985 case EU_RZA: // PIDS_VM_RSS_ANON
6986 case EU_RZF: // PIDS_VM_RSS_FILE
6987 case EU_RZL: // PIDS_VM_RSS_LOCKED
6988 case EU_RZS: // PIDS_VM_RSS_SHARED
6989 case EU_SHR: // PIDS_MEM_SHR
6990 case EU_SWP: // PIDS_VM_SWAP
6991 case EU_USE: // PIDS_VM_USED
6992 case EU_USS: // PIDS_SMAP_PRV_TOTAL
6993 case EU_VRT: // PIDS_MEM_VIRT
6994 cp = scale_mem(S, rSv(i, ul_int), W, Jn);
6995 break;
6996 /* ul_int, scale_num */
6997 case EU_FL1: // PIDS_FLT_MAJ
6998 case EU_FL2: // PIDS_FLT_MIN
6999 case EU_IRB: // PIDS_IO_READ_BYTES
7000 case EU_IRO: // PIDS_IO_READ_OPS
7001 case EU_IWB: // PIDS_IO_WRITE_BYTES
7002 case EU_IWO: // PIDS_IO_WRITE_OPS
7003 cp = scale_num(rSv(i, ul_int), W, Jn);
7004 break;
7005 /* ul_int, scale_pcnt */
7006 case EU_MEM: // derive from PIDS_MEM_RES
7007 if (Restrict_some) {
7008 cp = justify_pad("?", W, Jn);
7009 break;
7010 }
7011 cp = scale_pcnt((float)rSv(EU_MEM, ul_int) * 100 / MEM_VAL(mem_TOT), W, Jn, 0);
7012 break;
7013 /* ul_int, make_str with special handling */
7014 case EU_FLG: // PIDS_FLAGS
7015 cp = make_str(hex_make(rSv(EU_FLG, ul_int), 1), W, Js, AUTOX_NO);
7016 break;
7017 /* ull_int, scale_tics (try 'minutes:seconds.hundredths') */
7018 case EU_TM2: // PIDS_TICS_ALL
7019 case EU_TME: // PIDS_TICS_ALL
7020 { TIC_t t;
7021 if (CHKw(q, Show_CTIMES)) t = rSv(eu_TICS_ALL_C, ull_int);
7022 else t = rSv(i, ull_int);
7023 cp = scale_tics(t, W, Jn, TICS_AS_SECS);
7024 }
7025 break;
7026 /* ull_int, scale_tics (try 'minutes:seconds') */
7027 case EU_TM3: // PIDS_TICS_BEGAN
7028 cp = scale_tics(rSv(EU_TM3, ull_int), W, Jn, TICS_AS_MINS);
7029 break;
7030 /* real, scale_tics (try 'hour,minutes') */
7031 case EU_TM4: // PIDS_TIME_ELAPSED
7032 cp = scale_tics(rSv(EU_TM4, real) * Hertz, W, Jn, TICS_AS_HOUR);
7033 break;
7034 /* str, make_str (all AUTOX yes) */
7035 case EU_LXC: // PIDS_LXCNAME
7036 case EU_TTY: // PIDS_TTY_NAME
7037 case EU_WCH: // PIDS_WCHAN_NAME
7038 cp = make_str(rSv(i, str), W, Js, i);
7039 break;
7040 /* str, make_str_utf8 (all AUTOX yes) */
7041 case EU_GRP: // PIDS_ID_EGROUP
7042 case EU_UEN: // PIDS_ID_EUSER
7043 case EU_URN: // PIDS_ID_RUSER
7044 case EU_USN: // PIDS_ID_SUSER
7045 cp = make_str_utf8(rSv(i, str), W, Js, i);
7046 break;
7047 /* str, make_str_utf8 with variable width */
7048 case EU_CGN: // PIDS_CGNAME
7049 case EU_CGR: // PIDS_CGROUP
7050 case EU_ENV: // PIDS_ENVIRON
7051 case EU_EXE: // PIDS_EXE
7052 case EU_SGN: // PIDS_SUPGROUPS
7053 varUTF8(rSv(i, str))
7054 break;
7055 /* str, make_str with variable width */
7056 case EU_SGD: // PIDS_SUPGIDS
7057 makeVAR(rSv(EU_SGD, str))
7058 break;
7059 /* str, make_str with variable width + additional decoration */
7060 case EU_CMD: // PIDS_CMD or PIDS_CMDLINE
7061 varUTF8(forest_display(q, idx))
7062 break;
7063 default: // keep gcc happy
7064 continue;
7065 } // end: switch 'procflag'
7066
7067 if (cp) {
7068 if (q->osel_tot && !osel_matched(q, i, cp)) return "";
7069 rp = scat(rp, cp);
7070 }
7071 #undef S
7072 #undef W
7073 #undef Js
7074 #undef Jn
7075 } // end: for 'maxpflgs'
7076
7077 if (!CHKw(q, NOPRINT_xxx)) {
7078 const char *cap = ((CHKw(q, Show_HIROWS) && 'R' == rSv(EU_STA, s_ch)))
7079 ? q->capclr_rowhigh : q->capclr_rownorm;
7080 char *row = rbuf;
7081 int ofs;
7082 /* since we can't predict what the search string will be and,
7083 considering what a single space search request would do to
7084 potential buffer needs, when any matches are found we skip
7085 normal output routing and send all of the results directly
7086 to the terminal (and we sound asthmatic: poof, putt, puff) */
7087 if (-1 < (ofs = find_ofs(q, row))) {
7088 POOF("\n", cap);
7089 do {
7090 row[ofs] = '\0';
7091 PUTT("%s%s%s%s", row, q->capclr_hdr, q->findstr, cap);
7092 row += (ofs + q->findlen);
7093 ofs = find_ofs(q, row);
7094 } while (-1 < ofs);
7095 PUTT("%s%s", row, Caps_endline);
7096 // with a corrupted rbuf, ensure row is 'counted' by window_show
7097 rbuf[0] = '!';
7098 } else
7099 PUFF("\n%s%s%s", cap, row, Caps_endline);
7100 }
7101 return rbuf;
7102 #undef rSv
7103 #undef makeVAR
7104 #undef varUTF8
7105 } // end: task_show
7106
7107
7108 /*
7109 * A window_show *Helper* function ensuring that a window 'begtask' |
7110 * represents a visible process (not any hidden/filtered-out task). |
7111 * In reality this function is called exclusively for the 'current' |
7112 * window and only after available user keystroke(s) are processed. |
7113 * Note: it's entirely possible there are NO visible tasks to show! | */
7114 static void window_hlp (void) {
7115 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
7116 int i, reversed;
7117 int beg = w->focus_pid ? w->focus_beg : 0;
7118 int end = w->focus_pid ? w->focus_end : PIDSmaxt;
7119
7120 SETw(w, NOPRINT_xxx);
7121 w->begtask += w->begnext;
7122 // next 'if' will force a forward scan ...
7123 if (w->begtask <= beg) { w->begtask = beg; w->begnext = +1; }
7124 else if (w->begtask >= end) w->begtask = end - 1;
7125
7126 reversed = 0;
7127 // potentially scroll forward ...
7128 if (w->begnext > 0) {
7129 fwd_redux:
7130 for (i = w->begtask; i < end; i++) {
7131 if (wins_usrselect(w, i)
7132 && (*task_show(w, i)))
7133 break;
7134 }
7135 if (i < end) {
7136 w->begtask = i;
7137 goto wrap_up;
7138 }
7139 // no luck forward, so let's try backward
7140 w->begtask = end - 1;
7141 }
7142
7143 // potentially scroll backward ...
7144 for (i = w->begtask; i > beg; i--) {
7145 if (wins_usrselect(w, i)
7146 && (*task_show(w, i)))
7147 break;
7148 }
7149 w->begtask = i;
7150
7151 // reached the top, but maybe this guy ain't visible
7152 if (w->begtask == beg && !reversed) {
7153 if (!(wins_usrselect(w, beg))
7154 || (!(*task_show(w, beg)))) {
7155 reversed = 1;
7156 goto fwd_redux;
7157 }
7158 }
7159
7160 wrap_up:
7161 mkVIZoff(w)
7162 OFFw(w, NOPRINT_xxx);
7163 } // end: window_hlp
7164
7165
7166 /*
7167 * Squeeze as many tasks as we can into a single window,
7168 * after sorting the passed proc table. */
7169 static int window_show (WIN_t *q, int wmax) {
7170 #define sORDER CHKw(q, Qsrt_NORMAL) ? PIDS_SORT_DESCEND : PIDS_SORT_ASCEND
7171 /* the isBUSY macro determines if a task is 'active' --
7172 it returns true if some cpu was used since the last sample.
7173 ( actual 'running' tasks will be a subset of those selected ) */
7174 #define isBUSY(x) (0 < PID_VAL(EU_CPU, u_int, (x)))
7175 #define winMIN(a,b) (((a) < (b)) ? (a) : (b))
7176 int i, lwin, numtasks;
7177
7178 // Display Column Headings -- and distract 'em while we sort (maybe)
7179 PUFF("\n%s%s%s", q->capclr_hdr, q->columnhdr, Caps_endline);
7180 // and just in case 'Monpids' is active but matched no processes ...
7181 if (!PIDSmaxt) return 1; // 1 for the column header
7182
7183 if (CHKw(q, Show_FOREST)) {
7184 forest_begin(q);
7185 if (q->focus_pid) forest_config(q);
7186 } else {
7187 enum pids_item item = Fieldstab[q->rc.sortindx].item;
7188 if (item == PIDS_CMD && CHKw(q, Show_CMDLIN))
7189 item = PIDS_CMDLINE;
7190 else if (item == PIDS_TICS_ALL && CHKw(q, Show_CTIMES))
7191 item = PIDS_TICS_ALL_C;
7192 if (!(procps_pids_sort(Pids_ctx, q->ppt , PIDSmaxt, item, sORDER)))
7193 error_exit(fmtmk(N_fmt(LIB_errorpid_fmt), __LINE__, strerror(errno)));
7194 }
7195
7196 if (mkVIZyes) window_hlp();
7197 else OFFw(q, NOPRINT_xxx);
7198
7199 i = q->begtask;
7200 lwin = 1; // 1 for the column header
7201 wmax = winMIN(wmax, q->winlines + 1); // ditto for winlines, too
7202 numtasks = q->focus_pid ? winMIN(q->focus_end, PIDSmaxt) : PIDSmaxt;
7203
7204 /* the least likely scenario is also the most costly, so we'll try to avoid
7205 checking some stuff with each iteration and check it just once... */
7206 if (CHKw(q, Show_IDLEPS) && !q->usrseltyp)
7207 while (i < numtasks && lwin < wmax) {
7208 if (*task_show(q, i++))
7209 ++lwin;
7210 }
7211 else
7212 while (i < numtasks && lwin < wmax) {
7213 if ((CHKw(q, Show_IDLEPS) || isBUSY(q->ppt[i]))
7214 && wins_usrselect(q, i)
7215 && *task_show(q, i))
7216 ++lwin;
7217 ++i;
7218 }
7219
7220 return lwin;
7221 #undef sORDER
7222 #undef isBUSY
7223 #undef winMIN
7224 } // end: window_show
7225
7226 /*###### Entry point plus two ##########################################*/
7227
7228 /*
7229 * This guy's just a *Helper* function who apportions the
7230 * remaining amount of screen real estate under multiple windows */
7231 static void frame_hlp (int wix, int max) {
7232 int i, size, wins;
7233
7234 // calc remaining number of visible windows
7235 for (i = wix, wins = 0; i < GROUPSMAX; i++)
7236 if (CHKw(&Winstk[i], Show_TASKON))
7237 ++wins;
7238
7239 if (!wins) wins = 1;
7240 // deduct 1 line/window for the columns heading
7241 size = (max - wins) / wins;
7242
7243 /* for subject window, set WIN_t winlines to either the user's
7244 maxtask (1st choice) or our 'foxized' size calculation
7245 (foxized adj. - 'fair and balanced') */
7246 Winstk[wix].winlines =
7247 Winstk[wix].rc.maxtasks ? Winstk[wix].rc.maxtasks : size;
7248 } // end: frame_hlp
7249
7250
7251 /*
7252 * Initiate the Frame Display Update cycle at someone's whim!
7253 * This routine doesn't do much, mostly he just calls others.
7254 *
7255 * (Whoa, wait a minute, we DO caretake those row guys, plus)
7256 * (we CALCULATE that IMPORTANT Max_lines thingy so that the)
7257 * (*subordinate* functions invoked know WHEN the user's had)
7258 * (ENOUGH already. And at Frame End, it SHOULD be apparent)
7259 * (WE am d'MAN -- clearing UNUSED screen LINES and ensuring)
7260 * (that those auto-sized columns are addressed, know what I)
7261 * (mean? Huh, "doesn't DO MUCH"! Never, EVER think or say)
7262 * (THAT about THIS function again, Ok? Good that's better.)
7263 *
7264 * (ps. we ARE the UNEQUALED justification KING of COMMENTS!)
7265 * (No, I don't mean significance/relevance, only alignment.)
7266 */
7267 static void frame_make (void) {
7268 WIN_t *w = Curwin; // avoid gcc bloat with a local copy
7269 int i, scrlins;
7270
7271 // check auto-sized width increases from the last iteration...
7272 if (AUTOX_MODE && Autox_found)
7273 widths_resize();
7274
7275 /* deal with potential signal(s) since the last time around
7276 plus any input which may change 'tasks_refresh' needs... */
7277 if (Frames_signal) {
7278 if (Frames_signal == BREAK_sig
7279 || (Frames_signal == BREAK_screen))
7280 BOT_TOSS;
7281 zap_fieldstab();
7282 }
7283
7284 #ifdef THREADED_TSK
7285 sem_post(&Semaphore_tasks_beg);
7286 #else
7287 tasks_refresh(NULL);
7288 #endif
7289
7290 if (!Restrict_some) {
7291 #ifdef THREADED_CPU
7292 sem_post(&Semaphore_cpus_beg);
7293 #else
7294 cpus_refresh(NULL);
7295 #endif
7296 #ifdef THREADED_MEM
7297 sem_post(&Semaphore_memory_beg);
7298 #else
7299 memory_refresh(NULL);
7300 #endif
7301 }
7302
7303 // whoa either first time or thread/task mode change, (re)prime the pump...
7304 if (Pseudo_row == PROC_XTRA) {
7305 usleep(LIB_USLEEP);
7306 #ifdef THREADED_TSK
7307 sem_wait(&Semaphore_tasks_end);
7308 sem_post(&Semaphore_tasks_beg);
7309 #else
7310 tasks_refresh(NULL);
7311 #endif
7312 putp(Cap_clr_scr);
7313 } else
7314 putp(Batch ? "\n\n" : Cap_home);
7315
7316 Tree_idx = Pseudo_row = Msg_row = scrlins = 0;
7317 summary_show();
7318 Max_lines = (SCREEN_ROWS - Msg_row) - 1;
7319
7320 // we're now on Msg_row so clear out any residual messages ...
7321 putp(Cap_clr_eol);
7322
7323 if (!Rc.mode_altscr) {
7324 // only 1 window to show so, piece o' cake
7325 w->winlines = w->rc.maxtasks ? w->rc.maxtasks : Max_lines;
7326 scrlins = window_show(w, Max_lines);
7327 } else {
7328 // maybe NO window is visible but assume, pieces o' cakes
7329 for (i = 0 ; i < GROUPSMAX; i++) {
7330 if (CHKw(&Winstk[i], Show_TASKON)) {
7331 frame_hlp(i, Max_lines - scrlins);
7332 scrlins += window_show(&Winstk[i], Max_lines - scrlins);
7333 }
7334 if (Max_lines <= scrlins) break;
7335 }
7336 }
7337
7338 /* clear to end-of-screen - critical if last window is 'idleps off'
7339 (main loop must iterate such that we're always called before sleep) */
7340 if (!Batch && scrlins < Max_lines) {
7341 if (!BOT_PRESENT)
7342 putp(Cap_nl_clreos);
7343 else {
7344 for (i = scrlins + Msg_row + 1; i < SCREEN_ROWS; i++) {
7345 putp(tg2(0, i));
7346 putp(Cap_clr_eol);
7347 }
7348 }
7349 PSU_CLREOS(Pseudo_row);
7350 }
7351
7352 if (CHKw(w, View_SCROLL) && VIZISw(Curwin)) show_scroll();
7353 if (Bot_show_func) Bot_show_func();
7354 fflush(stdout);
7355
7356 /* we'll deem any terminal not supporting tgoto as dumb and disable
7357 the normal non-interactive output optimization... */
7358 if (!Cap_can_goto) PSU_CLREOS(0);
7359 } // end: frame_make
7360
7361
7362 /*
7363 * duh... */
7364 int main (int argc, char *argv[]) {
7365 before(*argv);
7366 // +-------------+
7367 wins_stage_1(); // top (sic) slice
7368 configs_reads(); // > spread etc, <
7369 parse_args(argc, argv); // > onions etc, <
7370 signals_set(); // > lean stuff, <
7371 whack_terminal(); // > more stuff. <
7372 wins_stage_2(); // as bottom slice
7373 // +-------------+
7374
7375 for (;;) {
7376 struct timespec ts;
7377
7378 frame_make();
7379
7380 if (0 < Loops) --Loops;
7381 if (!Loops) bye_bye(NULL);
7382
7383 ts.tv_sec = Rc.delay_time;
7384 ts.tv_nsec = (Rc.delay_time - (int)Rc.delay_time) * 1000000000;
7385
7386 if (Batch)
7387 pselect(0, NULL, NULL, NULL, &ts, NULL);
7388 else {
7389 if (ioa(&ts))
7390 do_key(iokey(IOKEY_ONCE));
7391 }
7392 /* note: that above ioa routine exists to consolidate all logic
7393 which is susceptible to signal interrupt and must then
7394 produce a screen refresh. in this main loop frame_make
7395 assumes responsibility for such refreshes. other logic
7396 in contact with users must deal more obliquely with an
7397 interrupt/refresh (hint: Frames_signal + return code)!
7398
7399 (everything is perfectly justified plus right margins)
7400 (are completely filled, but of course it must be luck)
7401 */
7402 }
7403 return 0;
7404 } // end: main