diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/Makefile.am | 30 | ||||
-rw-r--r-- | src/ascii.c | 1228 | ||||
-rw-r--r-- | src/ascii.h | 9 | ||||
-rw-r--r-- | src/charts.c | 1663 | ||||
-rw-r--r-- | src/charts.h | 31 | ||||
-rw-r--r-- | src/clickety.c | 8 | ||||
-rw-r--r-- | src/composite.c | 10 | ||||
-rw-r--r-- | src/context.c | 2 | ||||
-rw-r--r-- | src/desktop.c | 2 | ||||
-rw-r--r-- | src/key.c | 108 | ||||
-rw-r--r-- | src/launch.c | 126 | ||||
-rw-r--r-- | src/launchers.def | 14 | ||||
-rw-r--r-- | src/libvmon/LICENSE | 912 | ||||
-rw-r--r-- | src/libvmon/defs/proc_stat.def | 2 | ||||
-rw-r--r-- | src/libvmon/defs/proc_wants.def | 8 | ||||
-rw-r--r-- | src/libvmon/vmon.c | 869 | ||||
-rw-r--r-- | src/libvmon/vmon.h | 34 | ||||
-rw-r--r-- | src/logo.c | 2 | ||||
-rw-r--r-- | src/screen.c | 20 | ||||
-rw-r--r-- | src/screen.h | 12 | ||||
-rw-r--r-- | src/util.h | 3 | ||||
-rw-r--r-- | src/vcr.c | 2418 | ||||
-rw-r--r-- | src/vcr.h | 86 | ||||
-rw-r--r-- | src/vmon.c | 820 | ||||
-rw-r--r-- | src/vwm.c | 31 | ||||
-rw-r--r-- | src/vwm.h | 2 | ||||
-rw-r--r-- | src/window.c | 51 | ||||
-rw-r--r-- | src/window.h | 3 | ||||
-rw-r--r-- | src/xevent.c | 11 | ||||
-rw-r--r-- | src/xserver.c | 2 | ||||
-rw-r--r-- | src/xwindow.c | 36 | ||||
-rw-r--r-- | src/xwindow.h | 1 |
32 files changed, 6403 insertions, 2151 deletions
diff --git a/src/Makefile.am b/src/Makefile.am index 45428f9..a8d1035 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,10 +1,26 @@ SUBDIRS = libvmon -bin_PROGRAMS = vwm vmon +bin_PROGRAMS = vmon -vwm_SOURCES = clickety.c composite.c context.c desktop.c key.c launch.c logo.c charts.c screen.c vwm.c window.c xevent.c xserver.c xwindow.c clickety.h composite.h context.h desktop.h direction.h key.h launch.h list.h logo.h charts.h screen.h util.h vwm.h window.h xevent.h xserver.h xwindow.h colors.def context_colors.def launchers.def -vwm_LDADD = @VWM_LIBS@ libvmon/libvmon.a -vwm_CPPFLAGS = @VWM_CFLAGS@ +vmon_SOURCES = ascii.c charts.c vcr.c vmon.c ascii.h charts.h vcr.h +vmon_LDADD = libvmon/libvmon.a +vmon_CPPFLAGS = -O2 -vmon_SOURCES = vmon.c charts.c xserver.c charts.h xserver.h -vmon_LDADD= @VMON_LIBS@ libvmon/libvmon.a -vmon_CPPFLAGS = @VMON_CFLAGS@ +if HAVE_XCLIENT_DEV +vmon_SOURCES += xserver.c xserver.h +vmon_LDADD += @XCLIENT_DEV_LIBS@ +vmon_CPPFLAGS += @XCLIENT_DEV_CFLAGS@ -DUSE_XLIB +endif + +if HAVE_PNG_DEV +vmon_CPPFLAGS += @PNG_DEV_CFLAGS@ -DUSE_PNG +vmon_LDADD += @PNG_DEV_LIBS@ +endif + + +if ENABLE_VWM +bin_PROGRAMS += vwm + +vwm_SOURCES = ascii.c clickety.c composite.c context.c desktop.c key.c launch.c logo.c charts.c screen.c vcr.c vwm.c window.c xevent.c xserver.c xwindow.c ascii.h clickety.h composite.h context.h desktop.h direction.h key.h launch.h list.h logo.h charts.h screen.h util.h vcr.h vwm.h window.h xevent.h xserver.h xwindow.h colors.def context_colors.def launchers.def +vwm_LDADD = @XWM_DEV_LIBS@ libvmon/libvmon.a +vwm_CPPFLAGS = @XWM_DEV_CFLAGS@ -DUSE_XLIB +endif diff --git a/src/ascii.c b/src/ascii.c new file mode 100644 index 0000000..5e6183f --- /dev/null +++ b/src/ascii.c @@ -0,0 +1,1228 @@ +/* this comes from rototiller (gplv2) */ +#include "ascii.h" + +const char ascii_chars[256][ASCII_WIDTH * ASCII_HEIGHT] = { + ['!'] = { + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['"'] = { + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['#'] = { + 0, 0, 0, 0, 0, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 1, 1, 1, 1, 1, + 0, 1, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['$'] = { + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 1, + 1, 0, 1, 0, 0, + 1, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 1, 0, 1, + 0, 0, 1, 0, 1, + 1, 1, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['%'] = { + 0, 1, 0, 0, 1, + 1, 0, 1, 0, 1, + 0, 1, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, + 1, 0, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['&'] = { + 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 1, 0, 0, + 1, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 1, 0, 0, + 1, 0, 0, 1, 1, + 1, 0, 0, 1, 0, + 0, 1, 1, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['\''] = { + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['('] = { + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + }, + [')'] = { + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + }, + ['*'] = { + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 1, 0, 1, 0, 1, + 0, 1, 1, 1, 0, + 1, 0, 1, 0, 1, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['+'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + [','] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['-'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['.'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['/'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['0'] = { + 0, 0, 1, 0, 0, + 0, 1, 0, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['1'] = { + 0, 0, 1, 0, 0, + 0, 1, 1, 0, 0, + 1, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['2'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['3'] = { + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['4'] = { + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 1, 1, 0, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 1, 0, 0, 1, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['5'] = { + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 1, 1, 0, + 1, 1, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['6'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['7'] = { + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['8'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['9'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + + [':'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + [';'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['<'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + }, + ['='] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['>'] = { + 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['?'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['@'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 1, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 1, 0, + 1, 0, 0, 0, 0, + 0, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['a'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 1, + 0, 1, 1, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 1, 1, + 0, 1, 1, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['b'] = { + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['c'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['d'] = { + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 1, 1, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['e'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['f'] = { + 0, 0, 1, 1, 0, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 1, 1, 1, 1, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['g'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 1, + 0, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + }, + ['h'] = { + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 1, 1, 0, + 1, 1, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['i'] = { + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['j'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 1, 0, 0, 1, 0, + 1, 0, 0, 1, 0, + 0, 1, 1, 0, 0, + }, + ['k'] = { + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 1, 0, + 1, 0, 1, 0, 0, + 1, 1, 0, 0, 0, + 1, 0, 1, 0, 0, + 1, 0, 0, 1, 0, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['l'] = { + 0, 1, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['m'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 1, 0, 1, 0, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['n'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 0, 1, 1, 0, + 1, 1, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['o'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['p'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + }, + ['q'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + }, + ['r'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 0, 1, 1, 0, + 1, 1, 0, 0, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['s'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 0, 1, 1, 0, 0, + 0, 0, 0, 1, 0, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['t'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 1, 1, 1, 1, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 1, + 0, 0, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['u'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 1, 1, + 0, 1, 1, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['v'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['w'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['x'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 0, 1, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 1, 0, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['y'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 1, 1, + 0, 1, 1, 0, 1, + 0, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 1, + }, + ['z'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['A'] = { + 0, 0, 1, 0, 0, + 0, 1, 0, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['B'] = { + 1, 1, 1, 1, 0, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 1, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['C'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['D'] = { + 1, 1, 1, 1, 0, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 0, 1, 0, 0, 1, + 1, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['E'] = { + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['F'] = { + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['G'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['H'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['I'] = { + 0, 1, 1, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['J'] = { + 0, 0, 1, 1, 1, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 1, 0, 0, 1, 0, + 0, 1, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['K'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 1, 0, + 1, 0, 1, 0, 0, + 1, 1, 0, 0, 0, + 1, 0, 1, 0, 0, + 1, 0, 0, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['L'] = { + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['M'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 0, 1, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['N'] = { + 1, 0, 0, 0, 1, + 1, 1, 0, 0, 1, + 1, 1, 0, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 0, 1, 1, + 1, 0, 0, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['O'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['P'] = { + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['Q'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 1, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 1, + }, + ['R'] = { + 1, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 0, + 1, 0, 1, 0, 0, + 1, 0, 0, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['S'] = { + 0, 1, 1, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['T'] = { + 1, 1, 1, 1, 1, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['U'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 1, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['V'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['W'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 1, 0, 1, + 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['X'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['Y'] = { + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 0, 1, 0, 1, 0, + 0, 1, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['Z'] = { + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + + ['['] = { + 0, 1, 1, 1, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 1, 1, 0, + }, + ['\\'] = { + 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + }, + [']'] = { + 0, 1, 1, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 1, 0, + 0, 1, 1, 1, 0, + }, + ['^'] = { + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 1, 0, 1, 0, + 1, 0, 0, 0, 1, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['_'] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, + }, + ['`'] = { + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, + ['{'] = { + 0, 0, 0, 1, 1, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 1, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 1, + }, + ['|'] = { + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + }, + ['}'] = { + 1, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 1, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, + 1, 1, 0, 0, 0, + }, + ['~'] = { + 0, 1, 0, 0, 1, + 1, 0, 1, 0, 1, + 1, 0, 0, 1, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + }, +}; diff --git a/src/ascii.h b/src/ascii.h new file mode 100644 index 0000000..6c86898 --- /dev/null +++ b/src/ascii.h @@ -0,0 +1,9 @@ +#ifndef _ASCII_H +#define _ASCII_H + +#define ASCII_WIDTH 5 +#define ASCII_HEIGHT 11 + +extern const char ascii_chars[256][ASCII_WIDTH * ASCII_HEIGHT]; + +#endif diff --git a/src/charts.c b/src/charts.c index 6566f0a..da74400 100644 --- a/src/charts.c +++ b/src/charts.c @@ -1,10 +1,10 @@ /* * \/\/\ * - * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> + * Copyright (C) 2012-2025 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -18,63 +18,63 @@ /* libvmon integration, warning: this gets a little crazy especially in the rendering. */ -#include <X11/Xatom.h> -#include <X11/Xlib.h> -#include <X11/extensions/Xfixes.h> -#include <X11/extensions/Xrender.h> #include <assert.h> #include <math.h> #include <stdarg.h> #include <stdlib.h> -#include <sys/time.h> +#include <time.h> + +#ifdef USE_XLIB +#include <X11/extensions/Xfixes.h> +#endif #include "charts.h" -#include "composite.h" #include "libvmon/vmon.h" #include "list.h" -#include "vwm.h" -#include "xwindow.h" +#include "util.h" +#include "vcr.h" -#define CHART_MASK_DEPTH 8 /* XXX: 1 would save memory, but Xorg isn't good at it */ -#define CHART_FIXED_FONT "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1" -#define CHART_ROW_HEIGHT 15 /* this should always be larger than the font height */ -#define CHART_GRAPH_MIN_WIDTH 200 /* always create graphs at least this large */ -#define CHART_GRAPH_MIN_HEIGHT (4 * CHART_ROW_HEIGHT) -#define CHART_ISTHREAD_ARGV "~" /* use this string to mark threads in the argv field */ -#define CHART_NOCOMM_ARGV "#missed it!" /* use this string to substitute the command when missing in argv field */ -#define CHART_MAX_ARGC 64 /* this is a huge amount */ -#define CHART_VMON_PROC_WANTS (VMON_WANT_PROC_STAT | VMON_WANT_PROC_FOLLOW_CHILDREN | VMON_WANT_PROC_FOLLOW_THREADS) -#define CHART_VMON_SYS_WANTS (VMON_WANT_SYS_STAT) -#define CHART_MAX_COLUMNS 16 +#ifdef USE_XLIB +#include "composite.h" +#include "xwindow.h" +#include "vwm.h" +#endif + +#define CHART_ISTHREAD_ARGV "~" /* use this string to mark threads in the argv field */ +#define CHART_NOCOMM_ARGV "# missed it!" /* use this string to substitute the command when missing in argv field */ +#define CHART_MAX_ARGC 64 /* this is a huge amount */ +#define CHART_VMON_PROC_WANTS (VMON_WANT_PROC_STAT | VMON_WANT_PROC_FOLLOW_CHILDREN | VMON_WANT_PROC_FOLLOW_THREADS) +#define CHART_VMON_SYS_WANTS (VMON_WANT_SYS_STAT) +#define CHART_MAX_COLUMNS 16 +#define CHART_DELTA_SECONDS_EPSILON .001f /* adherence errors smaller than this are treated as zero */ +#define CHART_NUM_FIXED_HEADER_ROWS 3 /* number of rows @ top before the hierarchy: { IOWait/Idle, IRQ/SoftIRQ, Adherence } */ +#define CHART_DEFAULT_INTERVAL_SECS .1f /* default to 10Hz */ /* the global charts state, supplied to vwm_chart_create() which keeps a reference for future use. */ typedef struct _vwm_charts_t { - vwm_xserver_t *xserver; /* xserver supplied to vwm_charts_init() */ + vcr_backend_t *vcr_backend; /* supplied to vwm_charts_create() */ /* libvmon */ - struct timeval maybe_sample, last_sample, this_sample; + struct timespec maybe_sample, last_sample, this_sample; + unsigned this_sample_duration; + float this_sample_adherence; /* 0 = on time, (+) behind schedule, (-) ahead of schedule, units is fraction of .sampling_interval_secs */ typeof(((vmon_sys_stat_t *)0)->user) last_user_cpu; typeof(((vmon_sys_stat_t *)0)->system) last_system_cpu; unsigned long long last_total, this_total, total_delta; unsigned long long last_idle, last_iowait, idle_delta, iowait_delta; + unsigned long long last_irq, last_softirq, irq_delta, softirq_delta; vmon_t vmon; - float prev_sampling_interval, sampling_interval; - int sampling_paused, contiguous_drops; - - /* X */ - XFontStruct *chart_font; - GC text_gc; - Picture shadow_fill, - text_fill, - bg_fill, - snowflakes_text_fill, - grapha_fill, - graphb_fill, - finish_fill; + float prev_sampling_interval_secs, sampling_interval_secs; + int sampling_paused, contiguous_drops, primed; + unsigned marker_distance; + float inv_ticks_per_sec, inv_total_delta; + unsigned defer_maintenance:1; + unsigned no_threads:1; } vwm_charts_t; typedef enum _vwm_column_type_t { VWM_COLUMN_VWM, + VWM_COLUMN_ROW, VWM_COLUMN_PROC_USER, VWM_COLUMN_PROC_SYS, VWM_COLUMN_PROC_WALL, @@ -83,6 +83,7 @@ typedef enum _vwm_column_type_t { VWM_COLUMN_PROC_PID, VWM_COLUMN_PROC_WCHAN, VWM_COLUMN_PROC_STATE, + VWM_COLUMN_PROC_RSS, VWM_COLUMN_CNT } vwm_column_type_t; @@ -95,9 +96,9 @@ typedef enum _vwm_side_t { /* how to horizontally justify contents within a given column's area */ typedef enum _vwm_justify_t { + VWM_JUSTIFY_CENTER, VWM_JUSTIFY_LEFT, VWM_JUSTIFY_RIGHT, - VWM_JUSTIFY_CENTER, VWM_JUSTIFY_CNT } vwm_justify_t; @@ -105,32 +106,47 @@ typedef struct _vwm_column_t { /* TODO: make the columns configurable and add more description/toggled state here */ unsigned enabled:1; vwm_column_type_t type; - vwm_side_t side; int width; } vwm_column_t; +/* a row-column is a row's instance of a column, to facilitate rows that want to reference a column multiple times, + * as well as the multi-row use adding per-proc memory rows will start doing - there will need to be a way to + * for instance get the _TREE column into the memory row for continuity purposes (though it will likely need to be + * augmented slightly in the sub-row or whatever that becomes) as there won't be any Argv to point at in the memory + * row following the CPU row. + */ +typedef struct _vwm_row_column_t { + vwm_column_t *column; + vwm_side_t side; + vwm_justify_t justify; +} vwm_row_column_t; + /* everything needed by the per-window chart's context */ typedef struct _vwm_chart_t { - vmon_proc_t *monitor; /* vmon process monitor handle */ - Pixmap text_pixmap; /* pixmap for charted text (kept around for XDrawText usage) */ - Picture text_picture; /* picture representation of text_pixmap */ - Picture shadow_picture; /* text shadow layer */ - Picture grapha_picture; /* graph A layer */ - Picture graphb_picture; /* graph B layer */ - Picture tmp_picture; /* 1 row worth of temporary picture space */ - Picture picture; /* chart picture derived from the pixmap, for render compositing */ - int width; /* current width of the chart */ - int height; /* current height of the chart */ - int visible_width; /* currently visible width of the chart */ - int visible_height; /* currently visible height of the chart */ - int phase; /* current position within the (horizontally scrolling) graphs */ - int heirarchy_end; /* row where the process heirarchy currently ends */ - int snowflakes_cnt; /* count of snowflaked rows (reset to zero to truncate snowflakes display) */ - int gen_last_composed; /* the last composed vmon generation */ - int redraw_needed; /* if a redraw is required (like when the window is resized...) */ - char *name; /* name if provided, included in chart by the \/\/\ */ - vwm_column_t columns[CHART_MAX_COLUMNS]; /* columns in the chart TODO, for now just stowing the real/user/sys width here */ - vwm_column_t snowflake_columns[CHART_MAX_COLUMNS]; /* columns in the snowflaked rows */ + vmon_proc_t *proc; /* vmon process monitor handle */ + vcr_t *vcr; + + int hierarchy_end; /* row where the process hierarchy currently ends */ + + /* FIXME TODO: this is redundant with the same things in vcr_t now, dedupe them */ + int visible_width; /* currently visible width of the chart */ + int visible_height; /* currently visible height of the chart */ + + int snowflakes_cnt; /* count of snowflaked rows (reset to zero to truncate snowflakes display) */ + int gen_last_composed; /* the last composed vmon generation */ + int redraw_needed; /* if a redraw is required (like when the window is resized...) */ + char *name; /* name if provided, included in chart by the \/\/\ */ + vwm_column_t top_columns[CHART_MAX_COLUMNS]; /* "top" columns in the chart (vwm logo, hz) */ + vwm_column_t proc_cpu_columns[CHART_MAX_COLUMNS]; /* per-proc+thread CPU columns in the chart TODO, for now just stowing the widths here */ + vwm_column_t proc_mem_columns[CHART_MAX_COLUMNS]; /* per-proc Memory columns in the chart TODO, for now just stowing the widths here */ + vwm_column_t snowflake_cpu_columns[CHART_MAX_COLUMNS]; /* per-proc+thread CPU columns in the snowflaked rows */ + vwm_column_t snowflake_mem_columns[CHART_MAX_COLUMNS]; /* per-proc Memory columns in the snowflaked rows */ + + vwm_row_column_t top_row_columns[CHART_MAX_COLUMNS]; /* "top" columns in the chart (vwm logo, hz) */ + vwm_row_column_t proc_cpu_row_columns[CHART_MAX_COLUMNS]; + vwm_row_column_t proc_mem_row_columns[CHART_MAX_COLUMNS]; + vwm_row_column_t snowflake_cpu_row_columns[CHART_MAX_COLUMNS]; /* per-proc+thread CPU columns in the snowflaked rows */ + vwm_row_column_t snowflake_mem_row_columns[CHART_MAX_COLUMNS]; /* per-proc Memory columns in the snowflaked rows */ } vwm_chart_t; /* space we need for every process being monitored */ @@ -140,27 +156,17 @@ typedef struct _vwm_perproc_ctxt_t { typeof(((vmon_proc_stat_t *)0)->stime) last_stime; typeof(((vmon_proc_stat_t *)0)->utime) utime_delta; typeof(((vmon_proc_stat_t *)0)->stime) stime_delta; + int row; } vwm_perproc_ctxt_t; -static float sampling_intervals[] = { - INFINITY, /* STOPPED */ - 1, /* ~1Hz */ - .1, /* ~10Hz */ - .05, /* ~20Hz */ - .025, /* ~40Hz */ - .01666}; /* ~60Hz */ - -static XRenderColor chart_visible_color = { 0xffff, 0xffff, 0xffff, 0xffff }, - chart_shadow_color = { 0x0000, 0x0000, 0x0000, 0xC000}, - chart_bg_color = { 0x0, 0x1000, 0x0, 0x9000}, - chart_div_color = { 0x2000, 0x3000, 0x2000, 0x9000}, - chart_snowflakes_visible_color = { 0xd000, 0xd000, 0xd000, 0x8000 }, - chart_trans_color = {0x00, 0x00, 0x00, 0x00}, - chart_grapha_color = { 0xff00, 0x0000, 0x0000, 0x3000 }, /* ~red */ - chart_graphb_color = { 0x0000, 0xffff, 0xffff, 0x3000 }; /* ~cyan */ -static XRenderPictureAttributes pa_repeat = { .repeat = 1 }; -static XRenderPictureAttributes pa_no_repeat = { .repeat = 0 }; +static float sampling_intervals[] = { + 1, /* ~1Hz */ + .1, /* ~10Hz */ + .05, /* ~20Hz */ + .025, /* ~40Hz */ + .01666, /* ~60Hz */ + }; /* wrapper around snprintf always returning the length of what's in the buf */ @@ -188,8 +194,11 @@ static void sample_callback(vmon_t *vmon, void *arg) sys_stat->softirq + sys_stat->steal + sys_stat->guest; charts->total_delta = charts->this_total - charts->last_total; + charts->inv_total_delta = 1.f / (float)charts->total_delta; charts->idle_delta = sys_stat->idle - charts->last_idle; charts->iowait_delta = sys_stat->iowait - charts->last_iowait; + charts->irq_delta = sys_stat->irq - charts->last_irq; + charts->softirq_delta = sys_stat->softirq - charts->last_softirq; } @@ -211,66 +220,11 @@ static void vmon_dtor_cb(vmon_t *vmon, vmon_proc_t *proc) } -/* convenience helper for creating a pixmap */ -static Pixmap create_pixmap(vwm_charts_t *charts, unsigned width, unsigned height, unsigned depth) -{ - vwm_xserver_t *xserver = charts->xserver; - - return XCreatePixmap(xserver->display, XSERVER_XROOT(xserver), width, height, depth); -} - - -/* convenience helper for creating a picture, supply res_pixmap to keep a reference to the pixmap drawable. */ -static Picture create_picture(vwm_charts_t *charts, unsigned width, unsigned height, unsigned depth, unsigned long attr_mask, XRenderPictureAttributes *attr, Pixmap *res_pixmap) -{ - vwm_xserver_t *xserver = charts->xserver; - Pixmap pixmap; - Picture picture; - int format; - - /* FIXME this pixmap->picture dance seems silly, investigate further. TODO */ - switch (depth) { - case 8: - format = PictStandardA8; - break; - case 32: - format = PictStandardARGB32; - break; - default: - assert(0); - } - - pixmap = create_pixmap(charts, width, height, depth); - picture = XRenderCreatePicture(xserver->display, pixmap, XRenderFindStandardFormat(xserver->display, format), attr_mask, attr); - - if (res_pixmap) { - *res_pixmap = pixmap; - } else { - XFreePixmap(xserver->display, pixmap); - } - - return picture; -} - - -/* convenience helper for creating a filled picture, supply res_pixmap to keep a reference to the pixmap drawable. */ -static Picture create_picture_fill(vwm_charts_t *charts, unsigned width, unsigned height, unsigned depth, unsigned long attrs_mask, XRenderPictureAttributes *attrs, const XRenderColor *color, Pixmap *res_pixmap) -{ - vwm_xserver_t *xserver = charts->xserver; - Picture picture; - - picture = create_picture(charts, width, height, depth, attrs_mask, attrs, res_pixmap); - XRenderFillRectangle(xserver->display, PictOpSrc, picture, color, 0, 0, width, height); - - return picture; -} - - /* initialize charts system */ -vwm_charts_t * vwm_charts_create(vwm_xserver_t *xserver) +vwm_charts_t * vwm_charts_create(vcr_backend_t *vbe, unsigned flags) { + vmon_flags_t vmon_flags = VMON_FLAG_2PASS; vwm_charts_t *charts; - Pixmap bitmask; charts = calloc(1, sizeof(vwm_charts_t)); if (!charts) { @@ -278,10 +232,19 @@ vwm_charts_t * vwm_charts_create(vwm_xserver_t *xserver) goto _err; } - charts->xserver = xserver; - charts->prev_sampling_interval = charts->sampling_interval = 0.1f; /* default to 10Hz */ + charts->vcr_backend = vbe; + + if (flags & VWM_CHARTS_FLAG_DEFER_MAINTENANCE) + charts->defer_maintenance = 1; + + if (flags & VWM_CHARTS_NO_THREADS) { + charts->no_threads = 1; + vmon_flags |= VMON_FLAG_NEGLECT_THREADS; + } + + charts->prev_sampling_interval_secs = charts->sampling_interval_secs = CHART_DEFAULT_INTERVAL_SECS; - if (!vmon_init(&charts->vmon, VMON_FLAG_2PASS, CHART_VMON_SYS_WANTS, CHART_VMON_PROC_WANTS)) { + if (!vmon_init(&charts->vmon, vmon_flags, CHART_VMON_SYS_WANTS, CHART_VMON_PROC_WANTS)) { VWM_ERROR("unable to initialize libvmon"); goto _err_charts; } @@ -290,42 +253,13 @@ vwm_charts_t * vwm_charts_create(vwm_xserver_t *xserver) charts->vmon.proc_dtor_cb = vmon_dtor_cb; charts->vmon.sample_cb = sample_callback; charts->vmon.sample_cb_arg = charts; - gettimeofday(&charts->this_sample, NULL); + clock_gettime(CLOCK_MONOTONIC_RAW, &charts->this_sample); - /* get all the text and graphics stuff setup for charts */ - charts->chart_font = XLoadQueryFont(xserver->display, CHART_FIXED_FONT); - if (!charts->chart_font) { - VWM_ERROR("unable to load chart font \"%s\"", CHART_FIXED_FONT); - goto _err_vmon; - } - - /* create a GC for rendering the text using Xlib into the text chart stencils */ - bitmask = create_pixmap(charts, 1, 1, CHART_MASK_DEPTH); - charts->text_gc = XCreateGC(xserver->display, bitmask, 0, NULL); - XSetForeground(xserver->display, charts->text_gc, WhitePixel(xserver->display, xserver->screen_num)); - XFreePixmap(xserver->display, bitmask); - - /* create some repeating source fill pictures for drawing through the text and graph stencils */ - charts->text_fill = create_picture_fill(charts, 1, 1, 32, CPRepeat, &pa_repeat, &chart_visible_color, NULL); - charts->shadow_fill = create_picture_fill(charts, 1, 1, 32, CPRepeat, &pa_repeat, &chart_shadow_color, NULL); - - charts->bg_fill = create_picture(charts, 1, CHART_ROW_HEIGHT, 32, CPRepeat, &pa_repeat, NULL); - XRenderFillRectangle(xserver->display, PictOpSrc, charts->bg_fill, &chart_bg_color, 0, 0, 1, CHART_ROW_HEIGHT); - XRenderFillRectangle(xserver->display, PictOpSrc, charts->bg_fill, &chart_div_color, 0, CHART_ROW_HEIGHT - 1, 1, 1); - - charts->snowflakes_text_fill = create_picture_fill(charts, 1, 1, 32, CPRepeat, &pa_repeat, &chart_snowflakes_visible_color, NULL); - charts->grapha_fill = create_picture_fill(charts, 1, 1, 32, CPRepeat, &pa_repeat, &chart_grapha_color, NULL); - charts->graphb_fill = create_picture_fill(charts, 1, 1, 32, CPRepeat, &pa_repeat, &chart_graphb_color, NULL); - - charts->finish_fill = create_picture(charts, 1, 2, 32, CPRepeat, &pa_repeat, NULL); - XRenderFillRectangle(xserver->display, PictOpSrc, charts->finish_fill, &chart_visible_color, 0, 0, 1, 1); - XRenderFillRectangle(xserver->display, PictOpSrc, charts->finish_fill, &chart_trans_color, 0, 1, 1, 1); + /* cache multiplicative inverse so we can multiply instead of divide constantly */ + charts->inv_ticks_per_sec = 1.f / (float)charts->vmon.ticks_per_sec; return charts; -_err_vmon: - vmon_destroy(&charts->vmon); - _err_charts: free(charts); @@ -342,174 +276,114 @@ void vwm_charts_destroy(vwm_charts_t *charts) } -/* copies a row from src to dest */ -static void copy_row(vwm_charts_t *charts, vwm_chart_t *chart, int src_row, Picture src, int dest_row, Picture dest) +/* moves what's below a given row up above it, preserve the lost row's graphs @ hierarchy end */ +static void snowflake_row(vwm_charts_t *charts, vwm_chart_t *chart, int row) { - XRenderComposite(charts->xserver->display, PictOpSrc, src, None, dest, - 0, src_row * CHART_ROW_HEIGHT, /* src */ - 0, 0, /* mask */ - 0, dest_row * CHART_ROW_HEIGHT, /* dest */ - chart->width, CHART_ROW_HEIGHT); /* dimensions */ -} + VWM_TRACE("pid=%i chart=%p row=%i heirarhcy_end=%i", chart->proc->pid, chart, row, chart->hierarchy_end); + /* stash the graph rows */ + vcr_stash_row(chart->vcr, VCR_LAYER_GRAPHA, row); + vcr_stash_row(chart->vcr, VCR_LAYER_GRAPHB, row); -/* fills a row with the specified color */ -static void fill_row(vwm_charts_t *charts, vwm_chart_t *chart, int row, Picture pic, XRenderColor *color) -{ - XRenderFillRectangle(charts->xserver->display, PictOpSrc, pic, color, - 0, row * CHART_ROW_HEIGHT, /* dest */ - chart->width, CHART_ROW_HEIGHT); /* dimensions */ -} + /* shift _all_ the layers up by 1 row */ + vcr_shift_below_row_up_one(chart->vcr, row); + /* unstash the graph rows @ hierarchy end so we have them in the snowflakes */ + vcr_unstash_row(chart->vcr, VCR_LAYER_GRAPHA, chart->hierarchy_end); + vcr_unstash_row(chart->vcr, VCR_LAYER_GRAPHB, chart->hierarchy_end); -/* copy what's below a given row up the specified amount within the same picture */ -static void shift_below_row_up(vwm_charts_t *charts, vwm_chart_t *chart, int row, Picture pic, int rows) -{ - vwm_xserver_t *xserver = charts->xserver; - - XRenderChangePicture(xserver->display, pic, CPRepeat, &pa_no_repeat); - XRenderComposite(xserver->display, PictOpSrc, pic, None, pic, - 0, (rows + row) * CHART_ROW_HEIGHT, /* src */ - 0, 0, /* mask */ - 0, row * CHART_ROW_HEIGHT, /* dest */ - chart->width, (rows + chart->heirarchy_end) * CHART_ROW_HEIGHT - (rows + row) * CHART_ROW_HEIGHT); /* dimensions */ - XRenderChangePicture(xserver->display, pic, CPRepeat, &pa_repeat); + /* clear the others @ hierarchy end, new argv will get stamped over it */ + vcr_clear_row(chart->vcr, VCR_LAYER_TEXT, chart->hierarchy_end, -1, -1); + vcr_clear_row(chart->vcr, VCR_LAYER_SHADOW, chart->hierarchy_end, -1, -1); } -/* moves what's below a given row up above it if specified, the row becoming discarded */ -static void snowflake_row(vwm_charts_t *charts, vwm_chart_t *chart, Picture pic, int copy, int row) -{ - VWM_TRACE("pid=%i chart=%p row=%i copy=%i heirarhcy_end=%i", chart->monitor->pid, chart, row, copy, chart->heirarchy_end); - - if (copy) - copy_row(charts, chart, row, pic, 0, chart->tmp_picture); - - shift_below_row_up(charts, chart, row, pic, 1); - - if (copy) { - copy_row(charts, chart, 0, chart->tmp_picture, chart->heirarchy_end, pic); - } else { - fill_row(charts, chart, chart->heirarchy_end, pic, &chart_trans_color); - } -} - /* XXX TODO libvmon automagic children following races with explicit X client pid monitoring with different outcomes, it should be irrelevant which wins, - * currently the only visible difference is the snowflakes gap (heirarchy_end) varies, which is why I haven't bothered to fix it, I barely even notice. + * currently the only visible difference is the snowflakes gap (hierarchy_end) varies, which is why I haven't bothered to fix it, I barely even notice. */ -static void shift_below_row_down(vwm_charts_t *charts, vwm_chart_t *chart, int row, Picture pic, int rows) -{ - XRenderComposite(charts->xserver->display, PictOpSrc, pic, None, pic, - 0, row * CHART_ROW_HEIGHT, /* src */ - 0, 0, /* mask */ - 0, (row + rows) * CHART_ROW_HEIGHT, /* dest */ - chart->width, chart->height - (rows + row) * CHART_ROW_HEIGHT); /* dimensions */ -} - - /* shifts what's below a given row down a row, and clears the row, preparing it for populating */ -static void allocate_row(vwm_charts_t *charts, vwm_chart_t *chart, Picture pic, int row) +static void allocate_row(vwm_charts_t *charts, vwm_chart_t *chart, int row) { - VWM_TRACE("pid=%i chart=%p row=%i", chart->monitor->pid, chart, row); + VWM_TRACE("pid=%i chart=%p row=%i", chart->proc->pid, chart, row); - shift_below_row_down(charts, chart, row, pic, 1); - fill_row(charts, chart, row, pic, &chart_trans_color); -} - - -/* shadow a row from the text layer in the shadow layer */ -static void shadow_row(vwm_charts_t *charts, vwm_chart_t *chart, int row) -{ - vwm_xserver_t *xserver = charts->xserver; - - /* the current technique for creating the shadow is to simply render the text at +1/-1 pixel offsets on both axis in translucent black */ - XRenderComposite(xserver->display, PictOpSrc, charts->shadow_fill, chart->text_picture, chart->shadow_picture, - 0, 0, - -1, row * CHART_ROW_HEIGHT, - 0, row * CHART_ROW_HEIGHT, - chart->visible_width, CHART_ROW_HEIGHT); - - XRenderComposite(xserver->display, PictOpOver, charts->shadow_fill, chart->text_picture, chart->shadow_picture, - 0, 0, - 0, -1 + row * CHART_ROW_HEIGHT, - 0, row * CHART_ROW_HEIGHT, - chart->visible_width, CHART_ROW_HEIGHT); - - XRenderComposite(xserver->display, PictOpOver, charts->shadow_fill, chart->text_picture, chart->shadow_picture, - 0, 0, - 1, row * CHART_ROW_HEIGHT, - 0, row * CHART_ROW_HEIGHT, - chart->visible_width, CHART_ROW_HEIGHT); - - XRenderComposite(xserver->display, PictOpOver, charts->shadow_fill, chart->text_picture, chart->shadow_picture, - 0, 0, - 0, 1 + row * CHART_ROW_HEIGHT, - 0, row * CHART_ROW_HEIGHT, - chart->visible_width, CHART_ROW_HEIGHT); + vcr_shift_below_row_down_one(chart->vcr, row); + /* FIXME TODO: the vcr layers api needs to just support bitmasks for which layers the operation + * applies to. + */ + vcr_clear_row(chart->vcr, VCR_LAYER_GRAPHA, row, -1, -1); + vcr_clear_row(chart->vcr, VCR_LAYER_GRAPHB, row, -1, -1); + vcr_clear_row(chart->vcr, VCR_LAYER_TEXT, row, -1, -1); + vcr_clear_row(chart->vcr, VCR_LAYER_SHADOW, row, -1, -1); } /* simple helper to map the vmon per-proc argv array into an XTextItem array, deals with threads vs. processes and the possibility of the comm field not getting read in before the process exited... */ -static void argv2xtext(const vmon_proc_t *proc, XTextItem *items, int max_items, int *nr_items) +static void proc_argv2strs(const vmon_proc_t *proc, vcr_str_t *strs, int max_strs, int *res_n_strs) { - int i; - int nr = 0; + static char n_threads_str[sizeof(STRINGIFY(UINT_MAX)) + sizeof("[]")]; + int nr = 0; + + assert(proc); + assert(strs); + assert(max_strs > 2); + assert(res_n_strs); if (proc->is_thread) { /* stick the thread marker at the start of threads */ - items[0].nchars = sizeof(CHART_ISTHREAD_ARGV) - 1; - items[0].chars = CHART_ISTHREAD_ARGV; - items[0].delta = 4; - items[0].font = None; + strs[0].str = CHART_ISTHREAD_ARGV; + strs[0].len = sizeof(CHART_ISTHREAD_ARGV) - 1; + nr++; + } else if (!proc->is_stale) { + strs[0].str = n_threads_str; + if (proc->is_threaded) + strs[0].len = snprintf(n_threads_str, sizeof(n_threads_str), "[%u]", proc->n_current_threads); + else + strs[0].len = snprintf(n_threads_str, sizeof(n_threads_str), "[]"); nr++; } if (((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len) { - items[nr].nchars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1; - items[nr].chars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array; + strs[nr].str = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array; + strs[nr].len = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1; } else { /* sometimes a process is so ephemeral we don't manage to sample its comm, XXX TODO: we always have a pid, stringify it? */ - items[nr].nchars = sizeof(CHART_NOCOMM_ARGV) - 1; - items[nr].chars = CHART_NOCOMM_ARGV; + strs[nr].str = CHART_NOCOMM_ARGV; + strs[nr].len = sizeof(CHART_NOCOMM_ARGV) - 1; } - items[nr].delta = 4; - items[nr].font = None; nr++; if (!proc->is_thread) { /* suppress the argv for threads */ - for (i = 1; nr < max_items && i < ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argc; nr++, i++) { - items[nr].chars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]; - items[nr].nchars = strlen(((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]); /* TODO: libvmon should inform us of the length */ - items[nr].delta = 4; - items[nr].font = None; + for (int i = 1; nr < max_strs && i < ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argc; nr++, i++) { + strs[nr].str = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]; + strs[nr].len = strlen(((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]); /* TODO: libvmon should inform us of the length */ } } - (*nr_items) = nr; + *res_n_strs = nr; } /* helper for counting number of existing descendants subtrees */ -static int count_rows(vmon_proc_t *proc) +static int count_rows(vmon_proc_t *proc, unsigned no_threads) { - int count = 1; /* XXX maybe suppress proc->is_new? */ + int count = no_threads ? !proc->is_thread : 1; /* XXX maybe suppress proc->is_new? */ vmon_proc_t *child; if (!proc->is_thread) { list_for_each_entry(child, &proc->threads, threads) - count += count_rows(child); + count += count_rows(child, no_threads); } list_for_each_entry(child, &proc->children, siblings) - count += count_rows(child); + count += count_rows(child, no_threads); return count; } -/* helper for detecting if any children/threads in the process heirarchy rooted @ proc are new/stale this sample */ -static int proc_heirarchy_changed(vmon_proc_t *proc) +/* helper for detecting if any children/threads in the process hierarchy rooted @ proc are new/stale this sample */ +static int proc_hierarchy_changed(vmon_proc_t *proc) { vmon_proc_t *child; @@ -518,13 +392,13 @@ static int proc_heirarchy_changed(vmon_proc_t *proc) if (!proc->is_thread) { list_for_each_entry(child, &proc->threads, threads) { - if (proc_heirarchy_changed(child)) + if (proc_hierarchy_changed(child)) return 1; } } list_for_each_entry(child, &proc->children, siblings) { - if (proc_heirarchy_changed(child)) + if (proc_hierarchy_changed(child)) return 1; } @@ -533,81 +407,61 @@ static int proc_heirarchy_changed(vmon_proc_t *proc) /* helper for drawing the vertical bars in the graph layers */ -static void draw_bars(vwm_charts_t *charts, vwm_chart_t *chart, int row, double a_fraction, double a_total, double b_fraction, double b_total) +static void draw_bars(vwm_charts_t *charts, vwm_chart_t *chart, int row, float mult, float a_fraction, float inv_a_total, vcr_layer_t a_layer, float b_fraction, float inv_b_total, vcr_layer_t b_layer) { - vwm_xserver_t *xserver = charts->xserver; - int a_height, b_height; + float a_t, b_t; - /* compute the bar heights for this sample */ - a_height = (a_fraction / a_total * (double)(CHART_ROW_HEIGHT - 1)); /* give up 1 pixel for the div */ - b_height = (b_fraction / b_total * (double)(CHART_ROW_HEIGHT - 1)); + /* compute the bar %ages for this sample */ + a_t = a_fraction * inv_a_total * mult; + b_t = b_fraction * inv_b_total * mult; - /* round up to 1 pixel when the scaled result is a fraction less than 1, + /* ensure at least 1 pixel when the scaled result is a fraction less than 1, * I want to at least see 1 pixel blips for the slightest cpu utilization */ - if (a_fraction && !a_height) - a_height = 1; - - if (b_fraction && !b_height) - b_height = 1; - - /* draw the two bars for this sample at the current phase in the graphs, note the first is ceiling-based, second floor-based */ - XRenderFillRectangle(xserver->display, PictOpSrc, chart->grapha_picture, &chart_visible_color, - chart->phase, row * CHART_ROW_HEIGHT, /* dst x, y */ - 1, a_height); /* dst w, h */ - XRenderFillRectangle(xserver->display, PictOpSrc, chart->graphb_picture, &chart_visible_color, - chart->phase, row * CHART_ROW_HEIGHT + (CHART_ROW_HEIGHT - b_height) - 1, /* dst x, y */ - 1, b_height); /* dst w, h */ + vcr_draw_bar(chart->vcr, a_layer, row, a_t, a_fraction != 0 ? 1 : 0 /* min_height */); + vcr_draw_bar(chart->vcr, b_layer, row, b_t, b_fraction != 0 ? 1 : 0 /* min_height */); } /* helper for marking a finish line at the current phase for the specified row */ static void mark_finish(vwm_charts_t *charts, vwm_chart_t *chart, int row) { - vwm_xserver_t *xserver = charts->xserver; - - XRenderComposite(xserver->display, PictOpSrc, charts->finish_fill, None, chart->grapha_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - chart->phase, row * CHART_ROW_HEIGHT, /* dst x, y */ - 1, CHART_ROW_HEIGHT - 1); - XRenderComposite(xserver->display, PictOpSrc, charts->finish_fill, None, chart->graphb_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - chart->phase, row * CHART_ROW_HEIGHT, /* dst x, y */ - 1, CHART_ROW_HEIGHT - 1); + vcr_mark_finish_line(chart->vcr, VCR_LAYER_GRAPHA, row); + vcr_mark_finish_line(chart->vcr, VCR_LAYER_GRAPHB, row); } /* helper for drawing a proc's argv @ specified x offset and row on the chart */ static void print_argv(const vwm_charts_t *charts, const vwm_chart_t *chart, int x, int row, const vmon_proc_t *proc, int *res_width) { - vwm_xserver_t *xserver = charts->xserver; - XTextItem items[CHART_MAX_ARGC]; - int nr_items; + vcr_str_t strs[VCR_DRAW_TEXT_N_STRS_MAX]; + int n_strs; - argv2xtext(proc, items, NELEMS(items), &nr_items); - XDrawText(xserver->display, chart->text_pixmap, charts->text_gc, - x, (row + 1) * CHART_ROW_HEIGHT - 3, /* dst x, y */ - items, nr_items); - - /* if the caller wants to know the width, compute it, it's dumb that XDrawText doesn't - * return the dimensions of what was drawn, fucking xlib. - */ - if (res_width) { - int width = 0; - - for (int i = 0; i < nr_items; i++) - width += XTextWidth(charts->chart_font, items[i].chars, items[i].nchars) + items[i].delta; + assert(chart); - *res_width = width; - } + proc_argv2strs(proc, strs, NELEMS(strs), &n_strs); + vcr_draw_text(chart->vcr, VCR_LAYER_TEXT, x, row, strs, n_strs, res_width); } -/* determine if a given process has subsequent siblings in the heirarchy */ -static inline int proc_has_subsequent_siblings(vmon_t *vmon, vmon_proc_t *proc) +/* determine if a given process has subsequent siblings in the hierarchy */ +static inline int proc_has_subsequent_siblings(vwm_charts_t *charts, vmon_proc_t *proc) { - struct list_head *sib, *head = &vmon->processes; + struct list_head *sib, *head = &charts->vmon.processes; + + if (proc->is_thread) { + if (!charts->no_threads) { + /* Supporting threads having children arrived late in vwm's existence, + * but it indeed is a thing. */ + assert(proc->parent && proc->parent->is_threaded); + head = &proc->parent->threads; + for (sib = proc->threads.next; sib != head; sib = sib->next) { + if (!(list_entry(sib, vmon_proc_t, threads)->is_stale)) + return 1; + } + } + + return 0; + } if (proc->parent) head = &proc->parent->children; @@ -622,126 +476,155 @@ static inline int proc_has_subsequent_siblings(vmon_t *vmon, vmon_proc_t *proc) /* convert chart sampling interval back into an integral hertz value, basically - * open-coded ceilf(1.f / charts->sampling_interval) to avoid needing -lm. + * open-coded ceilf(1.f / charts->sampling_interval_secs) to avoid needing -lm. */ static unsigned interval_as_hz(vwm_charts_t *charts) { - return (1.f / charts->sampling_interval + .5f); + return (1.f / charts->sampling_interval_secs + .5f); } /* draw a process' row slice of a process tree */ static void draw_tree_row(vwm_charts_t *charts, vwm_chart_t *chart, int x, int depth, int row, const vmon_proc_t *proc, int *res_width) { - vwm_xserver_t *xserver = charts->xserver; + int bar_x = 0, bar_y = (row + 1) * VCR_ROW_HEIGHT; + vmon_proc_t *child, *sibling, *last_sibling = NULL; /* only if this process isn't the root process @ the window shall we consider all relational drawing conditions */ - if (proc != chart->monitor) { - vmon_proc_t *child, *ancestor, *sibling, *last_sibling = NULL; - int bar_x = 0, bar_y = (row + 1) * CHART_ROW_HEIGHT; - int sub; + if (proc == chart->proc) + return; - /* XXX: everything done in this code block only dirties _this_ process' row in the rendered chart output */ + /* XXX: everything done in this code block only dirties _this_ process' row in the rendered chart output */ - /* walk up the ancestors until reaching chart->monitor, any ancestors we encounter which have more siblings we draw a vertical bar for */ + if (proc->parent) { + int sub = 1; + + /* walk up the ancestors until reaching chart->proc, any ancestors we encounter which have more siblings we draw a vertical bar for */ /* this draws the |'s in something like: | | | | comm */ - for (sub = 1, ancestor = proc->parent; ancestor && ancestor != chart->monitor; ancestor = ancestor->parent, sub++) { - bar_x = ((depth - 1) - sub) * (CHART_ROW_HEIGHT / 2) + 4; + for (vmon_proc_t *ancestor = proc->parent; ancestor != chart->proc; ancestor = ancestor->parent) { + bar_x = ((depth - 1) - sub) * (VCR_ROW_HEIGHT / 2) + 4; assert(depth > 0); /* determine if the ancestor has remaining siblings which are not stale, if so, draw a connecting bar at its depth */ - if (proc_has_subsequent_siblings(&charts->vmon, ancestor)) - XDrawLine(xserver->display, chart->text_pixmap, charts->text_gc, - x + bar_x, bar_y - CHART_ROW_HEIGHT, /* dst x1, y1 */ + if (proc_has_subsequent_siblings(charts, ancestor)) + vcr_draw_ortho_line(chart->vcr, VCR_LAYER_TEXT, + x + bar_x, bar_y - VCR_ROW_HEIGHT, /* dst x1, y1 */ x + bar_x, bar_y); /* dst x2, y2 (vertical line) */ + + sub += (!charts->no_threads || !ancestor->is_thread); + + /* it shouldn't be possible to run out of parents, we should always arrive at chart->proc */ + assert(ancestor->parent); } + } - /* determine if _any_ of our siblings have children requiring us to draw a tee immediately before our comm string. - * The only sibling which doesn't cause this to happen is the last one in the children list, if it has children it has no impact on its remaining - * siblings, as there are none. - * - * This draws the + in something like: | | | | +comm - */ + /* determine if _any_ of our siblings have children requiring us to draw a tee immediately before our comm string. + * The only sibling which doesn't cause this to happen is the last one in the children list, if it has children it has no impact on its remaining + * siblings, as there are none. + * + * This draws the + in something like: | | | | +comm + */ - /* find the last sibling (this has to be done due to the potential for stale siblings at the tail, and we'd rather not repeatedly check for it) */ + /* find the last sibling (this has to be done due to the potential for stale siblings at the tail, and we'd rather not repeatedly check for it) */ + if (!proc->is_thread) { list_for_each_entry(sibling, &proc->parent->children, siblings) { if (!sibling->is_stale) last_sibling = sibling; } + } else { + list_for_each_entry(sibling, &proc->parent->threads, threads) { + if (!sibling->is_stale) + last_sibling = sibling; + } - /* now look for siblings with non-stale children to determine if a tee is needed, ignoring the last sibling */ - list_for_each_entry(sibling, &proc->parent->children, siblings) { - int needs_tee = 0; - + /* now look for sibling threads with non-stale children to determine if a tee is needed, ignoring the last sibling */ + list_for_each_entry(sibling, &proc->parent->threads, threads) { /* skip stale siblings, they aren't interesting as they're invisible, and the last sibling has no bearing on wether we tee or not. */ if (sibling->is_stale || sibling == last_sibling) continue; /* if any of the other siblings have children which are not stale, put a tee in front of our name, but ignore stale children */ list_for_each_entry(child, &sibling->children, siblings) { + if (!child->is_stale) + goto needs_tee; + } + } + } + + /* now look for siblings with non-stale children to determine if a tee is needed, ignoring the last sibling */ + list_for_each_entry(sibling, &proc->parent->children, siblings) { + int needs_tee = 0; + + /* skip stale siblings, they aren't interesting as they're invisible, and the last sibling has no bearing on wether we tee or not. */ + if (sibling->is_stale || sibling == last_sibling) + continue; + + /* if any of the other siblings have children which are not stale, put a tee in front of our name, but ignore stale children */ + list_for_each_entry(child, &sibling->children, siblings) { + if (!child->is_stale) { + needs_tee = 1; + break; + } + } + + /* if we still don't think we need a tee, check if there are threads */ + if (!needs_tee) { + list_for_each_entry(child, &sibling->threads, threads) { if (!child->is_stale) { needs_tee = 1; break; } } + } - /* if we still don't think we need a tee, check if there are threads */ - if (!needs_tee) { - list_for_each_entry(child, &sibling->threads, threads) { - if (!child->is_stale) { - needs_tee = 1; - break; - } - } - } - - /* found a tee is necessary, all that's left is to determine if the tee is a corner and draw it accordingly, stopping the search. */ - if (needs_tee) { - bar_x = (depth - 1) * (CHART_ROW_HEIGHT / 2) + 4; + /* found a tee is necessary, all that's left is to determine if the tee is a corner and draw it accordingly, stopping the search. */ + if (needs_tee) { +needs_tee: + bar_x = (depth - 1) * (VCR_ROW_HEIGHT / 2) + 4; - /* if we're the last sibling, corner the tee by shortening the vbar */ - if (proc == last_sibling) { - XDrawLine(xserver->display, chart->text_pixmap, charts->text_gc, - x + bar_x, bar_y - CHART_ROW_HEIGHT, /* dst x1, y1 */ - x + bar_x, bar_y - 4); /* dst x2, y2 (vertical bar) */ - } else { - XDrawLine(xserver->display, chart->text_pixmap, charts->text_gc, - x + bar_x, bar_y - CHART_ROW_HEIGHT, /* dst x1, y1 */ - x + bar_x, bar_y); /* dst x2, y2 (vertical bar) */ - } + /* if we're the last sibling, corner the tee by shortening the vbar */ + if (proc == last_sibling) { + vcr_draw_ortho_line(chart->vcr, VCR_LAYER_TEXT, + x + bar_x, bar_y - VCR_ROW_HEIGHT, /* dst x1, y1 */ + x + bar_x, bar_y - 4); /* dst x2, y2 (vertical bar) */ + } else { + vcr_draw_ortho_line(chart->vcr, VCR_LAYER_TEXT, + x + bar_x, bar_y - VCR_ROW_HEIGHT, /* dst x1, y1 */ + x + bar_x, bar_y); /* dst x2, y2 (vertical bar) */ + } - XDrawLine(xserver->display, chart->text_pixmap, charts->text_gc, - x + bar_x, bar_y - 4, /* dst x1, y1 */ - x + bar_x + 2, bar_y - 4); /* dst x2, y2 (horizontal bar) */ + vcr_draw_ortho_line(chart->vcr, VCR_LAYER_TEXT, + x + bar_x, bar_y - 4, /* dst x1, y1 */ + x + bar_x + 2, bar_y - 4); /* dst x2, y2 (horizontal bar) */ - /* terminate the outer sibling loop upon drawing the tee... */ - break; - } + /* terminate the outer sibling loop upon drawing the tee... */ + break; } - - if (res_width) - *res_width = depth * (CHART_ROW_HEIGHT / 2); } + + if (res_width) + *res_width = depth * (VCR_ROW_HEIGHT / 2); } /* draw a proc row according to the columns configured in columns, * row==0 is treated specially as the heading row */ -static void draw_columns(vwm_charts_t *charts, vwm_chart_t *chart, vwm_column_t *columns, int depth, int row, const vmon_proc_t *proc) +static void draw_row_columns(vwm_charts_t *charts, vwm_chart_t *chart, vwm_row_column_t *row_columns, int heading, int depth, int row, const vmon_proc_t *proc) { vmon_sys_stat_t *sys_stat = charts->vmon.stores[VMON_STORE_SYS_STAT]; vmon_proc_stat_t *proc_stat = proc->stores[VMON_STORE_PROC_STAT]; - vwm_xserver_t *xserver = charts->xserver; + vwm_perproc_ctxt_t *proc_ctxt = proc->foo; char str[256]; for (int i = 0, left = 0, right = 0; i < CHART_MAX_COLUMNS; i++) { - vwm_column_t *c = &columns[i]; - vwm_justify_t str_justify = VWM_JUSTIFY_CENTER; - int str_len = 0, uniform = 1, advance = 1; + vwm_row_column_t *rc = &row_columns[i]; + vwm_column_t *c = rc->column; + vwm_justify_t str_justify = rc->justify; + int str_len = 0, uniform = 1, advance = 1; - if (!c->enabled) + if (!c || !c->enabled) continue; /* XXX FIXME: i don't constrain columns using a clip mask or restrained drawing, so they can scribble @@ -751,68 +634,70 @@ static void draw_columns(vwm_charts_t *charts, vwm_chart_t *chart, vwm_column_t * a column's width became too large, the clearing itself can be destructive. This works fine for * the currently configured columns, but long-term this will have to get fixed properly. */ - if (c->side == VWM_SIDE_LEFT) - XRenderFillRectangle(charts->xserver->display, PictOpSrc, chart->text_picture, &chart_trans_color, - left, row * CHART_ROW_HEIGHT, /* dst x, y */ - c->width + CHART_ROW_HEIGHT / 2, CHART_ROW_HEIGHT); /* dst w, h */ + if (rc->side == VWM_SIDE_LEFT) + vcr_clear_row(chart->vcr, VCR_LAYER_TEXT, row, left, c->width + VCR_ROW_HEIGHT / 2); else - XRenderFillRectangle(charts->xserver->display, PictOpSrc, chart->text_picture, &chart_trans_color, - chart->visible_width - (c->width + CHART_ROW_HEIGHT / 2 + right), row * CHART_ROW_HEIGHT, /* dst x, y */ - c->width + CHART_ROW_HEIGHT / 2, CHART_ROW_HEIGHT); /* dst w, h */ + vcr_clear_row(chart->vcr, VCR_LAYER_TEXT, row, chart->visible_width - (c->width + VCR_ROW_HEIGHT / 2 + right), c->width + VCR_ROW_HEIGHT / 2); switch (c->type) { case VWM_COLUMN_VWM: - if (!row) /* "\/\/\ # name @ XXHz" is only relevant to the heading */ + if (heading) /* "\/\/\ # name @ XXHz" is only relevant to the heading */ str_len = snpf(str, sizeof(str), "\\/\\/\\%s%s @ %2uHz ", chart->name ? " # " : "", chart->name ? chart->name : "", interval_as_hz(charts)); uniform = 0; /* XXX this suppresses the c->width assignment so the column can be absent outside the heading */ - str_justify = VWM_JUSTIFY_RIGHT; + break; + + case VWM_COLUMN_ROW: /* row in the chart */ + if (heading) + str_len = snpf(str, sizeof(str), "Row"); + else + str_len = snpf(str, sizeof(str), "%'i", row - CHART_NUM_FIXED_HEADER_ROWS); + + /* this is kind of hacky, but libvmon doesn't monitor our row, it's implicitly "sampled" when we draw */ + proc_ctxt->row = row; break; case VWM_COLUMN_PROC_USER: /* User CPU time */ - if (!row) + if (heading) str_len = snpf(str, sizeof(str), "User"); else - str_len = snpf(str, sizeof(str), "%.2fs", - (float)proc_stat->utime / (float)charts->vmon.ticks_per_sec); + str_len = snpf(str, sizeof(str), "%'.2fs", + (float)proc_stat->utime * charts->inv_ticks_per_sec); - str_justify = VWM_JUSTIFY_RIGHT; break; case VWM_COLUMN_PROC_SYS: /* Sys CPU time */ - if (!row) + if (heading) str_len = snpf(str, sizeof(str), "Sys"); else - str_len = snpf(str, sizeof(str), "%.2fs", - (float)proc_stat->stime / (float)charts->vmon.ticks_per_sec); + str_len = snpf(str, sizeof(str), "%'.2fs", + (float)proc_stat->stime * charts->inv_ticks_per_sec); - str_justify = VWM_JUSTIFY_RIGHT; break; case VWM_COLUMN_PROC_WALL: /* User Sys Wall times */ - if (!row) + if (heading) str_len = snpf(str, sizeof(str), "Wall"); - else if (!proc_stat->start) + else if (!proc_stat->start || proc_stat->start > sys_stat->boottime) str_len = snpf(str, sizeof(str), "??s"); else - str_len = snpf(str, sizeof(str), "%.2fs", - (float)(sys_stat->boottime - proc_stat->start) / (float)charts->vmon.ticks_per_sec); + str_len = snpf(str, sizeof(str), "%'.2fs", + (float)(sys_stat->boottime - proc_stat->start) * charts->inv_ticks_per_sec); - str_justify = VWM_JUSTIFY_RIGHT; break; - case VWM_COLUMN_PROC_TREE: { /* print a row of the process heirarchy tree */ + case VWM_COLUMN_PROC_TREE: { /* print a row of the process hierarchy tree */ int width = 0; advance = 0; /* tree column manages its own advance; c->width is meaningless */ - if (!row) /* tree markup needs no heading */ + if (heading) /* tree markup needs no heading */ break; - assert(c->side == VWM_SIDE_LEFT); /* XXX: technically SIDE_RIGHT could work, but doesn't currently */ + assert(rc->side == VWM_SIDE_LEFT); /* XXX: technically SIDE_RIGHT could work, but doesn't currently */ draw_tree_row(charts, chart, left, depth, row, proc, &width); left += width; @@ -820,13 +705,13 @@ static void draw_columns(vwm_charts_t *charts, vwm_chart_t *chart, vwm_column_t } case VWM_COLUMN_PROC_ARGV: { /* print the process' argv */ - if (!row) { - str_len = snpf(str, sizeof(str), "ArgV/~ThreadName"); - str_justify = VWM_JUSTIFY_LEFT; + if (heading) { + str_len = snpf(str, sizeof(str), "[NThreads] ArgV%s", + charts->no_threads ? "" : "/~ThreadName"); } else { int width; - print_argv(charts, chart, left /* FIXME: consider c->side */, row, proc, &width); + print_argv(charts, chart, left /* FIXME: consider rc->side */, row, proc, &width); if (width > c->width) { c->width = width; chart->redraw_needed++; @@ -836,21 +721,22 @@ static void draw_columns(vwm_charts_t *charts, vwm_chart_t *chart, vwm_column_t } case VWM_COLUMN_PROC_PID: /* print the process' PID */ - if (!row) + if (heading) str_len = snpf(str, sizeof(str), "PID"); else str_len = snpf(str, sizeof(str), "%5i", proc->pid); - str_justify = VWM_JUSTIFY_RIGHT; break; case VWM_COLUMN_PROC_WCHAN: /* print the process' wchan */ - if (!row) + if (heading) str_len = snpf(str, sizeof(str), "WChan"); else { - /* don't show wchan for processes with threads, since their main thread will show it. */ - if (!proc->is_thread && !list_empty(&proc->threads)) + /* don't show wchan for processes with threads, since their main thread will show it, + * unless we're in --no-threads mode. + */ + if (!proc->is_thread && !list_empty(&proc->threads) && !charts->no_threads) break; str_len = snpf(str, sizeof(str), "%.*s", @@ -858,39 +744,52 @@ static void draw_columns(vwm_charts_t *charts, vwm_chart_t *chart, vwm_column_t proc_stat->wchan.len == 1 && proc_stat->wchan.array[0] == '0' ? "-" : proc_stat->wchan.array); } - str_justify = VWM_JUSTIFY_RIGHT; break; case VWM_COLUMN_PROC_STATE: /* print the process' state */ - if (!row) + if (heading) str_len = snpf(str, sizeof(str), "State"); else { - /* don't show process state for processes with threads, since their main thread will show it. */ - if (!proc->is_thread && !list_empty(&proc->threads)) + /* don't show process state for processes with threads, since their main thread will show it. + * unless we're in --no-threads mode. + */ + if (!proc->is_thread && !list_empty(&proc->threads) && !charts->no_threads) break; str_len = snpf(str, sizeof(str), "%c", proc_stat->state); } - str_justify = VWM_JUSTIFY_CENTER; break; + case VWM_COLUMN_PROC_RSS: { /* print the process' RSS in kb */ + if (heading) /* RSS doesn't get a heading currently, as it's always below the process row and considered obvious with a units suffix */ + break; + + assert(!proc->is_thread); /* why are we printing RSS for threads? */ + + str_len = snpf(str, sizeof(str), "%'u KiB ^", proc_stat->rss * (4096 / 1024)); + + break; + } + default: assert(0); } /* for plain string draws, str_len is left non-zero and they all get handled equally here */ if (str_len) { - int str_width, xpos; + const vcr_str_t strs[1] = { (vcr_str_t){.str = str, .len = str_len} }; + int str_width, xpos; - str_width = XTextWidth(charts->chart_font, str, str_len); + /* get the width first, so we can place the text, note the -1 to suppress drawings */ + vcr_draw_text(chart->vcr, VCR_LAYER_TEXT, -1 /* x */, -1 /* row */, strs, 1, &str_width); if (uniform && str_width > c->width) { c->width = str_width; chart->redraw_needed++; } - /* get xpos to the left edge of the column WRT c->width and c->side */ - switch (c->side) { + /* get xpos to the left edge of the column WRT c->width and rc->side */ + switch (rc->side) { case VWM_SIDE_LEFT: xpos = left; break; @@ -921,24 +820,23 @@ static void draw_columns(vwm_charts_t *charts, vwm_chart_t *chart, vwm_column_t assert(0); } - XDrawString(xserver->display, chart->text_pixmap, charts->text_gc, - xpos, (row + 1) * CHART_ROW_HEIGHT - 3, - str, str_len); + vcr_draw_text(chart->vcr, VCR_LAYER_TEXT, xpos, row, strs, 1, NULL); } if (advance) { - left += (c->side == VWM_SIDE_LEFT) * (c->width + CHART_ROW_HEIGHT / 2); - right += (c->side == VWM_SIDE_RIGHT) * (c->width + CHART_ROW_HEIGHT / 2); + left += (rc->side == VWM_SIDE_LEFT) * (c->width + VCR_ROW_HEIGHT / 2); + right += (rc->side == VWM_SIDE_RIGHT) * (c->width + VCR_ROW_HEIGHT / 2); } } } /* return if any of the enabled columns in columns has changed its contents */ -static int columns_changed(const vwm_charts_t *charts, const vwm_chart_t *chart, vwm_column_t *columns, const vmon_proc_t *proc) +static int columns_changed(const vwm_charts_t *charts, const vwm_chart_t *chart, vwm_column_t *columns, int row, const vmon_proc_t *proc) { vmon_sys_stat_t *sys_stat = charts->vmon.stores[VMON_STORE_SYS_STAT]; vmon_proc_stat_t *proc_stat = proc->stores[VMON_STORE_PROC_STAT]; + vwm_perproc_ctxt_t *proc_ctxt = proc->foo; for (int i = 0; i < CHART_MAX_COLUMNS; i++) { const vwm_column_t *c = &columns[i]; @@ -950,6 +848,8 @@ static int columns_changed(const vwm_charts_t *charts, const vwm_chart_t *chart, case VWM_COLUMN_VWM: /* XXX: meh, maybe we should detect Hz changes here? */ break; + case VWM_COLUMN_ROW: + return (row != proc_ctxt->row); case VWM_COLUMN_PROC_USER: if (BITTEST(proc_stat->changed, VMON_PROC_STAT_UTIME)) return 1; @@ -990,192 +890,302 @@ static int columns_changed(const vwm_charts_t *charts, const vwm_chart_t *chart, } -/* draws proc in a row of the process heirarchy */ -static void draw_overlay_row(vwm_charts_t *charts, vwm_chart_t *chart, vmon_proc_t *proc, int depth, int row) +/* draws proc in a row of the process hierarchy */ +static void draw_overlay_row(vwm_charts_t *charts, vwm_chart_t *chart, vmon_proc_t *proc, int depth, int row, int deferred_pass) { + /* if we're in defer_maintenance mode, don't do any of this until the deferred pass */ + if (charts->defer_maintenance && !deferred_pass) + return; + /* skip if obviously unnecessary (this can be further improved, but this makes a big difference as-is) */ - if (!chart->redraw_needed && !columns_changed(charts, chart, chart->columns, proc)) + if (!deferred_pass && !chart->redraw_needed && + !columns_changed(charts, chart, chart->proc_cpu_columns, row, proc)) return; if (!proc->is_new) /* XXX for now always clear the row, this should be capable of being optimized in the future (if the datums driving the text haven't changed...) */ - XRenderFillRectangle(charts->xserver->display, PictOpSrc, chart->text_picture, &chart_trans_color, - 0, row * CHART_ROW_HEIGHT, /* dst x, y */ - chart->width, CHART_ROW_HEIGHT); /* dst w, h */ + vcr_clear_row(chart->vcr, VCR_LAYER_TEXT, row, -1, -1); - draw_columns(charts, chart, chart->columns, depth, row, proc); - shadow_row(charts, chart, row); + draw_row_columns(charts, chart, chart->proc_cpu_row_columns, 0 /* heading */, depth, row, proc); + vcr_shadow_row(chart->vcr, VCR_LAYER_TEXT, row); } -/* recursive draw function for "rest" of chart: the per-process rows (heirarchy, argv, state, wchan, pid...) */ -static void draw_chart_rest(vwm_charts_t *charts, vwm_chart_t *chart, vmon_proc_t *proc, int *depth, int *row) +/* recursive draw function for "rest" of chart: the per-process rows (hierarchy, argv, state, wchan, pid...) */ +static void draw_chart_rest(vwm_charts_t *charts, vwm_chart_t *chart, vmon_proc_t *proc, int *depth, int *row, int deferred_pass, unsigned sample_duration_idx) { vmon_proc_stat_t *proc_stat = proc->stores[VMON_STORE_PROC_STAT]; vwm_perproc_ctxt_t *proc_ctxt = proc->foo; vmon_proc_t *child; - double utime_delta, stime_delta; + float utime_delta, stime_delta; /* Some parts of this we must do on every sample to maintain coherence in the graphs, since they're incrementally kept - * in sync with the process heirarchy, allocating and shifting the rows as processes are created and destroyed. Everything + * in sync with the process hierarchy, allocating and shifting the rows as processes are created and destroyed. Everything * else we should be able to skip doing unless chart.redraw_needed or their contents changed. */ - if (proc->is_stale) { - /* what to do when a process (subtree) has gone away */ - static int in_stale = 0; - int in_stale_entrypoint = 0; - - /* I snowflake the stale processes from the leaves up for a more intuitive snowflake order... - * (I expect the command at the root of the subtree to appear at the top of the snowflakes...) */ - /* This does require that I do a separate forward recursion to determine the number of rows - * so I can correctly snowflake in reverse */ - if (!in_stale) { - VWM_TRACE("entered stale at chart=%p depth=%i row=%i", chart, *depth, *row); - in_stale_entrypoint = in_stale = 1; - (*row) += count_rows(proc) - 1; - } + /* if this is a deferred pass, we need to simply skip stale nodes, since they've already + * been snowflaked incrementally in the !deferred_pass branch below. + * Handling them in the deferred pass as well would just scribble over the snowflakes with + * stale stuff erroneously lingering in the live tree rows. + */ + if (deferred_pass && proc->is_stale) + return; - (*depth)++; - list_for_each_entry_prev(child, &proc->children, siblings) { - draw_chart_rest(charts, chart, child, depth, row); - (*row)--; - } + /* Don't render and don't allocate/snowflake thread rows in --no-threads mode */ + if (!proc->is_thread || !charts->no_threads) { + if (!deferred_pass) { + /* These incremental/structural aspects can't be repeated in the final defer_maintenance pass since it's + * a repeated pass within the same sample - we can't realize these effects twice. + */ + if (sample_duration_idx == 0) { /* some things need to only be done once per sample duration, some at the start, some at the end */ + static int in_stale = 0; + + if (proc->is_stale) { /* we "realize" stale processes only in the first draw within a sample duration */ + /* what to do when a process (subtree) has gone away */ + int in_stale_entrypoint = 0; + + /* I snowflake the stale processes from the leaves up for a more intuitive snowflake order... + * (I expect the command at the root of the subtree to appear at the top of the snowflakes...) */ + /* This does require that I do a separate forward recursion to determine the number of rows + * so I can correctly snowflake in reverse */ + if (!in_stale) { + VWM_TRACE("entered stale at chart=%p depth=%i row=%i", chart, *depth, *row); + in_stale_entrypoint = in_stale = 1; + + /* this advances row to the last row of all descendants, the minus one is needed since we're + * already at proc's row, and count_rows() includes it in the count. Imagine there are no + * descendants, count_rows returns 1, we turn that into 0, and (*row) stays unchanged, which + * is correct - we snowflake ourself and that's that. + */ + (*row) += count_rows(proc, charts->no_threads) - 1; + } - if (!proc->is_thread) { - list_for_each_entry_prev(child, &proc->threads, threads) { - draw_chart_rest(charts, chart, child, depth, row); - (*row)--; - } - } - (*depth)--; + (*depth)++; + list_for_each_entry_prev(child, &proc->children, siblings) { + draw_chart_rest(charts, chart, child, depth, row, deferred_pass, sample_duration_idx); + (*row)--; + } - VWM_TRACE("%i (%.*s) is stale @ depth %i row %i is_thread=%i", proc->pid, - ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1, - ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array, - (*depth), (*row), proc->is_thread); + if (!proc->is_thread) { + /* In --no-threads mode we hide the spatial effects of the followed threads, + * which amounts to messing with the depth and row variables. This could be + * done better. + */ + if (charts->no_threads) + (*depth)--; + + list_for_each_entry_prev(child, &proc->threads, threads) { + draw_chart_rest(charts, chart, child, depth, row, deferred_pass, sample_duration_idx); + if (!charts->no_threads) + (*row)--; + } + + if (charts->no_threads) + (*depth)++; + } + (*depth)--; - mark_finish(charts, chart, (*row)); + VWM_TRACE("%i (%.*s) is stale @ depth %i row %i is_thread=%i", proc->pid, + ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1, + ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array, + (*depth), (*row), proc->is_thread); - /* extract the row from the various layers */ - snowflake_row(charts, chart, chart->grapha_picture, 1, (*row)); - snowflake_row(charts, chart, chart->graphb_picture, 1, (*row)); - snowflake_row(charts, chart, chart->text_picture, 0, (*row)); - snowflake_row(charts, chart, chart->shadow_picture, 0, (*row)); - chart->snowflakes_cnt++; + mark_finish(charts, chart, (*row)); - /* stamp the name (and whatever else we include) into chart.text_picture */ - // print_argv(charts, chart, 5, chart->heirarchy_end, proc, NULL); - draw_columns(charts, chart, chart->snowflake_columns, 0, chart->heirarchy_end, proc); - shadow_row(charts, chart, chart->heirarchy_end); + /* extract the row from the various layers */ + snowflake_row(charts, chart, (*row)); + chart->snowflakes_cnt++; - chart->heirarchy_end--; + /* stamp the name (and whatever else we include) into chart.text_picture */ + draw_row_columns(charts, chart, chart->snowflake_cpu_row_columns, 0 /* heading */, 0 /* depth */, chart->hierarchy_end, proc); + vcr_shadow_row(chart->vcr, VCR_LAYER_TEXT, chart->hierarchy_end); - if (in_stale_entrypoint) { - VWM_TRACE("exited stale at chart=%p depth=%i row=%i", chart, *depth, *row); - in_stale = 0; - } + chart->hierarchy_end--; - return; - } else if (proc->is_new) { - /* what to do when a process has been introduced */ - VWM_TRACE("%i is new", proc->pid); + if (in_stale_entrypoint) { + VWM_TRACE("exited stale at chart=%p depth=%i row=%i", chart, *depth, *row); + in_stale = 0; + } - allocate_row(charts, chart, chart->grapha_picture, (*row)); - allocate_row(charts, chart, chart->graphb_picture, (*row)); - allocate_row(charts, chart, chart->text_picture, (*row)); - allocate_row(charts, chart, chart->shadow_picture, (*row)); + return; + } else { + /* If we're not stale, assert we're not in_stale, because the count_rows() used above is indiscriminate. + * if there's !is_stale descendents then we'll get confused as-is. + */ + assert(!in_stale); + } - chart->heirarchy_end++; - } -/* CPU utilization graphs */ - /* use the generation number to avoid recomputing this stuff for callbacks recurring on the same process in the same sample */ - if (proc_ctxt->generation != charts->vmon.generation) { - proc_ctxt->stime_delta = proc_stat->stime - proc_ctxt->last_stime; - proc_ctxt->utime_delta = proc_stat->utime - proc_ctxt->last_utime; - proc_ctxt->last_utime = proc_stat->utime; - proc_ctxt->last_stime = proc_stat->stime; + /* use the generation number to avoid recomputing this stuff for callbacks recurring on the same process in the same sample */ + if (proc_ctxt->generation != charts->vmon.generation) { + proc_ctxt->stime_delta = proc_stat->stime - proc_ctxt->last_stime; + proc_ctxt->utime_delta = proc_stat->utime - proc_ctxt->last_utime; + proc_ctxt->last_utime = proc_stat->utime; + proc_ctxt->last_stime = proc_stat->stime; - proc_ctxt->generation = charts->vmon.generation; - } + proc_ctxt->generation = charts->vmon.generation; + } + } - if (proc->is_new) { - /* we need a minimum of two samples before we can compute a delta to plot, - * so we suppress that and instead mark the start of monitoring with an impossible 100% of both graph contexts, a starting line. */ - stime_delta = utime_delta = charts->total_delta; - } else { - stime_delta = proc_ctxt->stime_delta; - utime_delta = proc_ctxt->utime_delta; - } + if (proc->is_stale) + return; /* is_stale is already handled on the first sample_diration_idx */ + + /* we "realize" new processes on the last draw within a duration. + * FIXME TODO: this could be placed more accurately in time by referencing the process's + * PROC_STAT_START time and allocating the row at that point within a duration. + * but for now it's still an improvement over losing time to simply place it at the end of + * the duration. We don't have two samples to compute cpu utilizations for it anyways, so + * even if we were to place it accurately on the timeline, there wouldn't be data to put + * in the intervening space between the start line and the end anyways, which would be less + * accurate/potentially misleading - basically the start line would have to be repeated to + * fill in the space where we have no data so as to still indicate "hey, the process started + * back here, but this filled white region is where we couldn't collect anything about it + * since its start point. This raises an interesting issue in general surrounding start lines + * in general; many processes tend to already exist when vmon starts up, and we draw the start + * lines when we begin monitoring a given process... and that is misleading if the process was + * preexisting. In such caes, when the start time is way in the past, we should either suppress + * the start line, or be willing to place it out of phase - if the graph covers that moment. If + * we were to place it out of phase, we'd have another situation where we can't leave the space + * between then and the current sample empty, it would have to all be filled with start line. + */ + if (proc->is_new) { + if (sample_duration_idx != (charts->this_sample_duration - 1)) + return; /* suppress doing anything aboout new processes until the last draw within the duration */ + + /* what to do when a process has been introduced */ + VWM_TRACE("%i is new", proc->pid); + + allocate_row(charts, chart, (*row)); + + chart->hierarchy_end++; + + /* we need a minimum of two samples before we can compute a delta to plot, + * so we suppress that and instead mark the start of monitoring with an impossible 100% of both graph contexts, a starting line. */ + stime_delta = utime_delta = charts->total_delta; + } else { + stime_delta = proc_ctxt->stime_delta; + utime_delta = proc_ctxt->utime_delta; + } - draw_bars(charts, chart, *row, stime_delta, charts->total_delta, utime_delta, charts->total_delta); - draw_overlay_row(charts, chart, proc, *depth, *row); + draw_bars(charts, chart, *row, + (proc->is_thread || !proc->is_threaded) ? charts->vmon.num_cpus : 1.f /* mult */, + -stime_delta, + charts->inv_total_delta, + VCR_LAYER_GRAPHA, + utime_delta, + charts->inv_total_delta, + VCR_LAYER_GRAPHB); + } + + /* unless a deferred pass, only try draw the overlay on the last draw within a duration */ + if (deferred_pass || sample_duration_idx == (charts->this_sample_duration - 1)) + draw_overlay_row(charts, chart, proc, *depth, *row, deferred_pass); - (*row)++; + /* note these are suppressed for --no-threads */ + (*row)++; + (*depth)++; + } /* recur any threads first, then any children processes */ - (*depth)++; if (!proc->is_thread) { /* XXX: the threads member serves as the list head only when not a thread */ list_for_each_entry(child, &proc->threads, threads) { - draw_chart_rest(charts, chart, child, depth, row); + draw_chart_rest(charts, chart, child, depth, row, deferred_pass, sample_duration_idx); } } list_for_each_entry(child, &proc->children, siblings) { - draw_chart_rest(charts, chart, child, depth, row); + draw_chart_rest(charts, chart, child, depth, row, deferred_pass, sample_duration_idx); } - (*depth)--; + + if (!proc->is_thread || !charts->no_threads) + (*depth)--; } /* recursive draw function entrypoint, draws the IOWait/Idle/HZ row, then enters draw_chart_rest() */ -static void draw_chart(vwm_charts_t *charts, vwm_chart_t *chart, vmon_proc_t *proc, int *depth, int *row) +static void draw_chart(vwm_charts_t *charts, vwm_chart_t *chart, vmon_proc_t *proc, int deferred_pass, unsigned sample_duration_idx) { - vwm_xserver_t *xserver = charts->xserver; - int prev_redraw_needed; + int prev_redraw_needed = chart->redraw_needed; + int row = 0, depth = 0; -/* CPU utilization graphs */ /* IOWait and Idle % @ row 0 */ - draw_bars(charts, chart, 0, charts->iowait_delta, charts->total_delta, charts->idle_delta, charts->total_delta); - - /* only draw the \/\/\ and HZ if necessary */ - if (chart->redraw_needed || charts->prev_sampling_interval != charts->sampling_interval) { - XRenderFillRectangle(xserver->display, PictOpSrc, chart->text_picture, &chart_trans_color, - 0, 0, /* dst x, y */ - chart->visible_width, CHART_ROW_HEIGHT); /* dst w, h */ - draw_columns(charts, chart, chart->columns, 0, 0, proc); - shadow_row(charts, chart, 0); + draw_bars(charts, chart, row, + 1.f /* mult */, + -charts->iowait_delta, + charts->inv_total_delta, + VCR_LAYER_GRAPHA, + charts->idle_delta, + charts->inv_total_delta, + VCR_LAYER_GRAPHB); + + /* IRQ and SoftIRQ % @ row 1 */ + draw_bars(charts, chart, row + 1, + 1.f /* mult */, + -charts->irq_delta, + charts->inv_total_delta, + VCR_LAYER_GRAPHA, + charts->softirq_delta, + charts->inv_total_delta, + VCR_LAYER_GRAPHB); + + /* "Adherence" @ row 2 */ + draw_bars(charts, chart, row + 2, + 1.f /* mult */, + charts->this_sample_adherence > 0.f ? -charts->this_sample_adherence : 0.f /* a_fraction */, + 1.f /* inv_a_total */, + VCR_LAYER_GRAPHA, + charts->this_sample_adherence < 0.f ? -charts->this_sample_adherence : 0.f /* b_fraction */, + 1.f /* inv_b_total */, + VCR_LAYER_GRAPHB); + + /* only draw the column headings, \/\/\ and HZ if necessary */ + if (sample_duration_idx == (charts->this_sample_duration - 1)) { + if (deferred_pass || (!charts->defer_maintenance && (chart->redraw_needed || charts->prev_sampling_interval_secs != charts->sampling_interval_secs))) { + vcr_clear_row(chart->vcr, VCR_LAYER_TEXT, row, -1, -1); + draw_row_columns(charts, chart, chart->top_row_columns, 1 /* heading */, 0 /* depth */, row, proc); + vcr_shadow_row(chart->vcr, VCR_LAYER_TEXT, row); + + /* XXX: note at this time there's no overlay text for the IRQ/SoftIRQ (row + 1) (which should probably change) */ + + vcr_clear_row(chart->vcr, VCR_LAYER_TEXT, row + 1, -1, -1); + draw_row_columns(charts, chart, chart->proc_cpu_row_columns, 1 /* heading */, 0 /* depth */, row + 2, proc); + vcr_shadow_row(chart->vcr, VCR_LAYER_TEXT, row + 1); + } + + if (!prev_redraw_needed) + chart->redraw_needed = proc_hierarchy_changed(proc); + } + row = CHART_NUM_FIXED_HEADER_ROWS; + + /* now everything else */ + draw_chart_rest(charts, chart, proc, &depth, &row, deferred_pass, sample_duration_idx); + if (sample_duration_idx == (charts->this_sample_duration - 1)) { + if (chart->redraw_needed > prev_redraw_needed) { + /* Drawing bumped redraw_needed (like a layout change from widths changing), + * so don't reset the counter to zero forcing the next redraw. TODO: this does cause + * a small delay between width-affecting values showing and column widths adjusting to them, + * resulting in a sort of eventually-consistent behavior. + * We could trigger a redraw here immediately by basically jumping back to the start of + * this function, but there are problems doing that as-is due to the stateful/incremental + * relationship between the charts and vmon's sample. Rather than attacking that refactor + * now, I'll leave it like this for now. + */ + chart->redraw_needed = 1; + } else + chart->redraw_needed = 0; } - (*row)++; - - if (!chart->redraw_needed) - chart->redraw_needed = proc_heirarchy_changed(proc); - - prev_redraw_needed = chart->redraw_needed; - draw_chart_rest(charts, chart, proc, depth, row); - if (chart->redraw_needed > prev_redraw_needed) { - /* Drawing bumped redraw_needed (like a layout change from widths changing), - * so don't reset the counter to zero forcing the next redraw. TODO: this does cause - * a small delay between width-affecting values showing and column widths adjusting to them, - * resulting in a sort of eventually-consistent behavior. - * We could trigger a redraw here immediately by basically jumping back to the start of - * this function, but there are problems doing that as-is due to the stateful/incremental - * relationship between the charts and vmon's sample. Rather than attacking that refactor - * now, I'll leave it like this for now. - */ - chart->redraw_needed = 1; - } else - chart->redraw_needed = 0; } /* consolidated version of chart text and graph rendering, makes snowflakes integration cleaner, this always gets called regardless of the charts mode */ -static void maintain_chart(vwm_charts_t *charts, vwm_chart_t *chart) +static void maintain_chart(vwm_charts_t *charts, vwm_chart_t *chart, int deferred_pass) { - vwm_xserver_t *xserver = charts->xserver; - int row = 0, depth = 0; + assert(charts); + assert(chart); + /* let's make sure nobody's causing a deferred_pass=1 outside of defer_maintenance mode */ + assert(!deferred_pass || charts->defer_maintenance); - if (!chart->monitor || !chart->monitor->stores[VMON_STORE_PROC_STAT]) + if (!chart->proc || !chart->proc->stores[VMON_STORE_PROC_STAT]) return; /* TODO: @@ -1184,19 +1194,24 @@ static void maintain_chart(vwm_charts_t *charts, vwm_chart_t *chart) * However, simply resizing the charts is insufficient. Their contents need to be redrawn in the new dimensions, this is where it * gets annoying. The current maintain/draw_chart makes assumptions about being run from the periodic vmon per-process callback. * There needs to be a redraw mode added where draw_chart is just reconstructing the current state, which requires that we suppress - * the phase advance and in maintain_chart() and just enter draw_chart() to redraw everything for the same generation. + * the phase advance in maintain_chart() and just enter draw_chart() to redraw everything for the same generation. * So this probably requires some tweaking of draw_chart() as well as maintain_chart(). I want to be able tocall mainta_charts() * from anywhere, and have it detect if it's being called on the same generation or if the generation has advanced. * For now, the monitors will just be a little latent in window resizes which is pretty harmless artifact. + * XXX: ^^^ this comment is somewhat stale at this point now that deferred maintenance for headless mode happened, + * furthermore this_sample_duration overlaps a bit with what's said above. */ - chart->phase += (chart->width - 1); /* simply change this to .phase++ to scroll the other direction */ - chart->phase %= chart->width; - XRenderFillRectangle(xserver->display, PictOpSrc, chart->grapha_picture, &chart_trans_color, chart->phase, 0, 1, chart->height); - XRenderFillRectangle(xserver->display, PictOpSrc, chart->graphb_picture, &chart_trans_color, chart->phase, 0, 1, chart->height); + /* deferred pass updates the arbitrarily reproducible overlays, not incrementally rendered graphs; this_sample_duration is irrelevant */ + if (deferred_pass) + return draw_chart(charts, chart, chart->proc, deferred_pass, 0 /* sample_duration_idx */); - /* recursively draw the monitored processes to the chart */ - draw_chart(charts, chart, chart->monitor, &depth, &row); + for (unsigned i = 0; i < charts->this_sample_duration; i++) { + vcr_advance_phase(chart->vcr, -1); /* change this to +1 to scroll the other direction */ + + /* recursively draw the monitored processes to the chart */ + draw_chart(charts, chart, chart->proc, 0 /* deferred_pass */, i); + } } @@ -1212,7 +1227,7 @@ static void proc_sample_callback(vmon_t *vmon, void *sys_cb_arg, vmon_proc_t *pr /* render the various always-updated charts, this is the component we do regardless of the charts mode and window visibility, * essentially the incrementally rendered/historic components */ - maintain_chart(charts, chart); + maintain_chart(charts, chart, 0 /* deferred_pass */); /* XXX TODO: we used to mark repaint as being needed if this chart's window was mapped, but * since extricating charts from windows that's no longer convenient, and repaint is @@ -1222,15 +1237,6 @@ static void proc_sample_callback(vmon_t *vmon, void *sys_cb_arg, vmon_proc_t *pr } -/* return the composed height of the chart */ -static int vwm_chart_composed_height(vwm_charts_t *charts, vwm_chart_t *chart) -{ - int snowflakes = chart->snowflakes_cnt ? 1 + chart->snowflakes_cnt : 0; /* don't include the separator row if there are no snowflakes */ - - return MIN((chart->heirarchy_end + snowflakes) * CHART_ROW_HEIGHT, chart->visible_height); -} - - /* reset snowflakes on the specified chart */ void vwm_chart_reset_snowflakes(vwm_charts_t *charts, vwm_chart_t *chart) { @@ -1241,89 +1247,15 @@ void vwm_chart_reset_snowflakes(vwm_charts_t *charts, vwm_chart_t *chart) } -static void free_chart_pictures(vwm_charts_t *charts, vwm_chart_t *chart) -{ - vwm_xserver_t *xserver = charts->xserver; - - XRenderFreePicture(xserver->display, chart->grapha_picture); - XRenderFreePicture(xserver->display, chart->graphb_picture); - XRenderFreePicture(xserver->display, chart->tmp_picture); - XRenderFreePicture(xserver->display, chart->text_picture); - XFreePixmap(xserver->display, chart->text_pixmap); - XRenderFreePicture(xserver->display, chart->shadow_picture); - XRenderFreePicture(xserver->display, chart->picture); - -} - - -static void copy_chart_pictures(vwm_charts_t *charts, vwm_chart_t *src, vwm_chart_t *dest) -{ - vwm_xserver_t *xserver = charts->xserver; - - /* XXX: note the graph pictures are copied from their current phase in the x dimension */ - XRenderComposite(xserver->display, PictOpSrc, src->grapha_picture, None, dest->grapha_picture, - src->phase, 0, /* src x, y */ - 0, 0, /* mask x, y */ - dest->phase, 0, /* dest x, y */ - src->width, src->height); - XRenderComposite(xserver->display, PictOpSrc, src->graphb_picture, None, dest->graphb_picture, - src->phase, 0, /* src x, y */ - 0, 0, /* mask x, y */ - dest->phase, 0, /* dest x, y */ - src->width, src->height); - XRenderComposite(xserver->display, PictOpSrc, src->text_picture, None, dest->text_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - src->width, src->height); - XRenderComposite(xserver->display, PictOpSrc, src->shadow_picture, None, dest->shadow_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - src->width, src->height); - XRenderComposite(xserver->display, PictOpSrc, src->picture, None, dest->picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - src->width, src->height); -} - - /* (re)size the specified chart's visible dimensions */ int vwm_chart_set_visible_size(vwm_charts_t *charts, vwm_chart_t *chart, int width, int height) { - if (width != chart->visible_width || height != chart->visible_height) - chart->redraw_needed = 1; - - /* TODO error handling: if a create failed but we had an chart, free whatever we created and leave it be, succeed. - * if none existed it's a hard error and we must propagate it. */ - - /* if larger than the charts currently are, enlarge them */ - if (width > chart->width || height > chart->height) { - vwm_chart_t existing = *chart; - - chart->width = MAX(chart->width, MAX(width, CHART_GRAPH_MIN_WIDTH)); - chart->height = MAX(chart->height, MAX(height, CHART_GRAPH_MIN_HEIGHT)); - - chart->grapha_picture = create_picture_fill(charts, chart->width, chart->height, CHART_MASK_DEPTH, CPRepeat, &pa_repeat, &chart_trans_color, NULL); - chart->graphb_picture = create_picture_fill(charts, chart->width, chart->height, CHART_MASK_DEPTH, CPRepeat, &pa_repeat, &chart_trans_color, NULL); - chart->tmp_picture = create_picture(charts, chart->width, CHART_ROW_HEIGHT, CHART_MASK_DEPTH, 0, NULL, NULL); - - /* keep the text_pixmap reference around for XDrawText usage */ - chart->text_picture = create_picture_fill(charts, chart->width, chart->height, CHART_MASK_DEPTH, 0, NULL, &chart_trans_color, &chart->text_pixmap); - - chart->shadow_picture = create_picture_fill(charts, chart->width, chart->height, CHART_MASK_DEPTH, 0, NULL, &chart_trans_color, NULL); - chart->picture = create_picture(charts, chart->width, chart->height, 32, 0, NULL, NULL); - - if (existing.width) { - copy_chart_pictures(charts, &existing, chart); - free_chart_pictures(charts, &existing); - } - } - chart->visible_width = width; chart->visible_height = height; + if (vcr_resize_visible(chart->vcr, width, height) > 0) + chart->redraw_needed = 1; + return 1; } @@ -1347,35 +1279,71 @@ vwm_chart_t * vwm_chart_create(vwm_charts_t *charts, int pid, int width, int hei } } + chart->top_columns[0] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_VWM }; + /* TODO: make the columns interactively configurable @ runtime */ - chart->columns[0] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_USER, .side = VWM_SIDE_LEFT }; - chart->columns[1] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_SYS, .side = VWM_SIDE_LEFT }; - chart->columns[2] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_WALL, .side = VWM_SIDE_LEFT }; - chart->columns[3] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_TREE, .side = VWM_SIDE_LEFT }; - chart->columns[4] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_ARGV, .side = VWM_SIDE_LEFT }; - chart->columns[5] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_STATE, .side = VWM_SIDE_RIGHT }; - chart->columns[6] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_PID, .side = VWM_SIDE_RIGHT }; - chart->columns[7] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_WCHAN, .side = VWM_SIDE_RIGHT }; - chart->columns[8] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_VWM, .side = VWM_SIDE_RIGHT }; - - chart->snowflake_columns[0] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_USER, .side = VWM_SIDE_LEFT }; - chart->snowflake_columns[1] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_SYS, .side = VWM_SIDE_LEFT }; - chart->snowflake_columns[2] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_WALL, .side = VWM_SIDE_LEFT }; - chart->snowflake_columns[3] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_ARGV, .side = VWM_SIDE_LEFT }; - - /* add the client process to the monitoring heirarchy */ + chart->proc_cpu_columns[0] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_ROW }; + chart->proc_cpu_columns[1] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_USER }; + chart->proc_cpu_columns[2] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_SYS }; + chart->proc_cpu_columns[3] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_WALL }; + chart->proc_cpu_columns[4] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_TREE }; + chart->proc_cpu_columns[5] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_ARGV }; + chart->proc_cpu_columns[6] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_STATE }; + chart->proc_cpu_columns[7] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_PID }; + chart->proc_cpu_columns[8] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_WCHAN }; + + chart->proc_mem_columns[0] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_ROW }; + chart->proc_mem_columns[1] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_RSS }; + + chart->snowflake_cpu_columns[0] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_PID }; + chart->snowflake_cpu_columns[1] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_USER }; + chart->snowflake_cpu_columns[2] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_SYS }; + chart->snowflake_cpu_columns[3] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_WALL }; + chart->snowflake_cpu_columns[4] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_ARGV }; + + chart->snowflake_mem_columns[0] = (vwm_column_t){ .enabled = 1, .type = VWM_COLUMN_PROC_RSS }; + + + chart->top_row_columns[0] = (vwm_row_column_t){ .column = &chart->top_columns[0], .side = VWM_SIDE_RIGHT, .justify = VWM_JUSTIFY_RIGHT }; + + chart->proc_cpu_row_columns[0] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[0], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_LEFT }; + chart->proc_cpu_row_columns[1] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[1], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + chart->proc_cpu_row_columns[2] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[2], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + chart->proc_cpu_row_columns[3] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[3], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + chart->proc_cpu_row_columns[4] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[4], .side = VWM_SIDE_LEFT }; + chart->proc_cpu_row_columns[5] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[5], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_LEFT }; + chart->proc_cpu_row_columns[6] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[0], .side = VWM_SIDE_RIGHT, .justify = VWM_JUSTIFY_RIGHT }; + chart->proc_cpu_row_columns[7] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[6], .side = VWM_SIDE_RIGHT, .justify = VWM_JUSTIFY_CENTER }; + chart->proc_cpu_row_columns[8] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[7], .side = VWM_SIDE_RIGHT, .justify = VWM_JUSTIFY_RIGHT }; + chart->proc_cpu_row_columns[9] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[8], .side = VWM_SIDE_RIGHT, .justify = VWM_JUSTIFY_RIGHT }; + + chart->proc_mem_row_columns[0] = (vwm_row_column_t){ .column = &chart->proc_mem_columns[0], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_LEFT }; + chart->proc_mem_row_columns[1] = (vwm_row_column_t){ .column = &chart->proc_cpu_columns[0], .side = VWM_SIDE_RIGHT, .justify = VWM_JUSTIFY_RIGHT }; + chart->proc_mem_row_columns[2] = (vwm_row_column_t){ .column = &chart->proc_mem_columns[1], .side = VWM_SIDE_RIGHT, .justify = VWM_JUSTIFY_RIGHT }; + + chart->snowflake_cpu_row_columns[0] = (vwm_row_column_t){ .column = &chart->snowflake_cpu_columns[0], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + chart->snowflake_cpu_row_columns[1] = (vwm_row_column_t){ .column = &chart->snowflake_cpu_columns[1], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + chart->snowflake_cpu_row_columns[2] = (vwm_row_column_t){ .column = &chart->snowflake_cpu_columns[2], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + chart->snowflake_cpu_row_columns[3] = (vwm_row_column_t){ .column = &chart->snowflake_cpu_columns[3], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + chart->snowflake_cpu_row_columns[4] = (vwm_row_column_t){ .column = &chart->snowflake_cpu_columns[4], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_LEFT }; + + chart->snowflake_mem_row_columns[0] = (vwm_row_column_t){ .column = &chart->snowflake_mem_columns[0], .side = VWM_SIDE_LEFT, .justify = VWM_JUSTIFY_RIGHT }; + + /* add the client process to the monitoring hierarchy */ /* XXX note libvmon here maintains a unique callback for each unique callback+xwin pair, so multi-window processes work */ - chart->monitor = vmon_proc_monitor(&charts->vmon, NULL, pid, VMON_WANT_PROC_INHERIT, (void (*)(vmon_t *, void *, vmon_proc_t *, void *))proc_sample_callback, chart); - if (!chart->monitor) { + chart->proc = vmon_proc_monitor(&charts->vmon, pid, VMON_WANT_PROC_INHERIT, (void (*)(vmon_t *, void *, vmon_proc_t *, void *))proc_sample_callback, chart); + if (!chart->proc) { VWM_ERROR("Unable to establish proc monitor"); goto _err_free; } /* FIXME: count_rows() isn't returning the right count sometimes (off by ~1), it seems to be related to racing with the automatic child monitoring */ - /* the result is an extra row sometimes appearing below the process heirarchy */ - chart->heirarchy_end = 1 + count_rows(chart->monitor); + /* the result is an extra row sometimes appearing below the process hierarchy */ + chart->hierarchy_end = CHART_NUM_FIXED_HEADER_ROWS + count_rows(chart->proc, charts->no_threads); chart->gen_last_composed = -1; + chart->vcr = vcr_new(charts->vcr_backend, &chart->hierarchy_end, &chart->snowflakes_cnt, &charts->marker_distance); + if (!vwm_chart_set_visible_size(charts, chart, width, height)) { VWM_ERROR("Unable to set initial chart size"); goto _err_unmonitor; @@ -1384,7 +1352,7 @@ vwm_chart_t * vwm_chart_create(vwm_charts_t *charts, int pid, int width, int hei return chart; _err_unmonitor: - vmon_proc_unmonitor(&charts->vmon, chart->monitor, (void (*)(vmon_t *, void *, vmon_proc_t *, void *))proc_sample_callback, chart); + vmon_proc_unmonitor(&charts->vmon, chart->proc, (void (*)(vmon_t *, void *, vmon_proc_t *, void *))proc_sample_callback, chart); _err_free: free(chart->name); @@ -1397,151 +1365,94 @@ _err: /* stop monitoring and destroy the supplied chart */ void vwm_chart_destroy(vwm_charts_t *charts, vwm_chart_t *chart) { - vmon_proc_unmonitor(&charts->vmon, chart->monitor, (void (*)(vmon_t *, void *, vmon_proc_t *, void *))proc_sample_callback, chart); - free_chart_pictures(charts, chart); + vmon_proc_unmonitor(&charts->vmon, chart->proc, (void (*)(vmon_t *, void *, vmon_proc_t *, void *))proc_sample_callback, chart); + vcr_free(chart->vcr); + free(chart->name); free(chart); } /* this composes the maintained chart into the base chart picture, this gets called from paint_all() on every repaint of xwin */ -/* we noop the call if the gen_last_composed and monitor->proc.generation numbers match, indicating there's nothing new to compose. */ -void vwm_chart_compose(vwm_charts_t *charts, vwm_chart_t *chart, XserverRegion *res_damaged_region) +/* we noop the call if the gen_last_composed and proc->generation numbers match, indicating there's nothing new to compose. */ +void vwm_chart_compose(vwm_charts_t *charts, vwm_chart_t *chart) { - vwm_xserver_t *xserver = charts->xserver; - int height; - - if (!chart->width || !chart->height) + if (!chart->visible_width || !chart->visible_height) return; - if (chart->gen_last_composed == chart->monitor->generation) + if (chart->gen_last_composed == chart->proc->generation) return; /* noop if no sampling occurred since last compose */ - chart->gen_last_composed = chart->monitor->generation; /* remember this generation */ - - //VWM_TRACE("composing %p", chart); - - height = vwm_chart_composed_height(charts, chart); - - /* fill the chart picture with the background */ - XRenderComposite(xserver->display, PictOpSrc, charts->bg_fill, None, chart->picture, - 0, 0, - 0, 0, - 0, 0, - chart->visible_width, height); - - /* draw the graphs into the chart through the stencils being maintained by the sample callbacks */ - XRenderComposite(xserver->display, PictOpOver, charts->grapha_fill, chart->grapha_picture, chart->picture, - 0, 0, - chart->phase, 0, - 0, 0, - chart->visible_width, height); - XRenderComposite(xserver->display, PictOpOver, charts->graphb_fill, chart->graphb_picture, chart->picture, - 0, 0, - chart->phase, 0, - 0, 0, - chart->visible_width, height); - - /* draw the shadow into the chart picture using a translucent black source drawn through the shadow mask */ - XRenderComposite(xserver->display, PictOpOver, charts->shadow_fill, chart->shadow_picture, chart->picture, - 0, 0, - 0, 0, - 0, 0, - chart->visible_width, height); - - /* render chart text into the chart picture using a white source drawn through the chart text as a mask, on top of everything */ - XRenderComposite(xserver->display, PictOpOver, charts->text_fill, chart->text_picture, chart->picture, - 0, 0, - 0, 0, - 0, 0, - chart->visible_width, (chart->heirarchy_end * CHART_ROW_HEIGHT)); - - XRenderComposite(xserver->display, PictOpOver, charts->snowflakes_text_fill, chart->text_picture, chart->picture, - 0, 0, - 0, chart->heirarchy_end * CHART_ROW_HEIGHT, - 0, chart->heirarchy_end * CHART_ROW_HEIGHT, - chart->visible_width, height - (chart->heirarchy_end * CHART_ROW_HEIGHT)); - - /* damage the window to ensure the updated chart is drawn (TODO: this can be done more selectively/efficiently) */ - if (res_damaged_region) { - XRectangle damage = {}; + /* In deferred maintenance mode, we skip maintaining a bunch of layers until the compose happens. + * Normally the layers are maintained incrementally with sampling so real-time visualized use cases + * like vwm/vmon-xlib can always have a readily composed set of current layers to flatten/compose + * into the output picture sourced during window rendering/compositing. + * + * But in offline viewing situations (vmon-png), especially for lower end embedded devices, the + * libvmon sample rate tends to be orders of mangitude higher than the visualization rate. e.g. + * sampling occurs @ 1Hz, with vmon snapshotting a png every half hour. In such situations it's + * wasteful to be maintaining all layers on every libvmon sample. This is when deferred maintenance + * should be used - it puts off maintaining layers which can be reproduced at any time, while still + * maintaining the bare minimum needed for achieving correctness by compose time. All the layers + * deferred between compose calls must still be maintained for compose to produce complete results, + * so we do one last maintain_chart() call with deferred_pass=1, forcing maintenance of all layers. + */ + if (charts->defer_maintenance) + maintain_chart(charts, chart, 1 /* deferred_pass */); - damage.width = chart->visible_width; - damage.height = chart->visible_height; + chart->gen_last_composed = chart->proc->generation; /* remember this generation */ - *res_damaged_region = XFixesCreateRegion(xserver->display, &damage, 1); - } + /* FIXME TODO: errors */ (void) vcr_compose(chart->vcr); } -/* render the chart into a picture at the specified coordinates and dimensions */ -void vwm_chart_render(vwm_charts_t *charts, vwm_chart_t *chart, int op, Picture dest, int x, int y, int width, int height) +#ifdef USE_XLIB +/* xdamage producing variant of the above for vwm composited WM use */ +void vwm_chart_compose_xdamage(vwm_charts_t *charts, vwm_chart_t *chart, XserverRegion *res_damaged_region) { - vwm_xserver_t *xserver = charts->xserver; - - if (!chart->width || !chart->height) - return; + assert(charts); + assert(chart); + assert(res_damaged_region); - /* draw the monitoring chart atop dest, note we stay within the window borders here. */ - XRenderComposite(xserver->display, op, chart->picture, None, dest, - 0, 0, 0, 0, /* src x,y, maxk x, y */ - x, /* dst x */ - y, /* dst y */ - width, MIN(vwm_chart_composed_height(charts, chart), height) /* FIXME */); /* w, h */ + vwm_chart_compose(charts, chart); + /* damage the window to ensure the updated chart is drawn (TODO: this can be done more selectively/efficiently) */ + /* TODO errors: */ (void) vcr_get_composed_xdamage(chart->vcr, res_damaged_region); } +#endif -/* render the chart into a newly allocated pixmap, intended for snapshotting purposes */ -void vwm_chart_render_as_pixmap(vwm_charts_t *charts, vwm_chart_t *chart, const XRenderColor *bg_color, Pixmap *res_pixmap) +/* render the chart into a picture at the specified coordinates and dimensions */ +void vwm_chart_render(vwm_charts_t *charts, vwm_chart_t *chart, vcr_present_op_t op, vcr_dest_t *dest, int x, int y, int width, int height) { - static const XRenderColor blackness = { 0x0000, 0x0000, 0x0000, 0xFFFF}; - Picture dest; - - assert(charts); - assert(chart); - assert(res_pixmap); - - if (!bg_color) - bg_color = &blackness; + if (!chart->visible_width || !chart->visible_height) + return; - dest = create_picture_fill(charts, chart->width, vwm_chart_composed_height(charts, chart), 32, 0, NULL, bg_color, res_pixmap); - vwm_chart_render(charts, chart, PictOpOver, dest, 0, 0, chart->width, vwm_chart_composed_height(charts, chart)); - XRenderFreePicture(charts->xserver->display, dest); + vcr_present(chart->vcr, op, dest, x, y, width, height); } -void vwm_chart_render_as_ximage(vwm_charts_t *charts, vwm_chart_t *chart, const XRenderColor *bg_color, XImage **res_ximage) +static void set_sampling_interval(vwm_charts_t *charts, float interval) { - Pixmap dest_pixmap; - assert(charts); - assert(chart); - assert(res_ximage); - - vwm_chart_render_as_pixmap(charts, chart, bg_color, &dest_pixmap); - *res_ximage = XGetImage(charts->xserver->display, - dest_pixmap, - 0, - 0, - chart->width, - vwm_chart_composed_height(charts, chart), - AllPlanes, - ZPixmap); - - XFreePixmap(charts->xserver->display, dest_pixmap); + assert(interval > 0.f); + + /* if we're unpausing, make this_sample current so we don't have some + * potentially huge time delta to then try fill in with nonsense + */ + if (charts->sampling_interval_secs == INFINITY) + clock_gettime(CLOCK_MONOTONIC_RAW, &charts->this_sample); + + charts->sampling_interval_secs = interval; } /* increase the sample rate relative to current using the table of intervals */ void vwm_charts_rate_increase(vwm_charts_t *charts) { - int i; - assert(charts); - for (i = 0; i < NELEMS(sampling_intervals); i++) { - if (sampling_intervals[i] < charts->sampling_interval) { - charts->sampling_interval = sampling_intervals[i]; - break; + for (int i = 0; i < NELEMS(sampling_intervals); i++) { + if (sampling_intervals[i] < charts->sampling_interval_secs) { + return set_sampling_interval(charts, sampling_intervals[i]); } } } @@ -1550,14 +1461,11 @@ void vwm_charts_rate_increase(vwm_charts_t *charts) /* decrease the sample rate relative to current using the table of intervals */ void vwm_charts_rate_decrease(vwm_charts_t *charts) { - int i; - assert(charts); - for (i = NELEMS(sampling_intervals) - 1; i >= 0; i--) { - if (sampling_intervals[i] > charts->sampling_interval) { - charts->sampling_interval = sampling_intervals[i]; - break; + for (int i = NELEMS(sampling_intervals) - 1; i >= 0; i--) { + if (sampling_intervals[i] > charts->sampling_interval_secs) { + return set_sampling_interval(charts, sampling_intervals[i]); } } } @@ -1569,49 +1477,94 @@ void vwm_charts_rate_set(vwm_charts_t *charts, unsigned hertz) assert(charts); /* XXX: note floating point divide by 0 simply results in infinity */ - charts->sampling_interval = 1.0f / (float)hertz; + set_sampling_interval(charts, 1.f / (float)hertz); +} + + +/* set an arbitrary marker spacing in pixels, 0 disables markers (default) */ +void vwm_charts_marker_distance_set(vwm_charts_t *charts, unsigned distance) +{ + assert(charts); + + charts->marker_distance = distance; } /* convenience function for returning the time delta as a seconds.fraction float */ -static float delta(struct timeval *cur, struct timeval *prev) +static float delta(struct timespec *cur, struct timespec *prev) { - struct timeval res; + struct timespec res; float delta; /* determine the # of whole.fractional seconds between prev and cur */ - timersub(cur, prev, &res); + /* this is basically open-coded timersub() to operate on timespec */ + res.tv_sec = cur->tv_sec - prev->tv_sec; + res.tv_nsec = cur->tv_nsec - prev->tv_nsec; + if (res.tv_nsec < 0 ) { + res.tv_sec--; + res.tv_nsec += 1000000000; + } delta = res.tv_sec; - delta += (float)((float)res.tv_usec) / 1000000.0; + delta += (float)((float)res.tv_nsec) * .000000001f; return delta; } -/* update the charts if necessary, return if updating occurred, and duration before another update needed in *desired_delay */ -int vwm_charts_update(vwm_charts_t *charts, int *desired_delay) +static inline int delta_close_enough(vwm_charts_t *charts, float delta) { - float this_delta = 0.0f; - int ret = 0; + float remainder = charts->sampling_interval_secs - delta; - gettimeofday(&charts->maybe_sample, NULL); - if ((charts->sampling_interval == INFINITY && !charts->sampling_paused) || /* XXX this is kind of a kludge to get the 0 Hz indicator drawn before pausing */ - (charts->sampling_interval != INFINITY && ((this_delta = delta(&charts->maybe_sample, &charts->this_sample)) >= charts->sampling_interval))) { + /* if within .1ms of the scheduled next sample (or behind schedule at all), consider it "close enough" and take the sample. */ + if (remainder <= CHART_DELTA_SECONDS_EPSILON) + return 1; + + return 0; +} + + +/* update the charts if necessary, return if updating occurred, and duration before another update needed in *desired_delay_us */ +int vwm_charts_update(vwm_charts_t *charts, int *desired_delay_us) +{ + int ret = 0, sampled = 0; + float this_delta = 0.f; + + clock_gettime(CLOCK_MONOTONIC_RAW, &charts->maybe_sample); + this_delta = delta(&charts->maybe_sample, &charts->this_sample); + if (!charts->primed || + (charts->sampling_interval_secs == INFINITY && !charts->sampling_paused) || /* XXX this is kind of a kludge to get the 0 Hz indicator drawn before pausing */ + (charts->sampling_interval_secs != INFINITY && delta_close_enough(charts, this_delta))) { vmon_sys_stat_t *sys_stat; /* automatically lower the sample rate if we can't keep up with the current sample rate */ - if (charts->sampling_interval < INFINITY && - charts->sampling_interval <= charts->prev_sampling_interval && - this_delta >= (charts->sampling_interval * 1.5)) { + if (charts->sampling_interval_secs < INFINITY && + charts->sampling_interval_secs <= charts->prev_sampling_interval_secs && + this_delta >= (charts->sampling_interval_secs * 1.5f)) { + + /* adjust charts->this_sample_duration as needed since we've missed our deadline. + * This is more of an issue in headless mode, especially when run on slower/embedded + * devices, even worse when periodically snapshoting costly PNGs that may take + * several seconds during which no sampling occurs. + */ + charts->this_sample_duration = (this_delta / charts->sampling_interval_secs) + .5f /* rounded to int */; /* require > 1 contiguous drops before lowering the rate, tolerates spurious one-off stalls */ if (++charts->contiguous_drops > 2) vwm_charts_rate_decrease(charts); } else { charts->contiguous_drops = 0; + charts->this_sample_duration = 1; /* ideally always 1, but > 1 when sample deadline missed (repeat sample) */ } + charts->this_sample_adherence = -(charts->sampling_interval_secs - this_delta); + if (charts->this_sample_adherence < CHART_DELTA_SECONDS_EPSILON && charts->this_sample_adherence > -CHART_DELTA_SECONDS_EPSILON) + charts->this_sample_adherence = 0; + charts->this_sample_adherence /= charts->sampling_interval_secs; /* turn adherence into a fraction of the current interval */ + + VWM_TRACE("sample_duration=%u sample_adherence=%f", + charts->this_sample_duration, charts->this_sample_adherence); + /* age the sys-wide sample data into "last" variables, before the new sample overwrites them. */ charts->last_sample = charts->this_sample; charts->this_sample = charts->maybe_sample; @@ -1619,28 +1572,60 @@ int vwm_charts_update(vwm_charts_t *charts, int *desired_delay) charts->last_user_cpu = sys_stat->user; charts->last_system_cpu = sys_stat->system; charts->last_total = sys_stat->user + - sys_stat->nice + - sys_stat->system + - sys_stat->idle + - sys_stat->iowait + - sys_stat->irq + - sys_stat->softirq + - sys_stat->steal + - sys_stat->guest; + sys_stat->nice + + sys_stat->system + + sys_stat->idle + + sys_stat->iowait + + sys_stat->irq + + sys_stat->softirq + + sys_stat->steal + + sys_stat->guest; charts->last_idle = sys_stat->idle; charts->last_iowait = sys_stat->iowait; + charts->last_irq = sys_stat->irq; + charts->last_softirq = sys_stat->softirq; } ret = vmon_sample(&charts->vmon); /* XXX: calls proc_sample_callback() for explicitly monitored processes after sampling their descendants */ - /* XXX: also calls sample_callback() per invocation after sampling the sys wants */ + /* XXX: also calls sample_callback() per invocation after sampling the sys wants */ + + charts->sampling_paused = (charts->sampling_interval_secs == INFINITY); + charts->prev_sampling_interval_secs = charts->sampling_interval_secs; + + /* "primed" is just a flag to ensure we always perform the first sample */ + if (!charts->primed) + charts->primed = 1; - charts->sampling_paused = (charts->sampling_interval == INFINITY); - charts->prev_sampling_interval = charts->sampling_interval; + sampled = 1; } - /* TODO: make some effort to compute how long to sleep, but this is perfectly fine for now. */ - *desired_delay = charts->sampling_interval == INFINITY ? -1 : charts->sampling_interval * 300.0; + if (charts->sampling_interval_secs == INFINITY) { + *desired_delay_us = -1; /* sleep forever */ + } else { + float remaining_secs; + + if (sampled) { /* sampling takes time, so let's subtract that from the interval-derived sleep time to try get the next sample started on-time (if possible) */ + struct timespec post_sampled; + + clock_gettime(CLOCK_MONOTONIC_RAW, &post_sampled); + this_delta += delta(&post_sampled, &charts->this_sample); + } + + remaining_secs = charts->sampling_interval_secs - this_delta; + if (remaining_secs <= 0) { + /* always sleep some minimal amount, we don't want to spin */ + *desired_delay_us = CHART_DELTA_SECONDS_EPSILON * 1000000.f; + } else { + *desired_delay_us = remaining_secs * 1000000.f; + } + } return ret; } + + +void charts_vmon_dump_procs(vwm_charts_t *charts, FILE *out) +{ + vmon_dump_procs(&charts->vmon, out); +} diff --git a/src/charts.h b/src/charts.h index 9e28afa..6db51be 100644 --- a/src/charts.h +++ b/src/charts.h @@ -1,28 +1,43 @@ #ifndef _CHARTS_H #define _CHARTS_H -#include <X11/extensions/Xfixes.h> -#include <X11/extensions/Xrender.h> +#include <stdio.h> /* just for charts_vmon_dump_procs() */ +#ifdef USE_XLIB +#include <X11/extensions/Xfixes.h> /* this is just for XserverRegion/vwm_chart_compose_xdamage() */ #include "xserver.h" +#endif + +#include "vcr.h" + +#define VWM_CHARTS_FLAG_DEFER_MAINTENANCE 0x1 +#define VWM_CHARTS_NO_THREADS 0x2 typedef struct _vwm_charts_t vwm_charts_t; typedef struct _vwm_chart_t vwm_chart_t; -vwm_charts_t * vwm_charts_create(vwm_xserver_t *xserver); +vwm_charts_t * vwm_charts_create(vcr_backend_t *vbe, unsigned flags); void vwm_charts_destroy(vwm_charts_t *charts); void vwm_charts_rate_increase(vwm_charts_t *charts); void vwm_charts_rate_decrease(vwm_charts_t *charts); void vwm_charts_rate_set(vwm_charts_t *charts, unsigned hertz); -int vwm_charts_update(vwm_charts_t *charts, int *desired_delay); +void vwm_charts_marker_distance_set(vwm_charts_t *charts, unsigned distance); +int vwm_charts_update(vwm_charts_t *charts, int *desired_delay_us); +void charts_vmon_dump_procs(vwm_charts_t *charts, FILE *out); vwm_chart_t * vwm_chart_create(vwm_charts_t *charts, int pid, int width, int height, const char *name); void vwm_chart_destroy(vwm_charts_t *charts, vwm_chart_t *chart); void vwm_chart_reset_snowflakes(vwm_charts_t *charts, vwm_chart_t *chart); int vwm_chart_set_visible_size(vwm_charts_t *charts, vwm_chart_t *chart, int width, int height); -void vwm_chart_compose(vwm_charts_t *charts, vwm_chart_t *chart, XserverRegion *res_damaged_region); -void vwm_chart_render(vwm_charts_t *charts, vwm_chart_t *chart, int op, Picture dest, int x, int y, int width, int height); -void vwm_chart_render_as_pixmap(vwm_charts_t *charts, vwm_chart_t *chart, const XRenderColor *bg_color, Pixmap *res_pixmap); -void vwm_chart_render_as_ximage(vwm_charts_t *charts, vwm_chart_t *chart, const XRenderColor *bg_color, XImage **res_ximage); +void vwm_chart_compose(vwm_charts_t *charts, vwm_chart_t *chart); +#ifdef USE_XLIB +/* XXX: this is annoying, and frankly could probably go away if I don't ever actually bother with producing + * an accurate damaged region. Right now it's just a visible area of the composed charts rectangle, + * which could just as well be served by a simple x,y,w,h visible area description the caller could then + * turn into an XserverRegion is desired. + */ +void vwm_chart_compose_xdamage(vwm_charts_t *charts, vwm_chart_t *chart, XserverRegion *res_damaged_region); +#endif +void vwm_chart_render(vwm_charts_t *charts, vwm_chart_t *chart, vcr_present_op_t op, vcr_dest_t *dest, int x, int y, int width, int height); #endif diff --git a/src/clickety.c b/src/clickety.c index fc2f6d3..b7495c8 100644 --- a/src/clickety.c +++ b/src/clickety.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -74,19 +74,19 @@ static void compute_resize(XEvent *terminus, XWindowAttributes *new) xdelta = xdelta / width_inc * width_inc; ydelta = ydelta / height_inc * height_inc; - if (clickety.impetus_x < dw && clickety.impetus_y < dh) { + if (clickety.impetus_x <= dw && clickety.impetus_y <= dh) { /* grabbed top left */ new->x = clickety.orig.x + xdelta; new->y = clickety.orig.y + ydelta; new->width = clickety.orig.width - xdelta; new->height = clickety.orig.height - ydelta; - } else if (clickety.impetus_x > dw && clickety.impetus_y < dh) { + } else if (clickety.impetus_x > dw && clickety.impetus_y <= dh) { /* grabbed top right */ new->x = clickety.orig.x; new->y = clickety.orig.y + ydelta; new->width = clickety.orig.width + xdelta; new->height = clickety.orig.height - ydelta; - } else if (clickety.impetus_x < dw && clickety.impetus_y > dh) { + } else if (clickety.impetus_x <= dw && clickety.impetus_y > dh) { /* grabbed bottom left */ new->x = clickety.orig.x + xdelta; new->y = clickety.orig.y; diff --git a/src/composite.c b/src/composite.c index f575909..353253f 100644 --- a/src/composite.c +++ b/src/composite.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -27,6 +27,7 @@ #include "charts.h" #include "xwindow.h" +#include "vcr.h" #include "vwm.h" /* compositing manager stuff */ @@ -38,6 +39,7 @@ typedef enum _vwm_compositing_mode_t { static vwm_compositing_mode_t compositing_mode = VWM_COMPOSITING_OFF; /* current compositing mode */ static XserverRegion combined_damage = None; static Picture root_picture = None, root_buffer = None; /* compositing gets double buffered */ +static vcr_dest_t *root_dest; static XWindowAttributes root_attrs; static XRenderPictureAttributes pa_inferiors = { .subwindow_mode = IncludeInferiors }; static int repaint_needed; @@ -172,6 +174,7 @@ void vwm_composite_invalidate_root(vwm_t *vwm) if (root_buffer) { XRenderFreePicture(VWM_XDISPLAY(vwm), root_buffer); root_buffer = None; + root_dest = vcr_dest_free(root_dest); } } @@ -211,6 +214,7 @@ void vwm_composite_paint_all(vwm_t *vwm) CPSubwindowMode, &pa_inferiors); root_pixmap = XCreatePixmap(VWM_XDISPLAY(vwm), VWM_XROOT(vwm), root_attrs.width, root_attrs.height, VWM_XDEPTH(vwm)); root_buffer = XRenderCreatePicture(VWM_XDISPLAY(vwm), root_pixmap, XRenderFindVisualFormat(VWM_XDISPLAY(vwm), VWM_XVISUAL(vwm)), 0, 0); + root_dest = vcr_dest_xpicture_new(vwm->vcr_backend, root_buffer); XFreePixmap(VWM_XDISPLAY(vwm), root_pixmap); } @@ -245,7 +249,7 @@ void vwm_composite_paint_all(vwm_t *vwm) if (xwin->chart) { XserverRegion chart_damage = None; - vwm_chart_compose(vwm->charts, xwin->chart, &chart_damage); + vwm_chart_compose_xdamage(vwm->charts, xwin->chart, &chart_damage); if (chart_damage != None) { /* the damage region is in chart coordinate space, translation necessary. */ XFixesTranslateRegion(VWM_XDISPLAY(vwm), chart_damage, @@ -288,7 +292,7 @@ void vwm_composite_paint_all(vwm_t *vwm) if (xwin->chart) { /* draw the monitoring chart atop the window, note we stay within the window borders here. */ - vwm_chart_render(vwm->charts, xwin->chart, PictOpOver, root_buffer, + vwm_chart_render(vwm->charts, xwin->chart, VCR_PRESENT_OP_OVER, root_dest, xwin->attrs.x + xwin->attrs.border_width, xwin->attrs.y + xwin->attrs.border_width, xwin->attrs.width, diff --git a/src/context.c b/src/context.c index 255480c..c44563d 100644 --- a/src/context.c +++ b/src/context.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, diff --git a/src/desktop.c b/src/desktop.c index d88fa93..0901d4f 100644 --- a/src/desktop.c +++ b/src/desktop.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -16,6 +16,7 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include <assert.h> #include <X11/Xlib.h> #include <X11/keysym.h> #include <stdlib.h> @@ -29,9 +30,10 @@ #include "window.h" #include "xwindow.h" -static int key_is_grabbed; /* flag for tracking keyboard grab state */ +static int key_is_grabbed; /* flag for tracking keyboard grab state */ static vwm_direction_t direction = VWM_DIRECTION_FORWARD; /* flag for reversing directional actions */ -static int send_it; /* flag for "sending" a migration operation without following it */ +static int send_it; /* flag for "sending" a migration operation without following it */ +static int chase_it; /* flag for "chasing" a focus operation with the pointer */ /* Poll the keyboard state to see if _any_ keys are pressed */ static int keys_pressed(vwm_t *vwm) @@ -80,6 +82,12 @@ void vwm_key_released(vwm_t *vwm, Window win, XKeyReleasedEvent *keyrelease) break; + case XK_m: + VWM_TRACE("XK_m released with chase_it=%i", chase_it); + chase_it = 0; + break; + + case XK_r: VWM_TRACE("XK_r released with direction=%i", direction); direction = VWM_DIRECTION_FORWARD; @@ -107,12 +115,12 @@ void vwm_key_released(vwm_t *vwm, Window win, XKeyReleasedEvent *keyrelease) /* Called in response to KeyPress events, I currenly only grab Mod1 keypress events */ void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress) { - vwm_window_t *vwin; - KeySym sym; - static KeySym last_sym; - static typeof(keypress->state) last_state; - static int repeat_cnt = 0; - int do_grab = 0; + vwm_window_t *vwin; + KeySym sym; + static KeySym last_sym; + static typeof(keypress->state) last_state; + static int repeat_cnt = 0; + int do_grab = 0; sym = XLookupKeysym(keypress, 0); @@ -128,12 +136,12 @@ void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress) switch (sym) { #define launcher(_sym, _label, _argv)\ - case _sym: \ - { \ + case _sym: { \ char *args[] = {"/bin/sh", "-c", "screen -dr " CONSOLE_SESSION_STRING " -X screen /bin/sh -i -x -c \"" _argv " || sleep 86400\"", NULL};\ vwm_launch(vwm, args, VWM_LAUNCH_MODE_BG);\ break; \ } + #include "launchers.def" #undef launcher case XK_Alt_L: /* transaction abort */ @@ -144,6 +152,11 @@ void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress) VWM_TRACE("aborting with origin %p", vwm->focused_origin); break; + case XK_m: /* "chase" focus actions with pointer */ + VWM_TRACE("XK_r pressed with chase_it=%i", chase_it); + chase_it = 1; + break; + case XK_r: /* reverse directional actions */ VWM_TRACE("XK_r pressed with direction=%i", direction); direction = VWM_DIRECTION_REVERSE; @@ -196,21 +209,40 @@ void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress) case XK_backslash: do_grab = 1; + /* Backslash is all about screen boundaries within the current desktop. + * Screens are funky since they're basically just subrects within the X "screen" + * that spans all the displays in multihead setups (xinerama). + */ + if (vwin) { - if (keypress->state & ShiftMask) { - /* TODO: migrate window to another screen within this desktop, - * like VWM_FENCE_MASKED_VIOLATE would focus the next window on - * the next screen, but instead of focusing the next window on - * the next display, move the focused one to that next desktop. - * - * since screens are handled within vwm_win_focus_next() via - * the fence abstraction, but fences aren't exposed outside of - * their, it's non-trivial to implement here. I may want to - * break that out into a more public interface to make things - * more composable at the screen level. - */ - VWM_TRACE("migrate window to screen not implemented yet"); + if (send_it || (keypress->state & ShiftMask)) { + vwm_screen_rel_t rel; + + /* "migrate" the focused window to the next screen */ + + switch (direction) { + case VWM_DIRECTION_FORWARD: + rel = VWM_SCREEN_REL_XWIN_NEXT; + break; + case VWM_DIRECTION_REVERSE: + rel = VWM_SCREEN_REL_XWIN_PREV; + break; + default: + assert(0); + } + + if (send_it) { + /* "sending" only differs in that we try to focus the next window before migrating, + * if vwin is the only window, it stays focused, and this degrades gracefully into + * a migrate. This is done because we never leave a situation without any window + * focused in a desktop. + */ + vwm_win_focus_next(vwm, vwin, direction, VWM_FENCE_RESPECT); + } + + vwm_win_autoconf(vwm, vwin, rel, vwin->autoconfigured, vwin->autoconfigured_param); } else { + /* focus the MRU window on the next screen */ vwm_win_focus_next(vwm, vwin, direction, VWM_FENCE_MASKED_VIOLATE); } } @@ -228,9 +260,13 @@ void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress) } else if (send_it) { /* "send" the focused window to a new desktop in the current context, kind of an alias of send_it+XK_v */ if (vwin) vwm_win_send(vwm, vwin, vwm_desktop_mru(vwm, vwm_desktop_create(vwm, vwin->desktop->context))); - } else if (keypress->state & ShiftMask) { /* migrate the focused window with the desktop focus to the most recently used desktop */ - if (vwin) + } else if (keypress->state & ShiftMask) { /* migrate the focused window with the desktop focus to the most recently used desktop, creating one if none exists for convenience */ + if (vwin) { + if (next_desktop == vwm->focused_desktop) + next_desktop = vwm_desktop_create(vwm, vwin->desktop->context); + vwm_win_migrate(vwm, vwin, next_desktop); + } } else { vwm_desktop_focus(vwm, next_desktop); } @@ -467,11 +503,31 @@ void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress) vwm_charts_rate_decrease(vwm->charts); break; + case XK_z: /* zero sampling frequency (disables monitoring) */ + vwm_charts_rate_set(vwm->charts, 0); + break; + default: VWM_TRACE("Unhandled keycode: %x", (unsigned int)sym); break; } + /* if we're chasing focus with the pointer, center the pointer in the focused window */ + if (chase_it) { + /* We have to get the latest window attrs for this to always do the right thing, + * otherwise it's kind of racy as we've often _just_ changed window attrs, + * and want to query them to warp the pointer to the current configuration. + */ + XSync(VWM_XDISPLAY(vwm), False); + vwin = vwm_win_get_focused(vwm); + if (vwin) { + XWindowAttributes attrs; + + XGetWindowAttributes(VWM_XDISPLAY(vwm), vwin->xwindow->id, &attrs); + XWarpPointer(VWM_XDISPLAY(vwm), None, vwin->xwindow->id, 0, 0, 0, 0, attrs.width / 2, attrs.height / 2); + } + } + /* if what we're doing requests a grab, if not already grabbed, grab keyboard */ if (!key_is_grabbed && do_grab) { VWM_TRACE("saving focused_origin of %p", vwin); diff --git a/src/launch.c b/src/launch.c index 3a30eca..45b8ccb 100644 --- a/src/launch.c +++ b/src/launch.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -17,6 +17,8 @@ */ /* launching of external processes / X clients */ +#include <assert.h> +#include <stdio.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/time.h> @@ -26,21 +28,141 @@ #include "launch.h" #include "vwm.h" +#include "window.h" +#include "xwindow.h" #define LAUNCHED_RELATIVE_PRIORITY 10 /* the wm priority plus this is used as the priority of launched processes */ + +/* return an interpolated copy of arg */ +static char * arg_interpolate(const vwm_t *vwm, const char *arg) +{ + FILE *memfp; + char *xarg = NULL; + size_t xarglen; + int fmt = 0; + + assert(vwm); + assert(arg); + + /* this came from vmon.c, it'd be nice if they could share */ + + memfp = open_memstream(&xarg, &xarglen); + if (!memfp) { + VWM_PERROR("unable to create memstream"); + return NULL; + } + + for (size_t i = 0; arg[i]; i++) { + char c = arg[i]; + + if (!fmt) { + if (c == '%') + fmt = 1; + else + fputc(c, memfp); + + continue; + } + + switch (c) { + case 'W': { /* focused X window id in hex, root window if nothing focused */ + vwm_window_t *vwin; + Window winid; + + vwin = vwm_win_get_focused(vwm); + if (vwin) + winid = vwin->xwindow->id; + else + winid = VWM_XROOT(vwm); + + fprintf(memfp, "%#x", (unsigned)winid); + break; + } + + case '%': /* literal % */ + fputc(c, memfp); + break; + + default: + VWM_ERROR("Unrecognized specifier \'%c\'", c); + goto _err; + } + + fmt = 0; + } + + fclose(memfp); + + return xarg; + +_err: + fclose(memfp); + free(xarg); + + return NULL; +} + + +static char ** args_interpolate(vwm_t *vwm, char **argv) +{ + char **args; + int n_args; + + assert(vwm); + assert(argv); + + for (n_args = 0; argv[n_args]; n_args++); + + args = calloc(n_args + 1, sizeof(*args)); + if (!args) + return NULL; + + for (int i = 0; i < n_args; i++) { + args[i] = arg_interpolate(vwm, argv[i]); + if (!args[i]) { + for (int j = 0; j < n_args; j++) + free(args[j]); + free(args); + + return NULL; + } + } + + return args; +} + + +static void args_free(char **args) +{ + assert(args); + + for (int i = 0; args[i]; i++) + free(args[i]); + free(args); +} + + /* launch a child command specified in argv, mode decides if we wait for the child to exit before returning. */ void vwm_launch(vwm_t *vwm, char **argv, vwm_launch_mode_t mode) { + char **args; + + args = args_interpolate(vwm, argv); + if (!args) + return; + /* XXX: in BG mode I double fork and let init inherit the orphan so I don't have to collect the return status */ if (mode == VWM_LAUNCH_MODE_FG || !fork()) { if (!fork()) { /* child */ setpriority(PRIO_PROCESS, getpid(), vwm->priority + LAUNCHED_RELATIVE_PRIORITY); - execvp(argv[0], argv); + execvp(args[0], args); } if (mode == VWM_LAUNCH_MODE_BG) exit(0); } wait(NULL); /* TODO: could wait for the specific pid, particularly in FG mode ... */ + + args_free(args); } diff --git a/src/launchers.def b/src/launchers.def index ea06683..e8407a7 100644 --- a/src/launchers.def +++ b/src/launchers.def @@ -1,8 +1,8 @@ /* it's up to you to ensure you don't conflict with the global VWM keys */ -/* keysym, label, cmd */ -launcher( XK_x, "xterm", "/usr/bin/xterm") -launcher( XK_b, "firefox", "/usr/bin/firefox -ProfileManager -no-remote") -launcher( XK_g, "gimp", "/usr/bin/gimp") -launcher( XK_period, "lock", "/usr/bin/xlock") -launcher( XK_minus, "dpms off", "/usr/bin/xset -dpms s off") -launcher( XK_equal, "dpms on", "/usr/bin/xset +dpms s on") +/* keysym, label, cmd */ +launcher( XK_x, "xterm", "xterm") +launcher( XK_period, "lock", "xlock") +launcher( XK_minus, "dpms off", "xset -dpms s off") +launcher( XK_equal, "dpms on", "xset +dpms s on") +launcher( XK_BackSpace, "record window", "recordmydesktop --need-shortcuts --no-frame --windowid %W --fps 60 --workdir ~/.rmd/work --output ~/.rmd/caps/vwm.ogv") +launcher( XK_Delete, "record desktop", "recordmydesktop --need-shortcuts --no-frame --fps 60 --workdir ~/.rmd/work --output ~/.rmd/caps/vwm.ogv") diff --git a/src/libvmon/LICENSE b/src/libvmon/LICENSE index 94a9ed0..d60c31a 100644 --- a/src/libvmon/LICENSE +++ b/src/libvmon/LICENSE @@ -1,626 +1,285 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 - Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - Preamble + Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to this License. - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it @@ -628,15 +287,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least +convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> - This program is free software: you can redistribute it and/or modify + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or + the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -645,30 +304,37 @@ the "copyright" line and a pointer to where the full notice is found. GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Also add information on how to contact you by electronic and paper mail. - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: - <program> Copyright (C) <year> <name of author> - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -<http://www.gnu.org/licenses/>. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -<http://www.gnu.org/philosophy/why-not-lgpl.html>. +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/src/libvmon/defs/proc_stat.def b/src/libvmon/defs/proc_stat.def index db704e9..61d3338 100644 --- a/src/libvmon/defs/proc_stat.def +++ b/src/libvmon/defs/proc_stat.def @@ -60,7 +60,7 @@ vmon_datum_ulonglong( start, PROC_STAT_START, "StartTime", "start time relativ vmon_omit_run( ' ', PROC_STAT_VSIZE_SP) vmon_datum_ulonglong( vsize, PROC_STAT_VSIZE, "VirtSize", "virtual memory size (bytes)") vmon_omit_run( ' ', PROC_STAT_RSS_SP) -vmon_datum_ulonglong( rss, PROC_STAT_RSS, "ResSize", "resident set size (bytes)") +vmon_datum_ulonglong( rss, PROC_STAT_RSS, "ResSize", "resident set size (pages)") vmon_omit_run( ' ', PROC_STAT_RSSLIM_SP) vmon_datum_ulonglong( rsslim, PROC_STAT_RSSLIM, "ResSizeLimit", "resident set size ulimit") vmon_omit_run( ' ', PROC_STAT_STARTCODE_SP) diff --git a/src/libvmon/defs/proc_wants.def b/src/libvmon/defs/proc_wants.def index 7f02602..a3c3cd7 100644 --- a/src/libvmon/defs/proc_wants.def +++ b/src/libvmon/defs/proc_wants.def @@ -1,7 +1,11 @@ #include "_begin.def" -/* the available per-process wants, the order here matters, put wants which affect the sampling heirarchy first */ -/* otherwise they will change the heirarchy after samples have been collected, leaving newly introduced nodes with uninitialized sample stores after return from vmon_sample() */ +/* the available per-process wants, the order here matters, put wants which affect the sampling hierarchy first */ +/* otherwise they will change the hierarchy after samples have been collected, leaving newly introduced nodes with uninitialized sample stores after return from vmon_sample() */ +/* also PROC_FOLLOW_THREADS must be the last thing before the sampling wants, because those get skipped + * if VMON_FLAG_NEGLECT_THREADS is set even when following threaads, and that's done by skipping wants + * greater than VMON_FLAG_NEGLECT_THREADS for threads at sample time. + */ /* sym, name, internal fulfilllment function */ vmon_want(PROC_FOLLOW_CHILDREN, proc_follow_children, proc_follow_children) diff --git a/src/libvmon/vmon.c b/src/libvmon/vmon.c index 83d78c4..b4c008c 100644 --- a/src/libvmon/vmon.c +++ b/src/libvmon/vmon.c @@ -5,10 +5,10 @@ * This has been written specifically for use in vwm, my window manager, * but includes some facilities for other uses. * - * Copyright (c) 2012-2017 Vito Caputo - <vcaputo@pengaru.com> + * Copyright (c) 2012-2025 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 3 as + * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -20,6 +20,7 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include <assert.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> @@ -51,6 +52,8 @@ typedef enum _sample_ret_t { /* some private convenience functions */ static void try_free(void **ptr) { + assert(ptr); + if ((*ptr)) { free((*ptr)); (*ptr) = NULL; @@ -60,6 +63,8 @@ static void try_free(void **ptr) static void try_close(int *fd) { + assert(fd); + if ((*fd) != -1) { close((*fd)); (*fd) = -1; @@ -69,6 +74,8 @@ static void try_close(int *fd) static void try_closedir(DIR **dir) { + assert(dir); + if ((*dir)) { closedir((*dir)); (*dir) = NULL; @@ -78,6 +85,8 @@ static void try_closedir(DIR **dir) static ssize_t try_pread(int fd, void *buf, size_t count, off_t offset) { + assert(buf); + if (fd != -1) { return pread(fd, buf, count, offset); } else { @@ -89,10 +98,14 @@ static ssize_t try_pread(int fd, void *buf, size_t count, off_t offset) /* this does a copy from src to dest * sets the bit specified by changed_pos in the bitmap *changed if what was copied to src was different from what was already there */ -static void memcmpcpy(void *dest, const void *src, size_t n, char *changed, int changed_pos) +static void memcmpcpy(void *dest, const void *src, size_t n, char *changed, unsigned changed_pos) { size_t i = 0; + assert(dest); + assert(src); + assert(changed); + /* if the changed bit is set on entry we don't execute the comparison-copy */ if (!BITTEST(changed, changed_pos)) { /* a simple slow compare and copy loop, break out if we've found a change */ @@ -119,30 +132,40 @@ typedef enum _vmon_load_flags_t { } vmon_load_flags_t; /* we enlarge *alloc if necessary, but never shrink it. changed[changed_pos] bit is set if a difference is detected, supply LOAD_FLAGS_NOTRUNCATE if we don't want empty contents to truncate last-known data */ -static char * load_contents_fd(vmon_t *vmon, vmon_char_array_t *array, int fd, vmon_load_flags_t flags, char *changed, int changed_pos) +static int load_contents_fd(vmon_t *vmon, vmon_char_array_t *array, int fd, vmon_load_flags_t flags, char *changed, unsigned changed_pos) { - int total = 0, len, alloc_len = array->alloc_len; - char *alloc = array->array, *tmp; + size_t total = 0; + ssize_t len; + assert(vmon); + assert(array); + assert(changed); + + if (fd < 0) /* no use attempting the pread() on -1 fds */ + return 0; + + /* FIXME: this is used to read proc files, you can't actually read proc files iteratively + * without race conditions; it needs to be all done as a single read. + */ while ((len = pread(fd, vmon->buf, sizeof(vmon->buf), total)) > 0) { - if (total + len > alloc_len) { - /* realloc to accomodate the new total */ - tmp = realloc(alloc, total + len); + size_t newsize = total + len; + + if (newsize > array->alloc_len) { + char *tmp; + + tmp = realloc(array->array, newsize); if (!tmp) - return NULL; + return -ENOMEM; - alloc_len = total + len; - alloc = tmp; + array->array = tmp; + array->alloc_len = newsize; } - memcmpcpy(&alloc[total], vmon->buf, len, changed, changed_pos); + memcmpcpy(&array->array[total], vmon->buf, len, changed, changed_pos); total += len; } - array->array = alloc; - array->alloc_len = alloc_len; - /* if we read something or didn't encounter an error, store the new total */ if (total || (len == 0 && !(flags & LOAD_FLAGS_NOTRUNCATE))) { /* if the new length differs ensure the changed bit is set */ @@ -152,7 +175,7 @@ static char * load_contents_fd(vmon_t *vmon, vmon_char_array_t *array, int fd, v array->len = total; } - return alloc; + return 0; } @@ -163,6 +186,10 @@ static int openf(vmon_t *vmon, int flags, DIR *dir, char *fmt, ...) va_list va_arg; char buf[4096]; + assert(vmon); + assert(dir); + assert(fmt); + va_start(va_arg, fmt); vsnprintf(buf, sizeof(buf), fmt, va_arg); /* XXX accepting the possibility of truncating the path */ va_end(va_arg); @@ -180,6 +207,10 @@ static DIR * opendirf(vmon_t *vmon, DIR *dir, char *fmt, ...) va_list va_arg; char buf[4096]; + assert(vmon); + assert(dir); + assert(fmt); + va_start(va_arg, fmt); vsnprintf(buf, sizeof(buf), fmt, va_arg); /* XXX accepting the possibility of truncating the path */ va_end(va_arg); @@ -193,164 +224,252 @@ static DIR * opendirf(vmon_t *vmon, DIR *dir, char *fmt, ...) /* enlarge an array by the specified amount */ -static int grow_array(vmon_char_array_t *array, int amount) +static int grow_array(vmon_char_array_t *array, size_t amount) { char *tmp; + assert(array); + tmp = realloc(array->array, array->alloc_len + amount); if (!tmp) - return 0; + return -ENOMEM; array->alloc_len += amount; array->array = tmp; - return 1; + return 0; } /* load the contents of a symlink, dir is not optional */ #define READLINKF_GROWINIT 10 #define READLINKF_GROWBY 2 -static char * readlinkf(vmon_t *vmon, vmon_char_array_t *array, DIR *dir, char *fmt, ...) +static int readlinkf(vmon_t *vmon, vmon_char_array_t *array, DIR *dir, char *fmt, ...) { - va_list va_arg; - int len; char buf[4096]; + va_list va_arg; + ssize_t len; + + assert(vmon); + assert(array); + assert(dir); + assert(fmt); va_start(va_arg, fmt); vsnprintf(buf, sizeof(buf), fmt, va_arg); va_end(va_arg); - if (!array->array && !grow_array(array, READLINKF_GROWINIT)) - goto _fail; + if (!array->array && grow_array(array, READLINKF_GROWINIT) < 0) + return -ENOMEM; do { len = readlinkat(dirfd(dir), buf, array->array, (array->alloc_len - 1)); - } while (len != -1 && len == (array->alloc_len - 1) && (len = grow_array(array, READLINKF_GROWBY))); + } while (len != -1 && len == (array->alloc_len - 1) && (len = grow_array(array, READLINKF_GROWBY)) >= 0); - if (len <= 0) - goto _fail; + if (len < 0) + return -errno; array->len = len; array->array[array->len] = '\0'; - return array->array; - -_fail: - return NULL; + return 0; } /* here starts private per-process samplers and other things like following children implementation etc. */ -/* sample stat process stats */ -typedef enum _vmon_proc_stat_fsm_t { -#define VMON_ENUM_PARSER_STATES -#include "defs/proc_stat.def" -} vmon_proc_stat_fsm_t; - -static sample_ret_t proc_sample_stat(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_stat_t **store) +/* simple helper for installing callbacks on the callback lists, currently only used for the per-process sample callbacks */ +/* will not install the same callback function & arg combination more than once, and will not install NULL-functioned callbacks at all! */ +static int maybe_install_proc_callback(vmon_t *vmon, list_head_t *callbacks, void (*func)(vmon_t *, void *, vmon_proc_t *, void *), void *arg) { - int changes = 0; - int i, len, total = 0; - char *arg; - int argn, prev_argc; - vmon_proc_stat_fsm_t state = VMON_PARSER_STATE_PROC_STAT_PID; -#define VMON_PREPARE_PARSER -#include "defs/proc_stat.def" + assert(vmon); + assert(callbacks); + assert(!arg || func); - if (!proc) { /* dtor */ - try_close(&(*store)->comm_fd); - try_free((void **)&(*store)->comm); - try_close(&(*store)->cmdline_fd); - try_free((void **)&(*store)->cmdline); - try_close(&(*store)->wchan_fd); - try_close(&(*store)->stat_fd); - try_free((void **)&(*store)->exe); + if (func) { + vmon_proc_callback_t *cb; - return DTOR_FREE; + list_for_each_entry(cb, callbacks, callbacks) { + if (cb->func == func && cb->arg == arg) + break; + } + + if (&cb->callbacks == callbacks) { + cb = calloc(1, sizeof(vmon_proc_callback_t)); + if (!cb) + return 0; + + cb->func = func; + cb->arg = arg; + list_add_tail(&cb->callbacks, callbacks); + } } -/* _retry: */ - if (!(*store)) { /* ctor */ + return 1; +} - *store = calloc(1, sizeof(vmon_proc_stat_t)); - if (proc->is_thread) { - (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/comm", proc->pid, proc->pid); - (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/cmdline", proc->pid, proc->pid); - (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/wchan", proc->pid, proc->pid); - (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/stat", proc->pid, proc->pid); - } else { - (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/comm", proc->pid); - (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/cmdline", proc->pid); - (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/wchan", proc->pid); - (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/stat", proc->pid); - } +/* helper for searching for the process in the process array, specify NULL to find a free slot */ +static int find_proc_in_array(vmon_t *vmon, vmon_proc_t *proc, int hint) +{ + int ret = -1; - /* initially everything is considered changed */ - memset((*store)->changed, 0xff, sizeof((*store)->changed)); + assert(vmon); + + if (hint >= 0 && hint < vmon->array_allocated_nr && vmon->array[hint] == proc) { + /* the hint was accurate, bypass the search */ + ret = hint; } else { - /* clear the entire changed bitmap */ - memset((*store)->changed, 0, sizeof((*store)->changed)); + int i; + + /* search for the entry in the array */ + for (i = 0; i < vmon->array_allocated_nr; i++) { + if (vmon->array[i] == proc) { + ret = i; + break; + } + } } - /* XXX TODO: integrate load_contents_fd() calls into changes++ maintenance */ - /* /proc/$pid/comm */ - load_contents_fd(vmon, &(*store)->comm, (*store)->comm_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_COMM); + if (!proc && ret == -1) { + vmon_proc_t **tmp; - /* /proc/$pid/cmdline */ - load_contents_fd(vmon, &(*store)->cmdline, (*store)->cmdline_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_CMDLINE); - for (prev_argc = (*store)->argc, (*store)->argc = 0, i = 0; i < (*store)->cmdline.len; i++) { - if (!(*store)->cmdline.array[i]) - (*store)->argc++; + /* enlarge the array */ + tmp = realloc(vmon->array, (vmon->array_allocated_nr + VMON_ARRAY_GROWBY) * sizeof(vmon_proc_t *)); + if (tmp) { + memset(&tmp[vmon->array_allocated_nr], 0, VMON_ARRAY_GROWBY * sizeof(vmon_proc_t *)); + ret = vmon->array_hint_free = vmon->array_allocated_nr; + vmon->array_allocated_nr += VMON_ARRAY_GROWBY; + vmon->array = tmp; + } /* XXX TODO: handle realloc failure */ } - /* if the cmdline has changed, allocate argv array and store ptrs to the fields within it */ - if (BITTEST((*store)->changed, VMON_PROC_STAT_CMDLINE)) { - if (prev_argc != (*store)->argc) { - try_free((void **)&(*store)->argv); /* XXX could realloc */ - (*store)->argv = calloc(1, (*store)->argc * sizeof(char *)); - } + return ret; +} - for (argn = 0, arg = (*store)->cmdline.array, i = 0; i < (*store)->cmdline.len; i++) { - if (!(*store)->cmdline.array[i]) { - (*store)->argv[argn++] = arg; - arg = &(*store)->cmdline.array[i + 1]; + +/* this is the private variant that allows providing a parent, which libvmon needs for constructing hierarchies, but callers shouldn't be doing themselves */ +static vmon_proc_t * proc_monitor(vmon_t *vmon, vmon_proc_t *parent, int pid, vmon_proc_wants_t wants, void (*sample_cb)(vmon_t *, void *, vmon_proc_t *, void *), void *sample_cb_arg) +{ + vmon_proc_t *proc; + int hash = (pid % VMON_HTAB_SIZE), i; + int is_thread = (wants & VMON_INTERNAL_PROC_IS_THREAD) ? 1 : 0; + + assert(vmon); + assert(!sample_cb_arg || sample_cb); + + wants &= ~VMON_INTERNAL_PROC_IS_THREAD; + + if (pid < 0) + return NULL; + + list_for_each_entry(proc, &vmon->htab[hash], bucket) { + /* search for the process to see if it's already monitored, we allow threads to exist with the same pid hence the additional is_thread comparison */ + if (proc->pid == pid && proc->is_thread == is_thread) { + if (!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_arg)) + return NULL; + + proc->wants = wants; /* we can alter wants this way, though it clearly needs more consideration XXX */ + + if (parent) { + /* This is a predicament. If the top-level (externally-established) process monitor wins the race, the process has no parent and is on the vmon->processes list. + * Then the follow_children-established monitor comes along and wants to assign a parent, this isn't such a big deal, and we should be able to permit it, however, + * we're in the process of iterating the top-level processes list when we run the follow_children() sampler of a descendant which happens to also be the parent. + * We can't simply remove the process from the top-level processes list mid-iteration and stick it on the children list of the parent, the iterator could wind up + * following the new pointer into the parents children. + * + * What I'm doing for now is allowing the assignment of a parent when there is no parent, but we don't perform the vmon->processes to parent->children migration + * until the top-level sample_siblings() function sees the node with the parent. At that point, the node will migrate to the parent's children list. Since + * this particular migration happens immediately within the same sample, it + */ + if (!proc->parent) { + /* if a parent was supplied, and there is no current parent, the process is top-level currently by external callers, but now appears to be a child of something as well, + * so in this scenario, we'll remove it from the top-level siblings list, and make it a child of the new parent. I don't think there needs to be concern about its being a thread here. */ + /* Note we can't simply move the process from its current processes list and add it to the supplied parent's children list, as that would break the iterator above us at the top-level, so + * we must defer the migration until the processes iterator context can do it for us - but this is tricky because we're in the middle of traversing our hierarchy and this process may + * be in a critical is_new state which must be realized this sample at its location in the hierarchy for correctness, there will be no reappearance of that critical state in the correct + * tree position for users like vwm. */ + /* the VMON_FLAG_2PASS flag has been introduced for users like vwm */ + proc->parent = parent; + proc->refcnt++; + } +#if 0 + else if (parent != proc->parent) { + /* We're switching parents; this used to be considered unexpected, but then vmon happened and it monitors the whole tree from PID1 down. + * PID1 is special in that it inherits orphans, so we can already be monitoring a child of an exited parent, and here PID1's children + * following is looking up a newly inherited orphan, which reaches here finding proc with a non-NULL, but different parent. + * Note the introduction of PR_SET_CHILD_SUBREAPER has made this no longer limited to PID1 either. + */ + /* now, we can't simply switch parents in a single step... since the is_stale=1 state must be seen by the front-end before we can + * unlink it from the structure in a subsequent sample. So instead, we should be queueing an adoption by the new parent, but + * for the time being we can just suppress the refcnt bump and let the adoptive parent reestablish the monitor anew after + * runs its course under its current parent. + */ + } +#endif + } else { + proc->refcnt++; } + + return proc; } } - /* /proc/$pid/wchan */ - load_contents_fd(vmon, &(*store)->wchan, (*store)->wchan_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_WCHAN); - - /* /proc/$pid/exe */ - if ((*store)->cmdline.len) /* kernel threads have no cmdline, and always fail readlinkf() on exe, skip readlinking the exe for them using this heuristic */ - readlinkf(vmon, &(*store)->exe, vmon->proc_dir, "%i/exe", proc->pid); + proc = (vmon_proc_t *)calloc(1, sizeof(vmon_proc_t)); + if (proc == NULL) + return NULL; /* TODO: report an error */ - /* XXX TODO: there's a race between discovering comm_len from /proc/$pid/comm and applying it in the parsing of /proc/$pid/stat, detect the race - * scenario and retry the sample when detected by goto _retry (see commented _retry label above) */ + proc->pid = pid; + proc->wants = wants; + proc->generation = vmon->generation; + proc->refcnt = 1; + proc->is_new = 1; /* newly created process */ + proc->is_thread = is_thread; + proc->parent = parent; + INIT_LIST_HEAD(&proc->sample_callbacks); + INIT_LIST_HEAD(&proc->children); + INIT_LIST_HEAD(&proc->siblings); + INIT_LIST_HEAD(&proc->threads); - /* read in stat and parse it assigning the stat members accordingly */ - while ((len = try_pread((*store)->stat_fd, vmon->buf, sizeof(vmon->buf), total)) > 0) { - total += len; + if (!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_arg)) { + free(proc); + return NULL; + } - for (i = 0; i < len; i++) { - /* parse the fields from the file, stepping through... */ - _p.input = vmon->buf[i]; - switch (state) { -#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ -#define VMON_IMPLEMENT_PARSER -#include "defs/proc_stat.def" - default: - /* we're finished parsing once we've fallen off the end of the symbols */ - goto _out; /* this saves us the EOF read syscall */ - } + if (parent) { + /* if a parent is specified, attach this process to the parent's children or threads with its siblings */ + if (is_thread) { + list_add_tail(&proc->threads, &parent->threads); + parent->threads_changed = 1; + parent->is_threaded = 1; + parent->n_current_threads++; + } else { + list_add_tail(&proc->siblings, &parent->children); + parent->children_changed = 1; } + } else { + /* if no parent is specified, this is a toplevel process, attach it to the vmon->processes list with its siblings */ + /* XXX ignoring is_thread if no parent is specified, it shouldn't occur, unless I want to support external callers monitoring specific threads explicitly, maybe... */ + list_add_tail(&proc->siblings, &vmon->processes); + vmon->processes_changed = 1; } -_out: - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; + /* add this process to the hash table */ + list_add_tail(&proc->bucket, &vmon->htab[hash]); + + /* if process table maintenance is enabled acquire a free slot for this process */ + if ((vmon->flags & VMON_FLAG_PROC_ARRAY) && (i = find_proc_in_array(vmon, NULL, vmon->array_hint_free)) != -1) { + vmon->array[i] = proc; + + /* cache where we get inserted into the array */ + proc->array_hint_pos = i; + } + + /* invoke ctor callback if set, note it's only called when a new vmon_proc_t has been instantiated */ + if (vmon->proc_ctor_cb) + vmon->proc_ctor_cb(vmon, proc); + + return proc; } @@ -362,15 +481,15 @@ static int proc_follow_children(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follo vmon_proc_t *tmp, *_tmp; list_head_t *cur, *start; + assert(vmon); + assert(store); + if (!proc) { /* dtor */ try_close(&(*store)->children_fd); return DTOR_FREE; } - if (proc->is_thread) /* don't follow children of threads */ - return SAMPLE_UNCHANGED; - if (!(*store)) { /* implicit ctor on first sample */ *store = calloc(1, sizeof(vmon_proc_follow_children_t)); @@ -420,14 +539,30 @@ static int proc_follow_children(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follo } } - if (found || (tmp = vmon_proc_monitor(vmon, proc, child_pid, proc->wants, NULL, NULL))) { - /* position the process in the siblings list, and update the start */ - /* move to front breaks vwm, we rely on the stale processes maintaining their position! maybe make it an option to vmon_init() since it can be a useful optimization. */ - start = &tmp->siblings; - } /* else { vmon_proc_monitor failed just move on } */ + if (found || (tmp = proc_monitor(vmon, proc, child_pid, proc->wants, NULL, NULL))) { + /* There's an edge case where vmon_proc_monitor() finds child_pid existing as a child of something else, + * in that case we're effectively migrating it to a new parent. This occurs in the vmon use case where + * it's monitoring PID1-down, and PID1 of course inherits orphans. So some descendant proc is already + * being monitored with its children monitored too, but that proc has exited, orphaning its children. + * The kernel has since moved the orphaned children up to be children of PID1, and we could be performing + * children following for PID1 here, discovering those newly inherited orphans whose exited parent hasn't + * even been flagged as is_stale yet in libvmon, let alone been unreffed/removed from the htab. + * + * In such a scenario, we need to _not_ use its siblings node as a search start, because we'll be stepping + * into the other parent's children list, which would be Very Broken. What we instead do, is basically + * nothing, so it can be handled in a future sample, after the exited parent can go through its is_stale=1 + * cycle and unlink itself from the orphaned descendants. There are more complicated ways to handle this + * which would technically be more accurate, but let's just do the simple and correct thing for now. + */ + if (tmp->parent == proc) + start = &tmp->siblings; + } /* else { proc_monitor failed just move on } */ child_pid = 0; break; + + default: + assert(0); } } } @@ -462,6 +597,9 @@ static int proc_follow_threads(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow vmon_proc_t *tmp, *_tmp; int found; + assert(vmon); + assert(store); + if (!proc) { /* dtor */ try_closedir(&(*store)->task_dir); @@ -471,7 +609,8 @@ static int proc_follow_threads(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow if (proc->is_thread) /* bypass following the threads of threads */ return SAMPLE_UNCHANGED; - if (!proc->stores || !proc->stores[VMON_STORE_PROC_STAT] || (((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->num_threads <= 1 && list_empty(&proc->threads))) + if (!proc->stores[VMON_STORE_PROC_STAT] || + (((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->num_threads <= 1 && list_empty(&proc->threads))) /* bypass following of threads if we either can't determine the number from the proc stat sample or if the sample says there's 1 or less (and an empty threads list, handling stale exited threads) */ /* XXX I'm not sure if this is always the right thing to do, there may be some situations where one could play games with clone() directly * and escape the monitoring library with a lone thread having had the main thread exit, leaving the count at 1 while having a process @@ -495,6 +634,24 @@ static int proc_follow_threads(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow vmon_proc_unmonitor(vmon, tmp, NULL, NULL); } + /* If proc is stale, assume all the threads are stale as well. In vwm/charts.c we assume all descendants of a stale node + * are implicitly stale, so let's ensure that's a consistent assumumption WRT libvmon's maintenance of the hierarchy. + * The readdir below seems like it would't find any threads of a stale process, but maybe there's some potential for a race there, + * particularly since we reuse an open reference on the task_dir. + * This reflects a similar implicit is_stale propagation in follow_children. + */ + if (proc->is_stale) { + list_for_each_entry(tmp, &proc->threads, threads) + tmp->is_stale = 1; + + proc->n_current_threads = 0; + + /* FIXME: the changes count seems to be unused here, so this currently always returns SAMPLE_UNCHANGED, and + * it's unclear to me if that was intentional or just never finished. + */ + return SAMPLE_UNCHANGED; + } + start = &proc->threads; while ((dentry = readdir((*store)->task_dir))) { int tid; @@ -519,25 +676,148 @@ static int proc_follow_threads(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow } } - if (found || (tmp = vmon_proc_monitor(vmon, proc, tid, (proc->wants | VMON_INTERNAL_PROC_IS_THREAD), NULL, NULL))) + if (found || (tmp = proc_monitor(vmon, proc, tid, (proc->wants | VMON_INTERNAL_PROC_IS_THREAD), NULL, NULL))) start = &tmp->threads; } list_for_each_entry_safe(tmp, _tmp, &proc->threads, threads) { /* set children not found to stale status so the caller can respond and on our next sample invocation we will unmonitor them */ - if (tmp->generation != vmon->generation) + if (tmp->generation != vmon->generation) { tmp->is_stale = 1; + assert(proc->n_current_threads); + proc->n_current_threads--; + } } return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; } +/* sample stat process stats */ +typedef enum _vmon_proc_stat_fsm_t { +#define VMON_ENUM_PARSER_STATES +#include "defs/proc_stat.def" +} vmon_proc_stat_fsm_t; + +static sample_ret_t proc_sample_stat(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_stat_t **store) +{ + int changes = 0; + int i, len, total = 0; + char *arg; + int argn, prev_argc; + vmon_proc_stat_fsm_t state = VMON_PARSER_STATE_PROC_STAT_PID; +#define VMON_PREPARE_PARSER +#include "defs/proc_stat.def" + + assert(vmon); + assert(store); + + if (!proc) { /* dtor */ + try_close(&(*store)->comm_fd); + try_free((void **)&(*store)->comm.array); + try_close(&(*store)->cmdline_fd); + try_free((void **)&(*store)->cmdline.array); + try_free((void **)&(*store)->argv); + try_close(&(*store)->wchan_fd); + try_free((void **)&(*store)->wchan.array); + try_close(&(*store)->stat_fd); + try_free((void **)&(*store)->exe.array); + + return DTOR_FREE; + } + +/* _retry: */ + if (!(*store)) { /* ctor */ + + *store = calloc(1, sizeof(vmon_proc_stat_t)); + + if (proc->is_thread) { + (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/comm", proc->pid, proc->pid); + (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/cmdline", proc->pid, proc->pid); + (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/wchan", proc->pid, proc->pid); + (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/stat", proc->pid, proc->pid); + } else { + (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/comm", proc->pid); + (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/cmdline", proc->pid); + (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/wchan", proc->pid); + (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/stat", proc->pid); + } + + /* initially everything is considered changed */ + memset((*store)->changed, 0xff, sizeof((*store)->changed)); + } else { + /* clear the entire changed bitmap */ + memset((*store)->changed, 0, sizeof((*store)->changed)); + } + + /* XXX TODO: integrate load_contents_fd() calls into changes++ maintenance */ + /* /proc/$pid/comm */ + load_contents_fd(vmon, &(*store)->comm, (*store)->comm_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_COMM); + + /* /proc/$pid/cmdline */ + load_contents_fd(vmon, &(*store)->cmdline, (*store)->cmdline_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_CMDLINE); + for (prev_argc = (*store)->argc, (*store)->argc = 0, i = 0; i < (*store)->cmdline.len; i++) { + if (!(*store)->cmdline.array[i]) + (*store)->argc++; + } + + /* if the cmdline has changed, allocate argv array and store ptrs to the fields within it */ + if (BITTEST((*store)->changed, VMON_PROC_STAT_CMDLINE)) { + if (prev_argc != (*store)->argc) { + try_free((void **)&(*store)->argv); /* XXX could realloc */ + (*store)->argv = calloc(1, (*store)->argc * sizeof(char *)); + } + + for (argn = 0, arg = (*store)->cmdline.array, i = 0; i < (*store)->cmdline.len; i++) { + if (!(*store)->cmdline.array[i]) { + (*store)->argv[argn++] = arg; + arg = &(*store)->cmdline.array[i + 1]; + } + } + } + + /* /proc/$pid/wchan */ + load_contents_fd(vmon, &(*store)->wchan, (*store)->wchan_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_WCHAN); + + /* /proc/$pid/exe */ + if ((*store)->cmdline.len) /* kernel threads have no cmdline, and always fail readlinkf() on exe, skip readlinking the exe for them using this heuristic */ + readlinkf(vmon, &(*store)->exe, vmon->proc_dir, "%i/exe", proc->pid); + + /* XXX TODO: there's a race between discovering comm_len from /proc/$pid/comm and applying it in the parsing of /proc/$pid/stat, detect the race + * scenario and retry the sample when detected by goto _retry (see commented _retry label above) */ + + /* read in stat and parse it assigning the stat members accordingly */ + while ((len = try_pread((*store)->stat_fd, vmon->buf, sizeof(vmon->buf), total)) > 0) { + total += len; + + for (i = 0; i < len; i++) { + /* parse the fields from the file, stepping through... */ + _p.input = vmon->buf[i]; + switch (state) { +#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ +#define VMON_IMPLEMENT_PARSER +#include "defs/proc_stat.def" + default: + /* we're finished parsing once we've fallen off the end of the symbols */ + goto _out; /* this saves us the EOF read syscall */ + } + } + } + +_out: + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + + + /* helper for maintaining reference counted global objects table */ static vmon_fobject_t * fobject_lookup_hinted(vmon_t *vmon, const char *path, vmon_fobject_t *hint) { - vmon_fobject_t *fobject = NULL, *tmp = NULL; - uint64_t inum; + vmon_fobject_t *fobject = NULL, *tmp = NULL; + uint64_t inum; + + assert(vmon); /* TODO maintain the fobject hash tables, they should probably be isolated/scoped based on the string before the : */ /* in reality there needs to be a list somewhere of the valid prefixes we wish to support, and that list should associate @@ -582,6 +862,9 @@ static vmon_fobject_t * fobject_lookup_hinted(vmon_t *vmon, const char *path, vm /* add a reference to an fobject, fd_ref is optional (should be present if the reference is due to an open fd, which may not be the case) */ static void fobject_ref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t *fd_ref) { + assert(vmon); + assert(fobject); + fobject->refcnt++; if (fd_ref) @@ -592,6 +875,9 @@ static void fobject_ref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t *f /* fobject is required and is the object being unrefereced, fd_ref is optional but represents the per-process fd reference being used to access this fobject via */ static int fobject_unref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t *fd_ref) { + assert(vmon); + assert(fobject); + if (fd_ref) list_del(&fd_ref->ref_fds); @@ -616,10 +902,13 @@ static int fobject_unref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t * /* helper for deleting an fd from the per-process fds list list */ static void del_fd(vmon_t *vmon, vmon_proc_fd_t *fd) { + assert(vmon); + assert(fd); + list_del(&fd->fds); if (fd->object) fobject_unref(vmon, fd->object, fd); /* note we supply both the fobject ptr and proc_fd ptr (fd) */ - try_free((void **)&fd->object_path); + try_free((void **)&fd->object_path.array); free(fd); } @@ -634,6 +923,9 @@ static sample_ret_t proc_sample_files(vmon_t *vmon, vmon_proc_t *proc, vmon_proc vmon_proc_fd_t *fd, *_fd; vmon_fobject_t *cur_object = NULL; + assert(vmon); + assert(store); + if (!proc) { /* dtor implementation */ if (--((*store)->refcnt)) /* suppress dtor while references exist, the store is shared */ @@ -755,6 +1047,9 @@ static sample_ret_t proc_sample_vm(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_vm #define VMON_PREPARE_PARSER #include "defs/proc_vm.def" + assert(vmon); + assert(store); + if (!proc) { /* dtor */ try_close(&(*store)->statm_fd); @@ -812,6 +1107,9 @@ static sample_ret_t proc_sample_io(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_io #define VMON_PREPARE_PARSER #include "defs/proc_io.def" + assert(vmon); + assert(store); + if (!proc) { /* dtor */ try_close(&(*store)->io_fd); @@ -873,6 +1171,8 @@ static sample_ret_t sys_sample_stat(vmon_t *vmon, vmon_sys_stat_t **store) #define VMON_PREPARE_PARSER #include "defs/sys_stat.def" + assert(store); + if (!vmon) { /* dtor */ try_close(&(*store)->stat_fd); return DTOR_FREE; @@ -932,6 +1232,8 @@ static sample_ret_t sys_sample_vm(vmon_t *vmon, vmon_sys_vm_t **store) #define VMON_PREPARE_PARSER #include "defs/sys_vm.def" + assert(store); + if (!vmon) { /* dtor */ try_close(&(*store)->meminfo_fd); return DTOR_FREE; @@ -975,6 +1277,8 @@ int vmon_init(vmon_t *vmon, vmon_flags_t flags, vmon_sys_wants_t sys_wants, vmon { int i; + assert(vmon); + if ((flags & VMON_FLAG_PROC_ALL) && (proc_wants & VMON_WANT_PROC_FOLLOW_CHILDREN)) return 0; @@ -1001,6 +1305,9 @@ int vmon_init(vmon_t *vmon, vmon_flags_t flags, vmon_sys_wants_t sys_wants, vmon vmon->sys_wants = sys_wants; vmon->proc_wants = proc_wants; vmon->ticks_per_sec = sysconf(_SC_CLK_TCK); + vmon->num_cpus = sysconf(_SC_NPROCESSORS_ONLN); + if (vmon->num_cpus <= 0) + vmon->num_cpus = 1; /* default to 1 cpu */ /* here we populate the sys and proc function tables */ #define vmon_want(_sym, _name, _func) \ @@ -1029,169 +1336,12 @@ void vmon_destroy(vmon_t *vmon) } -/* helper for searching for the process in the process array, specify NULL to find a free slot */ -static int find_proc_in_array(vmon_t *vmon, vmon_proc_t *proc, int hint) -{ - int ret = -1; - - if (hint >= 0 && hint < vmon->array_allocated_nr && vmon->array[hint] == proc) { - /* the hint was accurate, bypass the search */ - ret = hint; - } else { - int i; - - /* search for the entry in the array */ - for (i = 0; i < vmon->array_allocated_nr; i++) { - if (vmon->array[i] == proc) { - ret = i; - break; - } - } - } - - if (!proc && ret == -1) { - vmon_proc_t **tmp; - - /* enlarge the array */ - tmp = realloc(vmon->array, (vmon->array_allocated_nr + VMON_ARRAY_GROWBY) * sizeof(vmon_proc_t *)); - if (tmp) { - memset(&tmp[vmon->array_allocated_nr], 0, VMON_ARRAY_GROWBY * sizeof(vmon_proc_t *)); - ret = vmon->array_hint_free = vmon->array_allocated_nr; - vmon->array_allocated_nr += VMON_ARRAY_GROWBY; - vmon->array = tmp; - } /* XXX TODO: handle realloc failure */ - } - - return ret; -} - - -/* simple helper for installing callbacks on the callback lists, currently only used for the per-process sample callbacks */ -/* will not install the same callback function & arg combination more than once, and will not install NULL-functioned callbacks at all! */ -static int maybe_install_proc_callback(vmon_t *vmon, list_head_t *callbacks, void (*func)(vmon_t *, void *, vmon_proc_t *, void *), void *arg) -{ - if (func) { - vmon_proc_callback_t *cb; - - list_for_each_entry(cb, callbacks, callbacks) { - if (cb->func == func && cb->arg == arg) - break; - } - - if (&cb->callbacks == callbacks) { - cb = calloc(1, sizeof(vmon_proc_callback_t)); - if (!cb) - return 0; - - cb->func = func; - cb->arg = arg; - list_add_tail(&cb->callbacks, callbacks); - } - } - - return 1; -} - - /* monitor a process under a given vmon instance, the public interface. * XXX note it's impossible to say "none" for wants per-process, just "inherit", if vmon_init() was told a proc_wants of "inherit" then it's like having "none" * proc_wants for all proceses, perhaps improve this if there's a pressure to support this use case */ -vmon_proc_t * vmon_proc_monitor(vmon_t *vmon, vmon_proc_t *parent, int pid, vmon_proc_wants_t wants, void (*sample_cb)(vmon_t *, void *, vmon_proc_t *, void *), void *sample_cb_arg) +vmon_proc_t * vmon_proc_monitor(vmon_t *vmon, int pid, vmon_proc_wants_t wants, void (*sample_cb)(vmon_t *, void *, vmon_proc_t *, void *), void *sample_cb_arg) { - vmon_proc_t *proc; - int hash = (pid % VMON_HTAB_SIZE), i; - int is_thread = (wants & VMON_INTERNAL_PROC_IS_THREAD) ? 1 : 0; - - wants &= ~VMON_INTERNAL_PROC_IS_THREAD; - - if (pid < 0) - return NULL; - - list_for_each_entry(proc, &vmon->htab[hash], bucket) { - /* search for the process to see if it's already monitored, we allow threads to exist with the same pid hence the additional is_thread comparison */ - if (proc->pid == pid && proc->is_thread == is_thread) { - if (!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_arg)) - return NULL; - - proc->wants = wants; /* we can alter wants this way, though it clearly needs more consideration XXX */ - proc->refcnt++; - /* This is a predicament. If the top-level (externally-established) process monitor wins the race, the process has no parent and is on the vmon->processes list. - * Then the follow_children-established monitor comes along and wants to assign a parent, this isn't such a big deal, and we should be able to permit it, however, - * we're in the process of iterating the top-level processes list when we run the follow_children() sampler of a descendant which happens to also be the parent. - * We can't simply remove the process from the top-level processes list mid-iteration and stick it on the children list of the parent, the iterator could wind up - * following the new pointer into the parents children. - * - * What I'm doing for now is allowing the assignment of a parent when there is no parent, but we don't perform the vmon->processes to parent->children migration - * until the top-level sample_siblings() function sees the node with the parent. At that point, the node will migrate to the parent's children list. - */ - if (parent && !proc->parent) { - /* if a parent was supplied, and there is no current parent, the process is a top-level currently by external callers, but now appears to be a child of something as well, - * so in this scenario, we'll remove it from the top-level siblings list, and make it a child of the new parent. I don't think there needs to be concern about its being a thread here. */ - /* Note we can't simply move the process from its current processes list and add it to the supplied parent's children list, as that would break the iterator above us at the top-level, so - * we must defer the migration until the processes iterator context can do it for us - but this is tricky because we're in the middle of traversing our heirarchy and this process may - * be in a critical is_new state which must be realized this sample at its location in the heirarchy for correctness, there will be no reappearance of that critical state in the correct - * tree position for users like vwm. */ - /* the VMON_FLAG_2PASS flag has been introduced for users like vwm */ - proc->parent = parent; - } /* else if (parent && proc->parent) { XXX TODO: it shouldn't be possible to have conflicting parents, but may want to log an error if it happens. */ - - return proc; - } - } - - proc = (vmon_proc_t *)calloc(1, sizeof(vmon_proc_t)); - if (proc == NULL) - return NULL; /* TODO: report an error */ - - proc->pid = pid; - proc->wants = wants; - proc->generation = vmon->generation; - proc->refcnt = 1; - proc->is_new = 1; /* newly created process */ - proc->is_thread = is_thread; - proc->parent = parent; - INIT_LIST_HEAD(&proc->sample_callbacks); - INIT_LIST_HEAD(&proc->children); - INIT_LIST_HEAD(&proc->siblings); - INIT_LIST_HEAD(&proc->threads); - - if (!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_arg)) { - free(proc); - return NULL; - } - - if (parent) { - /* if a parent is specified, attach this process to the parent's children or threads with its siblings */ - if (is_thread) { - list_add_tail(&proc->threads, &parent->threads); - parent->threads_changed = 1; - } else { - list_add_tail(&proc->siblings, &parent->children); - parent->children_changed = 1; - } - } else { - /* if no parent is specified, this is a toplevel process, attach it to the vmon->processes list with its siblings */ - /* XXX ignoring is_thread if no parent is specified, it shouldn't occur, unless I want to support external callers monitoring specific threads explicitly, maybe... */ - list_add_tail(&proc->siblings, &vmon->processes); - vmon->processes_changed = 1; - } - - /* add this process to the hash table */ - list_add_tail(&proc->bucket, &vmon->htab[hash]); - - /* if process table maintenance is enabled acquire a free slot for this process */ - if ((vmon->flags & VMON_FLAG_PROC_ARRAY) && (i = find_proc_in_array(vmon, NULL, vmon->array_hint_free)) != -1) { - vmon->array[i] = proc; - - /* cache where we get inserted into the array */ - proc->array_hint_pos = i; - } - - /* invoke ctor callback if set, note it's only called when a new vmon_proc_t has been instantiated */ - if (vmon->proc_ctor_cb) - vmon->proc_ctor_cb(vmon, proc); - - return proc; + return proc_monitor(vmon, NULL, pid, wants, sample_cb, sample_cb_arg); } @@ -1201,6 +1351,10 @@ void vmon_proc_unmonitor(vmon_t *vmon, vmon_proc_t *proc, void (*sample_cb)(vmon vmon_proc_t *child, *_child; int i; + assert(vmon); + assert(proc); + assert(!sample_cb_arg || sample_cb); + if (sample_cb) { /* uninstall callback */ vmon_proc_callback_t *cb, *_cb; @@ -1225,7 +1379,7 @@ void vmon_proc_unmonitor(vmon_t *vmon, vmon_proc_t *proc, void (*sample_cb)(vmon vmon_proc_unmonitor(vmon, child, NULL, NULL); } - /* unmonitor all threads being monitored, suppressed if this process is a thread itself, as threads don't have children */ + /* unmonitor all threads being monitored, suppressed if this process is a thread itself */ if (!proc->is_thread) { list_for_each_entry_safe(child, _child, &proc->threads, threads) vmon_proc_unmonitor(vmon, child, NULL, NULL); @@ -1258,8 +1412,18 @@ void vmon_proc_unmonitor(vmon_t *vmon, vmon_proc_t *proc, void (*sample_cb)(vmon for (i = 0; i < sizeof(vmon->proc_funcs) / sizeof(vmon->proc_funcs[VMON_STORE_PROC_STAT]); i++) { if (proc->stores[i] != NULL) { /* any non-NULL stores must have a function installed and must have been sampled, invoke the dtor branch */ - if (vmon->proc_funcs[i](vmon, NULL, &proc->stores[i]) == DTOR_FREE) + sample_ret_t r; + + r = vmon->proc_funcs[i](vmon, NULL, &proc->stores[i]); + switch (r) { + case DTOR_FREE: try_free((void **)&proc->stores[i]); + break; + case DTOR_NOFREE: + break; + default: + assert(0); + } } } @@ -1276,6 +1440,9 @@ static void sample(vmon_t *vmon, vmon_proc_t *proc) { int i, wants, cur; + assert(vmon); + assert(proc); + proc->children_changed = proc->threads_changed = 0; /* load this process monitors wants, or inherit the default */ @@ -1284,8 +1451,14 @@ static void sample(vmon_t *vmon, vmon_proc_t *proc) proc->activity = 0; for (i = 0, cur = 1; wants; cur <<= 1, i++) { if (wants & cur) { - if (vmon->proc_funcs[i](vmon, proc, &proc->stores[i]) == SAMPLE_CHANGED) - proc->activity |= cur; + /* XXX: this is a bit awkward, but in constrained environments you might want to only follow threads while + * suppressing their sampling of the other WANT_PROC* data. To achieve that you specify VMON_FLAG_NEGLECT_THREADS + * in combination with VMON_WANT_PROC_FOLLOW_THREADS. The following line is what makes that actually work. + * This also adds another ordering dependency in proc_wants.def + */ + if (!proc->is_thread || !(vmon->flags & VMON_FLAG_NEGLECT_THREADS) || cur <= VMON_WANT_PROC_FOLLOW_THREADS) + if (vmon->proc_funcs[i](vmon, proc, &proc->stores[i]) == SAMPLE_CHANGED) + proc->activity |= cur; wants &= ~cur; } @@ -1293,21 +1466,53 @@ static void sample(vmon_t *vmon, vmon_proc_t *proc) } +static int sample_siblings_unipass(vmon_t *vmon, list_head_t *siblings); +static int sample_siblings_pass1(vmon_t *vmon, list_head_t *siblings); +static int sample_siblings_pass2(vmon_t *vmon, list_head_t *siblings); + /* internal sampling helper, perform sampling for all sibling processes in the provided siblings list */ -static int sample_threads(vmon_t *vmon, list_head_t *threads) +static int sample_threads_unipass(vmon_t *vmon, list_head_t *threads) { vmon_proc_t *proc; + assert(vmon); + assert(threads); + list_for_each_entry(proc, threads, threads) { sample(vmon, proc); + sample_siblings_unipass(vmon, &proc->children); /* invoke samplers for this thread's children (which strangely is a thing) */ + } -#if 0 - /* callbacks can't be installed currently on threads */ - vmon_proc_callback_t *cb; + return 1; +} - list_for_each_entry(cb, &proc->sample_callbacks, callbacks) - cb->func(vmon, vmon->sample_cb_arg, proc, cb->arg); -#endif + +/* internal sampling helper, perform sampling for all sibling processes in the provided siblings list */ +static int sample_threads_pass1(vmon_t *vmon, list_head_t *threads) +{ + vmon_proc_t *proc; + + assert(vmon); + assert(threads); + + list_for_each_entry(proc, threads, threads) { + sample(vmon, proc); + sample_siblings_pass1(vmon, &proc->children); /* invoke samplers for this thread's children (which strangely is a thing) */ + } + + return 1; +} + + +static int sample_threads_pass2(vmon_t *vmon, list_head_t *threads) +{ + vmon_proc_t *proc; + + assert(vmon); + assert(threads); + + list_for_each_entry(proc, threads, threads) { + sample_siblings_pass2(vmon, &proc->children); /* invoke samplers for this thread's children (which strangely is a thing) */ } return 1; @@ -1315,10 +1520,13 @@ static int sample_threads(vmon_t *vmon, list_head_t *threads) /* internal single-pass sampling helper, recursively perform sampling and callbacks for all sibling processes in the provided siblings list */ -static int sample_siblings(vmon_t *vmon, list_head_t *siblings) +static int sample_siblings_unipass(vmon_t *vmon, list_head_t *siblings) { vmon_proc_t *proc, *_proc; + assert(vmon); + assert(siblings); + list_for_each_entry_safe(proc, _proc, siblings, siblings) { vmon_proc_callback_t *cb; int entered_new = 0; @@ -1327,9 +1535,9 @@ static int sample_siblings(vmon_t *vmon, list_head_t *siblings) if (proc->is_new) entered_new = 1; - sample(vmon, proc); /* invoke samplers for this node */ - sample_threads(vmon, &proc->threads); /* invoke samplers for this node's threads */ - sample_siblings(vmon, &proc->children); /* invoke samplers for this node's children, and their callbacks, by recursing into this function */ + sample(vmon, proc); /* invoke samplers for this node */ + sample_threads_unipass(vmon, &proc->threads); /* invoke samplers for this node's threads */ + sample_siblings_unipass(vmon, &proc->children); /* invoke samplers for this node's children, and their callbacks, by recursing into this function */ /* XXX TODO: error returns */ /* if this is the top-level processes list, and proc has found a parent through the above sampling, migrate it to the parent's children list */ @@ -1340,7 +1548,7 @@ static int sample_siblings(vmon_t *vmon, list_head_t *siblings) } /* XXX note that sample_callbacks are called only after all the descendants have had their sampling performed (and their potential callbacks invoked) - * this enables the installation of a callback at a specific node in the process heirarchy which can also perform duties on behalf of the children + * this enables the installation of a callback at a specific node in the process hierarchy which can also perform duties on behalf of the children * being monitored, handy when automatically following children, an immediately relevant use case (vwm) */ list_for_each_entry(cb, &proc->sample_callbacks, callbacks) @@ -1361,16 +1569,19 @@ static int sample_siblings(vmon_t *vmon, list_head_t *siblings) } -/* 2pass version of the internal heirarchical sampling helper */ +/* 2pass version of the internal hierarchical sampling helper */ static int sample_siblings_pass1(vmon_t *vmon, list_head_t *siblings) { vmon_proc_t *proc, *_proc; + assert(vmon); + assert(siblings); + /* invoke samplers */ list_for_each_entry_safe(proc, _proc, siblings, siblings) { - sample(vmon, proc); /* invoke samplers for this node */ - sample_threads(vmon, &proc->threads); /* invoke samplers for this node's threads */ - sample_siblings_pass1(vmon, &proc->children); /* invoke samplers for this node's children, by recursing into this function */ + sample(vmon, proc); /* invoke samplers for this node */ + sample_threads_pass1(vmon, &proc->threads); /* invoke samplers for this node's threads */ + sample_siblings_pass1(vmon, &proc->children); /* invoke samplers for this node's children, by recursing into this function */ /* XXX TODO: error returns */ /* if this is the top-level processes list, and proc has found a parent through the above sampling, migrate it to the parent's children list */ @@ -1401,10 +1612,14 @@ static int sample_siblings_pass2(vmon_t *vmon, list_head_t *siblings) { vmon_proc_t *proc; + assert(vmon); + assert(siblings); + /* invoke callbacks */ list_for_each_entry(proc, siblings, siblings) { vmon_proc_callback_t *cb; + sample_threads_pass2(vmon, &proc->threads); /* recurse into any children of the threads, invoking callbacks as encountered from the leaves up */ sample_siblings_pass2(vmon, &proc->children); /* recurse into children, we invoke callbacks as encountered on nodes from the leaves up */ list_for_each_entry(cb, &proc->sample_callbacks, callbacks) @@ -1427,6 +1642,8 @@ int vmon_sample(vmon_t *vmon) { int i, wants, cur, ret = 1; + assert(vmon); + vmon->generation++; /* first manage the "all processes monitored" use case, this doesn't do any sampling, it just maintains the top-level list of processes being monitored */ @@ -1460,7 +1677,7 @@ int vmon_sample(vmon_t *vmon) if (!found) { /* monitor the process */ - vmon_proc_t *proc = vmon_proc_monitor(vmon, NULL, pid, vmon->proc_wants, NULL, NULL); + vmon_proc_t *proc = proc_monitor(vmon, NULL, pid, vmon->proc_wants, NULL, NULL); if (!proc) continue; /* TODO error */ @@ -1505,12 +1722,12 @@ int vmon_sample(vmon_t *vmon) /* then the per-process samplers */ if ((vmon->flags & VMON_FLAG_PROC_ARRAY)) { int j; - /* TODO: determine if this really makes sense, if we always maintain a heirarchy even in array mode, then we - * should probably always sample in the heirarchical order, or maybe make it caller-specified. - * There is a benefit to invoking the callbacks in heirarchical order, the callbacks can make assumptions about the children + /* TODO: determine if this really makes sense, if we always maintain a hierarchy even in array mode, then we + * should probably always sample in the hierarchical order, or maybe make it caller-specified. + * There is a benefit to invoking the callbacks in hierarchical order, the callbacks can make assumptions about the children * having the callbacks invoked prior to the current node, if done in depth-first order.... - * XXX this is a problem, figure out what to do with this, for now we don't even maintain the heirarchy in VMON_FLAG_PROC_ALL - * mode, only FOLLOW_CHILDREN mode, and it's likely PROC_ARRAY will generally be used together with PROC_ALL, so no heirarchy + * XXX this is a problem, figure out what to do with this, for now we don't even maintain the hierarchy in VMON_FLAG_PROC_ALL + * mode, only FOLLOW_CHILDREN mode, and it's likely PROC_ARRAY will generally be used together with PROC_ALL, so no hierarchy * is available to traverse even if we wanted to. */ @@ -1534,7 +1751,7 @@ int vmon_sample(vmon_t *vmon) } } } else if ((vmon->flags & VMON_FLAG_2PASS)) { - /* recursive heirarchical depth-first processes tree sampling, at each node threads come before children, done in two passes: + /* recursive hierarchical depth-first processes tree sampling, at each node threads come before children, done in two passes: * Pass 1. samplers * Pass 2. callbacks * XXX this is the path vwm utilizes, everything else is for other uses, like implementing top-like programs. @@ -1542,11 +1759,29 @@ int vmon_sample(vmon_t *vmon) ret = sample_siblings_pass1(vmon, &vmon->processes); /* XXX TODO: errors */ ret = sample_siblings_pass2(vmon, &vmon->processes); } else { - /* recursive heirarchical depth-first processes tree sampling, at each node threads come before children, done in a single pass: + /* recursive hierarchical depth-first processes tree sampling, at each node threads come before children, done in a single pass: * Pass 1. samplers; callbacks (for every node) */ - ret = sample_siblings(vmon, &vmon->processes); + ret = sample_siblings_unipass(vmon, &vmon->processes); } return ret; } + + +void vmon_dump_procs(vmon_t *vmon, FILE *out) +{ + assert(vmon); + assert(out); + + fprintf(out, "generation=%i\n", vmon->generation); + for (int i = 0; i < VMON_HTAB_SIZE; i++) { + vmon_proc_t *proc; + + list_for_each_entry(proc, &vmon->htab[i], bucket) { + fprintf(out, "[%i] proc=%p parent=%p gen=%i pid=%i rc=%i is_threaded=%i is_thread=%i is_new=%u is_stale=%u\n", + i, proc, proc->parent, proc->generation, proc->pid, proc->refcnt, (unsigned)proc->is_threaded, (unsigned)proc->is_thread, (unsigned)proc->is_new, (unsigned)proc->is_stale); + + } + } +} diff --git a/src/libvmon/vmon.h b/src/libvmon/vmon.h index cefcb43..4f17d12 100644 --- a/src/libvmon/vmon.h +++ b/src/libvmon/vmon.h @@ -4,12 +4,13 @@ #include <sys/types.h> #include <dirent.h> #include <stdint.h> +#include <stdio.h> /* just for vmon_dump_procs() */ #include <string.h> /* I use strcmp() in the type comparator definitions */ #include "bitmap.h" #include "list.h" -#define VMON_HTAB_SIZE 128 /* number of buckets in the processes hash table */ +#define VMON_HTAB_SIZE 1024 /* number of buckets in the processes hash table */ #define VMON_ARRAY_GROWBY 5 /* number of elements to grow the processes array */ typedef enum _vmon_flags_t { @@ -17,6 +18,9 @@ typedef enum _vmon_flags_t { VMON_FLAG_PROC_ARRAY = 1L, /* maintain a process array (useful if you need to do things like implement top(1) */ VMON_FLAG_PROC_ALL = 1L << 1, /* monitor all the processes in the system (XXX this has some follow_children implications...) */ VMON_FLAG_2PASS = 1L << 2, /* perform all sampling/wants in a first pass, then invoke all callbacks in second in vmon_sample(), important if your callbacks are layout-sensitive (vwm) */ + VMON_FLAG_NEGLECT_THREADS = 1L << 3, /* only actually sample processes, even if we're following threads + * (for situations where you still want to monitor children of threads, but don't care about per-thread monitoring) + */ } vmon_flags_t; /* store ids, used as indices into the stores array, and shift offsets for the wants mask */ @@ -49,14 +53,14 @@ typedef enum _vmon_proc_wants_t { /* we add some new complex types */ typedef struct _vmon_char_array_t { char *array; - int len; - int alloc_len; + size_t len; + size_t alloc_len; } vmon_char_array_t; typedef struct _vmon_str_array_t { char **array; - int len; - int alloc_len; + size_t len; + size_t alloc_len; } vmon_str_array_t; @@ -228,6 +232,7 @@ typedef struct _vmon_proc_t { list_head_t children; /* head of the children of this process, empty when no children */ list_head_t siblings; /* node in siblings list */ list_head_t threads; /* head or node for the threads list, empty when process has no threads */ + unsigned n_current_threads; /* count of non-stale nodes in the threads list */ struct _vmon_proc_t *parent; /* reference to the parent */ @@ -246,11 +251,12 @@ typedef struct _vmon_proc_t { list_head_t sample_callbacks; /* list of callbacks to invoke sample_cb on behalf of (and supply as parameteres to) */ void *foo; /* another per-process hook for whatever per-process uses the caller may have, but not managed by the api */ - int children_changed:1; /* gets set when any of my immediate children have had is_new or is_stale set in the last sample */ - int threads_changed:1; /* gets set when any of my threads have had is_new or is_stale set in the last sample */ - int is_new:1; /* process is new in the most recent sample, automatically cleared on subsequent sample */ - int is_stale:1; /* process became stale in the most recent sample, automatically cleared on subsequent sample (process will be discarded) */ - int is_thread:1; /* process is a thread belonging to parent */ + unsigned children_changed:1; /* gets set when any of my immediate children have had is_new or is_stale set in the last sample */ + unsigned threads_changed:1; /* gets set when any of my threads have had is_new or is_stale set in the last sample */ + unsigned is_new:1; /* process is new in the most recent sample, automatically cleared on subsequent sample */ + unsigned is_stale:1; /* process became stale in the most recent sample, automatically cleared on subsequent sample (process will be discarded) */ + unsigned is_thread:1; /* process is a thread belonging to parent */ + unsigned is_threaded:1; /* gets set when any of my immediate children are/have been threads */ } vmon_proc_t; @@ -265,9 +271,9 @@ typedef struct _vmon_t { int array_hint_free; /* hint for a free element in the list */ list_head_t htab[VMON_HTAB_SIZE]; /* hash table for quickly finding processes being monitored */ - list_head_t processes; /* top of the processes heirarchy */ + list_head_t processes; /* top of the processes hierarchy */ list_head_t orphans; /* ephemeral list of processes orphaned this sample, orphans wind up becoming top-level processes */ - int processes_changed:1; /* flag set when the toplevel processes list changes */ + unsigned processes_changed:1; /* flag set when the toplevel processes list changes */ list_head_t fobjects; /* XXX TODO: temporary single fobjects table, in the future this will be an array of type-indexed * fobject hash tables */ @@ -277,6 +283,7 @@ typedef struct _vmon_t { vmon_sys_wants_t sys_wants; /* system-wide wants mask */ vmon_proc_wants_t proc_wants; /* inherited per-process wants mask */ long ticks_per_sec; /* sysconf(_SC_CLK_TCK) */ + long num_cpus; /* sysconf(_SC_NPROCESSORS_ONLN) */ /* function tables for mapping of wants bits to functions (sys-wide and per-process) */ int (*sys_funcs[VMON_STORE_SYS_NR])(struct _vmon_t *, void **); @@ -303,8 +310,9 @@ typedef struct _vmon_t { int vmon_init(vmon_t *, vmon_flags_t, vmon_sys_wants_t, vmon_proc_wants_t); void vmon_destroy(vmon_t *); -vmon_proc_t * vmon_proc_monitor(vmon_t *, vmon_proc_t *, int, vmon_proc_wants_t, void (*)(vmon_t *, void *, vmon_proc_t *, void *), void *); +vmon_proc_t * vmon_proc_monitor(vmon_t *, int, vmon_proc_wants_t, void (*)(vmon_t *, void *, vmon_proc_t *, void *), void *); void vmon_proc_unmonitor(vmon_t *, vmon_proc_t *, void (*)(vmon_t *, void *, vmon_proc_t *, void *), void *); int vmon_sample(vmon_t *); +void vmon_dump_procs(vmon_t *vmon, FILE *out); #endif @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, diff --git a/src/screen.c b/src/screen.c index 4449fb5..ed8af7b 100644 --- a/src/screen.c +++ b/src/screen.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -97,6 +97,8 @@ const vwm_screen_t * vwm_screen_find(vwm_t *vwm, vwm_screen_rel_t rel, ...) break; } + case VWM_SCREEN_REL_XWIN_NEXT: + case VWM_SCREEN_REL_XWIN_PREV: case VWM_SCREEN_REL_XWIN: { va_list ap; vwm_xwindow_t *xwin; @@ -113,6 +115,22 @@ const vwm_screen_t * vwm_screen_find(vwm_t *vwm, vwm_screen_rel_t rel, ...) best_pct = this_pct; } } + + if (rel != VWM_SCREEN_REL_XWIN) { + unsigned idx = best - vwm->xinerama_screens; + + /* find the neighboring screen according to rel, note this isn't + * a spatial neighbor trying to consider RandR screen layout - it's + * simply next/prev in the list of screens in the order they appear + * there. + */ + if (rel == VWM_SCREEN_REL_XWIN_NEXT) + idx += 1; + else if (rel == VWM_SCREEN_REL_XWIN_PREV) + idx += vwm->xinerama_screens_cnt - 1; + + best = &vwm->xinerama_screens[idx % vwm->xinerama_screens_cnt]; + } break; } diff --git a/src/screen.h b/src/screen.h index ad8ddce..dafd191 100644 --- a/src/screen.h +++ b/src/screen.h @@ -6,13 +6,15 @@ typedef struct _vwm_t vwm_t; typedef struct _vwm_xwindow_t vwm_xwindow_t; -typedef XineramaScreenInfo vwm_screen_t; /* conveniently reuse the xinerama type for describing screens */ +typedef XineramaScreenInfo vwm_screen_t; /* conveniently reuse the xinerama type for describing screens */ typedef enum _vwm_screen_rel_t { - VWM_SCREEN_REL_RECT, /* return the screen the supplied rectangle x,y,w,h most resides in */ - VWM_SCREEN_REL_XWIN, /* return the screen the supplied window most resides in */ - VWM_SCREEN_REL_POINTER, /* return the screen the pointer resides in */ - VWM_SCREEN_REL_TOTAL, /* return the bounding rectangle of all screens as one */ + VWM_SCREEN_REL_RECT, /* return the screen the supplied rectangle x,y,w,h most resides in */ + VWM_SCREEN_REL_XWIN, /* return the screen the supplied window most resides in */ + VWM_SCREEN_REL_XWIN_NEXT, /* return the next screen from the one the supplied window most resides in */ + VWM_SCREEN_REL_XWIN_PREV, /* return the prev screen from the one the supplied window most resides in */ + VWM_SCREEN_REL_POINTER, /* return the screen the pointer resides in */ + VWM_SCREEN_REL_TOTAL, /* return the bounding rectangle of all screens as one */ } vwm_screen_rel_t; const vwm_screen_t * vwm_screen_find(vwm_t *vwm, vwm_screen_rel_t rel, ...); @@ -23,4 +23,7 @@ #define MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b)) #define NELEMS(_a) (sizeof(_a) / sizeof(_a[0])) +#define _STRINGIFY(_a) #_a +#define STRINGIFY(_a) _STRINGIFY(_a) + #endif diff --git a/src/vcr.c b/src/vcr.c new file mode 100644 index 0000000..20f726a --- /dev/null +++ b/src/vcr.c @@ -0,0 +1,2418 @@ +/* + * \/\/\ + * + * Copyright (C) 2024 Vito Caputo - <vcaputo@pengaru.com> + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 as published + * by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* vcr = vwm charts rendering (api) + * + * This exists to decouple the rendering needs of charts.c/vmon.c from Xlib for + * enabling headless use of vmon in embedded/server circumstances. + * + * Rather than exploring serverless Xlib implementations which render + * in-process, embracing something like cairo, or worse - creating a new + * generic rendering library, a very targeted approach has been taken here + * catering specifically to the requirements of charts.c. + * + * The intention is to enable higher density in-memory representation of the + * chart layers especially relevant to embedded situations. The existing Xlib + * Render based charts usage utilizes several full-color full-size Picture + * objects for the various layers used to compose the charts. + * + * The vcr api should implement layers/planes for a common underlying object as + * a first-class entity. When the vcr object is X-backed, those layers may be + * Pictures just like previously. But when the vcr object is headless, those + * layers are free to be represented in whatever packed format makes the most + * sense, without consideration for real-time rendering efficiency. + * + * Imagine for instance if headless vcr allocated a single byte array + * dimensioned by the chart's dimensions, to represent eight layers in the bit + * planes of the bytes. This exploits the fact that chart layers contain + * monochromatic coverage information for the pixel. Turning these layers into + * color renderings could use a simple palette lookup to produce the + * appropriate blended colors given the combination of bits set in the various + * layers. + * + * So every layer would have a color associated with it, used when compositing + * the rendered chart from the layers. But the actual layer maintenance would + * simply be setting/unsetting the appropriate bit in the affected pixel + * positions. + */ + +#define _GNU_SOURCE /* for ppoll() */ +#include <assert.h> +#include <math.h> +#include <poll.h> +#include <stdarg.h> +#include <stdint.h> +#include <stdlib.h> + +#ifdef USE_XLIB +#include <X11/Xlib.h> +#include <X11/extensions/Xfixes.h> +#include <X11/extensions/Xrender.h> +#include "xserver.h" +#endif /* USE_XLIB */ + +#ifdef USE_PNG +#include <png.h> +#endif /* USE_PNG */ + +#include "ascii.h" +#include "util.h" +#include "vcr.h" + +#define VCR_USECS_PER_SECOND 1000000 + +/* backend is the root vcr object everything else here derives from, + * for an X backend it encompasses the xserver/display connection. + */ +typedef struct vcr_backend_t { + vcr_backend_type_t type; + + union { +#ifdef USE_XLIB + struct { + vwm_xserver_t *xserver; + + unsigned xserver_created:1; + Atom wm_protocols_atom; + Atom wm_delete_atom; + + /* X stuff needed for doing all the vwm_charts_t things + * (these once resided in vwm_charts_t) + */ + XFontStruct *chart_font; + GC text_gc; + Picture shadow_fill, + text_fill, + bg_fill, + snowflakes_text_fill, + grapha_fill, + graphb_fill, + finish_fill; + } xlib; +#endif /* USE_XLIB */ + struct { + /* TODO */ + } mem; + }; +} vcr_backend_t; + + +/* vcr is the per-chart object you can present to a dest object, + * it is tightly bound to backend type and shares the vcr_backend_type_t. + * + * where the backend encompasses a bunch of backend-global state applicable to all + * charts like the GC / "fill" picture sources etc, this object encompasses the chart-specific + * state like graph layer/shadow/text pictures etc. + */ +typedef struct vcr_t { + vcr_backend_t *backend; + + int width; /* current width of the chart */ + int height; /* current height of the chart */ + int visible_width; /* currently visible width of the chart */ + int visible_height; /* currently visible height of the chart */ + int phase; /* current position within the (horizontally scrolling) graphs */ + + /* these pointers point into variables within the chart_t because they're primarily maintained by + * the chart renderer, but we need to access them occasionally here.. it's a bit gross. + */ + int *hierarchy_end_ptr; /* pointer to row where the process hierarchy currently ends */ + int *snowflakes_cnt_ptr; /* pointer to count of snowflaked rows (reset to zero to truncate snowflakes display) */ + const unsigned *marker_distance_ptr; /* pointer to marker distance to use (0 disables markers, this is kind of silly but I don't want to add setters everywhere so sharing the instance in vwm_charts_t) */ + + union { +#ifdef USE_XLIB + struct { + Pixmap text_pixmap; /* pixmap for charted text (kept around for XDrawText usage) */ + Picture text_picture; /* picture representation of text_pixmap */ + Picture shadow_picture; /* text shadow layer */ + Picture grapha_picture; /* graph A layer */ + Picture graphb_picture; /* graph B layer */ + Picture tmp_a_picture; /* 1 row worth of temporary graph A space */ + Picture tmp_b_picture; /* 1 row worth of temporary graph B space */ + Picture picture; /* chart picture derived from the pixmap, for render compositing */ + } xlib; +#endif /* USE_XLIB */ + struct { + uint8_t *bits; /* .pitch * height bytes are used to represent the coverage status of up to 4 layers (was 8 until nibbles happened) */ + uint8_t *tmp; /* .pitch * VCR_ROW_HEIGHT bytes for a row's worth of temporary storage */ + int pitch; /* "pitch" of mem surface in bytes, which is half the width rounded up to an even number divisible by two. */ + } mem; + }; +} vcr_t; + + +/* dest represents an output destination for rendering/compositing vcr instances at. + * for an vmon-on-X scenario, it encompasses the viewable X Window + Picture of of vmon. + * for an headless vmon-to-PNGs scenario, it encompasses the PNG writer. + * for an vwm-on-X scenario, it encompasses the Picture associated with a vwm_window_t. + * + * it should also be possible to do things like render a vcr instance created from an xlib backend + * to something like a PNG dest. + */ +typedef enum vcr_dest_type_t { +#ifdef USE_XLIB + VCR_DEST_TYPE_XWINDOW, + VCR_DEST_TYPE_XPICTURE, +#endif /* USE_XLIB */ + VCR_DEST_TYPE_PNG +} vcr_dest_type_t; + + +typedef struct vcr_dest_t { + vcr_backend_t *backend; + vcr_dest_type_t type; + + union { +#ifdef USE_XLIB + struct { + /* vmon use case; xwindow dest maps to vmon's X window, no compositing */ + Window window; + Picture picture; + } xwindow; + + struct { + /* vwm use case; xpicture dest maps to composited X root window */ + Picture picture; + } xpicture; +#endif /* USE_XLIB */ +#ifdef USE_PNG + struct { + /* vmon use case; png dest is for persisting snapshots of the vcr state */ + /* this could actually apply to vwm too which would be useful for hot-key based + * snapshotting of a focused window's monitoring overlays. + */ + png_infop info_ctx; + png_structp png_ctx; + FILE *output; + } png; +#endif /* USE_PNG */ + }; +} vcr_dest_t; + + +#ifdef USE_XLIB +#define CHART_GRAPH_MIN_WIDTH 200 /* always create graphs at least this large */ +#define CHART_GRAPH_MIN_HEIGHT (4 * VCR_ROW_HEIGHT) +#define CHART_MASK_DEPTH 8 /* XXX: 1 would save memory, but Xorg isn't good at it */ +#define CHART_FIXED_FONT "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1" + +static XRenderColor chart_visible_color = { 0xffff, 0xffff, 0xffff, 0xffff }, + chart_shadow_color = { 0x0000, 0x0000, 0x0000, 0xC000}, + chart_bg_color = { 0x0, 0x1000, 0x0, 0x9000}, + chart_div_color = { 0x2000, 0x3000, 0x2000, 0x9000}, + chart_snowflakes_visible_color = { 0xd000, 0xd000, 0xd000, 0x8000 }, + chart_trans_color = {0x00, 0x00, 0x00, 0x00}, + chart_grapha_color = { 0xff00, 0x0000, 0x0000, 0x3000 }, /* ~red */ + chart_graphb_color = { 0x0000, 0xffff, 0xffff, 0x3000 }; /* ~cyan */ + +static XRenderPictureAttributes pa_repeat = { .repeat = 1 }; +static XRenderPictureAttributes pa_no_repeat = { .repeat = 0 }; + + +/* convenience helper for creating a pixmap */ +static Pixmap create_pixmap(vwm_xserver_t *xserver, unsigned width, unsigned height, unsigned depth) +{ + assert(xserver); + + return XCreatePixmap(xserver->display, XSERVER_XROOT(xserver), width, height, depth); +} + + +/* convenience helper for creating a picture, supply res_pixmap to keep a reference to the pixmap drawable. */ +static Picture create_picture(vwm_xserver_t *xserver, unsigned width, unsigned height, unsigned depth, unsigned long attr_mask, XRenderPictureAttributes *attr, Pixmap *res_pixmap) +{ + Pixmap pixmap; + Picture picture; + int format; + + assert(xserver); + + /* FIXME this pixmap->picture dance seems silly, investigate further. TODO */ + switch (depth) { + case 8: + format = PictStandardA8; + break; + case 32: + format = PictStandardARGB32; + break; + default: + assert(0); + } + + pixmap = create_pixmap(xserver, width, height, depth); + picture = XRenderCreatePicture(xserver->display, pixmap, XRenderFindStandardFormat(xserver->display, format), attr_mask, attr); + + if (res_pixmap) { + *res_pixmap = pixmap; + } else { + XFreePixmap(xserver->display, pixmap); + } + + return picture; +} + + +/* convenience helper for creating a filled picture, supply res_pixmap to keep a reference to the pixmap drawable. */ +static Picture create_picture_fill(vwm_xserver_t *xserver, unsigned width, unsigned height, unsigned depth, unsigned long attrs_mask, XRenderPictureAttributes *attrs, const XRenderColor *color, Pixmap *res_pixmap) +{ + Picture picture; + + assert(xserver); + + picture = create_picture(xserver, width, height, depth, attrs_mask, attrs, res_pixmap); + XRenderFillRectangle(xserver->display, PictOpSrc, picture, color, 0, 0, width, height); + + return picture; +} + + +/* returns NULL on failure, freeing vcr + * returns vcr on success, fully setup for the given backend. + */ +static vcr_backend_t * vcr_backend_xlib_setup(vcr_backend_t *vbe, vwm_xserver_t *xserver) +{ + Pixmap bitmask; + + assert(vbe); + + vbe->type = VCR_BACKEND_TYPE_XLIB; + + if (!xserver) { + /* we'll connect to the xserver if none is provided */ + xserver = vwm_xserver_open(); + if (!xserver) { + VWM_ERROR("unable to open xserver"); + goto err_vbe; + } + vbe->xlib.xserver_created = 1; + } + vbe->xlib.xserver = xserver; + + /* this is really only needed for the xwindow-dest/vmon scenario (where we create the xserver), + * but let's just always grab the atoms anyways + */ + vbe->xlib.wm_delete_atom = XInternAtom(xserver->display, "WM_DELETE_WINDOW", False); + vbe->xlib.wm_protocols_atom = XInternAtom(xserver->display, "WM_PROTOCOLS", False); + + /* get all the text and graphics stuff setup for charts, + * this all used to be part of vwm_charts_create(), but + * moved here as charts.c/vmon.c became X-decoupled and + * relied on vcr.c to abstract the X/mem/png specifics + * on the road to headless vmon support. + */ + vbe->xlib.chart_font = XLoadQueryFont(xserver->display, CHART_FIXED_FONT); + if (!vbe->xlib.chart_font) { + VWM_ERROR("unable to load chart font \"%s\"", CHART_FIXED_FONT); + goto err_vbe; + } + + /* FIXME: error handling for all this junk */ + /* create a GC for rendering the text using Xlib into the text chart stencils */ + bitmask = create_pixmap(xserver, 1, 1, CHART_MASK_DEPTH); + vbe->xlib.text_gc = XCreateGC(xserver->display, bitmask, 0, NULL); + XSetForeground(xserver->display, vbe->xlib.text_gc, WhitePixel(xserver->display, xserver->screen_num)); + XFreePixmap(xserver->display, bitmask); + + /* create some repeating source fill pictures for drawing through the text and graph stencils */ + vbe->xlib.text_fill = create_picture_fill(xserver, 1, 1, 32, CPRepeat, &pa_repeat, &chart_visible_color, NULL); + vbe->xlib.shadow_fill = create_picture_fill(xserver, 1, 1, 32, CPRepeat, &pa_repeat, &chart_shadow_color, NULL); + + vbe->xlib.bg_fill = create_picture(xserver, 1, VCR_ROW_HEIGHT, 32, CPRepeat, &pa_repeat, NULL); + XRenderFillRectangle(xserver->display, PictOpSrc, vbe->xlib.bg_fill, &chart_bg_color, 0, 0, 1, VCR_ROW_HEIGHT); + XRenderFillRectangle(xserver->display, PictOpSrc, vbe->xlib.bg_fill, &chart_div_color, 0, VCR_ROW_HEIGHT - 1, 1, 1); + + vbe->xlib.snowflakes_text_fill = create_picture_fill(xserver, 1, 1, 32, CPRepeat, &pa_repeat, &chart_snowflakes_visible_color, NULL); + vbe->xlib.grapha_fill = create_picture_fill(xserver, 1, 1, 32, CPRepeat, &pa_repeat, &chart_grapha_color, NULL); + vbe->xlib.graphb_fill = create_picture_fill(xserver, 1, 1, 32, CPRepeat, &pa_repeat, &chart_graphb_color, NULL); + + vbe->xlib.finish_fill = create_picture(xserver, 1, 2, 32, CPRepeat, &pa_repeat, NULL); + XRenderFillRectangle(xserver->display, PictOpSrc, vbe->xlib.finish_fill, &chart_visible_color, 0, 0, 1, 1); + XRenderFillRectangle(xserver->display, PictOpSrc, vbe->xlib.finish_fill, &chart_trans_color, 0, 1, 1, 1); + + return vbe; + +err_vbe: + if (vbe->xlib.xserver_created) + vwm_xserver_close(vbe->xlib.xserver); + + free(vbe); + + return NULL; +} +#endif /* USE_XLIB */ + + +vcr_backend_t * vcr_backend_new(vcr_backend_type_t backend, ...) +{ + vcr_backend_t *vbe; + va_list ap; + + vbe = calloc(1, sizeof(vcr_backend_t)); + if (!vbe) + return NULL; + + va_start(ap, backend); + switch (backend) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: + vbe = vcr_backend_xlib_setup(vbe, va_arg(ap, vwm_xserver_t *)); + break; +#endif /* USE_XLIB */ + case VCR_BACKEND_TYPE_MEM: + vbe->type = VCR_BACKEND_TYPE_MEM; + break; + default: + assert(0); + } + va_end(ap); + + return vbe; +} + + +/* returns the native dimensions of the backend, really only applies to xlib currently for fullscreen dims */ +int vcr_backend_get_dimensions(vcr_backend_t *vbe, int *res_width, int *res_height) +{ + assert(vbe); + assert(res_width); + assert(res_height); + + switch (vbe->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + XWindowAttributes wattr; + + if (!XGetWindowAttributes(vbe->xlib.xserver->display, XSERVER_XROOT(vbe->xlib.xserver), &wattr)) { + return -ENOENT; + } + + *res_width = wattr.width; + *res_height = wattr.height; + + return 0; + } +#endif + + case VCR_BACKEND_TYPE_MEM: + return -ENOTSUP; + + default: + assert(0); + } +} + + +/* this is basically just needed by the vmon use case */ +/* returns 1 if the backend has events to process, 0 on timeout, -1 on error. */ +int vcr_backend_poll(vcr_backend_t *vbe, int timeout_us) +{ + struct timespec ts, *pto = NULL; + + assert(vbe); + + /* TODO: keep signals blocked outside of ppoll() */ + + if (timeout_us >= 0) { + ts.tv_sec = timeout_us / VCR_USECS_PER_SECOND; + ts.tv_nsec = (timeout_us - (ts.tv_sec * VCR_USECS_PER_SECOND)) * 1000; + pto = &ts; + } + + switch (vbe->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + struct pollfd pfd = { + .events = POLLIN, + .fd = ConnectionNumber(vbe->xlib.xserver->display), + }; + + if (XPending(vbe->xlib.xserver->display)) + return 1; + + return ppoll(&pfd, 1, pto, NULL); + } +#endif + case VCR_BACKEND_TYPE_MEM: + return ppoll(NULL, 0, pto, NULL); + + default: + assert(0); + } +} + + +/* this is basically just needed by the vmon use case, called after + * vcr_backend_poll() returns 1. + * if VCR_BACKEND_EVENT_RESIZE is returned, res_width and res_height will be updated. + */ +vcr_backend_event_t vcr_backend_next_event(vcr_backend_t *vbe, int *res_width, int *res_height) +{ + assert(vbe); + assert(res_width); + assert(res_height); + + switch (vbe->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + XEvent ev; + + XNextEvent(vbe->xlib.xserver->display, &ev); + + switch (ev.type) { + case ConfigureNotify: + *res_width = ev.xconfigure.width; + *res_height = ev.xconfigure.height; + return VCR_BACKEND_EVENT_RESIZE; + + case Expose: + return VCR_BACKEND_EVENT_REDRAW; + + case ClientMessage: + if (ev.xclient.message_type != vbe->xlib.wm_protocols_atom) + break; + + if (ev.xclient.data.l[0] != vbe->xlib.wm_delete_atom) + break; + + return VCR_BACKEND_EVENT_QUIT; + } + break; + } +#endif + + case VCR_BACKEND_TYPE_MEM: + break; + + default: + assert(0); + } + + return VCR_BACKEND_EVENT_NOOP; +} + + +vcr_backend_t * vcr_backend_free(vcr_backend_t *vbe) +{ + if (vbe) { + switch (vbe->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: + XRenderFreePicture(vbe->xlib.xserver->display, vbe->xlib.shadow_fill); + XRenderFreePicture(vbe->xlib.xserver->display, vbe->xlib.text_fill); + XRenderFreePicture(vbe->xlib.xserver->display, vbe->xlib.bg_fill); + XRenderFreePicture(vbe->xlib.xserver->display, vbe->xlib.snowflakes_text_fill); + XRenderFreePicture(vbe->xlib.xserver->display, vbe->xlib.grapha_fill); + XRenderFreePicture(vbe->xlib.xserver->display, vbe->xlib.graphb_fill); + XRenderFreePicture(vbe->xlib.xserver->display, vbe->xlib.finish_fill); + XFreeFont(vbe->xlib.xserver->display, vbe->xlib.chart_font); + XFreeGC(vbe->xlib.xserver->display, vbe->xlib.text_gc); + + if (vbe->xlib.xserver_created) + vwm_xserver_close(vbe->xlib.xserver); + break; +#endif /* USE_XLIB */ + case VCR_BACKEND_TYPE_MEM: + break; + + default: + assert(0); + } + + free(vbe); + } + + return NULL; +} + + +#ifdef USE_XLIB +/* for the vmon use case, we need a window destination created */ +vcr_dest_t * vcr_dest_xwindow_new(vcr_backend_t *vbe, const char *name, unsigned width, unsigned height) +{ + XWindowAttributes wattr = {}; + XRenderPictureAttributes pattr = {}; + vwm_xserver_t *xserver; + vcr_dest_t *dest; + + assert(vbe); + assert(vbe->type == VCR_BACKEND_TYPE_XLIB); + assert(width > 0); + assert(height > 0); + + xserver = vbe->xlib.xserver; + + dest = calloc(1, sizeof(vcr_dest_t)); + if (!dest) + return NULL; + + dest->type = VCR_DEST_TYPE_XWINDOW; + dest->backend = vbe; + + dest->xwindow.window = XCreateSimpleWindow(xserver->display, XSERVER_XROOT(xserver), 0, 0, width, height, 1, 0, 0); + if (name) + XStoreName(xserver->display, dest->xwindow.window, name); + XGetWindowAttributes(xserver->display, dest->xwindow.window, &wattr); + dest->xwindow.picture = XRenderCreatePicture(xserver->display, dest->xwindow.window, XRenderFindVisualFormat(xserver->display, wattr.visual), 0, &pattr); + XMapWindow(xserver->display, dest->xwindow.window); + XSelectInput(xserver->display, dest->xwindow.window, StructureNotifyMask|ExposureMask); + XSync(xserver->display, False); + + return dest; +} + + +/* accessor to get the Window id out of the dest */ +unsigned vcr_dest_xwindow_get_id(vcr_dest_t *dest) +{ + assert(dest); + assert(dest->type == VCR_DEST_TYPE_XWINDOW); + + return dest->xwindow.window; +} + + +vcr_dest_t * vcr_dest_xpicture_new(vcr_backend_t *vbe, Picture picture) +{ + vcr_dest_t *dest; + + assert(vbe); + assert(vbe->type == VCR_BACKEND_TYPE_XLIB); + assert(picture != None); + + dest = calloc(1, sizeof(vcr_dest_t)); + if (!dest) + return NULL; + + dest->type = VCR_DEST_TYPE_XPICTURE; + dest->backend = vbe; + dest->xpicture.picture = picture; + + return dest; +} +#endif /* USE_XLIB */ + + +#ifdef USE_PNG +vcr_dest_t * vcr_dest_png_new(vcr_backend_t *vbe, FILE *output) +{ + vcr_dest_t *dest; + + assert(vbe); + assert(output != NULL); + + /* for png dest we just have to make sure vbe->type is one + * we can handle presenting from... the png dest doesn't + * actually have to derive any resources from the backend, + * unlike the xwindow dest which actually has to create a + * window etc. + */ + + dest = calloc(1, sizeof(vcr_dest_t)); + if (!dest) + return NULL; + + dest->type = VCR_DEST_TYPE_PNG; + dest->png.output = output; + + dest->png.png_ctx = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (!dest->png.png_ctx) { + free(dest); + return NULL; + } + + dest->png.info_ctx = png_create_info_struct(dest->png.png_ctx); + if (!dest->png.info_ctx) { + png_destroy_write_struct(&dest->png.png_ctx, NULL); + free(dest); + return NULL; + } + + png_init_io(dest->png.png_ctx, output); + + return dest; +} +#endif /* USE_PNG */ + + +vcr_dest_t * vcr_dest_free(vcr_dest_t *dest) +{ + if (dest) { + switch (dest->type) { +#ifdef USE_XLIB + case VCR_DEST_TYPE_XWINDOW: + XDestroyWindow(dest->backend->xlib.xserver->display, dest->xwindow.window); + XRenderFreePicture(dest->backend->xlib.xserver->display, dest->xwindow.picture); + break; + case VCR_DEST_TYPE_XPICTURE: + XRenderFreePicture(dest->backend->xlib.xserver->display, dest->xpicture.picture); + break; +#endif /* USE_XLIB */ +#ifdef USE_PNG + case VCR_DEST_TYPE_PNG: + /* XXX: we don't take ownership of the FILE* @ dest->png.output, but + * that could change. The thinking being the caller provided the + * FILE* pre-opened, and it could very well be something like stdout, + * which we might not want to close immediately after writing the png + * to it. But maybe it'd be better to just take ownership of it. + */ + png_destroy_write_struct(&dest->png.png_ctx, &dest->png.info_ctx); + break; +#endif /* USE_PNG */ + default: + assert(0); + } + + free(dest); + } + + return NULL; +} + + +/* vcr is the workhorse of doing the actual chart compositing/rendering using a given backend. + * + * The vcr object encapsulates a chart instance and the state of all its layers, in whatever form + * is appropriate for the backend it's derived from. + * + * In the xlib backend case, that closely resembles what the OG charts.c X-coupled implementation + * did, just shoved behind the vcr api. This results in efficient vcr_present() to X dests for + * real-time usage. + * + * In the mem backend case, X types are not used at all, and an ad-hoc packed byte array is used to + * represent the various chart layers as bit planes in the interests of saving memory. This makes for + * slower manipulation and compositing, and a slower present, but is intended for more embedded headless + * uses where the priority is more lower frequency (1HZ) and more history (larger dimensions) with periodic + * PNG presents on the order of minutes/hours for cloud uploading to facilitate investigations. + */ +vcr_t * vcr_new(vcr_backend_t *vbe, int *hierarchy_end_ptr, int *snowflakes_cnt_ptr, const unsigned *marker_distance_ptr) +{ + vcr_t *vcr; + + assert(vbe); + assert(hierarchy_end_ptr); + assert(snowflakes_cnt_ptr); + + vcr = calloc(1, sizeof(vcr_t)); + if (!vcr) + return NULL; + + vcr->backend = vbe; + vcr->hierarchy_end_ptr = hierarchy_end_ptr; + vcr->snowflakes_cnt_ptr = snowflakes_cnt_ptr; + vcr->marker_distance_ptr = marker_distance_ptr; + + return vcr; +} + + +#ifdef USE_XLIB +/* helper for _only_ freeing the xlib internal stuff embedded within the vcr, + * split out because resizes need to throw this stuff away after copying to the + * newly allocated instances. + */ +static void vcr_free_xlib_internal(vcr_t *vcr) +{ + vwm_xserver_t *xserver; + + assert(vcr); + assert(vcr->backend); + assert(vcr->backend->type == VCR_BACKEND_TYPE_XLIB); + + xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + XRenderFreePicture(xserver->display, vcr->xlib.grapha_picture); + XRenderFreePicture(xserver->display, vcr->xlib.graphb_picture); + XRenderFreePicture(xserver->display, vcr->xlib.tmp_a_picture); + XRenderFreePicture(xserver->display, vcr->xlib.tmp_b_picture); + XRenderFreePicture(xserver->display, vcr->xlib.text_picture); + XFreePixmap(xserver->display, vcr->xlib.text_pixmap); + XRenderFreePicture(xserver->display, vcr->xlib.shadow_picture); + XRenderFreePicture(xserver->display, vcr->xlib.picture); +} + + +/* helper for _only_ copying the xlib internal stuff embedded in the vcr, + * for resizing purposes. + */ +static void vcr_copy_xlib_internal(vcr_t *src, vcr_t *dest) +{ + vwm_xserver_t *xserver; + + assert(src); + assert(src->backend); + assert(src->backend->type == VCR_BACKEND_TYPE_XLIB); + assert(dest); + assert(dest->backend); + assert(dest->backend->type == VCR_BACKEND_TYPE_XLIB); + assert(src->backend->xlib.xserver == dest->backend->xlib.xserver); + + xserver = src->backend->xlib.xserver; + + /* XXX: note the graph pictures are copied from their current phase in the x dimension */ + XRenderComposite(xserver->display, PictOpSrc, src->xlib.grapha_picture, None, dest->xlib.grapha_picture, + src->phase, 0, /* src x, y */ + 0, 0, /* mask x, y */ + dest->phase, 0, /* dest x, y */ + src->width, src->height); + XRenderComposite(xserver->display, PictOpSrc, src->xlib.graphb_picture, None, dest->xlib.graphb_picture, + src->phase, 0, /* src x, y */ + 0, 0, /* mask x, y */ + dest->phase, 0, /* dest x, y */ + src->width, src->height); + XRenderComposite(xserver->display, PictOpSrc, src->xlib.text_picture, None, dest->xlib.text_picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + src->width, src->height); + XRenderComposite(xserver->display, PictOpSrc, src->xlib.shadow_picture, None, dest->xlib.shadow_picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + src->width, src->height); + XRenderComposite(xserver->display, PictOpSrc, src->xlib.picture, None, dest->xlib.picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + src->width, src->height); +} +#endif /* USE_XLIB */ + + +vcr_t * vcr_free(vcr_t *vcr) +{ + if (vcr) { + assert(vcr->backend); + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: + vcr_free_xlib_internal(vcr); + break; +#endif /* USE_XLIB */ + case VCR_BACKEND_TYPE_MEM: + free(vcr->mem.bits); + free(vcr->mem.tmp); + break; + + default: + assert(0); + } + + free(vcr); + } + + return NULL; +} + + +/* resize the specified vcr's visible dimensions, which may or may not require actual + * resizing of the underlying backend resources. + * + * -errno is returned on failure (will generally be -ENOMEM), 0 returned on success with no redraw needed, + * 1 returned on success with redraw needed. + */ +int vcr_resize_visible(vcr_t *vcr, int width, int height) +{ + assert(vcr); + assert(vcr->backend); + assert(width > 0); + assert(height > 0); + + /* nothing to do */ + if (width == vcr->visible_width && height == vcr->visible_height) + return 0; /* no redraw needed */ + + if (width <= vcr->width && height <= vcr->height) { + /* we've stayed within the current allocation, no need to involve the backend */ + vcr->visible_width = width; + vcr->visible_height = height; + /* you may be wondering how this can happen - when windows get resized smaller, we don't + * shrink the resources backing the vcr... they only grow. The shrinking just affects + * the visible_{height,width} dimensions, it doesn't resize the backend smaller. So + * when/if they grow again in visibility, it's just a matter of adjusting the visible + * dimensions, unless they exceed the maximum dimensions... which requires allocation. + */ + + return 1; /* redraw needed */ + } + + /* we're going outside the current allocation dimensions, so we need to involve the backend + * in _really_ resizing. + */ + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + vcr_t existing = *vcr; /* stow the current vcr's contents for copy+free */ + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + vcr->width = MAX(vcr->width, MAX(width, CHART_GRAPH_MIN_WIDTH)); + vcr->height = MAX(vcr->height, MAX(height, CHART_GRAPH_MIN_HEIGHT)); + + /* XXX: note this is actually _the_ place these things get allocated */ + vcr->xlib.grapha_picture = create_picture_fill(xserver, vcr->width, vcr->height, CHART_MASK_DEPTH, CPRepeat, &pa_repeat, &chart_trans_color, NULL); + vcr->xlib.graphb_picture = create_picture_fill(xserver, vcr->width, vcr->height, CHART_MASK_DEPTH, CPRepeat, &pa_repeat, &chart_trans_color, NULL); + vcr->xlib.tmp_a_picture = create_picture(xserver, vcr->width, VCR_ROW_HEIGHT, CHART_MASK_DEPTH, 0, NULL, NULL); + vcr->xlib.tmp_b_picture = create_picture(xserver, vcr->width, VCR_ROW_HEIGHT, CHART_MASK_DEPTH, 0, NULL, NULL); + + /* keep the text_pixmap reference around for XDrawText usage */ + vcr->xlib.text_picture = create_picture_fill(xserver, vcr->width, vcr->height, CHART_MASK_DEPTH, 0, NULL, &chart_trans_color, &vcr->xlib.text_pixmap); + + vcr->xlib.shadow_picture = create_picture_fill(xserver, vcr->width, vcr->height, CHART_MASK_DEPTH, 0, NULL, &chart_trans_color, NULL); + vcr->xlib.picture = create_picture(xserver, vcr->width, vcr->height, 32, 0, NULL, NULL); + + if (existing.width) { + vcr_copy_xlib_internal(&existing, vcr); + vcr_free_xlib_internal(&existing); + } + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + int pitch = (width + 1) >> 1; + + /* no attempt to preserve the existing contents is done for the mem backend, + * as it's intended for a non-interactive headless use case - there is no + * resizing @ runtime. We get entered once to create the initial dimensions, + * then never recurs. + */ + assert(!vcr->mem.bits); /* since we're assuming this doesn't recur, assert it */ + vcr->mem.bits = calloc(pitch * height, sizeof(uint8_t)); + if (!vcr->mem.bits) + return -ENOMEM; + + assert(!vcr->mem.tmp); /* since we're assuming this doesn't recur, assert it */ + vcr->mem.tmp = calloc(pitch * VCR_ROW_HEIGHT, sizeof(uint8_t)); + if (!vcr->mem.tmp) { + free(vcr->mem.bits); + return -ENOMEM; + } + + vcr->mem.pitch = pitch; + vcr->width = width; + vcr->height = height; + + break; + } + + default: + assert(0); + } + + vcr->visible_width = width; + vcr->visible_height = height; + + assert(vcr->width >= vcr->visible_width); + assert(vcr->height >= vcr->visible_height); + + return 0; +} + + +/* this is inspired by XDrawText and its XTextItem *items + nr_items API, + * primarily so it's easy to map the incoming call to an XDrawText call... + * but for non-xlib backends, an XDrawText equivalent will be needed. + * + * note the formatting and font-switching aspects of XTextItem have not + * been exposed here... this just takes an array of char* strings and + * turns it into an XTextItem array etc. + * + * this draws to the specified vcr layer. + * + * supply a res_width to get the rendered text width in pixels + * + * supply a negative row to suppress the actual drawing, but still get the would-be res_width + * + * x may be negative or extend outside vcr bounds, clipping will be performed as needed. + */ + /* XXX: maybe these strs should also include lengths instead of being null-terminated */ +void vcr_draw_text(vcr_t *vcr, vcr_layer_t layer, int x, int row, const vcr_str_t *strs, int n_strs, int *res_width) +{ + assert(vcr); + assert(vcr->backend); + assert(layer >= 0 && layer < VCR_LAYER_CNT); + assert(row >= 0 || res_width); + assert(strs); + assert(n_strs > 0); + /* FIXME: this should really be able to draw text into any valid layer, + * it's just the pictures/pixmaps in vcr_t aren't currently organized as an + * array easily indexed by the layer enum. TODO + */ + assert(layer == VCR_LAYER_TEXT); + + if (n_strs > VCR_DRAW_TEXT_N_STRS_MAX) + n_strs = VCR_DRAW_TEXT_N_STRS_MAX; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + XTextItem items[VCR_DRAW_TEXT_N_STRS_MAX]; + + for (int i = 0; i < n_strs; i++) { + items[i].nchars = strs[i].len; + items[i].chars = (char *)strs[i].str; + items[i].delta = 4; + items[i].font = None; + } + + if (row >= 0) { + XDrawText(vcr->backend->xlib.xserver->display, vcr->xlib.text_pixmap, vcr->backend->xlib.text_gc, + x, (row + 1) * VCR_ROW_HEIGHT - 3, /* dst x, y */ + items, n_strs); + } + + /* if the caller wants to know the width, compute it, it's dumb that XDrawText doesn't + * return the dimensions of what was drawn, fucking xlib. + */ + if (res_width) { + int width = 0; + + for (int i = 0; i < n_strs; i++) + width += XTextWidth(vcr->backend->xlib.chart_font, items[i].chars, items[i].nchars) + items[i].delta; + + *res_width = width; + } + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + if (row >= 0 && (row + 1) * VCR_ROW_HEIGHT < vcr->height) { + int y = row * VCR_ROW_HEIGHT + 3; + uint8_t mask = (0x1 << layer); + + for (int i = 0; i < n_strs && x < vcr->width; i++) { + unsigned char c; + + x += 4; /* match the delta used w/XDrawText */ + + for (int j = 0, n = 0; j < strs[i].len; j++) { + c = strs[i].str[j]; + + /* skip weird/non-printable chars */ + if (c < ' ' || c > '~') + continue; + + if (n > 0) + x += 1; + + if (x + ASCII_WIDTH >= vcr->width) { + x = vcr->width; + break; + } + + for (int k = 0; k < ASCII_HEIGHT; k++) { + for (int l = 0; l < ASCII_WIDTH; l++) { + int x_l = x + l; + uint8_t *p = &vcr->mem.bits[(y + k) * vcr->mem.pitch + (x_l >> 1)]; + + /* FIXME this can all be done more efficiently */ + if (x_l < 0) + continue; + + *p = (*p & ~(mask << ((x_l & 0x1) << 2))) | ((mask * ascii_chars[c][k * ASCII_WIDTH + l]) << ((x_l & 0x1) << 2)); + } + } + + x += ASCII_WIDTH; + n++; + } + } + } + + if (res_width) { + int w = 0; + /* assume fixed 5x11 ascii glyphs */ + for (int i = 0; i < n_strs; i++) { + w += 4; /* match the delta used w/XDrawText */ + + w += strs[i].len * (ASCII_WIDTH + 1); + } + *res_width = w; + } + break; + } + + default: + assert(0); + } +} + + +/* draw an arbitrary orthonormal line into the given layer, on the xlib backend this only works + * on the VCR_LAYER_TEXT layer, so it's just asserted to only go there for now.. which + * is fine for the existing callers. + */ +/* TODO: this could have a horiz/vert flag then an offset and length, but since + * the original code was using XDrawLine directly the call sites already had + * x1,y1,x2,y2 paramaters onhand.. but we really only draw orthonormal lines, + * which enforcing simplifies ad-hoc rendering for TYPE_MEM. + */ +void vcr_draw_ortho_line(vcr_t *vcr, vcr_layer_t layer, int x1, int y1, int x2, int y2) +{ + assert(vcr); + assert(vcr->backend); + assert(layer == VCR_LAYER_TEXT); /* this is just because only the text layer has the pixmap still */ + + assert(x1 >= 0 && y1 >= 0 && x2 >= 0 && y2 >= 0); + assert(x1 == x2 || y1 == y2); /* expected always orthonormal */ + + if (x1 >= vcr->width) + x1 = vcr->width - 1; + if (x2 >= vcr->width) + x2 = vcr->width - 1; + if (y1 >= vcr->height) + y1 = vcr->height - 1; + if (y2 >= vcr->height) + y2 = vcr->height - 1; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + XDrawLine(vcr->backend->xlib.xserver->display, vcr->xlib.text_pixmap, vcr->backend->xlib.text_gc, + x1, y1, x2, y2); + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + if (x1 == x2) { + unsigned which = (x1 & 0x1) << 2; + + if (y1 > y2) { + int t = y1; + + y1 = y2; + y2 = t; + } + + /* vertical */ + for (uint8_t *p = &vcr->mem.bits[y1 * vcr->mem.pitch + (x1 >> 1)]; y1 <= y2; p += vcr->mem.pitch, y1++) + *p |= (0x1 << layer) << which; + + } else { + /* horizontal */ + + if (x1 > x2) { + int t = x1; + + x1 = x2; + x2 = t; + } + + for (; x1 <= x2; x1++) { + uint8_t *p = &vcr->mem.bits[y1 * vcr->mem.pitch + (x1 >> 1)]; + unsigned which = (x1 & 0x1) << 2; + + *p |= (0x1 << layer) << which; + } + } + + break; + } + + default: + assert(0); + } + + +} + + +/* marks a "finish line" in layer for row @ current phase */ +void vcr_mark_finish_line(vcr_t *vcr, vcr_layer_t layer, int row) +{ + assert(vcr); + assert(vcr->backend); + assert(row >= 0); + /* FIXME: the layers in backend/vcr etc should be in a layer-indexable array */ + assert(layer == VCR_LAYER_GRAPHA || layer == VCR_LAYER_GRAPHB); + + if ((row + 1) * VCR_ROW_HEIGHT >= vcr->height) + return; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + Picture dest; + + switch (layer) { + case VCR_LAYER_GRAPHA: + dest = vcr->xlib.grapha_picture; + break; + case VCR_LAYER_GRAPHB: + dest = vcr->xlib.graphb_picture; + break; + default: + assert(0); + } + + assert(xserver); + + XRenderComposite(xserver->display, PictOpSrc, vcr->backend->xlib.finish_fill, None, dest, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + vcr->phase, row * VCR_ROW_HEIGHT, /* dst x, y */ + 1, VCR_ROW_HEIGHT - 1); + + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t mask = (0x1 << layer) << ((vcr->phase & 0x1) << 2); + uint8_t *p; + + p = &vcr->mem.bits[row * VCR_ROW_HEIGHT * vcr->mem.pitch + (vcr->phase >> 1)]; + for (int i = 0; i < VCR_ROW_HEIGHT; i++, p += vcr->mem.pitch) + *p = ((*p & ~mask) | (mask * (i & 0x1))); + + break; + } + + default: + assert(0); + } +} + + +/* draw a bar at the current phase into the specified layer of t % with a minimum of min_height pixels. + * + * the only layers supported right now are grapha/graphb + */ +void vcr_draw_bar(vcr_t *vcr, vcr_layer_t layer, int row, float t, int min_height) +{ + int height, y = row * VCR_ROW_HEIGHT; + + assert(vcr); + assert(vcr->backend); + assert(row >= 0); + assert(layer == VCR_LAYER_GRAPHA || layer == VCR_LAYER_GRAPHB); + assert(min_height >= 0 && min_height < (VCR_ROW_HEIGHT - 1)); + + if ((row + 1) * VCR_ROW_HEIGHT >= vcr->height) + return; + + height = fabsf(t) * (float)(VCR_ROW_HEIGHT - 1); + + if (height < min_height) + height = min_height; + + /* clamp the height to not potentially overflow */ + if (height > (VCR_ROW_HEIGHT - 1)) + height = (VCR_ROW_HEIGHT - 1); + + /* negative values project down from the top, positive up from bottom */ + if (t > 0.f) + y += VCR_ROW_HEIGHT - height - 1; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + Picture *dest; + + switch (layer) { + case VCR_LAYER_GRAPHA: + dest = &vcr->xlib.grapha_picture; + break; + case VCR_LAYER_GRAPHB: + dest = &vcr->xlib.graphb_picture; + break; + default: + assert(0); + } + + assert(xserver); + + XRenderFillRectangle(xserver->display, PictOpSrc, *dest, &chart_visible_color, + vcr->phase, y, /* dst x, y */ + 1, height); /* dst w, h */ + + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t mask = (0x1 << layer) << ((vcr->phase & 0x1) << 2); + uint8_t *p; + + p = &vcr->mem.bits[y * vcr->mem.pitch + (vcr->phase >> 1)]; + for (int i = 0; i < height; i++, p += vcr->mem.pitch) + *p |= mask; + + break; + } + + default: + assert(0); + } +} + + +/* clear a row in the specified layer */ +/* specify negative x and width to clear the entire row, otherwise constraints the clear to x..x+width */ +/* TODO FIXME an API that allowed providing a batch of layers would work _very_ well with TYPE_MEM. */ +void vcr_clear_row(vcr_t *vcr, vcr_layer_t layer, int row, int x, int width) +{ + assert(vcr); + assert(vcr->backend); + assert(layer < VCR_LAYER_CNT); + assert(row >= 0); + + if (x < 0) + x = 0; + + if (x > vcr->width) + x = vcr->width; + + if (width < 0) + width = vcr->width; + + if (x + width > vcr->width) + width = vcr->width - x; + + assert(x + width <= vcr->width); + + if ((row + 1) * VCR_ROW_HEIGHT >= vcr->height) + return; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + Picture *layers[] = { /* vcr->xlib should just have these in an array */ + &vcr->xlib.text_picture, + &vcr->xlib.shadow_picture, + &vcr->xlib.grapha_picture, + &vcr->xlib.graphb_picture, + }; + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + XRenderFillRectangle(xserver->display, PictOpSrc, *layers[layer], &chart_trans_color, + x, row * VCR_ROW_HEIGHT, /* dst x, y */ + width, VCR_ROW_HEIGHT); /* dst w, h */ + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t mask = ((uint8_t)(0x1 << layer)); + + /* naive but correct for now - TODO: optimize */ + for (int i = 0; i < VCR_ROW_HEIGHT; i++) { + uint8_t *p = &vcr->mem.bits[(row * VCR_ROW_HEIGHT + i) * vcr->mem.pitch + (x >> 1)]; + + if (width >= 2) { + int W = ((width >> 1) << 1); + + for (int j = 0; j < W; j++, p++) { + unsigned which = ((x + j) & 0x1) << 2; + + *p &= ~(mask << which); + + j++; + + which = ((x + j) & 0x1) << 2; + *p &= ~(mask << which); + } + } + + if (width & 0x1) { + unsigned which = ((x + 1) & 0x1) << 2; + + *p &= ~(mask << which); + } + } + break; + } + + default: + assert(0); + } +} + + +/* copy what's below a given row up by one row across all the layers */ +void vcr_shift_below_row_up_one(vcr_t *vcr, int row) +{ + assert(vcr); + assert(vcr->backend); + assert(row > 0); /* TODO? assert row doesn't overflow? clamp to hierarchy_end? */ + + if ((row + 1) * VCR_ROW_HEIGHT >= vcr->height) + return; + + assert(*(vcr->hierarchy_end_ptr) >= row); + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + Picture *layers[] = { /* vcr->xlib should just have these in an array */ + &vcr->xlib.text_picture, + &vcr->xlib.shadow_picture, + &vcr->xlib.grapha_picture, + &vcr->xlib.graphb_picture, + }; + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + for (int layer = 0; layer < NELEMS(layers); layer++) { + XRenderChangePicture(xserver->display, *layers[layer], CPRepeat, &pa_no_repeat); + XRenderComposite(xserver->display, PictOpSrc, *layers[layer], None, *layers[layer], + 0, (1 + row) * VCR_ROW_HEIGHT, /* src */ + 0, 0, /* mask */ + 0, row * VCR_ROW_HEIGHT, /* dest */ + vcr->width, (1 + *(vcr->hierarchy_end_ptr)) * VCR_ROW_HEIGHT - (1 + row) * VCR_ROW_HEIGHT); /* dimensions */ + XRenderChangePicture(xserver->display, *layers[layer], CPRepeat, &pa_repeat); + } + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t *dest = &vcr->mem.bits[row * VCR_ROW_HEIGHT * vcr->mem.pitch]; + uint8_t *src = &vcr->mem.bits[(1 + row) * VCR_ROW_HEIGHT * vcr->mem.pitch]; + size_t len = ((1 + *(vcr->hierarchy_end_ptr)) - (1 + row)) * VCR_ROW_HEIGHT * vcr->mem.pitch; + + assert(*(vcr->hierarchy_end_ptr) >= row); + + /* (hierarchy_end * VCR_ROW_HEIGHT) may overflow vcr->height, as it's not kept clipped. + * It more represents where the process hierarchy virtually ends - which may or may not stay within + * the chart's allocated area. So len must be clamped here to ensure we're not attempting + * to copy out of bounds. + */ + len = MIN(len, &vcr->mem.bits[vcr->height * vcr->mem.pitch] - src); + + assert(src + len <= vcr->mem.bits + vcr->mem.pitch * vcr->height); + assert(dest + len <= vcr->mem.bits + vcr->mem.pitch * vcr->height); + + /* XXX the xlib backend enjoys some luxuries in dealing with clipping that must be dealt with manually here, + * and that just hasn't been entirely fleshed out beyond "do enough to at least not segfault" + */ + + memmove(dest, src, len); + break; + } + + default: + assert(0); + } +} + + +/* copy what's below a given row down the specified amount across all layers */ +void vcr_shift_below_row_down_one(vcr_t *vcr, int row) +{ + int dest_y = (row + 1) * VCR_ROW_HEIGHT; + + assert(vcr); + assert(vcr->backend); + assert(row >= 0); + + if (dest_y >= vcr->height) + return; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + Picture *layers[] = { /* vcr->xlib should just have these in an array */ + &vcr->xlib.text_picture, + &vcr->xlib.shadow_picture, + &vcr->xlib.grapha_picture, + &vcr->xlib.graphb_picture, + }; + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + for (int layer = 0; layer < NELEMS(layers); layer++) { + XRenderComposite(xserver->display, PictOpSrc, *layers[layer], None, *layers[layer], + 0, row * VCR_ROW_HEIGHT, /* src */ + 0, 0, /* mask */ + 0, dest_y, /* dest */ + vcr->width, vcr->height - dest_y); /* dimensions */ + } + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t *dest = &vcr->mem.bits[dest_y * vcr->mem.pitch]; + uint8_t *src = &vcr->mem.bits[row * VCR_ROW_HEIGHT * vcr->mem.pitch]; + size_t len = (vcr->height - dest_y) * vcr->mem.pitch; + + memmove(dest, src, len); + break; + } + + default: + assert(0); + } +} + + +/* This shadows the provided layer into the shadow layer for the given row. + * Currently only layer == VCR_LAYER_TEXT is supported. + */ +void vcr_shadow_row(vcr_t *vcr, vcr_layer_t layer, int row) +{ + assert(vcr); + assert(vcr->backend); + assert(layer == VCR_LAYER_TEXT); + assert(row >= 0); + + if ((row + 1) * VCR_ROW_HEIGHT >= vcr->height) + return; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + /* the current technique for creating the shadow is to simply render the text at +1/-1 pixel offsets on both axis in translucent black */ + XRenderComposite(xserver->display, PictOpSrc, + vcr->backend->xlib.shadow_fill, vcr->xlib.text_picture, vcr->xlib.shadow_picture, + 0, 0, + -1, row * VCR_ROW_HEIGHT, + 0, row * VCR_ROW_HEIGHT, + vcr->visible_width, VCR_ROW_HEIGHT); + + XRenderComposite(xserver->display, PictOpOver, + vcr->backend->xlib.shadow_fill, vcr->xlib.text_picture, vcr->xlib.shadow_picture, + 0, 0, + 0, -1 + row * VCR_ROW_HEIGHT, + 0, row * VCR_ROW_HEIGHT, + vcr->visible_width, VCR_ROW_HEIGHT); + + XRenderComposite(xserver->display, PictOpOver, + vcr->backend->xlib.shadow_fill, vcr->xlib.text_picture, vcr->xlib.shadow_picture, + 0, 0, + 1, row * VCR_ROW_HEIGHT, + 0, row * VCR_ROW_HEIGHT, + vcr->visible_width, VCR_ROW_HEIGHT); + + XRenderComposite(xserver->display, PictOpOver, + vcr->backend->xlib.shadow_fill, vcr->xlib.text_picture, vcr->xlib.shadow_picture, + 0, 0, + 0, 1 + row * VCR_ROW_HEIGHT, + 0, row * VCR_ROW_HEIGHT, + vcr->visible_width, VCR_ROW_HEIGHT); + + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t text_mask = (0x1 << VCR_LAYER_TEXT); + uint8_t shadow_mask = (0x1 << VCR_LAYER_SHADOW); + int vcr_width = vcr->width; + + /* TODO: optimize this abomination, maybe switch to shadowing the text @ serialization to png time for the mem->png headless scenario? */ + + /* first pass has to clean up the shadow plane while doing one offset of shadow bits */ + for (int i = 0; i < VCR_ROW_HEIGHT; i++) { + uint8_t *s = &vcr->mem.bits[(row * VCR_ROW_HEIGHT + i) * vcr->mem.pitch]; + uint8_t *d = &vcr->mem.bits[(row * VCR_ROW_HEIGHT + i) * vcr->mem.pitch + 1]; + + for (int j = 0; j < vcr_width - 2; j++, d++) { + int s_shift = (((j + 1) & 0x1) << 2); + int d_shift = ((j & 0x1) << 2); + uint8_t t = ((*s & (0xf << s_shift) & (text_mask << s_shift)) << 1) >> s_shift; /* turn text bit into shadow bit by shifting over one */ + + *d = (*d & ~(shadow_mask << d_shift)) | (t << d_shift); + + j++; + s++; + + s_shift = (((j + 1) & 0x1) << 2); + d_shift = ((j & 0x1) << 2); + t = ((*s & (0xf << s_shift) & (text_mask << s_shift)) << 1) >> s_shift; /* turn text bit into shadow bit by shifting over one */ + *d = (*d & ~(shadow_mask << d_shift)) | (t << d_shift); + } + } + + /* second pass ORs the rest of the shadow bits into the now fully initialized shadow plane + * at the remaining surrounding offsets. These can all happen at once now that we can + * OR things additively. + */ + for (int i = 1; i < VCR_ROW_HEIGHT - 1; i++) { + uint8_t *s = &vcr->mem.bits[(row * VCR_ROW_HEIGHT + i) * vcr->mem.pitch]; + uint8_t *d = &vcr->mem.bits[(row * VCR_ROW_HEIGHT + i) * vcr->mem.pitch]; + + for (int j = 0; j < vcr_width - 2; j++, d++) { + int s_shift = (((j + 1) & 0x1) << 2); + int d_shift = ((j & 0x1) << 2); + uint8_t t = ((*s & (0xf << s_shift) & (text_mask << s_shift)) << 1) >> s_shift; /* turn text bit into shadow bit by shifting over one */ + + *d |= t << d_shift; + + /* for above and below use *s as dest */ + *(s - vcr->mem.pitch) |= t << s_shift; + *(s + vcr->mem.pitch) |= t << s_shift; + + j++; + s++; + + s_shift = (((j + 1) & 0x1) << 2); + d_shift = ((j & 0x1) << 2); + t = ((*s & (0xf << s_shift) & (text_mask << s_shift)) << 1) >> s_shift; /* turn text bit into shadow bit by shifting over one */ + *d |= t << d_shift; + + /* for above and below use *s as dest */ + *(s - vcr->mem.pitch) |= t << s_shift; + *(s + vcr->mem.pitch) |= t << s_shift; + } + } + break; + } + + default: + assert(0); + } +} + + +/* stash the row from the specified layer in temp storage which the next unstash will copy from */ +void vcr_stash_row(vcr_t *vcr, vcr_layer_t layer, int row) +{ + assert(vcr); + assert(vcr->backend); + assert(layer == VCR_LAYER_GRAPHA || layer == VCR_LAYER_GRAPHB); + /* for now we only support stashing graphs */ + + if ((row + 1) * VCR_ROW_HEIGHT >= vcr->height) + return; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + Picture *layers[] = { + [VCR_LAYER_GRAPHA] = &vcr->xlib.grapha_picture, + [VCR_LAYER_GRAPHB] = &vcr->xlib.graphb_picture, + }; + Picture *tmps[] = { + [VCR_LAYER_GRAPHA] = &vcr->xlib.tmp_a_picture, + [VCR_LAYER_GRAPHB] = &vcr->xlib.tmp_b_picture, + }; + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + XRenderComposite(xserver->display, PictOpSrc, *layers[layer], None, *tmps[layer], + 0, row * VCR_ROW_HEIGHT, /* src */ + 0, 0, /* mask */ + 0, 0, /* dest */ + vcr->width, VCR_ROW_HEIGHT); /* dimensions */ + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t *src = &vcr->mem.bits[row * VCR_ROW_HEIGHT * vcr->mem.pitch]; + uint8_t *dest = &vcr->mem.tmp[0]; + uint8_t mask = 0x1 << layer; + + /* we'll do both nibbles at once since this is simply a masked, full-pitch copy of a row, + * which means we need to prep the mask for doing both nibbles concurrently. + */ + mask |= mask << 4; + + for (int i = 0; i < VCR_ROW_HEIGHT; i++) { + for (int j = 0; j < vcr->mem.pitch; j++, dest++, src++) { + *dest = (*dest & ~mask) | (*src & mask); + } + } + break; + } + + default: + assert(0); + } +} + + +/* unstash the temp stored row to the destination row in the specified layer */ +void vcr_unstash_row(vcr_t *vcr, vcr_layer_t layer, int row) +{ + assert(vcr); + assert(vcr->backend); + assert(layer == VCR_LAYER_GRAPHA || layer == VCR_LAYER_GRAPHB); + + if ((row + 1) * VCR_ROW_HEIGHT >= vcr->height) + return; + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + Picture *layers[] = { + [VCR_LAYER_GRAPHA] = &vcr->xlib.grapha_picture, + [VCR_LAYER_GRAPHB] = &vcr->xlib.graphb_picture, + }; + Picture *tmps[] = { + [VCR_LAYER_GRAPHA] = &vcr->xlib.tmp_a_picture, + [VCR_LAYER_GRAPHB] = &vcr->xlib.tmp_b_picture, + }; + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + XRenderComposite(xserver->display, PictOpSrc, *tmps[layer], None, *layers[layer], + 0, 0, /* src */ + 0, 0, /* mask */ + 0, row * VCR_ROW_HEIGHT, /* dest */ + vcr->width, VCR_ROW_HEIGHT); /* dimensions */ + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t *dest = &vcr->mem.bits[row * VCR_ROW_HEIGHT * vcr->mem.pitch]; + uint8_t *src = &vcr->mem.tmp[0]; + uint8_t mask = (0x1 << layer); + + /* see comment above for stash_row */ + mask |= mask << 4; + + for (int i = 0; i < VCR_ROW_HEIGHT; i++) { + for (int j = 0; j < vcr->mem.pitch; j++, dest++, src++) { + *dest = (*dest & ~mask) | (*src & mask); + } + } + break; + } + + default: + assert(0); + } +} + + +/* for now delta is assumed to be either +1/-1, but it'd be interesting to capture delayed samples/updates + * by having a abs(delta)>1 and show them as gaps in the graph or something like that. TODO + */ +void vcr_advance_phase(vcr_t *vcr, int delta) +{ + assert(vcr); + assert(vcr->backend); + assert(delta == -1 || delta == 1); + + vcr->phase += (vcr->width + delta); + vcr->phase %= vcr->width; + + /* We clear the graphs at the new phase in preparation for the new sample being drawn, across *all* + * rows, the entire vertical slice of pixels at this phase is cleared. Just for the graph layers. + */ + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + XRenderFillRectangle(xserver->display, PictOpSrc, vcr->xlib.grapha_picture, &chart_trans_color, vcr->phase, 0, 1, vcr->height); + XRenderFillRectangle(xserver->display, PictOpSrc, vcr->xlib.graphb_picture, &chart_trans_color, vcr->phase, 0, 1, vcr->height); + + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: { + uint8_t mask = ~(((uint8_t)((0x1 << VCR_LAYER_GRAPHA) | (0x1 << VCR_LAYER_GRAPHB))) << ((vcr->phase & 0x1) << 2)); + uint8_t *p = &vcr->mem.bits[vcr->phase >> 1]; + + for (int i = 0; i < vcr->height; i++, p += vcr->mem.pitch) + *p &= mask; + + break; + } + + default: + assert(0); + } +} + + +/* return the # of combined hierarchy+snowflakes rows in chart */ +static inline int vcr_composed_rows(vcr_t *vcr) +{ + int snowflakes = *(vcr->snowflakes_cnt_ptr) ? 1 + *(vcr->snowflakes_cnt_ptr) : 0; /* don't include the separator row if there are no snowflakes */ + + return *(vcr->hierarchy_end_ptr) + snowflakes; +} + + +/* return the composed height of the chart */ +static inline int vcr_composed_height(vcr_t *vcr) +{ + int rows_height = vcr_composed_rows(vcr) * VCR_ROW_HEIGHT; + + return MIN(rows_height, vcr->visible_height); +} + + +/* Compose performs whatever work remains up to but not including the present-to-dest step, if there + * is any such intermediate work necessary to go from the incremental vcr state to a presentable + * form. For some backends this may do nothing at all, for others it may do a bunch of compositing + * of separate layers into a single cached layer which would then be used as the source for a + * present. + * + * This is decoupled from the present() because in cases like real-time visualization, the present may + * occur at 60FPS re-using the result of a single compose(), then compose() would occur on some lower + * frequency related to the chart update/sampling frequency, whenever the sampling was performed /and/ + * produced changes. + * + * So the compose is likely to be performed as part of the chart update, not part of the present. But + * depending on how present is implemented for a given vcr+dest, the present might implicitly perform + * a compose as part of the serialization of vcr->dest. (think a mem-vcr serializing to a png-dest, + * which might be doing some very tedious and slow row-of-pixels at a time compose while it writes the + * png file, with the mem vcr representation not having a composited result cached at all, instead always + * keeping the layers in a packed bit-planes in array of bytes form, with the vcr_compose doing effectively + * nothing for lack of memory to cache the composed results in. + * + * This can require allocations so it may fail, hence the non-voide return. + */ +int vcr_compose(vcr_t *vcr) +{ + assert(vcr); + assert(vcr->backend); + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + /* XXX: this came from charts.c::vwm_chart_compose() */ + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + int height = vcr_composed_height(vcr); + + assert(xserver); + + /* fill the chart picture with the background */ + /* FIXME TODO: this needs to apply vcr->marker_distance, which only mem_to_png actually does since it was added. */ + XRenderComposite(xserver->display, PictOpSrc, vcr->backend->xlib.bg_fill, None, vcr->xlib.picture, + 0, 0, + 0, 0, + 0, 0, + vcr->visible_width, height); + + /* draw the graphs into the chart through the stencils being maintained by the sample callbacks */ + XRenderComposite(xserver->display, PictOpOver, vcr->backend->xlib.grapha_fill, vcr->xlib.grapha_picture, vcr->xlib.picture, + 0, 0, + vcr->phase, 0, + 0, 0, + vcr->visible_width, height); + XRenderComposite(xserver->display, PictOpOver, vcr->backend->xlib.graphb_fill, vcr->xlib.graphb_picture, vcr->xlib.picture, + 0, 0, + vcr->phase, 0, + 0, 0, + vcr->visible_width, height); + + /* draw the shadow into the chart picture using a translucent black source drawn through the shadow mask */ + XRenderComposite(xserver->display, PictOpOver, vcr->backend->xlib.shadow_fill, vcr->xlib.shadow_picture, vcr->xlib.picture, + 0, 0, + 0, 0, + 0, 0, + vcr->visible_width, height); + + /* render chart text into the chart picture using a white source drawn through the chart text as a mask, on top of everything */ + XRenderComposite(xserver->display, PictOpOver, vcr->backend->xlib.text_fill, vcr->xlib.text_picture, vcr->xlib.picture, + 0, 0, + 0, 0, + 0, 0, + vcr->visible_width, (*(vcr->hierarchy_end_ptr) * VCR_ROW_HEIGHT)); + + XRenderComposite(xserver->display, PictOpOver, vcr->backend->xlib.snowflakes_text_fill, vcr->xlib.text_picture, vcr->xlib.picture, + 0, 0, + 0, *(vcr->hierarchy_end_ptr) * VCR_ROW_HEIGHT, + 0, *(vcr->hierarchy_end_ptr) * VCR_ROW_HEIGHT, + vcr->visible_width, height - (*(vcr->hierarchy_end_ptr) * VCR_ROW_HEIGHT)); + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: + /* this probably doesn't do anything since mem is embedded-targed, but variants could be + * introduced in the future . + */ + break; + + default: + assert(0); + } + + return 0; +} + + +#ifdef USE_XLIB +/* this is an xlib-backend specific helper for turning the composed area into an xdamage region, + * which is primarily needed by the vwm use case. + */ +int vcr_get_composed_xdamage(vcr_t *vcr, XserverRegion *res_damaged_region) +{ + XRectangle damage = {}; + + assert(vcr); + assert(vcr->backend); + assert(vcr->backend->type == VCR_BACKEND_TYPE_XLIB); + assert(res_damaged_region); + + /* TODO: ideally this would actually be a more granular damage region constructed + * piecemeal during the compose process since the last present of the vcr to an xlib dest. + * but for now it just produces a damage region of the visible area for the chart. + */ + damage.width = vcr->visible_width; + damage.height = vcr->visible_height; + + *res_damaged_region = XFixesCreateRegion(vcr->backend->xlib.xserver->display, &damage, 1); + + return 0; +} + + +#ifdef USE_PNG +/* present the chart into a newly allocated pixmap, intended for snapshotting purposes */ +static void vcr_present_xlib_to_pixmap(vcr_t *vcr, const XRenderColor *bg_color, Pixmap *res_pixmap) +{ + static const XRenderColor blackness = { 0x0000, 0x0000, 0x0000, 0xFFFF}; + vcr_dest_t *vcr_dest; + vwm_xserver_t *xserver; + Picture dest; + + assert(vcr); + assert(vcr->backend); + assert(vcr->backend->type == VCR_BACKEND_TYPE_XLIB); + assert(res_pixmap); + + xserver = vcr->backend->xlib.xserver; + + if (!bg_color) + bg_color = &blackness; + + dest = create_picture_fill(xserver, vcr->visible_width, vcr_composed_height(vcr), 32, 0, NULL, bg_color, res_pixmap); + vcr_dest = vcr_dest_xpicture_new(vcr->backend, dest); + vcr_present(vcr, VCR_PRESENT_OP_OVER, vcr_dest, -1, -1, -1, -1); + vcr_dest = vcr_dest_free(vcr_dest); +} + + +/* present the chart the chart into an ximage we can access locally for saving as a png */ +static void vcr_present_xlib_to_ximage(vcr_t *vcr, const XRenderColor *bg_color, XImage **res_ximage) +{ + Pixmap dest_pixmap; + vwm_xserver_t *xserver; + + assert(vcr); + assert(vcr->backend); + assert(vcr->backend->type == VCR_BACKEND_TYPE_XLIB); + assert(res_ximage); + + xserver = vcr->backend->xlib.xserver; + + assert(xserver); + + vcr_present_xlib_to_pixmap(vcr, bg_color, &dest_pixmap); + *res_ximage = XGetImage(xserver->display, + dest_pixmap, + 0, + 0, + vcr->visible_width, + vcr_composed_height(vcr), + AllPlanes, + ZPixmap); + XFreePixmap(xserver->display, dest_pixmap); +} + + +/* Implements present of an xlib-backed vcr to a png dest. + * This is basically the OG pre-vcr snapshot_as_png code from vmon.c, + * meaning it makes no effort to be super conservative in terms of memory + * consumption etc. + */ +static int vcr_present_xlib_to_png(vcr_t *vcr, vcr_dest_t *dest) +{ + XImage *chart_as_ximage; + png_bytepp row_pointers; + + assert(vcr); + assert(vcr->backend); + assert(vcr->backend->type == VCR_BACKEND_TYPE_XLIB); + assert(dest); + assert(dest->type == VCR_DEST_TYPE_PNG); + assert(dest->png.output); + + vcr_present_xlib_to_ximage(vcr, NULL, &chart_as_ximage); + + row_pointers = malloc(sizeof(void *) * chart_as_ximage->height); + if (!row_pointers) { + XDestroyImage(chart_as_ximage); + + return -ENOMEM; + } + + for (unsigned i = 0; i < chart_as_ximage->height; i++) + row_pointers[i] = &((png_byte *)chart_as_ximage->data)[i * chart_as_ximage->bytes_per_line]; + + if (setjmp(png_jmpbuf(dest->png.png_ctx)) != 0) { + XDestroyImage(chart_as_ximage); + free(row_pointers); + + return -ENOMEM; + } + + /* XXX: I'm sure this is making flawed assumptions about the color format + * and type etc, but this makes it work for me and that's Good Enough for now. + * One can easily turn runtime mapping of X color formats, endianness, and packing + * details to whatever a file format like PNG can express into a tar-filled rabbithole + * of fruitless wankery. + */ + png_set_bgr(dest->png.png_ctx); + png_set_IHDR(dest->png.png_ctx, dest->png.info_ctx, + chart_as_ximage->width, + chart_as_ximage->height, + 8, + PNG_COLOR_TYPE_RGBA, + PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, + PNG_FILTER_TYPE_BASE); + + png_write_info(dest->png.png_ctx, dest->png.info_ctx); + png_write_image(dest->png.png_ctx, row_pointers); + png_write_end(dest->png.png_ctx, NULL); + + XDestroyImage(chart_as_ximage); + free(row_pointers); + + return 0; +} +#endif /* USE_PNG */ + +#endif /* USE_XLIB */ + + +#ifdef USE_PNG + +/* We basically just statically define the blended outputs of all the layer combinations, + * so first we or together all the relevant palette indices for those combinations, and + * give them symbolic names to later use when populating hte palette with actual rgb values. + */ +#define VCR_TEXT (0x1 << VCR_LAYER_TEXT) +#define VCR_SHADOW (0x1 << VCR_LAYER_SHADOW) +#define VCR_GRAPHA (0x1 << VCR_LAYER_GRAPHA) +#define VCR_GRAPHB (0x1 << VCR_LAYER_GRAPHB) +#define VCR_GRAPHAB ((0x1 << VCR_LAYER_GRAPHA) | (0x1 << VCR_LAYER_GRAPHB)) +/* These bits aren't stored in the vcr->mem.bits[] nibbles, but do get used as palette indices. + * Their value is generated during the mem_to_png() process, derived from Y position within a row, + * and row position within a snapshot, and X position within a row's separator (for markers). + */ +#define VCR_SEP (0x1 << VCR_LAYER_CNT) +#define VCR_ODD (0x1 << (VCR_LAYER_CNT + 1)) +#define VCR_MARKER (0x1 << (VCR_LAYER_CNT + 2)) + +#define VCR_SEP_MARKER (VCR_SEP | VCR_MARKER) +#define VCR_SEP_MARKER_ODD (VCR_SEP | VCR_MARKER | VCR_ODD) +#define VCR_SEP_ODD (VCR_SEP | VCR_ODD) +#define VCR_MARKER_ODD (VCR_MARKER | VCR_ODD) +#define VCR_GRAPHA_ODD (VCR_GRAPHA | VCR_ODD) +#define VCR_GRAPHB_ODD (VCR_GRAPHB | VCR_ODD) +#define VCR_GRAPHAB_ODD (VCR_GRAPHAB | VCR_ODD) +#define VCR_SHADOW_ODD (VCR_SHADOW | VCR_ODD) + +/* text over anything is going to just be white */ +#define VCR_TEXT_SEP (VCR_TEXT | VCR_SEP) +#define VCR_TEXT_SEP_MARKER (VCR_TEXT | VCR_SEP | VCR_MARKER) + +#define VCR_TEXT_GRAPHA (VCR_TEXT | VCR_GRAPHA) +#define VCR_TEXT_GRAPHB (VCR_TEXT | VCR_GRAPHB) +#define VCR_TEXT_GRAPHAB (VCR_TEXT | VCR_GRAPHAB) +#define VCR_TEXT_SHADOW (VCR_TEXT | VCR_SHADOW) +#define VCR_TEXT_GRAPHA_SHADOW (VCR_TEXT | VCR_GRAPHA | VCR_SHADOW) +#define VCR_TEXT_GRAPHB_SHADOW (VCR_TEXT | VCR_GRAPHB | VCR_SHADOW) +#define VCR_TEXT_GRAPHAB_SHADOW (VCR_TEXT | VCR_GRAPHAB | VCR_SHADOW) + +#define VCR_TEXT_SEP_SHADOW (VCR_TEXT | VCR_SEP | VCR_SHADOW) +#define VCR_TEXT_SEP_MARKER_SHADOW (VCR_TEXT | VCR_SEP | VCR_MARKER | VCR_SHADOW) + +#define VCR_TEXT_ODD (VCR_TEXT | VCR_ODD) +#define VCR_TEXT_ODD_SEP (VCR_TEXT | VCR_ODD | VCR_SEP) +#define VCR_TEXT_ODD_SEP_MARKER (VCR_TEXT | VCR_ODD | VCR_SEP | VCR_MARKER) +#define VCR_TEXT_ODD_GRAPHA (VCR_TEXT | VCR_ODD | VCR_GRAPHA) +#define VCR_TEXT_ODD_GRAPHB (VCR_TEXT | VCR_ODD | VCR_GRAPHB) +#define VCR_TEXT_ODD_GRAPHAB (VCR_TEXT | VCR_ODD | VCR_GRAPHAB) +#define VCR_TEXT_ODD_SHADOW (VCR_TEXT | VCR_ODD | VCR_SHADOW) +#define VCR_TEXT_ODD_SEP_SHADOW (VCR_TEXT | VCR_ODD | VCR_SEP | VCR_SHADOW) +#define VCR_TEXT_ODD_SEP_MARKER_SHADOW (VCR_TEXT | VCR_ODD | VCR_SEP | VCR_MARKER | VCR_SHADOW) +#define VCR_TEXT_ODD_GRAPHA_SHADOW (VCR_TEXT | VCR_ODD | VCR_GRAPHA | VCR_SHADOW) +#define VCR_TEXT_ODD_GRAPHB_SHADOW (VCR_TEXT | VCR_ODD | VCR_GRAPHB | VCR_SHADOW) +#define VCR_TEXT_ODD_GRAPHAB_SHADOW (VCR_TEXT | VCR_ODD | VCR_GRAPHAB | VCR_SHADOW) + +/* shadows over graph colors get blended, otherwise they're left black */ +#define VCR_SHADOW_GRAPHA (VCR_SHADOW | VCR_GRAPHA) +#define VCR_SHADOW_GRAPHB (VCR_SHADOW | VCR_GRAPHB) +#define VCR_SHADOW_GRAPHAB (VCR_SHADOW | VCR_GRAPHAB) +#define VCR_SHADOW_ODD_GRAPHA (VCR_SHADOW | VCR_ODD | VCR_GRAPHA) +#define VCR_SHADOW_ODD_GRAPHB (VCR_SHADOW | VCR_ODD | VCR_GRAPHB) +#define VCR_SHADOW_ODD_GRAPHAB (VCR_SHADOW | VCR_ODD | VCR_GRAPHAB) + +/* when without shadow */ +#define VCR_PNG_WHITE {0xff, 0xff, 0xff} +#define VCR_PNG_RED {0xff, 0x00, 0x00} +#define VCR_PNG_CYAN {0x00, 0xff, 0xff} +#define VCR_PNG_YELLOW {0xc0, 0xc0, 0x00} +#define VCR_PNG_DARK_GRAY {0x30, 0x30, 0x30} /* used for separator */ +#define VCR_PNG_DARKER_GRAY {0x10, 0x10, 0x10} /* used for odd rows background */ + +/* when in shadow */ +#define VCR_PNG_DARK_WHITE {0x4a, 0x4a, 0x4a} +#define VCR_PNG_DARK_RED {0x80, 0x00, 0x00} +#define VCR_PNG_DARK_CYAN {0x00, 0x5b, 0x5b} + +enum { + VCR_LUT_BLACK = 0, + VCR_LUT_WHITE, + VCR_LUT_RED, + VCR_LUT_CYAN, + VCR_LUT_YELLOW, + VCR_LUT_DARK_GRAY, + VCR_LUT_DARKER_GRAY, + VCR_LUT_DARK_WHITE, + VCR_LUT_DARK_RED, + VCR_LUT_DARK_CYAN, +}; + + +static int vcr_present_mem_to_png(vcr_t *vcr, vcr_dest_t *dest) +{ + static png_color pal[] = { /* programming gfx like it's 1990 can be such a joy */ + [VCR_LUT_BLACK] = {}, + [VCR_LUT_WHITE] = VCR_PNG_WHITE, + [VCR_LUT_RED] = VCR_PNG_RED, + [VCR_LUT_CYAN] = VCR_PNG_CYAN, + [VCR_LUT_YELLOW] = VCR_PNG_YELLOW, + [VCR_LUT_DARK_GRAY] = VCR_PNG_DARK_GRAY, + [VCR_LUT_DARKER_GRAY] = VCR_PNG_DARKER_GRAY, + [VCR_LUT_DARK_WHITE] = VCR_PNG_DARK_WHITE, + [VCR_LUT_DARK_RED] = VCR_PNG_DARK_RED, + [VCR_LUT_DARK_CYAN] = VCR_PNG_DARK_CYAN, + }; + + /* lut is an indirection table for mapping layer bit combinations to the above deduplicated denser color palette */ + static uint8_t lut[256] = { + /* text solid white above all layers */ + [VCR_TEXT] = VCR_LUT_WHITE, + [VCR_TEXT_SEP] = VCR_LUT_WHITE, + [VCR_TEXT_SEP_MARKER] = VCR_LUT_WHITE, + [VCR_TEXT_SEP_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_SEP_MARKER_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_GRAPHA] = VCR_LUT_WHITE, + [VCR_TEXT_GRAPHB] = VCR_LUT_WHITE, + [VCR_TEXT_GRAPHAB] = VCR_LUT_WHITE, + [VCR_TEXT_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_GRAPHA_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_GRAPHB_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_GRAPHAB_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_ODD] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_SEP] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_SEP_MARKER] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_SEP_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_SEP_MARKER_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_GRAPHA] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_GRAPHB] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_GRAPHAB] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_GRAPHA_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_GRAPHB_SHADOW] = VCR_LUT_WHITE, + [VCR_TEXT_ODD_GRAPHAB_SHADOW] = VCR_LUT_WHITE, + + /* no shadow or text, plain graph colors */ + [VCR_GRAPHA] = VCR_LUT_RED, + [VCR_GRAPHB] = VCR_LUT_CYAN, + [VCR_GRAPHAB] = VCR_LUT_WHITE, + [VCR_GRAPHA_ODD] = VCR_LUT_RED, + [VCR_GRAPHB_ODD] = VCR_LUT_CYAN, + [VCR_GRAPHAB_ODD] = VCR_LUT_WHITE, + + /* shadowed same but dark */ + [VCR_SHADOW_GRAPHA] = VCR_LUT_DARK_RED, + [VCR_SHADOW_GRAPHB] = VCR_LUT_DARK_CYAN, + [VCR_SHADOW_GRAPHAB] = VCR_LUT_DARK_WHITE, + [VCR_SHADOW_ODD_GRAPHA] = VCR_LUT_DARK_RED, + [VCR_SHADOW_ODD_GRAPHB] = VCR_LUT_DARK_CYAN, + [VCR_SHADOW_ODD_GRAPHAB] = VCR_LUT_DARK_WHITE, + + /* the rest get defaulted to black, which is great. */ + [VCR_SEP] = VCR_LUT_DARK_GRAY, + [VCR_MARKER] = VCR_LUT_YELLOW, + [VCR_SEP_MARKER] = VCR_LUT_YELLOW, + [VCR_ODD] = VCR_LUT_DARKER_GRAY, + [VCR_SEP_ODD] = VCR_LUT_DARK_GRAY, + [VCR_SEP_MARKER_ODD] = VCR_LUT_YELLOW, + }; + + png_bytepp row_pointers; + uint8_t *row_pixels; + size_t row_stride = vcr->width >> 1; + + assert(vcr); + assert(vcr->backend); + assert(vcr->backend->type == VCR_BACKEND_TYPE_MEM); + assert(dest); + assert(dest->type == VCR_DEST_TYPE_PNG); + + row_pixels = malloc(VCR_ROW_HEIGHT * row_stride); + if (!row_pixels) + return -ENOMEM; + + row_pointers = malloc(sizeof(void *) * VCR_ROW_HEIGHT); + if (!row_pointers) { + free(row_pixels); + return -ENOMEM; + } + + for (int i = 0; i < VCR_ROW_HEIGHT; i++) + row_pointers[i] = &((png_byte *)row_pixels)[i * row_stride]; + + if (setjmp(png_jmpbuf(dest->png.png_ctx)) != 0) { + free(row_pixels); + free(row_pointers); + return -ENOMEM; + } + + png_set_IHDR(dest->png.png_ctx, dest->png.info_ctx, + vcr->width, /* always use the full width/height for the file dimensions, it's annoying when comparing images to have a variety of dimensions. */ + vcr->height, + 4, /* 4-bit color index (16 color palette) for smaller file sizes */ + PNG_COLOR_TYPE_PALETTE, /* we use a palette for mem->png for less ram and filesize */ + PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, + PNG_FILTER_TYPE_BASE); + + png_set_PLTE(dest->png.png_ctx, dest->png.info_ctx, pal, NELEMS(pal)); + + /* This differs from xlib_to_png in that it presents row-at-a-time from + * the packed form @ vcr->mem.bits to dest->png_ctx. Note "row" in this + * context is a row of chart data, not a single row of pixels. + * + * This approach saves memory by not needing another WxH full copy of + * the rendered form of vcr->mem.bits for png_write_image() to access. + * But it does make the implementation a bit more tedious, and probably + * a little slower. + */ + png_write_info(dest->png.png_ctx, dest->png.info_ctx); + { + int n_rows = MIN(vcr_composed_rows(vcr), vcr->height / VCR_ROW_HEIGHT); /* prevent n_rows from overflowing the height */ + unsigned marker_distance = 0; + + if (vcr->marker_distance_ptr) + marker_distance = *(vcr->marker_distance_ptr); + + for (int i = 0; i < n_rows; i++) { + uint8_t *d = row_pixels; + uint8_t mask = (0x1 << VCR_LAYER_GRAPHA) | (0x1 << VCR_LAYER_GRAPHB); + uint8_t odd = ((VCR_ODD << 4 | VCR_ODD) * (i & 0x1)); + + /* The graph layers need to be moved to vcr->phase, since the per-sample updates just draw + * individual graph bars without bothering to move the whole graph layer every sample. + * It makes the present more complicated / less efficient, but generally sampling is done + * more frequently. + */ + for (int j = 0; j < VCR_ROW_HEIGHT; j++) { + uint8_t *s = &vcr->mem.bits[(i * VCR_ROW_HEIGHT + j) * vcr->mem.pitch]; + uint8_t border = j == (VCR_ROW_HEIGHT - 1) ? VCR_SEP : 0x0; + + for (int k = 0; k < vcr->width; k++, s++, d++) { + unsigned phase_k_mod_width = ((vcr->phase + k) % vcr->width); + unsigned sg_shift = (phase_k_mod_width & 0x1) << 2; + uint8_t *sg = &vcr->mem.bits[(i * VCR_ROW_HEIGHT + j) * vcr->mem.pitch + (phase_k_mod_width >> 1)]; + uint8_t marker = 0; + uint8_t pp; + + /* FIXME TODO: be more clever/efficient about this (get rid of this conditional b.s. in the inner loop) */ + if ((j == (VCR_ROW_HEIGHT - 1)) && marker_distance && !(k % marker_distance)) + marker = VCR_MARKER; + + /* pp will hold the png-appropriate indexed-color 4bpp packed pixel */ + pp = lut[(*s & (~mask & 0xf)) | ((*sg & (mask << sg_shift)) >> sg_shift) | border | marker | odd] << 4; + + /* this copy pasta unrolls the loop to unpack two pixels from the nibbles at a time */ + k++; + /* note there's no need to advance s twice since we get two pixels out of it per byte, and sg + * is simply recomputed entirely again because of the phase wrapping that must be dealt with, + * this can all be optimized later if we care. + */ + + /* FIXME TODO: be more clever/efficient about this (get rid of this conditional b.s. in the inner loop) */ + marker = 0; + if ((j == (VCR_ROW_HEIGHT - 1)) && marker_distance && !(k % marker_distance)) + marker = VCR_MARKER; + + phase_k_mod_width = ((vcr->phase + k) % vcr->width); + sg_shift = (phase_k_mod_width & 0x1) << 2; + sg = &vcr->mem.bits[(i * VCR_ROW_HEIGHT + j) * vcr->mem.pitch + (phase_k_mod_width >> 1)]; + pp |= lut[((*s & ~(mask << 4)) >> 4) | ((*sg & (mask << sg_shift)) >> sg_shift) | border | marker | odd]; + + *d = pp; + } + } + + png_write_rows(dest->png.png_ctx, row_pointers, VCR_ROW_HEIGHT); + } + + /* just black out whatever remains */ + memset(row_pixels, 0x00, row_stride); + for (int i = n_rows * VCR_ROW_HEIGHT; i < vcr->height; i++) + png_write_row(dest->png.png_ctx, row_pointers[0]); + } + png_write_end(dest->png.png_ctx, dest->png.info_ctx); + + free(row_pixels); + free(row_pointers); + + return 0; +} +#endif /* USE_PNG */ + + +/* This serializes vcr's state to dest, which may be a fast and snappy operation + * like when the dest is an xwindow or xpicture from an xlib backend with a vcr + * from that same xlib backend. Or it might be a rather slow and tedious but + * memory-frugal operation like when dest is a png and vcr a mem backend, which + * targets more embedded-style memory-constrained headless use cases. + * + * Note there are coordinates/dimensions provided which most of the time will just + * match the destination, but especially in the vwm composited WM use case this + * won't be true because the dest is a picture representing the X root window. + * There we must translate the presented output within the root window wherever the + * related X window is being composited, and clip it to within the window's borders. + * + * Otherwise, we generally just spit out the entirety of the vcr's charts. + * + * providing x/y/width/height all as -1 is treated as a special case of present the whole vcr to the dest + * @ 0,0 - it's a convenience for use caases that just want to spit the full chart out to a dest containing + * nothing but the cart, so callers don't have to access+supply such things. + */ +int vcr_present(vcr_t *vcr, vcr_present_op_t op, vcr_dest_t *dest, int x, int y, int width, int height) +{ + assert(vcr); + assert(vcr->backend); + assert(dest); + + if (x == -1 && y == -1 && width == -1 && height == -1) { + x = y = 0; + width = vcr->visible_width; + height = vcr_composed_height(vcr); + } + + switch (vcr->backend->type) { +#ifdef USE_XLIB + case VCR_BACKEND_TYPE_XLIB: { + int xop; + + switch (op) { + case VCR_PRESENT_OP_SRC: + xop = PictOpSrc; + break; + case VCR_PRESENT_OP_OVER: + xop = PictOpOver; + break; + default: + assert(0); + } + switch (dest->type) { + case VCR_DEST_TYPE_XWINDOW: { + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + + /* present xlib->xwindow */ + /* vmon use case */ + + XRenderComposite(xserver->display, xop, vcr->xlib.picture, None, dest->xwindow.picture, + 0, 0, 0, 0, /* src x,y, maxk x, y */ + x, /* dst x */ + y, /* dst y */ + width, MIN(vcr_composed_height(vcr), height) /* FIXME */); /* w, h */ + break; + } + + case VCR_DEST_TYPE_XPICTURE: { + vwm_xserver_t *xserver = vcr->backend->xlib.xserver; + /* present xlib->xpicture */ + /* vwm use case */ + XRenderComposite(xserver->display, xop, vcr->xlib.picture, None, dest->xpicture.picture, + 0, 0, 0, 0, /* src x,y, maxk x, y */ + x, /* dst x */ + y, /* dst y */ + width, MIN(vcr_composed_height(vcr), height) /* FIXME */); /* w, h */ + break; + } + +#ifdef USE_PNG + case VCR_DEST_TYPE_PNG: + /* present xlib->png */ + /* this would enable snapshotting to png in vwm which isn't currently supported, + * but is also necessary to support the vmon PNG snapshotting from X use case, + * which is already supported in the pre-vcr era. + */ + return vcr_present_xlib_to_png(vcr, dest); +#endif /* USE_PNG */ + + default: + assert(0); + } + break; + } +#endif /* USE_XLIB */ + + case VCR_BACKEND_TYPE_MEM: + switch (dest->type) { +#ifdef USE_XLIB + case VCR_DEST_TYPE_XWINDOW: + /* present mem->xwindow */ + case VCR_DEST_TYPE_XPICTURE: + /* present mem->xpicture */ + VWM_ERROR("vcr_present(vcr=mem dest=x{window,picture}) unsupported"); + /* XXX: these aren't currently supported, but may be interesting to experiment + * with in the future as a low-memory real-time visualization mode, if it could + * be made efficient enough. + */ + assert(0); +#endif /* USE_XLIB */ + +#ifdef USE_PNG + case VCR_DEST_TYPE_PNG: + /* present mem->png */ + /* this is the headless vmon -> periodic png snapshots mode, + * which is the whole impetus for adding the vcr abstraction. + */ + return vcr_present_mem_to_png(vcr, dest); +#endif + default: + assert(0); + } + break; + + default: + assert(0); + } + + return 0; +} diff --git a/src/vcr.h b/src/vcr.h new file mode 100644 index 0000000..31c7dc6 --- /dev/null +++ b/src/vcr.h @@ -0,0 +1,86 @@ +#ifndef _VCR_H +#define _VCR_H + +#include <stdio.h> /* for FILE* */ + +#ifdef USE_XLIB +#include <X11/extensions/Xrender.h> /* for Picture */ +#endif /* USE_XLIB */ + +#define VCR_DRAW_TEXT_N_STRS_MAX 512 +#define VCR_ROW_HEIGHT 15 /* this should always be larger than the font height */ + +typedef enum vcr_backend_type_t { +#ifdef USE_XLIB + VCR_BACKEND_TYPE_XLIB, +#endif /* USE_XLIB */ + VCR_BACKEND_TYPE_MEM, +} vcr_backend_type_t; + +/* there are very minimal backend events plumbed out from the X events */ +typedef enum vcr_backend_event_t { + VCR_BACKEND_EVENT_NOOP, + VCR_BACKEND_EVENT_RESIZE, + VCR_BACKEND_EVENT_REDRAW, + VCR_BACKEND_EVENT_QUIT, +} vcr_backend_event_t; + +typedef enum vcr_present_op_t { + VCR_PRESENT_OP_SRC, /* equivalent to XRender PictOpSrc */ + VCR_PRESENT_OP_OVER, /* equivaletn to XRender PictOpOver */ +} vcr_present_op_t; + +typedef enum vcr_layer_t { + VCR_LAYER_TEXT, /* the text layer for threadName/argv/wchan/state/pid etc. */ + VCR_LAYER_SHADOW, /* the shadow layer below the text (XXX: this must be kept after text) */ + VCR_LAYER_GRAPHA, /* the graph A layer below the shadow layer */ + VCR_LAYER_GRAPHB, /* the graph B layer below the shadow layer */ + VCR_LAYER_CNT, +} vcr_layer_t; + +typedef struct vcr_backend_t vcr_backend_t; +typedef struct vcr_dest_t vcr_dest_t; +typedef struct vcr_t vcr_t; + +typedef struct vcr_str_t { + const char *str; + size_t len; +} vcr_str_t; + +vcr_backend_t * vcr_backend_new(vcr_backend_type_t backend, ...); +int vcr_backend_get_dimensions(vcr_backend_t *vbe, int *res_width, int *res_height); +int vcr_backend_poll(vcr_backend_t *vbe, int timeout_us); +vcr_backend_event_t vcr_backend_next_event(vcr_backend_t *vbe, int *res_width, int *res_height); +vcr_backend_t * vcr_backend_free(vcr_backend_t *vbe); + +#ifdef USE_XLIB +vcr_dest_t * vcr_dest_xwindow_new(vcr_backend_t *vbe, const char *name, unsigned width, unsigned height); +unsigned vcr_dest_xwindow_get_id(vcr_dest_t *dest); +vcr_dest_t * vcr_dest_xpicture_new(vcr_backend_t *vbe, Picture picture); +#endif /* USE_XLIB */ +#ifdef USE_PNG +vcr_dest_t * vcr_dest_png_new(vcr_backend_t *vbe, FILE *output); +#endif /* USE_PNG */ +vcr_dest_t * vcr_dest_free(vcr_dest_t *dest); + +vcr_t * vcr_new(vcr_backend_t *vbe, int *hierarchy_end_ptr, int *snowflakes_cnt_ptr, const unsigned *marker_distance_ptr); +vcr_t * vcr_free(vcr_t *vcr); +int vcr_resize_visible(vcr_t *vcr, int width, int height); +void vcr_draw_text(vcr_t *vcr, vcr_layer_t layer, int x, int row, const vcr_str_t *strs, int n_strs, int *res_width); +void vcr_draw_ortho_line(vcr_t *vcr, vcr_layer_t layer, int x1, int y1, int x2, int y2); +void vcr_mark_finish_line(vcr_t *vcr, vcr_layer_t layer, int row); +void vcr_draw_bar(vcr_t *vcr, vcr_layer_t layer, int row, float t, int min_height); +void vcr_clear_row(vcr_t *vcr, vcr_layer_t layer, int row, int x, int width); +void vcr_shift_below_row_up_one(vcr_t *vcr, int row); +void vcr_shift_below_row_down_one(vcr_t *vcr, int row); +void vcr_shadow_row(vcr_t *vcr, vcr_layer_t layer, int row); +void vcr_stash_row(vcr_t *vcr, vcr_layer_t layer, int row); +void vcr_unstash_row(vcr_t *vcr, vcr_layer_t layer, int row); +void vcr_advance_phase(vcr_t *vcr, int delta); +int vcr_compose(vcr_t *vcr); +#ifdef USE_XLIB +int vcr_get_composed_xdamage(vcr_t *vcr, XserverRegion *res_damaged_region); +#endif /* USE_XLIB */ +int vcr_present(vcr_t *vcr, vcr_present_op_t op, vcr_dest_t *dest, int x, int y, int width, int height); + +#endif /* _VCR_H */ @@ -1,10 +1,10 @@ /* * \/\/\ * - * Copyright (C) 2012-2021 Vito Caputo - <vcaputo@pengaru.com> + * Copyright (C) 2012-2025 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -16,44 +16,55 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include <X11/Xlib.h> #include <assert.h> +#include <errno.h> #include <limits.h> -#include <png.h> -#include <poll.h> +#include <locale.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> +#include <string.h> +#include <sys/mman.h> #include <sys/prctl.h> #include <time.h> #include <sys/stat.h> +#include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "charts.h" +#include "vcr.h" #include "util.h" -#include "xserver.h" /* vmon exposes the monitoring charts to the shell in an strace-like cli */ typedef struct vmon_t { - vwm_xserver_t *xserver; + vcr_backend_t *vcr_backend; + vcr_dest_t *vcr_dest; vwm_charts_t *charts; vwm_chart_t *chart; - Atom wm_protocols_atom; - Atom wm_delete_atom; - Window window; int width, height; - Picture picture; int pid; int done; int linger; + int dump_procs; + int mem_locked; + int reaper; + int no_threads; time_t start_time; + int snapshots_interval; int snapshot; + int marker_distance; + int now_names; + int headless; + int hertz; char *output_dir; char *name; + char *wip_name; unsigned n_snapshots; + const char * const *execv; + unsigned n_execv; } vmon_t; @@ -63,7 +74,7 @@ typedef struct vmon_t { #define WIDTH_MIN 200 #define HEIGHT_MIN 28 -static volatile int got_sigchld, got_sigusr1; +static volatile int got_sigchld, got_sigusr1, got_sigint, got_sigquit, got_sigterm; /* return if arg == flag or altflag if provided */ static int is_flag(const char *arg, const char *flag, const char *altflag) @@ -79,7 +90,7 @@ static int is_flag(const char *arg, const char *flag, const char *altflag) /* parse integer out of opt, stores parsed opt in *res on success */ -static int parse_flag_int(char * const *flag, char * const *end, char * const *opt, int min, int max, int *res) +static int parse_flag_int(const char * const *flag, const char * const *end, const char * const *opt, int min, int max, int *res) { long int num; char *endp; @@ -123,7 +134,7 @@ static int parse_flag_int(char * const *flag, char * const *end, char * const *o /* parse string out of opt, stores parsed opt in newly allocated *res on success */ -static int parse_flag_str(char * const *flag, char * const *end, char * const *opt, int min_len, char **res) +static int parse_flag_str(const char * const *flag, const char * const *end, const char * const *opt, int min_len, char **res) { char *tmp; @@ -158,20 +169,18 @@ static int parse_flag_str(char * const *flag, char * const *end, char * const *o /* set vmon->{width,height} to fullscreen dimensions */ static int set_fullscreen(vmon_t *vmon) { - XWindowAttributes wattr; - +#ifdef USE_XLIB assert(vmon); - assert(vmon->xserver); - if (!XGetWindowAttributes(vmon->xserver->display, XSERVER_XROOT(vmon->xserver), &wattr)) { - VWM_ERROR("unable to get root window attributes"); + if (vcr_backend_get_dimensions(vmon->vcr_backend, &vmon->width, &vmon->height) < 0) { + VWM_ERROR("unable to get vcr_backend dimensions"); return 0; } - vmon->width = wattr.width; - vmon->height = wattr.height; - return 1; +#else /* USE_XLIB */ + return -ENOTSUP; +#endif } @@ -179,22 +188,31 @@ static void print_help(void) { puts( "\n" - "-----------------------------------------------------------------------------\n" + "-------------------------------------------------------------------------------\n" " Flag Description\n" - "-----------------------------------------------------------------------------\n" + "-------------------------------------------------------------------------------\n" " -- Sentinel, subsequent arguments form command to execute\n" - " -f --fullscreen Fullscreen window\n" + " -f --fullscreen Fullscreen window (X only; no effect with --headless) \n" + " -d --headless Headless mode; no X, only snapshots (default on no-X builds)\n" " -h --help Show this help\n" - " -H --height Window height\n" + " -H --height Chart height\n" " -l --linger Don't exit when top-level process exits\n" + " -m --markers Draw markers every N pixels in row borders (0 disables)\n" " -n --name Name of chart, shows in window title and output filenames\n" + " -N --now-names Use current time in filenames instead of start time\n" " -o --output-dir Directory to store saved output to (\".\" if unspecified)\n" " -p --pid PID of the top-level process to monitor (1 if unspecified)\n" - " -s --snapshot Save a PNG snapshot upon receiving SIGCHLD\n" + " -i --snapshots Save a PNG snapshot every N seconds (SIG{TERM,USR1} also snapshots)\n" + " -s --snapshot Save a PNG snapshot upon receiving SIG{CHLD,TERM,USR1}\n" + " -w --wip-name Name to use for work-in-progress snapshot filename\n" " -v --version Print version\n" - " -W --width Window width\n" + " -D --dump-procs Dump libvmon internal processes table (debugging aid)\n" + " -L --mem-locked Lock in memory using mlockall(MCL_CURRENT|MCL_FUTURE)\n" + " -R --reaper Become the child subreaper (see prctl(2); PR_SET_CHILD_SUBREAPER)\n" + " -T --no-threads Don't monitor threads beyond tracking their potential children\n" + " -W --width Chart width\n" " -z --hertz Sample rate in hertz\n" - "-----------------------------------------------------------------------------" + "-------------------------------------------------------------------------------" ); } @@ -209,7 +227,7 @@ static void print_copyright(void) { puts( "\n" - "Copyright (C) 2012-2021 Vito Caputo <vcaputo@pengaru.com>\n" + "Copyright (C) 2012-2025 Vito Caputo <vcaputo@pengaru.com>\n" "\n" "This program comes with ABSOLUTELY NO WARRANTY. This is free software, and\n" "you are welcome to redistribute it under certain conditions. For details\n" @@ -218,23 +236,176 @@ static void print_copyright(void) } -/* collect status of child */ +/* collect status of child, triggering snapshot if snapshotting active */ static void handle_sigchld(int signum) { got_sigchld = 1; } +/* trigger a snapshot */ static void handle_sigusr1(int signum) { got_sigusr1 = 1; } +/* trigger a snapshot and exit immediately after it's been written */ +static void handle_sigterm(int signum) +{ + got_sigterm = 1; +} + + +/* propagates to child first time, quits second time */ +static void handle_sigint(int signum) +{ + got_sigint++; +} + + +/* propagates to child first time, quits second time */ +static void handle_sigquit(int signum) +{ + got_sigquit++; +} + + +/* sanitize name so it's usable as a filename */ +static char * filenamify(const char *name) +{ + char *filename; + + assert(name); + + filename = calloc(strlen(name) + 1, sizeof(*name)); + if (!filename) { + VWM_PERROR("unable to allocate filename for name \"%s\"", name); + return NULL; + } + + for (size_t i = 0; name[i]; i++) { + char c = name[i]; + + switch (c) { + /* replace characters relevant to path interpolation */ + case '/': + c = '\\'; + break; + + case '.': + /* no leading dot, and no ".." */ + if (i == 0 || (i == 1 && !name[2])) + c = '_'; + break; + } + + filename[i] = c; + } + + return filename; +} + + +/* return an interpolated copy of arg */ +static char * arg_interpolate(const vmon_t *vmon, const char *arg) +{ + FILE *memfp; + char *xarg = NULL; + size_t xarglen; + int fmt = 0; + + assert(vmon); + assert(arg); + + memfp = open_memstream(&xarg, &xarglen); + if (!memfp) { + VWM_PERROR("unable to create memstream"); + return NULL; + } + + for (size_t i = 0; arg[i]; i++) { + char c = arg[i]; + + if (!fmt) { + if (c == '%') + fmt = 1; + else + fputc(c, memfp); + + continue; + } + + switch (c) { +#ifdef USE_XLIB + case 'W': /* vmon's X window id in hex */ + assert(!vmon->headless); + fprintf(memfp, "%#x", vcr_dest_xwindow_get_id(vmon->vcr_dest)); + break; +#endif + case 'n': /* --name verbatim */ + if (!vmon->name) { + VWM_ERROR("%%n requires --name"); + goto _err; + } + + fprintf(memfp, "%s", vmon->name); + break; + + case 'N': { /* --name sanitized for filename use */ + char *filename; + + if (!vmon->name) { + VWM_ERROR("%%N requires --name"); + goto _err; + } + + filename = filenamify(vmon->name); + if (!filename) + goto _err; + + fprintf(memfp, "%s", filename); + free(filename); + break; + } + + case 'O': /* --output-dir */ + fprintf(memfp, "%s", vmon->output_dir); + break; + + case 'P': /* getpid() of vmon, convenient for triggering png snapshots on SIGUSR1 */ + /* XXX: note this assumes arg_interpolate() occurs pre-fork, true ATM */ + fprintf(memfp, "%li", (long)getpid()); + break; + + case '%': /* literal % */ + fputc(c, memfp); + break; + + default: + VWM_ERROR("Unrecognized specifier \'%c\'", c); + goto _err; + } + + fmt = 0; + } + + fclose(memfp); + + return xarg; + +_err: + fclose(memfp); + free(xarg); + + return NULL; +} + + /* parse and apply argv, implementing an strace-like cli, mutates vmon. */ -static int vmon_handle_argv(vmon_t *vmon, int argc, char * const argv[]) +static int vmon_handle_argv(vmon_t *vmon, int argc, const char * const *argv) { - char *const*end = &argv[argc - 1], *const*last = argv; + const char * const *end = &argv[argc - 1], * const *last = argv; assert(vmon); assert(!vmon->pid); @@ -262,6 +433,11 @@ static int vmon_handle_argv(vmon_t *vmon, int argc, char * const argv[]) return 0; last = ++argv; + } else if (is_flag(*argv, "-m", "--markers")) { + if (!parse_flag_int(argv, end, argv + 1, 0, INT_MAX, &vmon->marker_distance)) + return 0; + + last = ++argv; } else if (is_flag(*argv, "-o", "--output-dir")) { if (!parse_flag_str(argv, end, argv + 1, 1, &vmon->output_dir)) return 0; @@ -272,9 +448,30 @@ static int vmon_handle_argv(vmon_t *vmon, int argc, char * const argv[]) return 0; last = ++argv; - } else if (is_flag(*argv, "-s", "--snapshot")) { + } else if (is_flag(*argv, "-N", "--now-names")) { + vmon->now_names = 1; + last = argv; + } else if (is_flag(*argv, "-d", "--headless")) { + vmon->headless = 1; + last = argv; + } else if (is_flag(*argv, "-i", "--snapshots")) { + if (!parse_flag_int(argv, end, argv + 1, 1, INT_MAX, &vmon->snapshots_interval)) + return 0; + + last = ++argv; + } else if (is_flag(*argv, "-s", "--snapshot")) { vmon->snapshot = 1; last = argv; + } else if (is_flag(*argv, "-w", "--wip-name")) { + if (!parse_flag_str(argv, end, argv + 1, 1, &vmon->wip_name)) + return 0; + + if (strchr(vmon->wip_name, '/')) { + VWM_ERROR("invalid --wip-name: \"%s\"", vmon->wip_name); + return 0; + } + + last = ++argv; } else if (is_flag(*argv, "-f", "--fullscreen")) { if (!set_fullscreen(vmon)) { VWM_ERROR("unable to set fullscreen dimensions"); @@ -290,13 +487,9 @@ static int vmon_handle_argv(vmon_t *vmon, int argc, char * const argv[]) last = argv; break; } else if (is_flag(*argv, "-z", "--hertz")) { - int hertz; - - if (!parse_flag_int(argv, end, argv + 1, 1, 1000, &hertz)) + if (!parse_flag_int(argv, end, argv + 1, 1, 1000, &vmon->hertz)) return 0; - vwm_charts_rate_set(vmon->charts, hertz); - last = ++argv; } else if (is_flag(*argv, "-h", "--help")) { print_help(); @@ -304,6 +497,18 @@ static int vmon_handle_argv(vmon_t *vmon, int argc, char * const argv[]) } else if (is_flag(*argv, "-v", "--version")) { print_version(); exit(EXIT_SUCCESS); + } else if (is_flag(*argv, "-D", "--dump-procs")) { + vmon->dump_procs = 1; + last = argv; + } else if (is_flag(*argv, "-L", "--mem-locked")) { + vmon->mem_locked = 1; + last = argv; + } else if (is_flag(*argv, "-R", "--reaper")) { + vmon->reaper = 1; + last = argv; + } else if (is_flag(*argv, "-T", "--no-threads")) { + vmon->no_threads = 1; + last = argv; } else if ((*argv)[0] == '-') { VWM_ERROR("Unrecognized argument: \"%s\", try --help\n", argv[0]); exit(EXIT_FAILURE); @@ -315,60 +520,93 @@ static int vmon_handle_argv(vmon_t *vmon, int argc, char * const argv[]) /* if more argv remains, treat as a command to run */ if (last != end) { - pid_t pid; + last++; + vmon->n_execv = end - last + 1; + vmon->execv = last; + } - if (vmon->pid) { - VWM_ERROR("combining --pid with a command to run is not yet supported (TODO)\n"); - return 0; - } + return 1; +} - last++; - if (signal(SIGCHLD, handle_sigchld) == SIG_ERR) { - VWM_PERROR("unable to set SIGCHLD handler"); - return 0; - } +/* turn vmon->execv into a new process and execute what's described there after interpolation. */ +int vmon_execv(vmon_t *vmon) +{ + char **xargv; + pid_t pid; + + assert(vmon); + assert(vmon->execv); + assert(vmon->n_execv); + + xargv = calloc(vmon->n_execv + 1, sizeof(*xargv)); + if (!xargv) { + VWM_PERROR("unable to allocate interpolated argv"); + return 0; + } + + /* TODO: clean up xargv on failures perhaps? we just exit anyways */ - pid = fork(); - if (pid == -1) { - VWM_PERROR("unable to fork"); + /* clone args into xargs, performing any interpolations while at it */ + for (unsigned i = 0; i < vmon->n_execv; i++) { + xargv[i] = arg_interpolate(vmon, vmon->execv[i]); + if (!xargv[i]) { + VWM_ERROR("unable to allocate interpolated arg"); return 0; } + } - if (pid == 0) { - if (prctl(PR_SET_PDEATHSIG, SIGKILL) == -1) { - VWM_PERROR("unable to prctl(PR_SET_PDEATHSIG, SIGKILL)"); - exit(EXIT_FAILURE); - } + if (signal(SIGCHLD, handle_sigchld) == SIG_ERR) { + VWM_PERROR("unable to set SIGCHLD handler"); + return 0; + } - /* TODO: would be better to synchronize with the monitoring loop starting before the execvp() occurs, - * very early program start can be an interesting thing to observe. */ - if (execvp(*last, last) == -1) { - VWM_PERROR("unable to exec \"%s\"", *last); - exit(EXIT_FAILURE); - } + if (signal(SIGINT, handle_sigint) == SIG_ERR) { + VWM_PERROR("unable to set SIGTERM handler"); + return 0; + } + + if (signal(SIGQUIT, handle_sigquit) == SIG_ERR) { + VWM_PERROR("unable to set SIGQUIT handler"); + return 0; + } + + pid = fork(); + if (pid == -1) { + VWM_PERROR("unable to fork"); + return 0; + } + + if (pid == 0) { + if (prctl(PR_SET_PDEATHSIG, SIGKILL) == -1) { + VWM_PERROR("unable to prctl(PR_SET_PDEATHSIG, SIGKILL)"); + exit(EXIT_FAILURE); } - vmon->pid = pid; + /* TODO: would be better to synchronize with the monitoring loop starting before the execvp() occurs, + * very early program start can be an interesting thing to observe. */ + if (execvp(*xargv, xargv) == -1) { + VWM_PERROR("unable to exec \"%s\"", *xargv); + exit(EXIT_FAILURE); + } } - /* default to PID 1 when no PID or command was supplied */ - if (!vmon->pid) - vmon->pid = 1; + vmon->pid = pid; return 1; } -/* parse argv, connect to X, create window, attach libvmon to monitored process */ -static vmon_t * vmon_startup(int argc, char * const argv[]) +/* parse argv, init charts/vcr_backend/vcr_dest, attach libvmon to monitored process via vwm_chart_create() */ +static vmon_t * vmon_startup(int argc, const char * const *argv) { - vmon_t *vmon; - XRenderPictureAttributes pattr = {}; - XWindowAttributes wattr; + unsigned charts_flags = VWM_CHARTS_FLAG_DEFER_MAINTENANCE; + vcr_backend_type_t backend_type; + vmon_t *vmon; assert(argv); + setlocale(LC_ALL, ""); print_copyright(); vmon = calloc(1, sizeof(vmon_t)); @@ -386,53 +624,138 @@ static vmon_t * vmon_startup(int argc, char * const argv[]) goto _err_free; } - vmon->xserver = vwm_xserver_open(); - if (!vmon->xserver) { - VWM_ERROR("unable to open xserver"); + if (!vmon_handle_argv(vmon, argc, argv)) { + VWM_ERROR("unable to handle arguments"); + goto _err_vcr; + } + +#ifdef USE_XLIB + if (!vmon->headless) + backend_type = VCR_BACKEND_TYPE_XLIB; +#else + /* force headless without X support */ + vmon->headless = 1; +#endif + if (vmon->headless) + backend_type = VCR_BACKEND_TYPE_MEM; + + vmon->vcr_backend = vcr_backend_new(backend_type, NULL); + if (!vmon->vcr_backend) { + VWM_ERROR("unable to create vcr backend"); goto _err_free; } - vmon->wm_delete_atom = XInternAtom(vmon->xserver->display, "WM_DELETE_WINDOW", False); - vmon->wm_protocols_atom = XInternAtom(vmon->xserver->display, "WM_PROTOCOLS", False); + if (vmon->no_threads) + charts_flags |= VWM_CHARTS_NO_THREADS; - vmon->charts = vwm_charts_create(vmon->xserver); + vmon->charts = vwm_charts_create(vmon->vcr_backend, charts_flags); if (!vmon->charts) { VWM_ERROR("unable to create charts instance"); - goto _err_xserver; + goto _err_vcr; } - if (!vmon_handle_argv(vmon, argc, argv)) { - VWM_ERROR("unable to handle arguments"); - goto _err_charts; - } + if (vmon->hertz) + vwm_charts_rate_set(vmon->charts, vmon->hertz); + + if (vmon->marker_distance) + vwm_charts_marker_distance_set(vmon->charts, vmon->marker_distance); if (signal(SIGUSR1, handle_sigusr1) == SIG_ERR) { VWM_PERROR("unable to set SIGUSR1 handler"); - goto _err_charts; + goto _err_vcr; } - vmon->chart = vwm_chart_create(vmon->charts, vmon->pid, vmon->width, vmon->height, vmon->name); - if (!vmon->chart) { - VWM_ERROR("unable to create chart"); - goto _err_charts; + if (signal(SIGALRM, handle_sigusr1) == SIG_ERR) { + VWM_PERROR("unable to set SIGALRM handler"); + goto _err_vcr; } - vmon->window = XCreateSimpleWindow(vmon->xserver->display, XSERVER_XROOT(vmon->xserver), 0, 0, vmon->width, vmon->height, 1, 0, 0); - if (vmon->name) - XStoreName(vmon->xserver->display, vmon->window, vmon->name); - XGetWindowAttributes(vmon->xserver->display, vmon->window, &wattr); - vmon->picture = XRenderCreatePicture(vmon->xserver->display, vmon->window, XRenderFindVisualFormat(vmon->xserver->display, wattr.visual), 0, &pattr); + if (signal(SIGTERM, handle_sigterm) == SIG_ERR) { + VWM_PERROR("unable to set SIGTERM handler"); + goto _err_vcr; + } + + if (vmon->snapshots_interval) { + int r; + + r = setitimer(ITIMER_REAL, + &(struct itimerval){ + .it_interval.tv_sec = vmon->snapshots_interval, + .it_value.tv_sec = vmon->snapshots_interval, + }, NULL); + if (r < 0) { + VWM_PERROR("unable to set interval timer"); + goto _err_vcr; + } + } + +#ifdef USE_XLIB + if (!vmon->headless) { + vmon->vcr_dest = vcr_dest_xwindow_new(vmon->vcr_backend, vmon->name, vmon->width, vmon->height); + if (!vmon->vcr_dest) { + VWM_ERROR("unable to create destination XWindow"); + goto _err_vcr; + } + } +#endif + + if (vmon->execv) { + if (vmon->pid) { + VWM_ERROR("combining --pid with a command to run is not yet supported (TODO)\n"); + goto _err_win; + } + + if (!vmon_execv(vmon)) + goto _err_win; + } + + { + pid_t root_pid = 1; - XMapWindow(vmon->xserver->display, vmon->window); + if (vmon->pid) + root_pid = vmon->pid; + + /* If vmon is executing the command and being the reaper, make vmon itself the monitored root. + * This way we get to see any orphans. + */ + if (vmon->execv && vmon->reaper) + root_pid = getpid(); + + vmon->chart = vwm_chart_create(vmon->charts, root_pid, vmon->width, vmon->height, vmon->name); + if (!vmon->chart) { + VWM_ERROR("unable to create chart"); + goto _err_win; + } + } + + if (vmon->mem_locked) { + if (mlockall(MCL_CURRENT|MCL_FUTURE) < 0) { + VWM_ERROR("unable to lock in memory: %s", strerror(errno)); + goto _err_win; + } + } + + if (vmon->reaper) { + if (prctl(PR_SET_CHILD_SUBREAPER, (unsigned long)1) < 0) { + VWM_ERROR("unable become child subreaper: %s", strerror(errno)); + goto _err_win; + } + } + + /* lets do some sanity checks; don't fail, but speak up, since I'm not interested */ + if (vmon->headless && vmon->linger) + VWM_ERROR("FYI: combining --headless and --linger likely doesn't make sense"); + + if (vmon->reaper && !vmon->execv) + VWM_ERROR("FYI: using --reaper without a command (e.g. w/--pid or the default '--pid 1' equiv) likely doesn't make sense"); - XSelectInput(vmon->xserver->display, vmon->window, StructureNotifyMask|ExposureMask); return vmon; -_err_charts: - vwm_charts_destroy(vmon->charts); -_err_xserver: - vwm_xserver_close(vmon->xserver); +_err_win: + (void) vcr_dest_free(vmon->vcr_dest); +_err_vcr: + (void) vcr_backend_free(vmon->vcr_backend); _err_free: free(vmon); _err: @@ -444,12 +767,11 @@ _err: static void vmon_shutdown(vmon_t *vmon) { assert(vmon); - assert(vmon->xserver); - XDestroyWindow(vmon->xserver->display, vmon->window); vwm_chart_destroy(vmon->charts, vmon->chart); vwm_charts_destroy(vmon->charts); - vwm_xserver_close(vmon->xserver); + (void) vcr_dest_free(vmon->vcr_dest); + (void) vcr_backend_free(vmon->vcr_backend); free(vmon); } @@ -465,183 +787,128 @@ static void vmon_resize(vmon_t *vmon, int width, int height) } -static int vmon_snapshot_as_png(vmon_t *vmon, FILE *output) -{ - XImage *chart_as_ximage; - png_bytepp row_pointers; - png_infop info_ctx; - png_structp png_ctx; - - assert(vmon); - assert(output); - - vwm_chart_render_as_ximage(vmon->charts, vmon->chart, NULL, &chart_as_ximage); - - row_pointers = malloc(sizeof(void *) * chart_as_ximage->height); - if (!row_pointers) { - XDestroyImage(chart_as_ximage); - - return -ENOMEM; - } - - for (unsigned i = 0; i < chart_as_ximage->height; i++) - row_pointers[i] = &((png_byte *)chart_as_ximage->data)[i * chart_as_ximage->bytes_per_line]; - - png_ctx = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - if (!png_ctx) { - free(row_pointers); - XDestroyImage(chart_as_ximage); - - return -ENOMEM; - } - - info_ctx = png_create_info_struct(png_ctx); - if (!info_ctx) { - png_destroy_write_struct(&png_ctx, NULL); - XDestroyImage(chart_as_ximage); - free(row_pointers); - - return -ENOMEM; - } - - png_init_io(png_ctx, output); - - if (setjmp(png_jmpbuf(png_ctx)) != 0) { - png_destroy_write_struct(&png_ctx, &info_ctx); - XDestroyImage(chart_as_ximage); - free(row_pointers); - - return -ENOMEM; - } - - /* XXX: I'm sure this is making flawed assumptions about the color format - * and type etc, but this makes it work for me and that's Good Enough for now. - * One can easily turn runtime mapping of X color formats, endianness, and packing - * details to whatever a file format like PNG can express into a tar-filled rabbithole - * of fruitless wankery. - */ - png_set_bgr(png_ctx); - png_set_IHDR(png_ctx, info_ctx, - chart_as_ximage->width, - chart_as_ximage->height, - 8, - PNG_COLOR_TYPE_RGBA, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_BASE, - PNG_FILTER_TYPE_BASE); - - png_write_info(png_ctx, info_ctx); - png_write_image(png_ctx, row_pointers); - png_write_end(png_ctx, NULL); - - XDestroyImage(chart_as_ximage); - free(row_pointers); - - return 0; -} - - static int vmon_snapshot(vmon_t *vmon) { - struct tm *start_time; - char start_str[32]; - char path[4096]; - char name[200] = {}; +#ifdef USE_PNG + time_t now, *t_ptr = &now; + struct tm *t; + char t_str[32]; + char *name = NULL; + char path[4096], tmp_path[4096]; FILE *output; int r; assert(vmon); if (vmon->name) { - for (int i = 0; i < sizeof(name) - 1 && vmon->name[i]; i++) { - char c = vmon->name[i]; - switch (c) { - /* replace characters relevant to path interpolation */ - case '/': - c = '\\'; - break; - - case '.': - /* no leading dot, and no ".." */ - if (i == 0 || (i == 1 && !vmon->name[2])) - c = '_'; - break; - default: - } - name[i] = c; - } + name = filenamify(vmon->name); + if (!name) + return -errno; } - if (mkdir(vmon->output_dir, 0755) == -1 && errno != EEXIST) + if (mkdir(vmon->output_dir, 0755) == -1 && errno != EEXIST) { + free(name); return -errno; + } - start_time = localtime(&vmon->start_time); - strftime(start_str, sizeof(start_str), "%m.%d.%y-%T", start_time); + if (vmon->now_names) + now = time(NULL); + else + t_ptr = &vmon->start_time; + + t = localtime(t_ptr); + strftime(t_str, sizeof(t_str), "%m.%d.%y-%T", t); snprintf(path, sizeof(path), "%s/%s%s%s-%u.png", vmon->output_dir, - name, - vmon->name ? "-" : "", - start_str, + name ? name : "", + name ? "-" : "", + t_str, vmon->n_snapshots++); + if (vmon->wip_name) { + snprintf(tmp_path, sizeof(tmp_path), "%s/%s", vmon->output_dir, vmon->wip_name); + } else { + snprintf(tmp_path, sizeof(tmp_path), "%s/.%s%s%s-%u.png-WIP", + vmon->output_dir, + name ? name : "", + name ? "-" : "", + t_str, + vmon->n_snapshots); + } + free(name); - output = fopen(path, "w+"); + output = fopen(tmp_path, "w+"); if (!output) return -errno; - r = vmon_snapshot_as_png(vmon, output); - if (r < 0) { - fclose(output); - return r; + { + vcr_dest_t *png_dest; + + png_dest = vcr_dest_png_new(vmon->vcr_backend, output); + if (!png_dest) { + (void) unlink(tmp_path); + (void) fclose(output); + return -ENOMEM; + } + + if (vmon->headless) + vwm_chart_compose(vmon->charts, vmon->chart); + + /* FIXME: render/libpng errors need to propagate and be handled */ + vwm_chart_render(vmon->charts, vmon->chart, VCR_PRESENT_OP_SRC, png_dest, -1, -1, -1, -1); + png_dest = vcr_dest_free(png_dest); } + fflush(output); fsync(fileno(output)); fclose(output); + r = rename(tmp_path, path); + if (r < 0) + return -errno; return 0; +#else + return -ENOTSUP; +#endif } -/* handle the next X event, may block */ +/* handle the next backend event, may block */ static void vmon_process_event(vmon_t *vmon) { - XEvent ev; + int width, height; + vcr_backend_event_t ev; assert(vmon); - XNextEvent(vmon->xserver->display, &ev); - - switch (ev.type) { - case ConfigureNotify: - vmon_resize(vmon, ev.xconfigure.width, ev.xconfigure.height); - vwm_chart_compose(vmon->charts, vmon->chart, NULL); - vwm_chart_render(vmon->charts, vmon->chart, PictOpSrc, vmon->picture, 0, 0, vmon->width, vmon->height); + ev = vcr_backend_next_event(vmon->vcr_backend, &width, &height); + switch (ev) { + case VCR_BACKEND_EVENT_RESIZE: + vmon_resize(vmon, width, height); + vwm_chart_compose(vmon->charts, vmon->chart); + vwm_chart_render(vmon->charts, vmon->chart, VCR_PRESENT_OP_SRC, vmon->vcr_dest, -1, -1, -1, -1); break; - case Expose: - vwm_chart_render(vmon->charts, vmon->chart, PictOpSrc, vmon->picture, 0, 0, vmon->width, vmon->height); + case VCR_BACKEND_EVENT_REDRAW: + vwm_chart_render(vmon->charts, vmon->chart, VCR_PRESENT_OP_SRC, vmon->vcr_dest, -1, -1, -1, -1); break; - case ClientMessage: - if (ev.xclient.message_type != vmon->wm_protocols_atom) - break; - - if (ev.xclient.data.l[0] != vmon->wm_delete_atom) - break; - + case VCR_BACKEND_EVENT_QUIT: vmon->done = 1; break; + case VCR_BACKEND_EVENT_NOOP: + break; + default: - VWM_TRACE("unhandled event: %x\n", ev.type); + VWM_TRACE("unhandled event: %x\n", ev); } } -int main(int argc, char * const argv[]) +int main(int argc, const char * const *argv) { - vmon_t *vmon; - struct pollfd pfd = { .events = POLLIN }; - int ret = EXIT_SUCCESS; + vmon_t *vmon; + int ret = EXIT_SUCCESS; vmon = vmon_startup(argc, argv); if (!vmon) { @@ -649,39 +916,86 @@ int main(int argc, char * const argv[]) return EXIT_FAILURE; } - pfd.fd = ConnectionNumber(vmon->xserver->display); - while (!vmon->done) { - int delay; + int delay_us; + + /* update only actually updates when enough time has passed, and always returns how much time + * to sleep before calling update again (-1 for infinity (paused)). + * + * if 0 is returned, no update was performed/no changes occured. + */ + if (vwm_charts_update(vmon->charts, &delay_us)) { + if (!vmon->headless) { + vwm_chart_compose(vmon->charts, vmon->chart); + vwm_chart_render(vmon->charts, vmon->chart, VCR_PRESENT_OP_SRC, vmon->vcr_dest, -1, -1, -1, -1); + } - if (vwm_charts_update(vmon->charts, &delay)) { - vwm_chart_compose(vmon->charts, vmon->chart, NULL); - vwm_chart_render(vmon->charts, vmon->chart, PictOpSrc, vmon->picture, 0, 0, vmon->width, vmon->height); + if (vmon->dump_procs) { + charts_vmon_dump_procs(vmon->charts, stdout); + fflush(stdout); + } } - if (XPending(vmon->xserver->display) || poll(&pfd, 1, delay) > 0) + if (vcr_backend_poll(vmon->vcr_backend, delay_us) > 0) vmon_process_event(vmon); - if (got_sigchld) { - int status; + if (got_sigint > 2 || got_sigquit > 2) { + vmon->done = 1; + } else if (got_sigint == 1) { + got_sigint++; + + kill(vmon->pid, SIGINT); + } else if (got_sigquit == 1) { + got_sigquit++; + + kill(vmon->pid, SIGQUIT); + } else if (got_sigterm) { + if (vmon->snapshot || vmon->snapshots_interval) { + /* simulate sigusr1 to trigger a final snapshot, */ + got_sigusr1 = 1; + } - if (vmon->snapshot && vmon_snapshot(vmon) < 0) - VWM_ERROR("error saving snapshot"); + vmon->done = 1; + } - got_sigchld = 0; - wait(&status); + while (got_sigchld) { + int status; + pid_t reaped; - if (WIFEXITED(status)) { - ret = WEXITSTATUS(status); + got_sigchld = 0; + /* exhaustively collect statuses for all the exited children, if another + * sigchld gets delivered while we're doing this, we'll do it again, until + * that stops. + */ + while ((reaped = waitpid(-1, &status, WNOHANG)) > 0) { + int r; + + /* potential exited orphans if we're being subreaper, ignore those */ + if (reaped != vmon->pid) + continue; + + if (WIFEXITED(status) || WIFSIGNALED(status)) { + if (vmon->snapshot && (r = vmon_snapshot(vmon)) < 0) + VWM_ERROR("error saving snapshot: %s", strerror(-r)); + + ret = WEXITSTATUS(status); + + if (!vmon->linger) + vmon->done = 1; + } + } - if (!vmon->linger) - vmon->done = 1; + if (reaped < 0) { + VWM_ERROR("failed to waitpid on SIGCHLD: %s", strerror(errno)); + vmon->done = 1; } } - if (got_sigusr1) { - if (vmon_snapshot(vmon) < 0) - VWM_ERROR("error saving snapshot"); + if (got_sigusr1 || (vmon->snapshots_interval && !vmon->n_snapshots)) { + int r; + + if ((r = vmon_snapshot(vmon)) < 0) + VWM_ERROR("error saving snapshot: %s", strerror(-r)); got_sigusr1 = 0; } @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -82,11 +82,16 @@ static vwm_t * vwm_startup(void) goto _err_free; } - if (!(vwm->charts = vwm_charts_create(vwm->xserver))) { - VWM_ERROR("Failed to create charts"); + if (!(vwm->vcr_backend = vcr_backend_new(VCR_BACKEND_TYPE_XLIB, vwm->xserver))) { + VWM_ERROR("Failed to create vcr backend"); goto _err_xclose; } + if (!(vwm->charts = vwm_charts_create(vwm->vcr_backend, 0))) { + VWM_ERROR("Failed to create charts"); + goto _err_vbe; + } + /* query the needed X extensions */ if (!XQueryExtension(VWM_XDISPLAY(vwm), COMPOSITE_NAME, &composite_opcode, &composite_event, &composite_error)) { VWM_ERROR("No composite extension available"); @@ -173,6 +178,9 @@ static vwm_t * vwm_startup(void) _err_charts: vwm_charts_destroy(vwm->charts); +_err_vbe: + vcr_backend_free(vwm->vcr_backend); + _err_xclose: vwm_xserver_close(vwm->xserver); @@ -313,29 +321,22 @@ void vwm_process_event(vwm_t *vwm) int main(int argc, char *argv[]) { - vwm_t *vwm; - struct pollfd pfd; + vwm_t *vwm; if (!(vwm = vwm_startup())) { VWM_ERROR("Unable to startup vwm"); goto _err; } - pfd.events = POLLIN; - pfd.revents = 0; - pfd.fd = ConnectionNumber(VWM_XDISPLAY(vwm)); - while (!vwm->done) { do { - int delay; + int delay_us; - if (vwm_charts_update(vwm->charts, &delay)) + if (vwm_charts_update(vwm->charts, &delay_us)) vwm_composite_repaint_needed(vwm); - if (!XPending(VWM_XDISPLAY(vwm))) { - if (poll(&pfd, 1, delay) == 0) - break; - } + if (vcr_backend_poll(vwm->vcr_backend, delay_us) == 0) + break; vwm_process_event(vwm); } while (QLength(VWM_XDISPLAY(vwm))); @@ -8,6 +8,7 @@ #include "list.h" #include "charts.h" #include "util.h" +#include "vcr.h" #include "xserver.h" #define WINDOW_BORDER_WIDTH 1 @@ -43,6 +44,7 @@ typedef enum _vwm_context_color_t { typedef struct _vwm_t { vwm_xserver_t *xserver; /* global xserver instance */ + vcr_backend_t *vcr_backend; /* global vcr backend for charts */ vwm_charts_t *charts; /* golbal charts instance */ /* extra X stuff needed by vwm */ diff --git a/src/window.c b/src/window.c index 5410ba6..0dfdbe9 100644 --- a/src/window.c +++ b/src/window.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -81,7 +81,7 @@ vwm_window_t * vwm_win_lookup(vwm_t *vwm, Window win) /* return the currently focused window, may return NULL */ -vwm_window_t * vwm_win_get_focused(vwm_t *vwm) +vwm_window_t * vwm_win_get_focused(const vwm_t *vwm) { return vwm->focused_desktop->focused_window; } @@ -126,12 +126,18 @@ void vwm_win_autoconf_magic(vwm_t *vwm, vwm_window_t *vwin, const vwm_screen_t * /* "autoconfigure" windows (configuration shortcuts like fullscreen/halfscreen/quarterscreen) and restoring the window */ void vwm_win_autoconf(vwm_t *vwm, vwm_window_t *vwin, vwm_screen_rel_t rel, vwm_win_autoconf_t conf, ...) { + XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; const vwm_screen_t *scr; va_list ap; - XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; /* remember the current configuration as the "client" configuration if it's not an autoconfigured one. */ - if (vwin->autoconfigured == VWM_WIN_AUTOCONF_NONE) + /* XXX: this isn't perfect, and makes me wonder if there should be two slots you can restore back to: + * 1. the OG window configuration from the X client, or + * 2. the last non-autoconf configuration, which may or may not reflect the OG one + * Right now, the OG one gets overwritten by #2, so you can only restore back to the last + * explicit window configuration with Mod1-Enter. + */ + if (conf != VWM_WIN_AUTOCONF_NONE && vwin->autoconfigured == VWM_WIN_AUTOCONF_NONE) vwin->client = vwin->xwindow->attrs; scr = vwm_screen_find(vwm, rel, vwin->xwindow); /* XXX FIXME: this becomes a bug when vwm_screen_find() uses non-xwin va_args */ @@ -162,6 +168,7 @@ void vwm_win_autoconf(vwm_t *vwm, vwm_window_t *vwin, vwm_screen_rel_t rel, vwm_ changes.y = scr->y_org + scr->height / 2; break; } + vwin->autoconfigured_param = corner; break; } @@ -196,6 +203,7 @@ void vwm_win_autoconf(vwm_t *vwm, vwm_window_t *vwin, vwm_screen_rel_t rel, vwm_ changes.y = scr->y_org; break; } + vwin->autoconfigured_param = side; break; } @@ -215,10 +223,30 @@ void vwm_win_autoconf(vwm_t *vwm, vwm_window_t *vwin, vwm_screen_rel_t rel, vwm_ break; case VWM_WIN_AUTOCONF_NONE: /* restore window if autoconfigured */ - changes.width = vwin->client.width; - changes.height = vwin->client.height; - changes.x = vwin->client.x; - changes.y = vwin->client.y; + if (vwin->autoconfigured == VWM_WIN_AUTOCONF_NONE) { + if (rel != VWM_SCREEN_REL_XWIN) { + const vwm_screen_t *from_scr; + + /* For now let's just try adjusting the x/y to scr, + * which may or may not change anything at all, but + * it /appears/ we might be trying to switch screens. + */ + from_scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, vwin->xwindow); + if (from_scr != scr) { + changes.x = vwin->xwindow->attrs.x - from_scr->x_org + scr->x_org; + changes.y = vwin->xwindow->attrs.y - from_scr->y_org + scr->y_org; + /* XXX: undecided on if w/h should get scaled proportionally, leaving alone for now */ + changes.width = vwin->xwindow->attrs.width; + changes.height = vwin->xwindow->attrs.height; + } + } + } else { + changes.width = vwin->client.width; + changes.height = vwin->client.height; + changes.x = vwin->client.x; + changes.y = vwin->client.y; + } + break; } va_end(ap); @@ -464,7 +492,10 @@ static void vwm_win_assimilate(vwm_t *vwm, vwm_window_t *vwin) /* FIXME TODO: there's some situation where we get here but focused_desktop->focused_window == NULL, * which shouldn't be possible; for there to be a non-empty screen, the focused_desktop must have a focused_window. */ - scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, vwm->focused_desktop->focused_window->xwindow); + if (vwm->focused_desktop->focused_window) + scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, vwm->focused_desktop->focused_window->xwindow); + else + VWM_BUG("Screen is not empty, but vwm->focused_desktop->focused_window is NULL!"); } changes.x = scr->x_org; @@ -555,7 +586,7 @@ vwm_window_t * vwm_win_manage_xwin(vwm_t *vwm, vwm_xwindow_t *xwin) /* if the desktop has no focused window yet, automatically focus the newly managed one */ if (!vwm->focused_desktop->focused_window) { - VWM_TRACE("Mapped new window \"%s\" is alone on desktop \"%s\", focusing", xwin->name, vwm->focused_desktop->name); + VWM_TRACE("Mapped new window \"%s\" is alone on desktop \"%p\", focusing", xwin->name, vwm->focused_desktop); vwm_win_focus(vwm, vwin); } diff --git a/src/window.h b/src/window.h index daddf14..cafabb8 100644 --- a/src/window.h +++ b/src/window.h @@ -33,6 +33,7 @@ typedef struct _vwm_window_t { long hints_supplied; /* bitfield reflecting the hints the client supplied */ unsigned int autoconfigured:3; /* autoconfigured window states (none/quarter/half/full/all) */ + unsigned int autoconfigured_param:2; unsigned int mapping:1; /* is the window being mapped? (by vwm) */ unsigned int unmapping:1; /* is the window being unmapped? (by vwm) */ } vwm_window_t; @@ -42,7 +43,7 @@ void vwm_win_unmap(vwm_t *vwm, vwm_window_t *vwin); void vwm_win_map(vwm_t *vwm, vwm_window_t *vwin); vwm_window_t * vwm_win_mru(vwm_t *vwm, vwm_window_t *vwin); vwm_window_t * vwm_win_lookup(vwm_t *vwm, Window win); -vwm_window_t * vwm_win_get_focused(vwm_t *vwm); +vwm_window_t * vwm_win_get_focused(const vwm_t *vwm); void vwm_win_set_focused(vwm_t *vwm, vwm_window_t *vwin); typedef enum _vwm_side_t { diff --git a/src/xevent.c b/src/xevent.c index 943ba78..06336e7 100644 --- a/src/xevent.c +++ b/src/xevent.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -152,13 +152,8 @@ void vwm_xevent_handle_map_notify(vwm_t *vwm, XMapEvent *ev) if ((xwin = vwm_xwin_lookup(vwm, ev->window))) { - /* XXX: in some circumstances (randomly mplayer -fs) it we see an event sequence for a window like: - * create_notify->map_request (manage)->configure_request->unmap_notify (unmanage)->configure_notify->map_notify (unmanaged!) - * which unless the window's an override_redirect is incorrect. - * So implicitly manage the window if it's not managed and !override_redirect, since it's now mapped. - */ - if (!xwin->managed && !xwin->attrs.override_redirect) - xwin->managed = vwm_win_manage_xwin(vwm, xwin); + if (!xwin->managed && vwm_xwin_should_manage(vwm, xwin)) + vwm_win_manage_xwin(vwm, xwin); if (xwin->managed && xwin->managed->mapping) { VWM_TRACE("swallowed vwm-induced MapNotify"); diff --git a/src/xserver.c b/src/xserver.c index 1db5f4c..94606b0 100644 --- a/src/xserver.c +++ b/src/xserver.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, diff --git a/src/xwindow.c b/src/xwindow.c index 18ebf5f..0bf988f 100644 --- a/src/xwindow.c +++ b/src/xwindow.c @@ -4,7 +4,7 @@ * Copyright (C) 2012-2018 Vito Caputo - <vcaputo@pengaru.com> * * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published + * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, @@ -109,6 +109,35 @@ void vwm_xwin_setup_chart(vwm_t *vwm, vwm_xwindow_t *xwin) } } +/* override_redirect windows typically should not be managed, and it'd be nice if we could + * just blindly respect that, but X is a dumpster fire and for multiple reasons I'm going + * to use some heuristics to only not manage override_redirect windows when they're substantially + * smaller than the size of the display (popup/popover type shit). + * + * When any old X client can create a fullscreen override_redirect window it not only makes + * fullscreen games and shit not explicitly focusable/managable from a vwm perspective, it + * also creates a real potential security issue. + */ +int vwm_xwin_should_manage(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + const vwm_screen_t *scr; + + if (!xwin->attrs.override_redirect) + return 1; + + scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, xwin); + if (!scr) + return 1; + + /* TODO: for now just using an >= fullscreen heuristic, but should really + * trigger for > XX% coverage. This suffices for managing annoying + * override_redirect fullscreen windows. + */ + if (xwin->attrs.width >= scr->width && xwin->attrs.height >= scr->height) + return 1; + + return 0; +} /* creates and potentially manages a new window (called in response to CreateNotify events, and during startup for all existing windows) */ /* if the window is already mapped and not an override_redirect window, it becomes managed here. */ @@ -159,7 +188,10 @@ vwm_xwindow_t * vwm_xwin_create(vwm_t *vwm, Window win, vwm_grab_mode_t grabbed) list_add_tail(&xwin->xwindows, &vwm->xwindows); /* created windows are always placed on the top of the stacking order */ - if (!attrs.override_redirect && xwin->client_mapped) + VWM_TRACE_WIN(win, "name=\"%s\" override_redirect=%i client_mapped=%i\n", + xwin->name, (int)attrs.override_redirect, (int)xwin->client_mapped); + + if (xwin->client_mapped && vwm_xwin_should_manage(vwm, xwin)) vwm_win_manage_xwin(vwm, xwin); _out_grabbed: diff --git a/src/xwindow.h b/src/xwindow.h index 1318421..65d0725 100644 --- a/src/xwindow.h +++ b/src/xwindow.h @@ -41,6 +41,7 @@ void vwm_xwin_message(vwm_t *vwm, vwm_xwindow_t *xwin, Atom type, long foo); vwm_xwindow_t * vwm_xwin_lookup(vwm_t *vwm, Window win); int vwm_xwin_is_mapped(vwm_t *vwm, vwm_xwindow_t *xwin); void vwm_xwin_monitor(vwm_t *vwm, vwm_xwindow_t *xwin); +int vwm_xwin_should_manage(vwm_t *vwm, vwm_xwindow_t *xwin); vwm_xwindow_t * vwm_xwin_create(vwm_t *vwm, Window win, vwm_grab_mode_t grabbed); void vwm_xwin_destroy(vwm_t *vwm, vwm_xwindow_t *xwin); void vwm_xwin_restack(vwm_t *vwm, vwm_xwindow_t *xwin, Window new_above); |