summaryrefslogtreecommitdiffstats
path: root/xload.c
blob: 7af489d499499f3799eff6090879b62b77ef178c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/* $XConsortium: xload.c,v 1.37 94/04/17 20:43:44 converse Exp $ */
/* $XFree86: contrib/programs/xload/xload.c,v 3.0 1994/06/05 08:00:09 dawes Exp $ */
/*

Copyright (c) 1989  X Consortium

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of the X Consortium shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the X Consortium.

*/

/*
 * xload - display system load average in a window
 */

#include <stdio.h> 
#include <X11/Intrinsic.h>
#include <X11/Xatom.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>

#include <X11/Xaw/Cardinals.h>
#include <X11/Xaw/Label.h>
#include <X11/Xaw/Paned.h>
#include <X11/Xaw/StripChart.h>
#include <X11/Xmu/SysUtil.h>

#include "xload.bit"

char *ProgramName;

char *remote_host, *remote_port;
static int switch_color = 0;
struct switch_widget_struct {
  Widget w;
  Pixel reach_color;
  Pixel unreach_color;
};
static struct switch_widget_struct switch_widget[2];
static int switch_count;

extern void exit(), (*GetLoadPoint)();
extern void InitLoadPoint(), LocalInitLoadPoint();
static void quit();
static void ClearLights();
static void SetLights();

/*
 * Definition of the Application resources structure.
 */

typedef struct _XLoadResources {
  Boolean show_label;
  Boolean use_lights;
  char *remote_host;
  char *remote_port;
  Pixel unreach_color;
} XLoadResources;

/*
 * Command line options table.  Only resources are entered here...there is a
 * pass over the remaining options after XtParseCommand is let loose. 
 */

static XrmOptionDescRec options[] = {
 {"-scale",		"*load.minScale",	XrmoptionSepArg,	NULL},
 {"-update",		"*load.update",		XrmoptionSepArg,	NULL},
 {"-hl",		"*load.highlight",	XrmoptionSepArg,	NULL},
 {"-highlight",		"*load.highlight",	XrmoptionSepArg,	NULL},
 {"-label",		"*label.label",		XrmoptionSepArg,	NULL},
 {"-nolabel",		"*showLabel",	        XrmoptionNoArg,       "False"},
 {"-lights",		"*useLights",		XrmoptionNoArg,	      "True"},
 {"-jumpscroll",	"*load.jumpScroll",	XrmoptionSepArg,	NULL},
 {"-remotehost",        "*remoteHost",          XrmoptionSepArg,        NULL},
 {"-remoteport",        "*remotePort",          XrmoptionSepArg,        NULL},
 {"-unreach",           "*unreachColor",        XrmoptionSepArg,        NULL},
};

/*
 * The structure containing the resource information for the
 * Xload application resources.
 */

#define Offset(field) (XtOffsetOf(XLoadResources, field))

static XtResource my_resources[] = {
  {"showLabel", XtCBoolean, XtRBoolean, sizeof(Boolean),
     Offset(show_label), XtRImmediate, (XtPointer) TRUE},
  {"useLights", XtCBoolean, XtRBoolean, sizeof(Boolean),
    Offset(use_lights), XtRImmediate, (XtPointer) FALSE},
  {"remoteHost", "RemoteHost", XtRString, sizeof(char *),
   Offset(remote_host), XtRString, (XtPointer) NULL},
  {"remotePort", "RemotePort", XtRString, sizeof(char *),
   Offset(remote_port), XtRString, (XtPointer) NULL},
  {"unreachColor", "UnreachColor", XtRPixel, sizeof(Pixel),
   Offset(unreach_color), XtRPixel, XtDefaultBackground}
};

#undef Offset

static XLoadResources resources;

static XtActionsRec xload_actions[] = {
    { "quit",	quit },
};
static Atom wm_delete_window;
static int light_update = 10 * 1000;

/*
 * Exit with message describing command line format.
 */

