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@canada.com).
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 /* Define one of these, as appropriate.
79 We should make configure detect this, one of these days.
81 /* #define HAVE_ICMP */
82 /* #define HAVE_ICMPHDR */
91 #if defined(HAVE_ICMP) || defined(HAVE_ICMPHDR)
96 # include <sys/types.h>
97 # include <sys/time.h>
100 # include <sys/socket.h>
101 # include <netinet/in_systm.h>
102 # include <netinet/in.h>
103 # include <netinet/ip.h>
104 # include <netinet/ip_icmp.h>
105 # include <netinet/udp.h>
106 # include <arpa/inet.h>
108 #endif /* HAVE_ICMP || HAVE_ICMPHDR */
110 #include "screenhack.h"
114 #include <X11/extensions/XShm.h>
120 #define MY_MIN(a,b) ((a)<(b)?(a - 50):(b - 10))
124 #if defined(HAVE_ICMP)
127 # define ICMP_TYPE(p) (p)->icmp_type
128 # define ICMP_CODE(p) (p)->icmp_code
129 # define ICMP_CHECKSUM(p) (p)->icmp_cksum
130 # define ICMP_ID(p) (p)->icmp_id
131 # define ICMP_SEQ(p) (p)->icmp_seq
132 #elif defined(HAVE_ICMPHDR)
134 # define ICMP icmphdr
135 # define ICMP_TYPE(p) (p)->type
136 # define ICMP_CODE(p) (p)->code
137 # define ICMP_CHECKSUM(p) (p)->checksum
138 # define ICMP_ID(p) (p)->un.echo.id
139 # define ICMP_SEQ(p) (p)->un.echo.sequence
144 /* Forward References */
147 static u_short checksum(u_short *, int);
149 static long delta(struct timeval *, struct timeval *);
151 /* Data Structures */
156 * This represents an object that is visable on the scope.
159 typedef struct Bogie {
160 char *name; /* The name of the thing being displayed */
161 int distance; /* The distance to this thing (0 - 100) */
162 int tick; /* The tick that it was found on */
163 int ttl; /* The time to live */
164 int age; /* How long it's been around */
165 struct Bogie *next; /* The next one in the list */
171 * This contains all of the runtime information about the sonar scope.
175 Display *dpy; /* The X display */
176 Window win; /* The window */
177 GC hi, /* The leading edge of the sweep */
178 lo, /* The trailing part of the sweep */
179 erase, /* Used to erase things */
180 grid, /* Used to draw the grid */
181 text; /* Used to draw text */
182 Colormap cmap; /* The colormap */
183 XFontStruct *font; /* The font to use for the labels */
184 int text_steps; /* How many steps to fade text. */
185 XColor *text_colors; /* Pixel values used to fade text */
186 int sweep_degrees; /* How much of the circle the sweep uses */
187 int sweep_segs; /* How many gradients in the sweep. */
188 XColor *sweep_colors; /* The sweep pixel values */
189 int width, height; /* Window dimensions */
190 int minx, miny, maxx, maxy, /* Bounds of the scope */
191 centrex, centrey, radius; /* Parts of the scope circle */
192 Bogie *visable; /* List of visable objects */
193 int current; /* Current position of sweep */
195 int delay; /* how long between each frame of the anim */
200 * Variables to support the differnt Sonar modes.
203 Bogie *(*sensor)(sonar_info *, void *); /* The current sensor */
204 void *sensor_info; /* Information about the sensor */
207 * A list of targets to ping.
211 typedef struct ping_target {
212 char *name; /* The name of the target */
213 struct sockaddr address; /* The address of the target */
214 struct ping_target *next; /* The next one in the list */
220 * This contains the information for the ping sensor.
224 int icmpsock; /* Socket for sending pings */
225 int pid; /* Our process ID */
226 int seq; /* Packet sequence number */
227 int timeout; /* Timeout value for pings */
228 ping_target *targets; /* List of targets to ping */
229 int numtargets; /* The number of targets to ping */
232 /* Flag to indicate that the timer has expired on us */
234 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 movedlasttick; /* Flag to indicate we just moved this one */
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, "Out of Memory\n");
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, "Could not resolve host %s\n", target->name);
455 memcpy(&iaddr->sin_addr, hent->h_addr_list[0],
456 sizeof(iaddr->sin_addr));
465 * Create a target for a host.
468 * name - The name of the host.
471 * A newly allocated target or null if the host could not be resolved.
478 /* Local Variables */
480 ping_target *target = NULL;
482 /* Create the target */
484 if ((target = calloc(1, sizeof(ping_target))) == NULL) {
485 fprintf(stderr, "Out of Memory\n");
486 goto target_init_error;
488 if ((target->name = strdup(name)) == NULL) {
489 fprintf(stderr, "Out of Memory\n");
490 goto target_init_error;
493 /* Lookup the host */
495 if (! lookupHost(target))
496 goto target_init_error;
502 /* Handle errors here */
511 * Generate a list of ping targets from the entries in a file.
514 * fname - The name of the file. This file is expected to be in the same
515 * format as /etc/hosts.
518 * A list of targets to ping or null if an error occured.
522 readPingHostsFile(char *fname)
525 /* Local Variables */
530 ping_target *list = NULL;
534 /* Make sure we in fact have a file to process */
536 if ((fname == NULL) || (fname[0] == '\0')) {
537 fprintf(stderr, "Invalid ping host file name\n");
543 if ((fp = fopen(fname, "r")) == NULL) {
545 sprintf(msg, "Unable to open host file %s", fname);
550 /* Read the file line by line */
552 while ((p = fgets(buf, LINE_MAX, fp)) != NULL) {
555 * Parse the line skipping those that start with '#'.
556 * The rest of the lines in the file should be in the same
557 * format as a /etc/hosts file. We are only concerned with
558 * the first two field, the IP address and the name
561 while ((*p == ' ') || (*p == '\t'))
566 /* Get the name and address */
569 if ((addr = strtok(buf, " \t\n")) != NULL)
570 name = strtok(NULL, " \t\n");
574 /* Create a new target using first the name then the address */
582 /* Add it to the list if we got one */
590 /* Close the file and return the list */
597 * Generate a list of ping targets from the entries in a string.
600 * list - A list of comma separated host names.
603 * A list of targets to ping or null if an error occured.
607 readPingHostsList(char *list)
610 /* Local Variables */
613 ping_target *hostlist = NULL;
616 /* Check that there is a list */
618 if ((list == NULL) || (list[0] == '\0'))
621 /* Loop through the hosts and add them to the list to return */
623 host = strtok(list, ",");
624 while (host != NULL) {
627 new->next = hostlist;
630 host = strtok(NULL, ",");
639 * Generate a list ping targets consisting of all of the entries on
643 * A list of all of the hosts on this net.
647 subnetHostsList(void)
650 /* Local Variables */
652 char hostname[BUFSIZ];
653 char address[BUFSIZ];
654 struct hostent *hent;
658 ping_target *list = NULL;
660 /* Get our hostname */
662 if (gethostname(hostname, BUFSIZ)) {
663 fprintf(stderr, "Unable to get local hostname\n");
667 /* Get our IP address and convert it to a string */
669 if ((hent = gethostbyname(hostname)) == NULL) {
670 fprintf(stderr, "Unable to lookup our IP address\n");
673 strcpy(address, inet_ntoa(*((struct in_addr *)hent->h_addr_list[0])));
675 /* Get a pointer to the last "." in the string */
677 if ((p = strrchr(address, '.')) == NULL) {
678 fprintf(stderr, "Can't parse IP address %s\n", address);
683 /* Construct targets for all addresses in this subnet */
685 for (i = 254; i > 0; i--) {
687 new = newHost(address);
700 * Initialize the ping sensor.
703 * A newly allocated ping_info structure or null if an error occured.
710 /* Local Variables */
712 ping_info *pi = NULL; /* The new ping_info struct */
713 char *src; /* The source of the ping hosts */
714 ping_target *pt; /* Used to count the targets */
716 /* Create the ping info structure */
718 if ((pi = (ping_info *) calloc(1, sizeof(ping_info))) == NULL) {
719 fprintf(stderr, "Out of memory\n");
720 goto ping_init_error;
723 /* Create the ICMP socket and turn off SUID */
725 if ((pi->icmpsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
726 perror("Can't create ICMP socket");
728 "%s: this program must be setuid to root for `ping mode' to work.\n",
730 goto ping_init_error;
733 pi->pid = getpid() & 0xFFFF;
735 pi->timeout = get_integer_resource("pingTimeout", "PingTimeout");
737 /* Generate a list of targets */
739 src = get_string_resource("pingSource", "PingSource");
740 if (strcmp(src, "file") == 0) {
743 * The list of ping targets is to come from a file in
747 pi->targets = readPingHostsFile(get_string_resource("pingFile",
750 } else if (strcmp(src, "list") == 0) {
752 /* The list of hosts is to come from the pinghostlist resource */
754 pi->targets = readPingHostsList(get_string_resource("pingList",
757 } else if (strcmp(src, "subnet") == 0) {
759 pi->targets = subnetHostsList();
765 fprintf(stderr, "Illegal pingSource: %s\n", src);
766 goto ping_init_error;
769 /* Make sure there is something to ping */
771 if (pi->targets == NULL) {
772 fprintf(stderr, "Nothing to ping");
773 goto ping_init_error;
776 /* Count the targets */
789 /* Handle initialization errors here */
801 * pi - The ping information strcuture.
802 * host - The name or IP address of the host to ping (in ascii).
806 sendping(ping_info *pi, ping_target *pt)
809 /* Local Variables */
816 * Note, we will send the character name of the host that we are
817 * pinging in the packet so that we don't have to keep track of the
818 * name or do an address lookup when it comes back.
821 int pcktsiz = sizeof(struct ICMP) + sizeof(struct timeval) +
822 strlen(pt->name) + 1;
824 /* Create the ICMP packet */
826 if ((packet = (u_char *) malloc(pcktsiz)) == (void *) 0)
827 return; /* Out of memory */
828 icmph = (struct ICMP *) packet;
829 ICMP_TYPE(icmph) = ICMP_ECHO;
830 ICMP_CODE(icmph) = 0;
831 ICMP_CHECKSUM(icmph) = 0;
832 ICMP_ID(icmph) = pi->pid;
833 ICMP_SEQ(icmph) = pi->seq++;
834 gettimeofday((struct timeval *) &packet[sizeof(struct ICMP)],
835 (struct timezone *) 0);
836 strcpy((char *) &packet[sizeof(struct ICMP) + sizeof(struct timeval)],
838 ICMP_CHECKSUM(icmph) = checksum((u_short *)packet, pcktsiz);
842 if ((result = sendto(pi->icmpsock, packet, pcktsiz, 0,
843 &pt->address, sizeof(pt->address))) != pcktsiz) {
846 sprintf(errbuf, "Error sending ping to %s", pt->name);
853 * Catch a signal and do nothing.
856 * sig - The signal that was caught.
866 * Compute the checksum on a ping packet.
869 * packet - A pointer to the packet to compute the checksum for.
870 * size - The size of the packet.
873 * The computed checksum
878 checksum(u_short *packet, int size)
881 /* Local Variables */
883 register int nleft = size;
884 register u_short *w = packet;
885 register int sum = 0;
889 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
890 * sequential 16 bit words to it, and at the end, fold back all the
891 * carry bits from the top 16 bits into the lower 16 bits.
899 /* mop up an odd byte, if necessary */
902 *(u_char *)(&answer) = *(u_char *)w ;
903 *(1 + (u_char *)(&answer)) = 0;
907 /* add back carry outs from top 16 bits to low 16 bits */
909 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
910 sum += (sum >> 16); /* add carry */
911 answer = ~sum; /* truncate to 16 bits */
919 * Look for ping replies.
921 * Retrieve all outstanding ping replies.
924 * si - Information about the sonar.
925 * pi - Ping information.
926 * ttl - The time each bogie is to live on the screen
929 * A Bogie list of all the machines that replied.
933 getping(sonar_info *si, ping_info *pi, int ttl)
936 /* Local Variables */
938 struct sockaddr from;
943 struct timeval *then;
953 /* Set up a signal to interupt our wait for a packet */
955 sigemptyset(&sa.sa_mask);
957 sa.sa_handler = sigcatcher;
958 if (sigaction(SIGALRM, &sa, 0) == -1) {
959 perror("Unable to trap sigalarm");
963 /* Set up a timer to interupt us if we don't get a packet */
965 it.it_interval.tv_sec = 0;
966 it.it_interval.tv_usec = 0;
967 it.it_value.tv_sec = 0;
968 it.it_value.tv_usec = pi->timeout;
970 setitimer(ITIMER_REAL, &it, NULL);
972 /* Wait for a result packet */
974 fromlen = sizeof(from);
975 while (! timer_expired &&
976 (result = recvfrom(pi->icmpsock, packet, sizeof(packet),
977 0, &from, &fromlen)) > 0) {
979 /* Check the packet */
981 gettimeofday(&now, (struct timezone *) 0);
982 ip = (struct ip *) packet;
983 iphdrlen = ip->ip_hl << 2;
984 icmph = (struct ICMP *) &packet[iphdrlen];
986 /* Was the packet a reply?? */
988 if (ICMP_TYPE(icmph) != ICMP_ECHOREPLY) {
989 /* Ignore anything but ICMP Replies */
995 if (ICMP_ID(icmph) != pi->pid) {
996 /* Ignore packets not set from us */
1000 /* Copy the name of the bogie */
1003 strdup((char *) &packet[iphdrlen +
1004 + sizeof(struct ICMP)
1005 + sizeof(struct timeval)])) == NULL) {
1006 fprintf(stderr, "Out of memory\n");
1010 /* If the name is an IP addr, try to resolve it. */
1014 if (4 == sscanf(name, " %d.%d.%d.%d %c",
1015 &iip[0], &iip[1], &iip[2], &iip[3], &c))
1017 unsigned char ip[4];
1019 ip[0] = iip[0]; ip[1] = iip[1]; ip[2] = iip[2]; ip[3] = iip[3];
1020 h = gethostbyaddr ((char *) ip, 4, AF_INET);
1021 if (h && h->h_name && *h->h_name)
1024 name = strdup (h->h_name);
1029 /* Create the new Bogie and add it to the list we are building */
1031 if ((new = newBogie(name, 0, si->current, ttl)) == NULL)
1036 /* Compute the round trip time */
1038 then = (struct timeval *) &packet[iphdrlen +
1039 sizeof(struct ICMP)];
1040 new->distance = delta(then, &now) / 100;
1041 if (new->distance == 0)
1042 new->distance = 2; /* HACK */
1054 * si - Sonar Information.
1055 * pi - Ping Information.
1058 * A list of hosts that replied to pings or null if there were none.
1062 ping(sonar_info *si, void *vpi)
1065 ping_info *pi = (ping_info *) vpi;
1066 static ping_target *ptr = NULL;
1068 int tick = si->current * -1 + 1;
1069 if ((ptr == NULL) && (tick == 1))
1072 if (pi->numtargets <= 90) {
1073 int xdrant = 90 / pi->numtargets;
1074 if ((tick % xdrant) == 0) {
1075 if (ptr != (ping_target *) 0) {
1081 } else if (pi->numtargets > 90) {
1082 if (ptr != (ping_target *) 0) {
1088 /* Get the results */
1090 return getping(si, pi, TTL);
1093 #endif /* HAVE_PING */
1096 * Calculate the difference between two timevals in microseconds.
1099 * then - The older timeval.
1100 * now - The newer timeval.
1103 * The difference between the two in microseconds.
1107 delta(struct timeval *then, struct timeval *now)
1109 return (((now->tv_sec - then->tv_sec) * 1000000) +
1110 (now->tv_usec - then->tv_usec));
1114 * Initialize the simulation mode.
1121 /* Local Variables */
1126 /* Create the simulation info structure */
1128 if ((si = (sim_info *) calloc(1, sizeof(sim_info))) == NULL) {
1129 fprintf(stderr, "Out of memory\n");
1135 si->numA = get_integer_resource("teamACount", "TeamACount");
1136 if ((si->teamA = (sim_target *)calloc(si->numA, sizeof(sim_target)))
1139 fprintf(stderr, "Out of Memory\n");
1142 si->teamAID = get_string_resource("teamAName", "TeamAName");
1143 for (i = 0; i < si->numA; i++) {
1144 if ((si->teamA[i].name = (char *) malloc(strlen(si->teamAID) + 4))
1147 fprintf(stderr, "Out of Memory\n");
1150 sprintf(si->teamA[i].name, "%s%03d", si->teamAID, i+1);
1151 si->teamA[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1152 si->teamA[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1157 si->numB = get_integer_resource("teamBCount", "TeamBCount");
1158 if ((si->teamB = (sim_target *)calloc(si->numB, sizeof(sim_target)))
1161 fprintf(stderr, "Out of Memory\n");
1164 si->teamBID = get_string_resource("teamBName", "TeamBName");
1165 for (i = 0; i < si->numB; i++) {
1166 if ((si->teamB[i].name = (char *) malloc(strlen(si->teamBID) + 4))
1169 fprintf(stderr, "Out of Memory\n");
1172 sprintf(si->teamB[i].name, "%s%03d", si->teamBID, i+1);
1173 si->teamB[i].nexttick = (int) (90.0 * random() / RAND_MAX);
1174 si->teamB[i].nextdist = (int) (100.0 * random() / RAND_MAX);
1183 * Initialize the Sonar.
1186 * dpy - The X display.
1187 * win - The X window;
1190 * A sonar_info strcuture or null if memory allocation problems occur.
1194 init_sonar(Display *dpy, Window win)
1197 /* Local Variables */
1200 XWindowAttributes xwa;
1204 double s1, s2, v1, v2;
1206 /* Create the Sonar information structure */
1208 if ((si = (sonar_info *) calloc(1, sizeof(sonar_info))) == NULL) {
1209 fprintf(stderr, "Out of memory\n");
1213 /* Initialize the structure for the current environment */
1218 XGetWindowAttributes(dpy, win, &xwa);
1219 si->cmap = xwa.colormap;
1220 si->width = xwa.width;
1221 si->height = xwa.height;
1222 si->centrex = si->width / 2;
1223 si->centrey = si->height / 2;
1224 si->maxx = si->centrex + MY_MIN(si->centrex, si->centrey) - 10;
1225 si->minx = si->centrex - MY_MIN(si->centrex, si->centrey) + 10;
1226 si->maxy = si->centrey + MY_MIN(si->centrex, si->centrey) - 10;
1227 si->miny = si->centrey - MY_MIN(si->centrex, si->centrey) + 10;
1228 si->radius = si->maxx - si->centrex;
1233 if (((si->font = XLoadQueryFont(dpy, get_string_resource ("font", "Font")))
1235 ((si->font = XLoadQueryFont(dpy, "fixed")) == NULL)) {
1236 fprintf(stderr, "Can't load an appropriate font\n");
1240 /* Get the delay between animation frames */
1242 si->delay = get_integer_resource ("delay", "Integer");
1243 if (si->delay < 0) si->delay = 0;
1245 /* Create the Graphics Contexts that will be used to draw things */
1248 get_pixel_resource ("sweepColor", "SweepColor", dpy, si->cmap);
1249 si->hi = XCreateGC(dpy, win, GCForeground, &gcv);
1250 gcv.font = si->font->fid;
1251 si->text = XCreateGC(dpy, win, GCForeground|GCFont, &gcv);
1252 gcv.foreground = get_pixel_resource("scopeColor", "ScopeColor",
1254 si->erase = XCreateGC (dpy, win, GCForeground, &gcv);
1255 gcv.foreground = get_pixel_resource("gridColor", "GridColor",
1257 si->grid = XCreateGC (dpy, win, GCForeground, &gcv);
1259 /* Compute pixel values for fading text on the display */
1261 XParseColor(dpy, si->cmap,
1262 get_string_resource("textColor", "TextColor"), &start);
1263 XParseColor(dpy, si->cmap,
1264 get_string_resource("scopeColor", "ScopeColor"), &end);
1266 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1267 rgb_to_hsv (end.red, end.green, end.blue, &h2, &s2, &v2);
1269 si->text_steps = get_integer_resource("textSteps", "TextSteps");
1270 if (si->text_steps < 0 || si->text_steps > 255)
1271 si->text_steps = 10;
1273 si->text_colors = (XColor *) calloc(si->text_steps, sizeof(XColor));
1274 make_color_ramp (dpy, si->cmap,
1277 si->text_colors, &si->text_steps,
1278 False, True, False);
1280 /* Compute the pixel values for the fading sweep */
1282 XParseColor(dpy, si->cmap,
1283 get_string_resource("sweepColor", "SweepColor"), &start);
1285 rgb_to_hsv (start.red, start.green, start.blue, &h1, &s1, &v1);
1287 si->sweep_degrees = get_integer_resource("sweepDegrees", "Degrees");
1288 if (si->sweep_degrees <= 0) si->sweep_degrees = 20;
1289 if (si->sweep_degrees > 350) si->sweep_degrees = 350;
1291 si->sweep_segs = get_integer_resource("sweepSegments", "SweepSegments");
1292 if (si->sweep_segs < 1 || si->sweep_segs > 255)
1293 si->sweep_segs = 255;
1295 si->sweep_colors = (XColor *) calloc(si->sweep_segs, sizeof(XColor));
1296 make_color_ramp (dpy, si->cmap,
1299 si->sweep_colors, &si->sweep_segs,
1300 False, True, False);
1308 * Update the location of a simulated bogie.
1312 updateLocation(sim_target *t)
1317 t->movedlasttick = 1;
1318 xtick = (int) (3.0 * random() / RAND_MAX) - 1;
1319 xdist = (int) (11.0 * random() / RAND_MAX) - 5;
1320 if (((t->nexttick + xtick) < 90) && ((t->nexttick + xtick) >= 0))
1321 t->nexttick += xtick;
1323 t->nexttick -= xtick;
1324 if (((t->nextdist + xdist) < 100) && ((t->nextdist+xdist) >= 0))
1325 t->nextdist += xdist;
1327 t->nextdist -= xdist;
1331 * The simulator. This uses information in the sim_info to simulate a bunch
1332 * of bogies flying around on the screen.
1336 * TODO: It would be cool to have the two teams chase each other around and
1341 simulator(sonar_info *si, void *vinfo)
1344 /* Local Variables */
1350 sim_info *info = (sim_info *) vinfo;
1354 for (i = 0; i < info->numA; i++) {
1355 t = &info->teamA[i];
1356 if (!t->movedlasttick && (t->nexttick == (si->current * -1))) {
1357 new = newBogie(strdup(t->name), t->nextdist, si->current, TTL);
1363 t->movedlasttick = 0;
1368 for (i = 0; i < info->numB; i++) {
1369 t = &info->teamB[i];
1370 if (!t->movedlasttick && (t->nexttick == (si->current * -1))) {
1371 new = newBogie(strdup(t->name), t->nextdist, si->current, TTL);
1375 t->movedlasttick = 1;
1378 t->movedlasttick = 0;
1387 * Compute the X coordinate of the label.
1390 * si - The sonar info block.
1391 * label - The label that will be drawn.
1392 * x - The x coordinate of the bogie.
1395 * The x coordinate of the start of the label.
1399 computeStringX(sonar_info *si, char *label, int x)
1402 int width = XTextWidth(si->font, label, strlen(label));
1403 return x - (width / 2);
1407 * Compute the Y coordinate of the label.
1410 * si - The sonar information.
1411 * y - The y coordinate of the bogie.
1414 * The y coordinate of the start of the label.
1417 /* TODO: Add smarts to keep label in sonar screen */
1420 computeStringY(sonar_info *si, int y)
1423 int fheight = si->font->ascent + si->font->descent;
1424 return y + 5 + fheight;
1428 * Draw a Bogie on the radar screen.
1431 * si - Sonar Information.
1432 * draw - A flag to indicate if the bogie should be drawn or erased.
1433 * name - The name of the bogie.
1434 * degrees - The number of degrees that it should apprear at.
1435 * distance - The distance the object is from the centre.
1436 * ttl - The time this bogie has to live.
1437 * age - The time this bogie has been around.
1441 DrawBogie(sonar_info *si, int draw, char *name, int degrees,
1442 int distance, int ttl, int age)
1445 /* Local Variables */
1449 int ox = si->centrex;
1450 int oy = si->centrey;
1453 /* Compute the coordinates of the object */
1455 distance = (log((double) distance) / 10.0) * si->radius;
1456 x = ox + ((double) distance * cos(4.0 * ((double) degrees)/57.29578));
1457 y = oy - ((double) distance * sin(4.0 * ((double) degrees)/57.29578));
1459 /* Set up the graphics context */
1463 /* Here we attempt to compute the distance into the total life of
1464 * object that we currently are. This distance is used against
1465 * the total lifetime to compute a fraction which is the index of
1466 * the color to draw the bogie.
1469 if (si->current <= degrees)
1470 delta = (si->current - degrees) * -1;
1472 delta = 90 + (degrees - si->current);
1473 delta += (age * 90);
1474 index = (si->text_steps - 1) * ((float) delta / (90.0 * (float) ttl));
1476 XSetForeground(si->dpy, gc, si->text_colors[index].pixel);
1481 /* Draw (or erase) the Bogie */
1483 XFillArc(si->dpy, si->win, gc, x, y, 5, 5, 0, 360 * 64);
1484 XDrawString(si->dpy, si->win, gc,
1485 computeStringX(si, name, x),
1486 computeStringY(si, y), name, strlen(name));
1491 * Draw the sonar grid.
1494 * si - Sonar information block.
1498 drawGrid(sonar_info *si)
1501 /* Local Variables */
1504 int width = si->maxx - si->minx;
1505 int height = si->maxy - si->miny;
1507 /* Draw the circles */
1509 XDrawArc(si->dpy, si->win, si->grid, si->minx - 10, si->miny - 10,
1510 width + 20, height + 20, 0, (360 * 64));
1512 XDrawArc(si->dpy, si->win, si->grid, si->minx, si->miny,
1513 width, height, 0, (360 * 64));
1515 XDrawArc(si->dpy, si->win, si->grid,
1516 (int) (si->minx + (.166 * width)),
1517 (int) (si->miny + (.166 * height)),
1518 (unsigned int) (.666 * width), (unsigned int)(.666 * height),
1521 XDrawArc(si->dpy, si->win, si->grid,
1522 (int) (si->minx + (.333 * width)),
1523 (int) (si->miny + (.333 * height)),
1524 (unsigned int) (.333 * width), (unsigned int) (.333 * height),
1527 /* Draw the radial lines */
1529 for (i = 0; i < 360; i += 10)
1531 XDrawLine(si->dpy, si->win, si->grid, si->centrex, si->centrey,
1532 (int) (si->centrex +
1533 (si->radius + 10) * (cos((double) i / 57.29578))),
1534 (int) (si->centrey -
1535 (si->radius + 10)*(sin((double) i / 57.29578))));
1537 XDrawLine(si->dpy, si->win, si->grid,
1538 (int) (si->centrex + si->radius *
1539 (cos((double) i / 57.29578))),
1540 (int) (si->centrey - si->radius *
1541 (sin((double) i / 57.29578))),
1542 (int) (si->centrex +
1543 (si->radius + 10) * (cos((double) i / 57.29578))),
1544 (int) (si->centrey -
1545 (si->radius + 10) * (sin((double) i / 57.29578))));
1549 * Update the Sonar scope.
1552 * si - The Sonar information.
1553 * bl - A list of bogies to add to the scope.
1557 Sonar(sonar_info *si, Bogie *bl)
1560 /* Local Variables */
1565 /* Check for expired tagets and remove them from the visable list */
1568 for (bp = si->visable; bp != NULL; bp = bp->next) {
1571 * Remove it from the visable list if it's expired or we have
1572 * a new target with the same name.
1577 if (((bp->tick == si->current) && (++bp->age >= bp->ttl)) ||
1578 (findNode(bl, bp->name) != NULL)) {
1579 DrawBogie(si, 0, bp->name, bp->tick,
1580 bp->distance, bp->ttl, bp->age);
1582 si->visable = bp->next;
1584 prev->next = bp->next;
1590 /* Draw the sweep */
1593 int seg_deg = (si->sweep_degrees * 64) / si->sweep_segs;
1594 int start_deg = si->current * 4 * 64;
1595 if (seg_deg <= 0) seg_deg = 1;
1596 for (i = 0; i < si->sweep_segs; i++) {
1597 XSetForeground(si->dpy, si->hi, si->sweep_colors[i].pixel);
1598 XFillArc(si->dpy, si->win, si->hi, si->minx, si->miny,
1599 si->maxx - si->minx, si->maxy - si->miny,
1600 start_deg + (i * seg_deg),
1604 /* Remove the trailing wedge the sonar */
1605 XFillArc(si->dpy, si->win, si->erase, si->minx, si->miny,
1606 si->maxx - si->minx, si->maxy - si->miny,
1607 start_deg + (i * seg_deg),
1611 /* Move the new targets to the visable list */
1613 for (bp = bl; bp != (Bogie *) 0; bp = bl) {
1615 bp->next = si->visable;
1619 /* Draw the visable targets */
1621 for (bp = si->visable; bp != NULL; bp = bp->next) {
1622 if (bp->age < bp->ttl) /* grins */
1623 DrawBogie(si, 1, bp->name, bp->tick, bp->distance, bp->ttl,bp->age);
1626 /* Redraw the grid */
1632 * Main screen saver hack.
1635 * dpy - The X display.
1636 * win - The X window.
1640 screenhack(Display *dpy, Window win)
1643 /* Local Variables */
1646 struct timeval start, finish;
1653 * Adding new sensors would involve supporting more modes other than
1654 * ping and initiailizing the sensor in the same way.
1657 mode = get_string_resource("mode", "Mode");
1659 if (!mode || !*mode || !strcmp(mode, "default")) /* Pick a good default. */
1662 if (geteuid() == 0) /* we're root or setuid -- ping will work. */
1666 mode = "simulation";
1670 if (strcmp(mode, "ping") == 0) {
1672 if ((sensor_info = (void *) init_ping()) == (void *) 0)
1674 fprintf (stderr, "%s: running in `simulation mode' instead.\n",
1679 #endif /* HAVE_PING */
1680 if (strcmp(mode, "simulation") == 0) {
1685 if ((sensor_info = (void *) init_sim()) == NULL)
1688 fprintf(stderr, "Unsupported Sonar mode: %s\n", mode);
1690 "\tCurrently supported modes are `ping' and `simulation'\n");
1693 if ((si = init_sonar(dpy, win)) == (sonar_info *) 0)
1698 TTL = get_integer_resource("ttl", "TTL");
1702 /* Call the sensor and display the results */
1704 gettimeofday(&start, (struct timezone *) 0);
1705 bl = sensor(si, sensor_info);
1708 /* Set up and sleep for the next one */
1710 si->current = (si->current - 1) % 90;
1712 gettimeofday(&finish, (struct timezone *) 0);
1713 sleeptime = si->delay - delta(&start, &finish);
1714 screenhack_handle_events (dpy);