1 /* sonar.c --- Simulate a sonar screen.
3 * This is an implementation of a general purpose reporting tool in the
4 * format of a Sonar display. It is designed such that a sensor is read
5 * on every movement of a sweep arm and the results of that sensor are
6 * displayed on the screen. The location of the display points (targets) on the
7 * screen are determined by the current localtion of the sweep and a distance
8 * value associated with the target.
10 * Currently the only two sensors that are implemented are the simulator
11 * (the default) and the ping sensor. The simulator randomly creates a set
12 * of bogies that move around on the scope while the ping sensor can be
13 * used to display hosts on your network.
15 * The ping code is only compiled in if you define HAVE_ICMP or HAVE_ICMPHDR,
16 * because, unfortunately, different systems have different ways of creating
17 * these sorts of packets.
19 * Also: creating an ICMP socket is a privileged operation, so the program
20 * needs to be installed SUID root if you want to use the ping mode. If you
21 * check the code you will see that this privilige is given up immediately
22 * after the socket is created.
24 * It should be easy to extend this code to support other sorts of sensors.
26 * - search the output of "netstat" for the list of hosts to ping;
27 * - plot the contents of /proc/interrupts;
28 * - plot the process table, by process size, cpu usage, or total time;
29 * - plot the logged on users by idle time or cpu usage.
31 * Copyright (C) 1998 by Stephen Martin (smartin@vanderfleet-martin.net).
32 * Permission to use, copy, modify, distribute, and sell this software and its
33 * documentation for any purpose is hereby granted without fee, provided that
34 * the above copyright notice appear in all copies and that both that
35 * copyright notice and this permission notice appear in supporting
36 * documentation. No representations are made about the suitability of this
37 * software for any purpose. It is provided "as is" without express or
42 * Version 1.0 April 27, 1998.
44 * - Submitted to RedHat Screensaver Contest
46 * Version 1.1 November 3, 1998.
47 * - Added simulation mode.
48 * - Added enhancements by Thomas Bahls <thommy@cs.tu-berlin.de>
49 * - Fixed huge memory leak.
50 * - Submitted to xscreensavers
53 * - All ping code is now ifdef-ed by the compile time symbol HAVE_PING;
54 * use -DHAVE_PING to include it when you compile.
55 * - Sweep now uses gradients.
56 * - Fixed portability problems with icmphdr on some systems.
57 * - removed lowColor option/resource.
58 * - changed copyright notice so that it could be included in the xscreensavers
61 * Version 1.3 November 16, 1998.
62 * - All ping code is now ifdef-ed by the compile time symbol PING use -DPING
63 * to include it when you compile.
64 * - Sweep now uses gradients.
65 * - Fixed portability problems with icmphdr on some systems.
66 * - removed lowcolour option/resource.
67 * - changed copyright notice so that it could be included in the xscreensavers
70 * Version 1.4 November 18, 1998.
71 * - More ping portability fixes.
73 * Version 1.5 November 19, 1998.
74 * - Synced up with jwz's changes.
75 * - Now need to define HAVE_PING to compile in the ping stuff.
78 /* These are computed by configure now:
90 #include "screenhack.h"
94 #if defined(HAVE_ICMP) || defined(HAVE_ICMPHDR)
99 # include <sys/types.h>
100 # include <sys/time.h>
101 # include <sys/ipc.h>
102 # include <sys/shm.h>
103 # include <sys/socket.h>
104 # include <netinet/in_systm.h>
105 # include <netinet/in.h>
106 # include <netinet/ip.h>
107 # include <netinet/ip_icmp.h>
108 # include <netinet/udp.h>
109 # include <arpa/inet.h>
111 #endif /* HAVE_ICMP || HAVE_ICMPHDR */
117 #define MY_MIN(a,b) ((a)<(b)?(a - 50):(b - 10))
120 # define LINE_MAX 2048
125 #if defined(HAVE_ICMP)
128 # define ICMP_TYPE(p) (p)->icmp_type
129 # define ICMP_CODE(p) (p)->icmp_code
130 # define ICMP_CHECKSUM(p) (p)->icmp_cksum
131 # define ICMP_ID(p) (p)->icmp_id
132 # define ICMP_SEQ(p) (p)->icmp_seq
133 #elif defined(HAVE_ICMPHDR)
135 # define ICMP icmphdr
136 # define ICMP_TYPE(p) (p)->type
137 # define ICMP_CODE(p) (p)->code
138 # define ICMP_CHECKSUM(p) (p)->checksum
139 # define ICMP_ID(p) (p)->un.echo.id
140 # define ICMP_SEQ(p) (p)->un.echo.sequence
145 /* Forward References */
148 static u_short checksum(u_short *, int);
150 static long delta(struct timeval *, struct timeval *);
152 /* Data Structures */
157 * This represents an object that is visable on the scope.
160 typedef struct Bogie {
161 char *name; /* The name of the thing being displayed */
162 int distance; /* The distance to this thing (0 - 100) */
163 int tick; /* The tick that it was found on */
164 int ttl; /* The time to live */
165 int age; /* How long it's been around */
166 struct Bogie *next; /* The next one in the list */
172 * This contains all of the runtime information about the sonar scope.
176 Display *dpy; /* The X display */
177 Window win; /* The window */
178 GC hi, /* The leading edge of the sweep */
179 lo, /* The trailing part of the sweep */
180 erase, /* Used to erase things */
181 grid, /* Used to draw the grid */
182 text; /* Used to draw text */
183 Colormap cmap; /* The colormap */
184 XFontStruct *font; /* The font to use for the labels */
185 int text_steps; /* How many steps to fade text. */
186 XColor *text_colors; /* Pixel values used to fade text */
187 int sweep_degrees; /* How much of the circle the sweep uses */
188 int sweep_segs; /* How many gradients in the sweep. */
189 XColor *sweep_colors; /* The sweep pixel values */
190 int width, height; /* Window dimensions */
191 int minx, miny, maxx, maxy, /* Bounds of the scope */
192 centrex, centrey, radius; /* Parts of the scope circle */
193 Bogie *visable; /* List of visable objects */
194 int current; /* Current position of sweep */
195 int sweepnum; /* The current id of the sweep */
196 int delay; /* how long between each frame of the anim */
201 * Variables to support the differnt Sonar modes.
204 Bogie *(*sensor)(sonar_info *, void *); /* The current sensor */
205 void *sensor_info; /* Information about the sensor */
208 * A list of targets to ping.
212 typedef struct ping_target {
213 char *name; /* The name of the target */
214 struct sockaddr address; /* The address of the target */
215 struct ping_target *next; /* The next one in the list */
221 * This contains the information for the ping sensor.
225 int icmpsock; /* Socket for sending pings */
226 int pid; /* Our process ID */
227 int seq; /* Packet sequence number */
228 int timeout; /* Timeout value for pings */
229 ping_target *targets; /* List of targets to ping */
230 int numtargets; /* The number of targets to ping */
233 /* Flag to indicate that the timer has expired on us */
235 static int timer_expired;
237 #endif /* HAVE_PING */
240 * A list of targets for the simulator
243 typedef struct sim_target {
244 char *name; /* The name of the target */
245 int nexttick; /* The next tick that this will be seen */
246 int nextdist; /* The distance on that tick */
247 int movedonsweep; /* The number of the sweep this last moved */
251 * Simulator Information.
253 * This contains the information for the simulator mode.
257 sim_target *teamA; /* The bogies for the A team */
258 int numA; /* The number of bogies in team A */
259 char *teamAID; /* The identifier for bogies in team A */
260 sim_target *teamB; /* The bogies for the B team */
261 int numB; /* The number of bogies in team B */
262 char *teamBID; /* The identifier for bogies in team B */
265 /* Name of the Screensaver hack */
267 char *progclass="sonar";
269 /* Application Defaults */
271 char *defaults [] = {
272 ".background: #000000",
273 ".sweepColor: #00FF00",
275 "*scopeColor: #003300",
276 "*gridColor: #00AA00",
277 "*textColor: #FFFF00",
283 "*textSteps: 80", /* npixels */
284 "*sweepSegments: 80", /* npixels */
287 "*pingTimeout: 3000",
289 "*pingFile: /etc/hosts",
290 "*pingList: localhost",
291 #endif /* HAVE_PING */
299 /* Options passed to this program */
301 XrmOptionDescRec options [] = {
302 {"-background", ".background", XrmoptionSepArg, 0 },
303 {"-sweep-color", ".sweepColor", XrmoptionSepArg, 0 },
304 {"-scope-color", ".scopeColor", XrmoptionSepArg, 0 },
305 {"-grid-color", ".gridColor", XrmoptionSepArg, 0 },
306 {"-text-color", ".textColor", XrmoptionSepArg, 0 },
307 {"-ttl", ".ttl", XrmoptionSepArg, 0 },
308 {"-mode", ".mode", XrmoptionSepArg, 0 },
309 {"-font", ".font", XrmoptionSepArg, 0 },
311 {"-ping-timeout", ".pingTimeout", XrmoptionSepArg, 0 },
312 {"-ping-source", ".pingSource", XrmoptionSepArg, 0 },
313 {"-ping-file", ".pingFile", XrmoptionSepArg, 0 },
314 {"-ping-list", ".pingList", XrmoptionSepArg, 0 },
315 #endif /* HAVE_PING */
316 {"-team-a-name", ".teamAName", XrmoptionSepArg, 0 },
317 {"-team-b-name", ".teamBName", XrmoptionSepArg, 0 },
318 {"-team-a-count", ".teamACount", XrmoptionSepArg, 0 },
319 {"-team-b-count", ".teamBCount", XrmoptionSepArg, 0 },
324 * The number of ticks that bogies are visable on the screen before they
331 * Create a new Bogie and set some initial values.
334 * name - The name of the bogie.
335 * distance - The distance value.
336 * tick - The tick value.
337 * ttl - The time to live value.
340 * The newly allocated bogie or null if a memory problem occured.
344 newBogie(char *name, int distance, int tick, int ttl)
347 /* Local Variables */
351 /* Allocate a bogie and initialize it */
353 if ((new = (Bogie *) calloc(1, sizeof(Bogie))) == NULL) {
354 fprintf(stderr, "%s: Out of Memory\n", progname);
358 new->distance = distance;
362 new->next = (Bogie *) 0;
370 * b - The bogie to free.
376 if (b->name != (char *) 0)
382 * Find a bogie by name in a list.
384 * This does a simple linear search of the list for a given name.
387 * bl - The Bogie list to search.
388 * name - The name to look for.
391 * The requested Bogie or null if it wasn't found.
395 findNode(Bogie *bl, char *name)
398 /* Local Variables */
402 /* Abort if the list is empty or no name is given */
404 if ((name == NULL) || (bl == NULL))
407 /* Search the list for the desired name */
411 if (strcmp(p->name, name) == 0)
424 * Lookup the address for a ping target;
427 * target - The ping_target fill in the address for.
430 * 1 if the host was successfully resolved, 0 otherwise.
434 lookupHost(ping_target *target)
437 /* Local Variables */
439 struct sockaddr_in *iaddr;
441 /* Set up the target address we first assume that the name is the
442 IP address as a string */
444 iaddr = (struct sockaddr_in *) &(target->address);
445 iaddr->sin_family = AF_INET;
446 if ((iaddr->sin_addr.s_addr = inet_addr(target->name)) == -1) {
448 /* Conversion of IP address failed, try to look the host up by name */
450 struct hostent *hent = gethostbyname(target->name);
452 fprintf(stderr, "%s: could not resolve host %s\n",
453 progname, target->name);
456 memcpy(&iaddr->sin_addr, hent->h_addr_list[0],
457 sizeof(iaddr->sin_addr));
466 * Create a target for a host.
469 * name - The name of the host.
472 * A newly allocated target or null if the host could not be resolved.
479 /* Local Variables */
481 ping_target *target = NULL;
483 /* Create the target */
485 if ((target = calloc(1, sizeof(ping_target))) == NULL) {
486 fprintf(stderr, "%s: Out of Memory\n", progname);
487 goto target_init_error;
489 if ((target->name = strdup(name)) == NULL) {
490 fprintf(stderr, "%s: Out of Memory\n", progname);
491 goto target_init_error;
494 /* Lookup the host */
496 if (! lookupHost(target))
497 goto target_init_error;
503 /* Handle errors here */
512 * Generate a list of ping targets from the entries in a file.
515 * fname - The name of the file. This file is expected to be in the same
516 * format as /etc/hosts.
519 * A list of targets to ping or null if an error occured.
523 readPingHostsFile(char *fname)
526 /* Local Variables */
531 ping_target *list = NULL;
535 /* Make sure we in fact have a file to process */
537 if ((fname == NULL) || (fname[0] == '\0')) {
538 fprintf(stderr, "%s: invalid ping host file name\n", progname);
544 if ((fp = fopen(fname, "r")) == NULL) {
546 sprintf(msg, "%s: unable to open host file %s", progname, fname);
551 /* Read the file line by line */
553 while ((p = fgets(buf, LINE_MAX, fp)) != NULL) {
556 * Parse the line skipping those that start with '#'.
557 * The rest of the lines in the file should be in the same
558 * format as a /etc/hosts file. We are only concerned with
559 * the first two field, the IP address and the name
562 while ((*p == ' ') || (*p == '\t'))
567 /* Get the name and address */
570 if ((addr = strtok(buf, " \t\n")) != NULL)
571 name = strtok(NULL, " \t\n");
575 /* Check to see if the addr looks like an addr. If not, assume
576 the addr is a name and there is no addr. This way, we can
577 handle files whose lines have "xx.xx.xx.xx hostname" as their
578 first two tokens, and also files that have a hostname as their
579 first token (like .ssh/known_hosts and .rhosts.)
583 if (4 != sscanf(addr, "%d.%d.%d.%d%c", &i, &i, &i, &i, &c))
589 /*printf ("\"%s\" \"%s\"\n", name, addr);*/
591 /* Create a new target using first the name then the address */
596 if (new == NULL && addr != NULL)
599 /* Add it to the list if we got one */
607 /* Close the file and return the list */
614 * Generate a list of ping targets from the entries in a string.
617 * list - A list of comma separated host names.
620 * A list of targets to ping or null if an error occured.
624 readPingHostsList(char *list)
627 /* Local Variables */
630 ping_target *hostlist = NULL;
633 /* Check that there is a list */
635 if ((list == NULL) || (list[0] == '\0'))
638 /* Loop through the hosts and add them to the list to return */
640 host = strtok(list, ",");
641 while (host != NULL) {
644 new->next = hostlist;
647 host = strtok(NULL, ",");
656 * Generate a list ping targets consisting of all of the entries on
660 * A list of all of the hosts on this net.
664 subnetHostsList(void)
667 /* Local Variables */
669 char hostname[BUFSIZ];
670 char address[BUFSIZ];
671 struct hostent *hent;
675 ping_target *list = NULL;
677 /* Get our hostname */
679 if (gethostname(hostname, BUFSIZ)) {
680 fprintf(stderr, "%s: unable to get local hostname\n", progname);
684 /* Get our IP address and convert it to a string */
686 if ((hent = gethostbyname(hostname)) == NULL) {
687 fprintf(stderr, "%s: unable to lookup our IP address\n", progname);
690 strcpy(address, inet_ntoa(*((struct in_addr *)hent->h_addr_list[0])));
692 /* Get a pointer to the last "." in the string */
694 if ((p = strrchr(address, '.')) == NULL) {
695 fprintf(stderr, "%s: can't parse IP address %s\n", progname, address);
700 /* Construct targets for all addresses in this subnet */
702 /* #### jwz: actually, this is wrong, since it assumes a
703 netmask of 255.255.255.0. But I'm not sure how to find
706 for (i = 254; i > 0; i--) {
708 new = newHost(address);
721 * Initialize the ping sensor.
724 * A newly allocated ping_info structure or null if an error occured.
731 /* Local Variables */
733 ping_info *pi = NULL; /* The new ping_info struct */
734 char *src; /* The source of the ping hosts */
735 ping_target *pt; /* Used to count the targets */
737 /* Create the ping info structure */
739 if ((pi = (ping_info *) calloc(1, sizeof(ping_info))) == NULL) {
740 fprintf(stderr, "%s: Out of memory\n", progname);
741 goto ping_init_error;
744 /* Create the ICMP socket and turn off SUID */
746 if ((pi->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
748 sprintf(msg, "%s: can't create ICMP socket", progname);
751 "%s: this program must be setuid to root for `ping mode' to work.\n",
753 goto ping_init_error;
756 pi->pid = getpid() & 0xFFFF;
758 pi->timeout = get_integer_resource("pingTimeout", "PingTimeout");
760 /* Generate a list of targets */
762 src = get_string_resource("pingSource", "PingSource");
763 if (strcmp(src, "file") == 0) {
766 * The list of ping targets is to come from a file in
770 pi->targets = readPingHostsFile(get_string_resource("pingFile",
773 } else if (strcmp(src, "list") == 0) {
775 /* The list of hosts is to come from the pinghostlist resource */
777 pi->targets = readPingHostsList(get_string_resource("pingList",
780 } else if (strcmp(src, "subnet") == 0) {
782 pi->targets = subnetHostsList();
789 "%s: pingSource must be `file', `list', or `subnet', not: %s\n",
794 /* Make sure there is something to ping */
796 if (pi->targets == NULL) {
797 fprintf(stderr, "%s: nothing to ping", progname);
798 goto ping_init_error;
801 /* Count the targets */
814 /* Handle initialization errors here */
826 * pi - The ping information strcuture.
827 * host - The name or IP address of the host to ping (in ascii).
831 sendping(ping_info *pi, ping_target *pt)
834 /* Local Variables */
841 * Note, we will send the character name of the host that we are
842 * pinging in the packet so that we don't have to keep track of the
843 * name or do an address lookup when it comes back.
846 int pcktsiz = sizeof(struct ICMP) + sizeof(struct timeval) +
847 strlen(pt->name) + 1;
849 /* Create the ICMP packet */
851 if ((packet = (u_char *) malloc(pcktsiz)) == (void *) 0)
852 return; /* Out of memory */
853 icmph = (struct ICMP *) packet;
854 ICMP_TYPE(icmph) = ICMP_ECHO;
855 ICMP_CODE(icmph) = 0;
856 ICMP_CHECKSUM(icmph) = 0;
857 ICMP_ID(icmph) = pi->pid;
858 ICMP_SEQ(icmph) = pi->seq++;
859 gettimeofday((struct timeval *) &packet[sizeof(struct ICMP)],
860 (struct timezone *) 0);
861 strcpy((char *) &packet[sizeof(struct ICMP) + sizeof(struct timeval)],
863 ICMP_CHECKSUM(icmph) = checksum((u_short *)packet, pcktsiz);
867 if ((result = sendto(pi->icmpsock, packet, pcktsiz, 0,
868 &pt->address, sizeof(pt->address))) != pcktsiz) {
871 sprintf(errbuf, "%s: error sending ping to %s", progname, pt->name);
878 * Catch a signal and do nothing.
881 * sig - The signal that was caught.
891 * Compute the checksum on a ping packet.
894 * packet - A pointer to the packet to compute the checksum for.
895 * size - The size of the packet.
898 * The computed checksum
903 checksum(u_short *packet, int size)
906 /* Local Variables */
908 register int nleft = size;
909 register u_short *w = packet;
910 register int sum = 0;
914 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
915 * sequential 16 bit words to it, and at the end, fold back all the
916 * carry bits from the top 16 bits into the lower 16 bits.
924 /* mop up an odd byte, if necessary */
927 *(u_char *)(&answer) = *(u_char *)w ;
928 *(1 + (u_char *)(&answer)) = 0;
932 /* add back carry outs from top 16 bits to low 16 bits */
934 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
935 sum += (sum >> 16); /* add carry */
936 answer = ~sum; /* truncate to 16 bits */
944 * Look for ping replies.
946 * Retrieve all outstanding ping replies.
949 * si - Information about the sonar.
950 * pi - Ping information.
951 * ttl - The time each bogie is to live on the screen
954 * A Bogie list of all the machines that replied.
958 getping(sonar_info *si, ping_info *pi, int ttl)
961 /* Local Variables */
963 struct sockaddr from;
968 struct timeval *then;
978 /* Set up a signal to interupt our wait for a packet */
980 sigemptyset(&sa.sa_mask);
982 sa.sa_handler = sigcatcher;
983 if (sigaction(SIGALRM, &sa, 0) == -1) {
985 sprintf(msg, "%s: unable to trap SIGALRM", progname);
990 /* Set up a timer to interupt us if we don't get a packet */
992 it.it_interval.tv_sec = 0;
993 it.it_interval.tv_usec = 0;
994 it.it_value.tv_sec = 0;
995 it.it_value.tv_usec = pi->timeout;
997 setitimer(ITIMER_REAL, &it, NULL);
999 /* Wait for a result packet */
1001 fromlen = sizeof(from);
1002 while (! timer_expired &&
1003 (result = recvfrom(pi->icmpsock, packet, sizeof(packet),
1004 0, &from, &fromlen)) > 0) {
1006 /* Check the packet */
1008 gettimeofday(&now, (struct timezone *) 0);
1009 ip = (struct ip *) packet;
1011 iphdrlen = ip->ip_hl << 2;
1012 /* On DEC OSF1 4.0, the preceeding line needs to be
1013 iphdrlen = (ip->ip_vhl & 0x0F) << 2;
1014 but I don't know how to do this portably. -- jwz.
1017 icmph = (struct ICMP *) &packet[iphdrlen];
1019 /* Was the packet a reply?? */
1021 if (ICMP_TYPE(icmph) != ICMP_ECHOREPLY) {
1022 /* Ignore anything but ICMP Replies */
1023 continue; /* Nope */
1026 /* Was it for us? */
1028 if (ICMP_ID(icmph) != pi->pid) {
1029 /* Ignore packets not set from us */
1030 continue; /* Nope */
1033 /* Copy the name of the bogie */
1036 strdup((char *) &packet[iphdrlen +
1037 + sizeof(struct ICMP)
1038 + sizeof(struct timeval)])) == NULL) {
1039 fprintf(stderr, "%s: Out of memory\n", progname);
1043 /* If the name is an IP addr, try to resolve it. */
1047 if (4 == sscanf(name, " %d.%d.%d.%d %c",
1048 &iip[0], &iip[1], &iip[2], &iip[3], &c))
1050 unsigned char ip[4];
1052 ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3];
1053 h = gethostbyaddr ((char *) ip, 4, AF_INET);
1054 if (h && h->h_name && *h->h_name)
1057 name = strdup (h->h_name);
1062 /* Create the new Bogie and add it to the list we are building */
1064 if ((new = newBogie(name, 0, si->current, ttl)) == NULL)
1069 /* Compute the round trip time */
1071 then = (struct timeval *) &packet[iphdrlen +
1072 sizeof(struct ICMP)];
1073 new->distance = delta(then, &now) / 100;
1074 if (new->distance == 0)
1075 new->distance = 2; /* HACK */
1087 * si - Sonar Information.
1088 * pi - Ping Information.
1091 * A list of hosts that replied to pings or null if there were none.
1095 ping(sonar_info *si, void *vpi)
1099 * This tries to distribute the targets evely around the field of the
1103 ping_info *pi = (ping_info *) vpi;
1104 static ping_target *ptr = NULL;
1106 int tick = si->current * -1 + 1;
1107 if ((ptr == NULL) && (tick == 1))
1110 if (pi->numtargets <= 90) {
1111 int xdrant = 90 / pi->numtargets;
1112 if ((tick % xdrant) == 0) {
1113 if (ptr != (ping_target *) 0) {
1119 } else if (pi->numtargets > 90) {
1120 if (ptr != (ping_target *) 0) {
1126 /* Get the results */
1128 return getping(si, pi, TTL);
1131 #endif /* HAVE_PING */
1134 * Calculate the difference between two timevals in microseconds.
1137 * then - The older timeval.
1138 * now - The newer timeval.
1141 * The difference between the two in microseconds.
1145 delta(struct timeval *then, struct timeval *now)
1147 return (((now->tv_sec - then->tv_sec) * 1000000) +
1148 (now->tv_usec - then->tv_usec));
1152 * Initialize the simulation mode.
1159 /* Local Variables */
1164 /* Create the simulation info structure */
1166 if ((si = (sim_info *) calloc(1, sizeof(sim_info))) == NULL) {
1167 fprintf(stderr, "%s: Out of memory\n", progname);
1173 si->numA = get_integer_resource("teamACount", "TeamACount");
1174 if ((si->teamA = (sim_target *)calloc(si->numA, sizeof(sim_target)))
1177 fprintf(stderr, "%s: Out of Memory\n", progname);
1180 si->teamAID = get_string_resource("teamAName", "TeamAName");
1181 for (i = 0; i < si->numA; i++) {
1182 if ((si->teamA[i].name = (char *) malloc(strlen(si->teamAID) + 4))
1185 fprintf(stderr, "%s: Out of Memory\n", progname);
1188 sprintf(si->teamA[i].name, "%s%03d", si->teamAID, i+1);
1189 si->teamA[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1190 si->teamA[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1191 si->teamA[i].movedonsweep = -1;
1196 si->numB = get_integer_resource("teamBCount", "TeamBCount");
1197 if ((si->teamB = (sim_target *)calloc(si->numB, sizeof(sim_target)))
1200 fprintf(stderr, "%s: Out of Memory\n", progname);
1203 si->teamBID = get_string_resource("teamBName", "TeamBName");
1204 for (i = 0; i < si->numB; i++) {
1205 if ((si->teamB[i].name = (char *) malloc(strlen(si->teamBID) + 4))
1208 fprintf(stderr, "%s: Out of Memory\n", progname);
1211 sprintf(si->teamB[i].name, "%s%03d", si->teamBID, i+1);
1212 si->teamB[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1213 si->teamB[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1214 si->teamB[i].movedonsweep = -1;
1223 * Initialize the Sonar.
1226 * dpy - The X display.
1227 * win - The X window;
1230 * A sonar_info strcuture or null if memory allocation problems occur.
1234 init_sonar(Display *dpy, Window win)
1237 /* Local Variables */
1240 XWindowAttributes xwa;
1244 double s1, s2, v1, v2;
1246 /* Create the Sonar information structure */
1248 if ((si = (sonar_info *) calloc(1, sizeof(sonar_info))) == NULL) {
1249 fprintf(stderr, "%s: Out of memory\n", progname);
1253 /* Initialize the structure for the current environment */
1258 XGetWindowAttributes(dpy, win, &xwa);
1259 si->cmap = xwa.colormap;
1260 si->width = xwa.width;
1261 si->height = xwa.height;
1262 si->centrex = si->width / 2;
1263 si->centrey = si->height / 2;
1264 si->maxx = si->centrex + MY_MIN(si->centrex, si->centrey) - 10;
1265 si->minx = si->centrex - MY_MIN(si->centrex, si->centrey) + 10;
1266 si->maxy = si->centrey + MY_MIN(si->centrex, si->centrey) - 10;
1267 si->miny = si->centrey - MY_MIN(si->centrex, si->centrey) + 10;
1268 si->radius = si->maxx - si->centrex;
1274 if (((si->font = XLoadQueryFont(dpy, get_string_resource ("font", "Font")))
1276 ((si->font = XLoadQueryFont(dpy, "fixed")) == NULL)) {
1277 fprintf(stderr, "%s: can't load an appropriate font\n", progname);
1281 /* Get the delay between animation frames */
1283 si->delay = get_integer_resource ("delay", "Integer");
1284 if (si->delay < 0) si->delay = 0;
1286 /* Create the Graphics Contexts that will be used to draw things */
1289 get_pixel_resource ("sweepColor", "SweepColor", dpy, si->cmap);
1290 si->hi = XCreateGC(dpy, win, GCForeground, &gcv);
1291 gcv.font = si->font->fid;
1292 si->text = XCreateGC(dpy, win, GCForeground|GCFont, &gcv);
1293 gcv.foreground = get_pixel_resource("scopeColor", "ScopeColor",
1295 si->erase = XCreateGC (dpy, win, GCForeground, &gcv);
1296 gcv.foreground = get_pixel_resource("gridColor", "GridColor",
1298 si->grid = XCreateGC (dpy, win, GCForeground, &gcv);
1300 /* Compute pixel values for fading text on the display */
1302 XParseColor(dpy, si->cmap,
1303 get_string_resource("textColor", "TextColor"), &start);
1304 XParseColor(dpy, si->cmap,
1305 get_string_resource("scopeColor", "ScopeColor"), &end);
1307 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1308 rgb_to_hsv (end.red, end.green, end.blue, &h2, &s2, &v2);
1310 si->text_steps = get_integer_resource("textSteps", "TextSteps");
1311 if (si->text_steps < 0 || si->text_steps > 255)
1312 si->text_steps = 10;
1314 si->text_colors = (XColor *) calloc(si->text_steps, sizeof(XColor));
1315 make_color_ramp (dpy, si->cmap,
1318 si->text_colors, &si->text_steps,
1319 False, True, False);
1321 /* Compute the pixel values for the fading sweep */
1323 XParseColor(dpy, si->cmap,
1324 get_string_resource("sweepColor", "SweepColor"), &start);
1326 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1328 si->sweep_degrees = get_integer_resource("sweepDegrees", "Degrees");
1329 if (si->sweep_degrees <= 0) si->sweep_degrees = 20;
1330 if (si->sweep_degrees > 350) si->sweep_degrees = 350;
1332 si->sweep_segs = get_integer_resource("sweepSegments", "SweepSegments");
1333 if (si->sweep_segs < 1 || si->sweep_segs > 255)
1334 si->sweep_segs = 255;
1336 si->sweep_colors = (XColor *) calloc(si->sweep_segs, sizeof(XColor));
1337 make_color_ramp (dpy, si->cmap,
1340 si->sweep_colors, &si->sweep_segs,
1341 False, True, False);
1349 * Update the location of a simulated bogie.
1353 updateLocation(sim_target *t)
1358 xtick = (int) (3.0 * random() / RAND_MAX) - 1;
1359 xdist = (int) (11.0 * random() / RAND_MAX) - 5;
1360 if (((t->nexttick + xtick) < 90) && ((t->nexttick + xtick) >= 0))
1361 t->nexttick += xtick;
1363 t->nexttick -= xtick;
1364 if (((t->nextdist + xdist) < 100) && ((t->nextdist+xdist) >= 0))
1365 t->nextdist += xdist;
1367 t->nextdist -= xdist;
1371 * The simulator. This uses information in the sim_info to simulate a bunch
1372 * of bogies flying around on the screen.
1376 * TODO: It would be cool to have the two teams chase each other around and
1381 simulator(sonar_info *si, void *vinfo)
1384 /* Local Variables */
1390 sim_info *info = (sim_info *) vinfo;
1394 for (i = 0; i < info->numA; i++) {
1395 t = &info->teamA[i];
1396 if ((t->movedonsweep != si->sweepnum) &&
1397 (t->nexttick == (si->current * -1))) {
1398 new = newBogie(strdup(t->name), t->nextdist, si->current, TTL);
1403 t->movedonsweep = si->sweepnum;
1409 for (i = 0; i < info->numB; i++) {
1410 t = &info->teamB[i];
1411 if ((t->movedonsweep != si->sweepnum) &&
1412 (t->nexttick == (si->current * -1))) {
1413 new = newBogie(strdup(t->name), t->nextdist, si->current, TTL);
1418 t->movedonsweep = si->sweepnum;
1428 * Compute the X coordinate of the label.
1431 * si - The sonar info block.
1432 * label - The label that will be drawn.
1433 * x - The x coordinate of the bogie.
1436 * The x coordinate of the start of the label.
1440 computeStringX(sonar_info *si, char *label, int x)
1443 int width = XTextWidth(si->font, label, strlen(label));
1444 return x - (width / 2);
1448 * Compute the Y coordinate of the label.
1451 * si - The sonar information.
1452 * y - The y coordinate of the bogie.
1455 * The y coordinate of the start of the label.
1458 /* TODO: Add smarts to keep label in sonar screen */
1461 computeStringY(sonar_info *si, int y)
1464 int fheight = si->font->ascent + si->font->descent;
1465 return y + 5 + fheight;
1469 * Draw a Bogie on the radar screen.
1472 * si - Sonar Information.
1473 * draw - A flag to indicate if the bogie should be drawn or erased.
1474 * name - The name of the bogie.
1475 * degrees - The number of degrees that it should apprear at.
1476 * distance - The distance the object is from the centre.
1477 * ttl - The time this bogie has to live.
1478 * age - The time this bogie has been around.
1482 DrawBogie(sonar_info *si, int draw, char *name, int degrees,
1483 int distance, int ttl, int age)
1486 /* Local Variables */
1490 int ox = si->centrex;
1491 int oy = si->centrey;
1494 /* Compute the coordinates of the object */
1497 distance = (log((double) distance) / 10.0) * si->radius;
1498 x = ox + ((double) distance * cos(4.0 * ((double) degrees)/57.29578));
1499 y = oy - ((double) distance * sin(4.0 * ((double) degrees)/57.29578));
1501 /* Set up the graphics context */
1505 /* Here we attempt to compute the distance into the total life of
1506 * object that we currently are. This distance is used against
1507 * the total lifetime to compute a fraction which is the index of
1508 * the color to draw the bogie.
1511 if (si->current <= degrees)
1512 delta = (si->current - degrees) * -1;
1514 delta = 90 + (degrees - si->current);
1515 delta += (age * 90);
1516 index = (si->text_steps - 1) * ((float) delta / (90.0 * (float) ttl));
1518 XSetForeground(si->dpy, gc, si->text_colors[index].pixel);
1523 /* Draw (or erase) the Bogie */
1525 XFillArc(si->dpy, si->win, gc, x, y, 5, 5, 0, 360 * 64);
1526 XDrawString(si->dpy, si->win, gc,
1527 computeStringX(si, name, x),
1528 computeStringY(si, y), name, strlen(name));
1533 * Draw the sonar grid.
1536 * si - Sonar information block.
1540 drawGrid(sonar_info *si)
1543 /* Local Variables */
1546 int width = si->maxx - si->minx;
1547 int height = si->maxy - si->miny;
1549 /* Draw the circles */
1551 XDrawArc(si->dpy, si->win, si->grid, si->minx - 10, si->miny - 10,
1552 width + 20, height + 20, 0, (360 * 64));
1554 XDrawArc(si->dpy, si->win, si->grid, si->minx, si->miny,
1555 width, height, 0, (360 * 64));
1557 XDrawArc(si->dpy, si->win, si->grid,
1558 (int) (si->minx + (.166 * width)),
1559 (int) (si->miny + (.166 * height)),
1560 (unsigned int) (.666 * width), (unsigned int)(.666 * height),
1563 XDrawArc(si->dpy, si->win, si->grid,
1564 (int) (si->minx + (.333 * width)),
1565 (int) (si->miny + (.333 * height)),
1566 (unsigned int) (.333 * width), (unsigned int) (.333 * height),
1569 /* Draw the radial lines */
1571 for (i = 0; i < 360; i += 10)
1573 XDrawLine(si->dpy, si->win, si->grid, si->centrex, si->centrey,
1574 (int) (si->centrex +
1575 (si->radius + 10) * (cos((double) i / 57.29578))),
1576 (int) (si->centrey -
1577 (si->radius + 10)*(sin((double) i / 57.29578))));
1579 XDrawLine(si->dpy, si->win, si->grid,
1580 (int) (si->centrex + si->radius *
1581 (cos((double) i / 57.29578))),
1582 (int) (si->centrey - si->radius *
1583 (sin((double) i / 57.29578))),
1584 (int) (si->centrex +
1585 (si->radius + 10) * (cos((double) i / 57.29578))),
1586 (int) (si->centrey -
1587 (si->radius + 10) * (sin((double) i / 57.29578))));
1591 * Update the Sonar scope.
1594 * si - The Sonar information.
1595 * bl - A list of bogies to add to the scope.
1599 Sonar(sonar_info *si, Bogie *bl)
1602 /* Local Variables */
1607 /* Check for expired tagets and remove them from the visable list */
1610 for (bp = si->visable; bp != NULL; bp = bp->next) {
1613 * Remove it from the visable list if it's expired or we have
1614 * a new target with the same name.
1619 if (((bp->tick == si->current) && (++bp->age >= bp->ttl)) ||
1620 (findNode(bl, bp->name) != NULL)) {
1621 DrawBogie(si, 0, bp->name, bp->tick,
1622 bp->distance, bp->ttl, bp->age);
1624 si->visable = bp->next;
1626 prev->next = bp->next;
1632 /* Draw the sweep */
1635 int seg_deg = (si->sweep_degrees * 64) / si->sweep_segs;
1636 int start_deg = si->current * 4 * 64;
1637 if (seg_deg <= 0) seg_deg = 1;
1638 for (i = 0; i < si->sweep_segs; i++) {
1639 XSetForeground(si->dpy, si->hi, si->sweep_colors[i].pixel);
1640 XFillArc(si->dpy, si->win, si->hi, si->minx, si->miny,
1641 si->maxx - si->minx, si->maxy - si->miny,
1642 start_deg + (i * seg_deg),
1646 /* Remove the trailing wedge the sonar */
1647 XFillArc(si->dpy, si->win, si->erase, si->minx, si->miny,
1648 si->maxx - si->minx, si->maxy - si->miny,
1649 start_deg + (i * seg_deg),
1653 /* Move the new targets to the visable list */
1655 for (bp = bl; bp != (Bogie *) 0; bp = bl) {
1657 bp->next = si->visable;
1661 /* Draw the visable targets */
1663 for (bp = si->visable; bp != NULL; bp = bp->next) {
1664 if (bp->age < bp->ttl) /* grins */
1665 DrawBogie(si, 1, bp->name, bp->tick, bp->distance, bp->ttl,bp->age);
1668 /* Redraw the grid */
1674 * Main screen saver hack.
1677 * dpy - The X display.
1678 * win - The X window.
1682 screenhack(Display *dpy, Window win)
1685 /* Local Variables */
1688 struct timeval start, finish;
1695 * Adding new sensors would involve supporting more modes other than
1696 * ping and initiailizing the sensor in the same way.
1699 mode = get_string_resource("mode", "Mode");
1701 if (!mode || !*mode || !strcmp(mode, "default")) /* Pick a good default. */
1704 if (geteuid() == 0) /* we're root or setuid -- ping will work. */
1708 mode = "simulation";
1712 if (strcmp(mode, "ping") == 0) {
1714 if ((sensor_info = (void *) init_ping()) == (void *) 0)
1716 fprintf (stderr, "%s: running in `simulation mode' instead.\n",
1721 #endif /* HAVE_PING */
1722 if (strcmp(mode, "simulation") == 0) {
1727 if ((sensor_info = (void *) init_sim()) == NULL)
1730 fprintf(stderr, "%s: unsupported Sonar mode: %s\n", progname, mode);
1732 "\tCurrently supported modes are `ping' and `simulation'\n");
1735 if ((si = init_sonar(dpy, win)) == (sonar_info *) 0)
1740 TTL = get_integer_resource("ttl", "TTL");
1744 /* Call the sensor and display the results */
1746 gettimeofday(&start, (struct timezone *) 0);
1747 bl = sensor(si, sensor_info);
1750 /* Set up and sleep for the next one */
1752 si->current = (si->current - 1) % 90;
1753 if (si->current == 0)
1756 gettimeofday(&finish, (struct timezone *) 0);
1757 sleeptime = si->delay - delta(&start, &finish);
1758 screenhack_handle_events (dpy);