void usage()
{
    fprintf (stderr, "usage:  %s [-options ...]\n\n", ProgramName);
    fprintf (stderr, "where options include:\n");
    fprintf (stderr,
      "    -display dpy            X server on which to display\n");
    fprintf (stderr,
      "    -geometry geom          size and location of window\n");
    fprintf (stderr, 
      "    -fn font                font to use in label\n");
    fprintf (stderr, 
      "    -scale number           minimum number of scale lines\n");
    fprintf (stderr, 
      "    -update seconds         interval between updates\n");
    fprintf (stderr,
      "    -label string           annotation text\n");
    fprintf (stderr, 
      "    -bg color               background color\n");
    fprintf (stderr, 
      "    -fg color               graph color\n");
    fprintf (stderr, 
      "    -hl color               scale and text color\n");
    fprintf (stderr,
      "    -unreach color          background color while host unreachable\n");
    fprintf (stderr, 
      "    -nolabel                removes the label from above the chart\n");
    fprintf (stderr, 
      "    -jumpscroll value       number of pixels to scroll on overflow\n");
    fprintf (stderr, 
      "    -remotehost hostname    read the load average from a remote host\n");
    fprintf (stderr, 
      "    -remoteport port        specify port to read load average from\n");

    fprintf (stderr, "\n");
    exit(1);
}

void main(argc, argv)
    int argc;
    char **argv;
{
    XtAppContext app_con;
    Widget toplevel, load, pane, label_wid, load_parent;
    Arg args[1];
    Pixmap icon_pixmap = None;
    char *label, host[256];
    int i;

    ProgramName = argv[0];

    /* For security reasons, we ought to reset our uid/gid after doing
       the necessary system initialization and before calling any X
       routines.  Therefore we do the local init even if we don't really
       need it.  Buggy, yes... blame the ones who designed their system so
       reading the load average is a privileged operation... */
    LocalInitLoadPoint();
    setgid(getgid());		/* reset gid first while still (maybe) root */
    setuid(getuid());

    toplevel = XtAppInitialize(&app_con, "XLoad", options, XtNumber(options),
			       &argc, argv, NULL, NULL, (Cardinal) 0);
    if (argc != 1) usage();

    XtGetApplicationResources( toplevel, (XtPointer) &resources, 
			      my_resources, XtNumber(my_resources),
			      NULL, (Cardinal) 0);

    remote_host = resources.remote_host;
    remote_port = resources.remote_port;

    InitLoadPoint();

    if (resources.use_lights)
    {
	char	    name[1024];
	XrmString   type;
	XrmValue    db_value;
	XrmValue    int_value;
	Bool	    found = False;

	(void) sprintf (name, "%s.paned.load.update", XtName(toplevel));
	found = XrmGetResource (XtScreenDatabase(XtScreen(toplevel)),
				name, "XLoad.Paned.StripChart.Interval",
				&type, &db_value);
	if (found) {
	    int_value.size = sizeof(int);
	    int_value.addr = (XPointer) &light_update;
	    found = XtConvertAndStore(toplevel, type, &db_value, XtRInt,
				      &int_value);
	    if (found) light_update *= 1000;
	}
	ClearLights (XtDisplay (toplevel));
	SetLights ((XtPointer) toplevel, (XtIntervalId *) 0);
    }
    else
    {
    	/*
     	 * This is a hack so that f.delete will do something useful in this
     	 * single-window application.
     	 */
    	XtAppAddActions (app_con, xload_actions, XtNumber(xload_actions));
    	XtOverrideTranslations(toplevel,
		    	XtParseTranslationTable ("<Message>WM_PROTOCOLS: quit()"));
    
    	XtSetArg (args[0], XtNiconPixmap, &icon_pixmap);
    	XtGetValues(toplevel, args, ONE);
    	if (icon_pixmap == None) {
	    XtSetArg(args[0], XtNiconPixmap, 
		     XCreateBitmapFromData(XtDisplay(toplevel),
				       	   XtScreen(toplevel)->root,
				       	   (char *)xload_bits,
				       	   xload_width, xload_height));
	    XtSetValues (toplevel, args, ONE);
    	}
    
    	if (resources.show_label) {
      	  pane = XtCreateManagedWidget ("paned", panedWidgetClass,
				    	toplevel, NULL, ZERO);
    
      	  label_wid = XtCreateManagedWidget ("label", labelWidgetClass,
					     pane, NULL, ZERO);
      	  
	  switch_widget[1].w = label_wid;
	  switch_count = 2;

      	  XtSetArg (args[0], XtNlabel, &label);
      	  XtGetValues(label_wid, args, ONE);
      	  
      	  if ( strcmp("label", label) == 0 ) {
	    if ( remote_host ) {
	      strcpy(host, remote_host);
	    } else {
#ifdef AMOEBA
              char *s;
              char *getenv();
       
              host[255] = '\0';
              if ((s = getenv("XLOAD_HOST")) != NULL) {
                   strncpy(host, s, 255);
              } else if ((s = getenv("RUN_SERVER")) != NULL) {
                  /* specific runserver specified; use its name */
                  strncpy(host, s, 255);
       
                  {   /* if the last component is ".run", remove it */
                      char *slash = strrchr(host, '/');
                      if (slash != NULL && strcmp(slash + 1, ".run") == 0) {
                          *slash = '\0';
                      }
                  }
              } else {
                  (void) XmuGetHostname (host, 255);  /* "amoeba" */
              }
#else
	    (void) XmuGetHostname (host, 255);
#endif
	    }
	    XtSetArg (args[0], XtNlabel, host);
	    XtSetValues (label_wid, args, ONE);
      	  }
    
      	  load_parent = pane;
    	}
    	else {
      	  load_parent = toplevel;
	  switch_count = 1;
	}

    	load = XtCreateManagedWidget ("load", stripChartWidgetClass,
				      load_parent, NULL, ZERO);    
   
	switch_widget[0].w = load;

    	XtAddCallback(load, XtNgetValue, GetLoadPoint, NULL);
    
	for ( i = 0 ; i < switch_count ; i++ ) {
	  XtSetArg (args[0], XtNbackground, &switch_widget[i].reach_color);
	  XtGetValues(switch_widget[i].w, args, ONE);
	  switch_widget[i].unreach_color = resources.unreach_color;
	  if ( switch_widget[i].reach_color != switch_widget[i].unreach_color )
	    switch_color = 1;
	}

    	XtRealizeWidget (toplevel);
    	wm_delete_window = XInternAtom (XtDisplay(toplevel), "WM_DELETE_WINDOW",
				    	False);
    	(void) XSetWMProtocols (XtDisplay(toplevel), XtWindow(toplevel),
			    	&wm_delete_window, 1);
    }
    XtAppMainLoop(app_con);
}

static unsigned long	current_leds;

static void
ClearLights (dpy)
    Display *dpy;
{
    XKeyboardControl	cntrl;

    cntrl.led_mode = LedModeOff;
    XChangeKeyboardControl (dpy, KBLedMode, &cntrl);
    current_leds = 0;
}

static void
SetLights (data, timer)
    XtPointer	    data;
    XtIntervalId    *timer;
{
    Widget		toplevel;
    Display		*dpy;
    double		value;
    unsigned long	new_leds, change, bit;
    int			i;
    XKeyboardControl	cntrl;

    toplevel = (Widget) data;
    dpy = XtDisplay (toplevel);
    GetLoadPoint (toplevel, (XtPointer) 0, (XtPointer) &value);
    new_leds = (1 << (int) (value + 0.1)) - 1;
    change = new_leds ^ current_leds;
    i = 1;
    bit = 1;
    while (current_leds != new_leds)
    {
	if (change & bit)
	{
	    cntrl.led = i;
	    cntrl.led_mode = new_leds & bit ? LedModeOn : LedModeOff;
	    XChangeKeyboardControl (dpy, KBLed|KBLedMode, &cntrl);
	    current_leds ^= bit;
	}
	i++;
	bit <<= 1;
    }
    XtAppAddTimeOut(XtWidgetToApplicationContext(toplevel), light_update,
		    SetLights, data);
}

static void quit (w, event, params, num_params)
    Widget w;
    XEvent *event;
    String *params;
    Cardinal *num_params;
{
    if (event->type == ClientMessage &&
        event->xclient.data.l[0] != wm_delete_window) {
        XBell (XtDisplay(w), 0);
        return;
    }
    if (resources.use_lights)
	ClearLights (XtDisplay (w));
    XtDestroyApplicationContext(XtWidgetToApplicationContext(w));
    exit (0);
}

void setgoodcolor()
{
  int i;
  Arg args[1];

  if ( switch_color == 2 ) {
    for ( i = 0 ; i < switch_count ; i++ ) {
      XtSetArg(args[0], XtNbackground, switch_widget[i].reach_color);
      XtSetValues(switch_widget[i].w, args, ONE);
    }
    switch_color = 1;
  }
}

void setbadcolor()
{
  int i;
  Arg args[1];

  if ( switch_color == 1 ) {
    for ( i = 0 ; i < switch_count ; i++ ) {
      XtSetArg(args[0], XtNbackground, switch_widget[i].unreach_color);
      XtSetValues(switch_widget[i].w, args, ONE);
    }
    switch_color = 2;
  }
}