http://www.archive.org/download/tucows_10294_XScreenSaver/xscreensaver-4.10.tar.gz
[xscreensaver] / hacks / xmatrix.c
1 /* xscreensaver, Copyright (c) 1999, 2001 Jamie Zawinski <jwz@jwz.org>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or 
9  * implied warranty.
10  *
11  * Matrix -- simulate the text scrolls from the movie "The Matrix".
12  *
13  * The movie people distribute their own Windows/Mac screensaver that does
14  * a similar thing, so I wrote one for Unix.  However, that version (the
15  * Windows/Mac version at http://www.whatisthematrix.com/) doesn't match my
16  * memory of what the screens in the movie looked like, so my `xmatrix'
17  * does things differently.
18  *
19  *
20  *     ==========================================================
21  *
22  *         NOTE:
23  *
24  *         People just love to hack on this one.  I get sent
25  *         patches to this all the time saying, ``here, I made
26  *         it better!''  Mostly this hasn't been true.
27  *
28  *         If you've made changes to xmatrix, when you send me
29  *         your patch, please explain, in English, both *what*
30  *         your changes are, and *why* you think those changes
31  *         make this screensaver behave more like the displays
32  *         in the movie did.  I'd rather not have to read your
33  *         diffs to try and figure that out for myself...
34  *
35  *         In particular, note that the characters in the movie
36  *         were, in fact, low resolution and somewhat blurry/
37  *         washed out.  They also definitely scrolled a
38  *         character at a time, not a pixel at a time.
39  *
40  *     ==========================================================
41  *
42  */
43
44 #include "screenhack.h"
45 #include "xpm-pixmap.h"
46 #include <stdio.h>
47 #include <X11/Xutil.h>
48
49 #if defined(HAVE_GDK_PIXBUF) || defined(HAVE_XPM)
50 # include "images/matrix0.xpm"
51 # include "images/matrix1.xpm"
52 # include "images/matrix2.xpm"
53 # include "images/matrix0b.xpm"
54 # include "images/matrix1b.xpm"
55 # include "images/matrix2b.xpm"
56 #endif
57
58 #include "images/matrix0.xbm"
59 #include "images/matrix1.xbm"
60 #include "images/matrix2.xbm"
61 #include "images/matrix0b.xbm"
62 #include "images/matrix1b.xbm"
63 #include "images/matrix2b.xbm"
64
65 #define CHAR_COLS 16
66 #define CHAR_ROWS 13
67 #define CHAR_MAPS 3
68 #define FADE_MAP  0
69 #define PLAIN_MAP 1
70 #define GLOW_MAP  2
71
72 typedef struct {
73            int glow    : 8;
74   unsigned int glyph   : 9;  /* note: 9 bit characters! */
75   unsigned int changed : 1;
76   unsigned int spinner : 1;
77 } m_cell;
78
79 typedef struct {
80   int remaining;
81   int throttle;
82   int y;
83 } m_feeder;
84
85 #define countof(x) (sizeof(x)/sizeof(*(x)))
86
87 static int matrix_encoding[] = { 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
88                                  192, 193, 194, 195, 196, 197, 198, 199,
89                                  200, 201, 202, 203, 204, 205, 206, 207 };
90 static int decimal_encoding[]  = { 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };
91 static int hex_encoding[]      = { 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
92                                    33, 34, 35, 36, 37, 38 };
93 static int binary_encoding[] = { 16, 17 };
94 static int dna_encoding[]    = { 33, 35, 39, 52 };
95 static unsigned char char_map[256] = {
96     3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  /*   0 */
97     3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  /*  16 */
98     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,  /*  32 */
99    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,  /*  48 */
100    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,  /*  64 */
101    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,  /*  80 */
102    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,  /*  96 */
103    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,  /* 112 */
104     3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  /* 128 */
105     3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  /* 144 */
106    96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,  /* 160 */
107   112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,  /* 176 */
108   128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,  /* 192 */
109   144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,  /* 208 */
110   160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,  /* 224 */
111   176,177,178,195,180,181,182,183,184,185,186,187,188,189,190,191   /* 240 */
112 };
113
114 #define CURSOR_GLYPH 97
115
116 typedef enum { TRACE0, TRACE1, TRACE2,
117                KNOCK0, KNOCK1, KNOCK2, KNOCK3,
118                KNOCK4, KNOCK5, KNOCK6, KNOCK7,
119                NMAP0, NMAP1,
120                MATRIX, DNA, BINARY, HEX } m_mode;
121
122 typedef struct {
123   Display *dpy;
124   Window window;
125   XWindowAttributes xgwa;
126   GC draw_gc, erase_gc;
127   int grid_width, grid_height;
128   int char_width, char_height;
129   m_cell *cells;
130   m_cell *cursor;
131   m_feeder *feeders;
132   int nspinners;
133   Bool knock_knock_p;
134   Bool small_p;
135   Bool insert_top_p, insert_bottom_p;
136   m_mode mode;
137   signed char *tracing;
138   int density;
139
140   Pixmap images[CHAR_MAPS];
141   int image_width, image_height;
142
143   int nglyphs;
144   int *glyph_map;
145
146 } m_state;
147
148
149 static void
150 load_images_1 (m_state *state, int which)
151 {
152 #if defined(HAVE_GDK_PIXBUF) || defined(HAVE_XPM)
153   if (!get_boolean_resource ("mono", "Boolean") &&
154       state->xgwa.depth > 1)
155     {
156       char **bits =
157         (which == 0 ? (state->small_p ? matrix0b_xpm : matrix0_xpm) :
158          which == 1 ? (state->small_p ? matrix1b_xpm : matrix1_xpm) :
159          (state->small_p ? matrix2b_xpm : matrix2_xpm));
160
161       state->images[which] =
162         xpm_data_to_pixmap (state->dpy, state->window, bits,
163                             &state->image_width, &state->image_height, 0);
164     }
165   else
166 #endif /* !HAVE_XPM && !HAVE_GDK_PIXBUF */
167     {
168       unsigned long fg, bg;
169       state->image_width  = (state->small_p ? matrix0b_width :matrix0_width);
170       state->image_height = (state->small_p ? matrix0b_height:matrix0_height);
171       fg = get_pixel_resource("foreground", "Foreground",
172                               state->dpy, state->xgwa.colormap);
173       bg = get_pixel_resource("background", "Background",
174                               state->dpy, state->xgwa.colormap);
175       state->images[which] =
176         XCreatePixmapFromBitmapData (state->dpy, state->window, (char *)
177                 (which == 0 ? (state->small_p ? matrix0b_bits :matrix0_bits) :
178                  which == 1 ? (state->small_p ? matrix1b_bits :matrix1_bits) :
179                               (state->small_p ? matrix2b_bits :matrix2_bits)),
180                                      state->image_width, state->image_height,
181                                      bg, fg, state->xgwa.depth);
182     }
183 }
184
185
186 static void
187 load_images (m_state *state)
188 {
189   load_images_1 (state, 0);
190   load_images_1 (state, 1);
191   load_images_1 (state, 2);
192 }
193
194
195 static void
196 flip_images_1 (m_state *state, int which)
197 {
198   XImage *im = XGetImage (state->dpy, state->images[which], 0, 0,
199                           state->image_width, state->image_height,
200                           ~0L, (state->xgwa.depth > 1 ? ZPixmap : XYPixmap));
201   int x, y, xx;
202   int ww = state->char_width;
203   unsigned long *row = (unsigned long *) malloc (sizeof(*row) * ww);
204
205   for (y = 0; y < state->image_height; y++)
206     {
207       for (x = 0; x < CHAR_COLS; x++)
208         {
209           for (xx = 0; xx < ww; xx++)
210             row[xx] = XGetPixel (im, (x * ww) + xx, y);
211           for (xx = 0; xx < ww; xx++)
212             XPutPixel (im, (x * ww) + xx, y, row[ww - xx - 1]);
213         }
214     }
215
216   XPutImage (state->dpy, state->images[which], state->draw_gc, im, 0, 0, 0, 0,
217              state->image_width, state->image_height);
218   XDestroyImage (im);
219   free (row);
220 }
221
222 static void
223 flip_images (m_state *state)
224 {
225   flip_images_1 (state, 0);
226   flip_images_1 (state, 1);
227   flip_images_1 (state, 2);
228 }
229
230
231 static void
232 init_spinners (m_state *state)
233 {
234   int i = state->nspinners;
235   int x, y;
236   m_cell *cell;
237
238   for (y = 0; y < state->grid_height; y++)
239     for (x = 0; x < state->grid_width; x++)
240       {
241         cell = &state->cells[state->grid_width * y + x];
242         cell->spinner = 0;
243       }
244
245   while (--i > 0)
246     {
247       x = random() % state->grid_width;
248       y = random() % state->grid_height;
249       cell = &state->cells[state->grid_width * y + x];
250       cell->spinner = 1;
251     }
252 }
253
254
255 static void
256 init_trace (m_state *state)
257 {
258   char *s = get_string_resource ("tracePhone", "TracePhone");
259   char *s2, *s3;
260   int i;
261   if (!s)
262     goto FAIL;
263
264   state->tracing = (char *) malloc (strlen (s) + 1);
265   s3 = state->tracing;
266
267   for (s2 = s; *s2; s2++)
268     if (*s2 >= '0' && *s2 <= '9')
269       *s3++ = *s2;
270   *s3 = 0;
271
272   if (s3 == (char *) state->tracing)
273     goto FAIL;
274
275   for (i = 0; i < strlen(state->tracing); i++)
276     state->tracing[i] = -state->tracing[i];
277
278   state->glyph_map = decimal_encoding;
279   state->nglyphs = countof(decimal_encoding);
280
281   return;
282
283  FAIL:
284   fprintf (stderr, "%s: bad phone number: \"%s\".\n",
285            progname, s ? s : "(null)");
286
287   if (s) free (s);
288   if (state->tracing) free (state->tracing);
289   state->tracing = 0;
290   state->mode = MATRIX;
291 }
292
293
294 static m_state *
295 init_matrix (Display *dpy, Window window)
296 {
297   XGCValues gcv;
298   char *insert, *mode;
299   m_state *state = (m_state *) calloc (sizeof(*state), 1);
300
301   state->dpy = dpy;
302   state->window = window;
303
304   XGetWindowAttributes (dpy, window, &state->xgwa);
305
306   {
307     const char *s = get_string_resource ("small", "Boolean");
308     if (s && *s)
309       state->small_p = get_boolean_resource ("small", "Boolean");
310     else
311       state->small_p = (state->xgwa.width < 300);
312   }
313
314   load_images (state);
315
316   gcv.foreground = get_pixel_resource("foreground", "Foreground",
317                                       state->dpy, state->xgwa.colormap);
318   gcv.background = get_pixel_resource("background", "Background",
319                                       state->dpy, state->xgwa.colormap);
320   state->draw_gc = XCreateGC (state->dpy, state->window,
321                               GCForeground|GCBackground, &gcv);
322   gcv.foreground = gcv.background;
323   state->erase_gc = XCreateGC (state->dpy, state->window,
324                                GCForeground|GCBackground, &gcv);
325
326   state->char_width =  state->image_width  / CHAR_COLS;
327   state->char_height = state->image_height / CHAR_ROWS;
328
329   state->grid_width  = state->xgwa.width  / state->char_width;
330   state->grid_height = state->xgwa.height / state->char_height;
331   state->grid_width++;
332   state->grid_height++;
333   if (state->grid_width  < 5) state->grid_width  = 5;
334   if (state->grid_height < 5) state->grid_height = 5;
335
336   state->glyph_map = matrix_encoding;
337   state->nglyphs = countof(matrix_encoding);
338
339   state->cells = (m_cell *)
340     calloc (sizeof(m_cell), state->grid_width * state->grid_height);
341   state->cursor = NULL;
342   state->feeders = (m_feeder *) calloc (sizeof(m_feeder), state->grid_width);
343
344   state->density = get_integer_resource ("density", "Integer");
345
346   insert = get_string_resource("insert", "Insert");
347   if (insert && !strcmp(insert, "top"))
348     {
349       state->insert_top_p = True;
350       state->insert_bottom_p = False;
351     }
352   else if (insert && !strcmp(insert, "bottom"))
353     {
354       state->insert_top_p = False;
355       state->insert_bottom_p = True;
356     }
357   else if (insert && !strcmp(insert, "both"))
358     {
359       state->insert_top_p = True;
360       state->insert_bottom_p = True;
361     }
362   else
363     {
364       if (insert && *insert)
365         fprintf (stderr,
366                  "%s: `insert' must be `top', `bottom', or `both', not `%s'\n",
367                  progname, insert);
368       state->insert_top_p = False;
369       state->insert_bottom_p = True;
370     }
371
372   state->nspinners = get_integer_resource ("spinners", "Integer");
373
374   if (insert)
375     free (insert);
376
377   state->knock_knock_p = get_boolean_resource ("knockKnock", "KnockKnock");
378
379   mode = get_string_resource ("mode", "Mode");
380   if (mode && !strcasecmp(mode, "trace"))
381     state->mode = TRACE0;
382   else if (mode && !strcasecmp(mode, "crack"))
383     state->mode = NMAP0;
384   else if (mode && !strcasecmp(mode, "dna"))
385     state->mode = DNA;
386   else if (mode && !strcasecmp(mode, "binary"))
387     state->mode = BINARY;
388   else if (mode && (!strcasecmp(mode, "hex") ||
389                     !strcasecmp(mode, "hexadecimal")))
390     state->mode = HEX;
391   else if (!mode || !*mode || !strcasecmp(mode, "matrix"))
392     state->mode = MATRIX;
393   else
394     {
395       fprintf (stderr,
396            "%s: `mode' must be matrix, trace, dna, binary, or hex: not `%s'\n",
397                progname, mode);
398       state->mode = MATRIX;
399     }
400
401   if (state->mode == DNA)
402     {
403       state->glyph_map = dna_encoding;
404       state->nglyphs = countof(dna_encoding);
405     }
406   else if (state->mode == BINARY)
407     {
408       state->glyph_map = binary_encoding;
409       state->nglyphs = countof(binary_encoding);
410     }
411   else if (state->mode == HEX)
412     {
413       state->glyph_map = hex_encoding;
414       state->nglyphs = countof(hex_encoding);
415     }
416   else if (state->mode == HEX)
417     {
418       state->glyph_map = hex_encoding;
419       state->nglyphs = countof(hex_encoding);
420     }
421   else if (state->mode == TRACE0)
422     init_trace (state);
423   else if (state->mode == NMAP0)
424     ;
425   else
426     {
427       flip_images (state);
428       init_spinners (state);
429     }
430
431   return state;
432 }
433
434
435 static void
436 insert_glyph (m_state *state, int glyph, int x, int y)
437 {
438   Bool bottom_feeder_p = (y >= 0);
439   m_cell *from, *to;
440
441   if (y >= state->grid_height)
442     return;
443
444   if (bottom_feeder_p)
445     {
446       to = &state->cells[state->grid_width * y + x];
447     }
448   else
449     {
450       for (y = state->grid_height-1; y > 0; y--)
451         {
452           from = &state->cells[state->grid_width * (y-1) + x];
453           to   = &state->cells[state->grid_width * y     + x];
454           to->glyph   = from->glyph;
455           to->glow    = from->glow;
456           to->changed = 1;
457         }
458       to = &state->cells[x];
459     }
460
461   to->glyph = glyph;
462   to->changed = 1;
463
464   if (!to->glyph)
465     ;
466   else if (bottom_feeder_p)
467     to->glow = 1 + (random() % 2);
468   else
469     to->glow = 0;
470 }
471
472
473 static void
474 feed_matrix (m_state *state)
475 {
476   int x;
477
478   switch (state->mode)
479     {
480     case TRACE2: case MATRIX: case DNA: case BINARY: case HEX:
481       break;
482     default:
483       return;
484     }
485
486   /* Update according to current feeders. */
487   for (x = 0; x < state->grid_width; x++)
488     {
489       m_feeder *f = &state->feeders[x];
490
491       if (f->throttle)          /* this is a delay tick, synced to frame. */
492         {
493           f->throttle--;
494         }
495       else if (f->remaining > 0)        /* how many items are in the pipe */
496         {
497           int g = state->glyph_map[(random() % state->nglyphs)] + 1;
498           insert_glyph (state, g, x, f->y);
499           f->remaining--;
500           if (f->y >= 0)  /* bottom_feeder_p */
501             f->y++;
502         }
503       else                              /* if pipe is empty, insert spaces */
504         {
505           insert_glyph (state, 0, x, f->y);
506           if (f->y >= 0)  /* bottom_feeder_p */
507             f->y++;
508         }
509
510       if ((random() % 10) == 0)         /* randomly change throttle speed */
511         {
512           f->throttle = ((random() % 5) + (random() % 5));
513         }
514     }
515 }
516
517
518 static void
519 redraw_cells (m_state *state, Bool active)
520 {
521   int x, y;
522   int count = 0;
523
524   for (y = 0; y < state->grid_height; y++)
525     for (x = 0; x < state->grid_width; x++)
526       {
527         m_cell *cell = &state->cells[state->grid_width * y + x];
528
529         if (cell->glyph)
530           count++;
531
532         if (state->mode == TRACE2 && active)
533           {
534             int xx = x % strlen(state->tracing);
535             Bool dead_p = state->tracing[xx] > 0;
536
537             if (y == 0 && x == xx)
538               cell->glyph = (dead_p
539                              ? state->glyph_map[state->tracing[xx]-'0'] + 1
540                              : 0);
541             else if (y == 0)
542               cell->glyph = 0;
543             else
544               cell->glyph = (dead_p ? 0 :
545                              (state->glyph_map[(random()%state->nglyphs)]
546                               + 1));
547
548             cell->changed = 1;
549           }
550
551         if (!cell->changed)
552           continue;
553
554         if (cell->glyph == 0 && cell != state->cursor)
555           XFillRectangle (state->dpy, state->window, state->erase_gc,
556                           x * state->char_width,
557                           y * state->char_height,
558                           state->char_width,
559                           state->char_height);
560         else
561           {
562             int g = (cell == state->cursor ? CURSOR_GLYPH : cell->glyph);
563             int cx = (g - 1) % CHAR_COLS;
564             int cy = (g - 1) / CHAR_COLS;
565             int map = ((cell->glow > 0 || cell->spinner) ? GLOW_MAP :
566                        (cell->glow < 0) ? FADE_MAP :
567                        PLAIN_MAP);
568
569             XCopyArea (state->dpy, state->images[map],
570                        state->window, state->draw_gc,
571                        cx * state->char_width,
572                        cy * state->char_height,
573                        state->char_width,
574                        state->char_height,
575                        x * state->char_width,
576                        y * state->char_height);
577           }
578
579         cell->changed = 0;
580
581         if (cell->glow > 0)
582           {
583             cell->glow--;
584             cell->changed = 1;
585           }
586         else if (cell->glow < 0)
587           {
588             cell->glow++;
589             if (cell->glow == 0)
590               cell->glyph = 0;
591             cell->changed = 1;
592           }
593
594         if (cell->spinner && active)
595           {
596             cell->glyph = (state->glyph_map[(random()%state->nglyphs)] + 1);
597             cell->changed = 1;
598           }
599       }
600
601   if (state->cursor)
602     {
603       state->cursor->changed = 1;
604     }
605 }
606
607
608 static int
609 densitizer (m_state *state)
610 {
611   /* Horrid kludge that converts percentages (density of screen coverage)
612      to the parameter that actually controls this.  I got this mapping
613      empirically, on a 1024x768 screen.  Sue me. */
614   if      (state->density < 10) return 85;
615   else if (state->density < 15) return 60;
616   else if (state->density < 20) return 45;
617   else if (state->density < 25) return 25;
618   else if (state->density < 30) return 20;
619   else if (state->density < 35) return 15;
620   else if (state->density < 45) return 10;
621   else if (state->density < 50) return 8;
622   else if (state->density < 55) return 7;
623   else if (state->density < 65) return 5;
624   else if (state->density < 80) return 3;
625   else if (state->density < 90) return 2;
626   else return 1;
627 }
628
629
630 static void drain_matrix (m_state *);
631
632 static void
633 handle_events (m_state *state)
634 {
635   XSync (state->dpy, False);
636   while (XPending (state->dpy))
637     {
638       XEvent event;
639       XNextEvent (state->dpy, &event);
640
641       if (event.xany.type == ConfigureNotify)
642         {
643           int ow = state->grid_width;
644           int oh = state->grid_height;
645           XGetWindowAttributes (state->dpy, state->window, &state->xgwa);
646           state->grid_width  = state->xgwa.width  / state->char_width;
647           state->grid_height = state->xgwa.height / state->char_height;
648           state->grid_width++;
649           state->grid_height++;
650           if (state->grid_width  < 5) state->grid_width  = 5;
651           if (state->grid_height < 5) state->grid_height = 5;
652
653           if (ow != state->grid_width ||
654               oh != state->grid_height)
655             {
656               m_cell *ncells = (m_cell *)
657                 calloc (sizeof(m_cell),
658                         state->grid_width * state->grid_height);
659               m_feeder *nfeeders = (m_feeder *)
660                 calloc (sizeof(m_feeder), state->grid_width);
661               int x, y, i;
662
663               /* fprintf(stderr, "resize: %d x %d  ==>  %d x %d\n",
664                         ow, oh, state->grid_width, state->grid_height); */
665
666               for (y = 0; y < oh; y++)
667                 for (x = 0; x < ow; x++)
668                   if (x < ow && x < state->grid_width &&
669                       y < oh && y < state->grid_height)
670                     ncells[y * state->grid_width + x] =
671                       state->cells[y * ow + x];
672               free (state->cells);
673               state->cells = ncells;
674
675               x = (ow < state->grid_width ? ow : state->grid_width);
676               for (i = 0; i < x; i++)
677                 nfeeders[i] = state->feeders[i];
678               free (state->feeders);
679               state->feeders = nfeeders;
680             }
681         }
682       else if (event.xany.type == KeyPress)
683         {
684           KeySym keysym;
685           char c = 0;
686           XLookupString (&event.xkey, &c, 1, &keysym, 0);
687           if (c == '0')
688             {
689               drain_matrix (state);
690               return;
691             }
692           else if (c == '+' || c == '=' || c == '>' || c == '.')
693             {
694               state->density += 10;
695               if (state->density > 100)
696                 state->density = 100;
697               else
698                 return;
699             }
700           else if (c == '-' || c == '_' || c == '<' || c == ',')
701             {
702               state->density -= 10;
703               if (state->density < 0)
704                 state->density = 0;
705               else
706                 return;
707             }
708         }
709
710       screenhack_handle_event (state->dpy, &event);
711     }
712 }
713
714
715 static void
716 matrix_usleep (m_state *state, unsigned long delay)
717 {
718   if (!delay) return;
719
720   if (state->cursor)
721     {
722       int blink_delay = 333000;
723       int tot_delay = 0;
724       m_cell *cursor = state->cursor;
725       while (tot_delay < delay)
726         {
727           if (state->cursor)
728             {
729               usleep (blink_delay * 2);
730               tot_delay += (2 * blink_delay);
731               state->cursor = NULL;
732             }
733           else
734             {
735               usleep (blink_delay);
736               tot_delay += blink_delay;
737               state->cursor = cursor;
738             }
739           cursor->changed = 1;
740           redraw_cells (state, False);
741           XSync (state->dpy, False);
742           handle_events (state);
743         }
744     }
745   else
746     {
747       XSync (state->dpy, False);
748       handle_events (state);
749       usleep (delay);
750     }
751 }
752
753
754 static void
755 hack_text_1 (m_state *state,
756              int *xP, int *yP,
757              const char *s,
758              Bool typing_delay,
759              Bool transmit_delay,
760              Bool long_delay,
761              Bool visible_cursor,
762              Bool scroll_p)
763 {
764   int x = *xP;
765   int y = *yP;
766   int i = state->grid_width * y + x;
767   Bool glow_p = False;
768
769   if (y >= state->grid_height-1) return;
770
771   while (*s)
772     {
773       m_cell *cell;
774       Bool done_p = s[1] == '\000';
775
776       long_delay = done_p;
777               
778       if (*s == '\n')
779         {
780           x = 0;
781           y++;
782           i = state->grid_width * y + x;
783
784           if (scroll_p)
785             {
786               int xx, yy;
787               for (yy = 0; yy < state->grid_height-1; yy++)
788                 for (xx = 0; xx < state->grid_width; xx++)
789                   {
790                     int ii = yy     * state->grid_width + xx;
791                     int jj = (yy+1) * state->grid_width + xx;
792                     state->cells[ii] = state->cells[jj];
793                     state->cells[ii].changed = 1;
794                   }
795               /* clear bottom row */
796               for (xx = 0; xx < state->grid_width; xx++)
797                 {
798                   int ii = yy * state->grid_width + xx;
799                   state->cells[ii].glyph   = 0;
800                   state->cells[ii].changed = 1;
801                 }
802               y--;  /* move it back */
803               i = state->grid_width * y + x;
804             }
805
806           if (y >= state->grid_height) return;
807
808           cell = &state->cells[i];
809           if (visible_cursor)
810             {
811               cell->changed = 1;
812               state->cursor = cell;
813             }
814         }
815       else if (*s == '\010')
816         ;
817       else if (*s == '\002')
818         glow_p = True;
819       else
820         {
821           cell = &state->cells[i];
822           if (x < state->grid_width-1)
823             {
824               cell->glyph = char_map[(unsigned char) *s] + 1;
825               if (*s == ' ' || *s == '\t') cell->glyph = 0;
826               cell->changed = 1;
827               cell->glow = (glow_p ? 8 : 0);
828               if (visible_cursor)
829                 {
830                   m_cell *next = &state->cells[i + 1];
831                   next->changed = 1;
832                   state->cursor = next;
833                 }
834               i++;
835             }
836           x++;
837         }
838       s++;
839       if (typing_delay || transmit_delay || long_delay)
840         {
841           redraw_cells (state, False);
842           XSync (state->dpy, False);
843           handle_events (state);
844           if (typing_delay)
845             {
846               usleep (50000);
847               if (typing_delay && 0 == random() % 3)
848                 usleep (0xFFFFFF & ((random() % 250000) + 1));
849             }
850           else
851             if (long_delay)
852               matrix_usleep (state, 1000000);
853             else
854               usleep (20000);
855         }
856     }
857
858   *xP = x;
859   *yP = y;
860 }
861
862
863 static void
864 hack_text (m_state *state)
865 {
866   int i;
867   int x = 0;
868   int y = 0;
869   const char *s;
870   Bool typing_delay = False;
871   Bool transmit_delay = False;
872   Bool long_delay = False;
873   Bool visible_cursor = False;
874   switch (state->mode)
875     {
876     case TRACE0: if (state->grid_width >= 52)
877                    s = "Call trans opt: received. 2-19-98 13:24:18 REC:Log>";
878                  else
879                    s = "Call trans opt: received.\n2-19-98 13:24:18 REC:Log>";
880                  transmit_delay = True;
881                  visible_cursor = True;
882                  break;
883     case TRACE1: s = "Trace program: running";
884                  transmit_delay = True;
885                  visible_cursor = True;
886                  break;
887     case KNOCK0: s = "Wake up, Neo..."; break;
888     case KNOCK1: s = ""; break;
889     case KNOCK2: s = "The Matrix has you..."; typing_delay = True; break;
890     case KNOCK3: s = ""; break;
891     case KNOCK4: s = "Follow the white rabbit."; typing_delay = True; break;
892     case KNOCK5: s = ""; break;
893     case KNOCK6: s = "Knock, knock, Neo."; break;
894     case KNOCK7:
895     case NMAP0:
896     case NMAP1:  s = ""; break;
897
898     default: abort(); break;
899     }
900
901   for (i = 0; i < state->grid_height * state->grid_width; i++)
902     {
903       m_cell *cell = &state->cells[i];
904       cell->changed = (cell->glyph != 0);
905       cell->glyph = 0;
906     }
907
908   if (state->mode == NMAP0)
909     {
910       /* Note that what Trinity is using here is moderately accurate:
911          She runs nmap (http://www.insecure.org/nmap/) then breaks in
912          with a (hypothetical) program called "sshnuke" that exploits
913          the (very real) SSHv1 CRC32 compensation attack detector bug
914          (http://staff.washington.edu/dittrich/misc/ssh-analysis.txt).
915
916          The command syntax of the power grid control software looks a
917          lot like Cisco IOS to me.  (IOS is a descendant of VMS.)
918        */
919       const char *blocks[] = {
920         "# ",
921
922         "\001nmap 10.2.2.2\n",
923         "Starting nmap V. 2.54BETA25\n"
924
925         "\010", "\010", "\010",
926
927         "Insufficient responses for TCP sequencing (3), OS detection "
928         "may be less\n"
929         "accurate\n"
930         "Interesting ports on 10.2.2.2:\n"
931         "(The 1538 ports scanned but not shown below are in state: filtered)\n"
932         "Port       state       service\n"
933         "22/tcp     open        ssh\n"
934         "\n"
935         "No exact OS matches for host\n"
936         "\n"
937         "Nmap run completed -- 1 IP address (1 host up) scanned\n"
938         "# ",
939
940         "\001sshnuke 10.2.2.2 -rootpw=\"Z1ON0101\"\n",
941
942         "Connecting to 10.2.2.2:ssh ... ",
943
944         "successful.\n"
945         "Attempting to exploit SSHv1 CRC32 ... ",
946
947         "successful.\n"
948         "Resetting root password to \"Z1ON0101\".\n",
949
950         "System open: Access Level <9>\n"
951         "# ",
952
953         "\001ssh 10.2.2.2 -l root\n",
954
955         "root@10.2.2.2's password: ",
956
957         "\001\010\010\010\010\010\010\010\010\n",
958
959         "\n"
960         "FFF-CONTROL> ",
961
962         "\001disable grid nodes 21 - 40\n",
963
964         "Warning: Disabling nodes 21-40 will disconnect sector 11 (27 nodes)\n"
965         "\n"
966         "\002         ARE YOU SURE? (y/n) ",
967
968         "\001\010\010y\n",
969         "\n"
970       };
971
972       int nblocks = countof(blocks);
973       int y = state->grid_height - 2;
974       int j;
975
976       visible_cursor = True;
977       x = 0;
978       for (j = 0; j < nblocks; j++)
979         {
980           const char *s = blocks[j];
981           typing_delay = (*s == '\001');
982           if (typing_delay) s++;
983
984           long_delay = False;
985           hack_text_1 (state, &x, &y, s,
986                        typing_delay, transmit_delay, long_delay,
987                        visible_cursor, True);
988         }
989
990       typing_delay = False;
991       long_delay = False;
992       for (j = 21; j <= 40; j++)
993         {
994           char buf[100];
995           sprintf (buf, "Grid Node %d offline...\n", j);
996           hack_text_1 (state, &x, &y, buf,
997                        typing_delay, transmit_delay, long_delay,
998                        visible_cursor, True);
999
1000         }
1001       hack_text_1 (state, &x, &y, "\nFFF-CONTROL> ",
1002                    typing_delay, transmit_delay, long_delay,
1003                    visible_cursor, True);
1004       return;
1005     }
1006   else
1007     {
1008       if (state->mode == TRACE0 || state->mode == TRACE1)
1009         x = y = 0;
1010       else
1011         {
1012           x = ((int)state->grid_width - (int)strlen(s)) / 2;
1013           y = (state->grid_height / 2) - 1;
1014           if (y < 0) y = 0;
1015           if (x < 0) x = 0;
1016         }
1017
1018       hack_text_1 (state, &x, &y, s,
1019                    typing_delay, transmit_delay, long_delay,
1020                    visible_cursor, False);
1021     }
1022 }
1023
1024
1025 static void
1026 drain_matrix (m_state *state)
1027 {
1028   int delay = get_integer_resource ("delay", "Integer");
1029   int i;
1030
1031   /* Fill the top row with empty top-feeders, to clear the screen. */
1032   for (i = 0; i < state->grid_width; i++)
1033     {
1034       m_feeder *f = &state->feeders[i];
1035       f->y = -1;
1036       f->remaining = 0;
1037       f->throttle = 0;
1038     }
1039
1040   /* Turn off all the spinners, else they never go away. */
1041   for (i = 0; i < state->grid_width * state->grid_height; i++)
1042     if (state->cells[i].spinner)
1043       {
1044         state->cells[i].spinner = 0;
1045         state->cells[i].changed = 1;
1046       }
1047
1048   /* Run the machine until there are no live cells left. */
1049   while (1)
1050     {
1051       Bool any_cells_p = False;
1052       for (i = 0; i < state->grid_width * state->grid_height; i++)
1053         if (state->cells[i].glyph)
1054           {
1055             any_cells_p = True;
1056             goto FOUND;
1057           }
1058     FOUND:
1059       if (! any_cells_p)
1060         return;
1061
1062       feed_matrix (state);
1063       redraw_cells (state, True);
1064       XSync (state->dpy, False);
1065       handle_events (state);
1066       if (delay) usleep (delay);
1067     }
1068 }
1069
1070
1071 static void
1072 roll_state (m_state *state)
1073 {
1074   int delay = 0;
1075   switch (state->mode)
1076     {
1077     case TRACE0:
1078       delay = 3;
1079       state->mode = TRACE1;
1080       break;
1081
1082     case TRACE1:
1083       delay = 2;
1084       state->mode = TRACE2;
1085       break;
1086
1087     case TRACE2:
1088       {
1089         Bool any = False;
1090         int i;
1091         for (i = 0; i < strlen(state->tracing); i++)
1092           if (state->tracing[i] < 0) any = True;
1093
1094         if (!any)
1095           {
1096             XSync (state->dpy, False);
1097             matrix_usleep (state, 3000000);
1098             state->mode = MATRIX;
1099             state->glyph_map = matrix_encoding;
1100             state->nglyphs = countof(matrix_encoding);
1101             flip_images (state);
1102             free (state->tracing);
1103             state->tracing = 0;
1104           }
1105         else if ((random() % 10) == 0)
1106           {
1107             int x = random() % strlen(state->tracing);
1108             if (state->tracing[x] < 0)
1109               state->tracing[x] = -state->tracing[x];
1110           }
1111         break;
1112       }
1113
1114     case KNOCK0: delay = 1; state->mode++; break; /* wake */
1115     case KNOCK1: delay = 4; state->mode++; break;
1116     case KNOCK2: delay = 2; state->mode++; break; /* has */
1117     case KNOCK3: delay = 4; state->mode++; break;
1118     case KNOCK4: delay = 2; state->mode++; break; /* rabbit */
1119     case KNOCK5: delay = 4; state->mode++; break;
1120     case KNOCK6: delay = 4; state->mode++; break; /* knock */
1121
1122     case NMAP0:  delay = 4; state->mode++; break; /* knock */
1123
1124     case KNOCK7:
1125       delay = 4;
1126     case NMAP1:
1127       state->mode = MATRIX;
1128       state->glyph_map = matrix_encoding;
1129       state->nglyphs = countof(matrix_encoding);
1130       flip_images (state);
1131       break;
1132
1133     case MATRIX:
1134       if (state->knock_knock_p && (! (random() % 3500)))
1135         {
1136           drain_matrix (state);
1137           if (! (random() % 5))
1138             state->mode = NMAP0;
1139           else
1140             state->mode = KNOCK0;
1141
1142           flip_images (state);
1143         }
1144       break;
1145
1146     case DNA: case BINARY: case HEX:
1147       break;
1148
1149     default:
1150       abort();
1151       break;
1152     }
1153
1154   matrix_usleep (state, delay * 1000000);
1155   state->cursor = NULL;
1156 }
1157
1158
1159 static void
1160 hack_matrix (m_state *state)
1161 {
1162   int x;
1163
1164   switch (state->mode)
1165     {
1166     case TRACE0: case TRACE1:
1167     case KNOCK0: case KNOCK1: case KNOCK2: case KNOCK3:
1168     case KNOCK4: case KNOCK5: case KNOCK6: case KNOCK7:
1169     case NMAP0:  case NMAP1:
1170       hack_text (state);
1171       return;
1172     case TRACE2: case MATRIX: case DNA: case BINARY: case HEX:
1173       break;
1174     default:
1175       abort(); break;
1176     }
1177
1178   /* Glow some characters. */
1179   if (!state->insert_bottom_p)
1180     {
1181       int i = random() % (state->grid_width / 2);
1182       while (--i > 0)
1183         {
1184           int x = random() % state->grid_width;
1185           int y = random() % state->grid_height;
1186           m_cell *cell = &state->cells[state->grid_width * y + x];
1187           if (cell->glyph && cell->glow == 0)
1188             {
1189               cell->glow = random() % 10;
1190               cell->changed = 1;
1191             }
1192         }
1193     }
1194
1195   /* Change some of the feeders. */
1196   for (x = 0; x < state->grid_width; x++)
1197     {
1198       m_feeder *f = &state->feeders[x];
1199       Bool bottom_feeder_p;
1200
1201       if (f->remaining > 0)     /* never change if pipe isn't empty */
1202         continue;
1203
1204       if ((random() % densitizer(state)) != 0) /* then change N% of the time */
1205         continue;
1206
1207       f->remaining = 3 + (random() % state->grid_height);
1208       f->throttle = ((random() % 5) + (random() % 5));
1209
1210       if ((random() % 4) != 0)
1211         f->remaining = 0;
1212
1213       if (state->mode == TRACE2)
1214         bottom_feeder_p = True;
1215       if (state->insert_top_p && state->insert_bottom_p)
1216         bottom_feeder_p = (random() & 1);
1217       else
1218         bottom_feeder_p = state->insert_bottom_p;
1219
1220       if (bottom_feeder_p)
1221         f->y = random() % (state->grid_height / 2);
1222       else
1223         f->y = -1;
1224     }
1225
1226   if (!state->mode == TRACE2 &&
1227       ! (random() % 500))
1228     init_spinners (state);
1229 }
1230
1231
1232 static void
1233 draw_matrix (m_state *state)
1234 {
1235   feed_matrix (state);
1236   hack_matrix (state);
1237   redraw_cells (state, True);
1238   roll_state (state);
1239
1240 #if 0
1241   {
1242     static int i = 0;
1243     static int ndens = 0;
1244     static int tdens = 0;
1245     i++;
1246     if (i > 50)
1247       {
1248         int dens = (100.0 *
1249                     (((double)count) /
1250                      ((double) (state->grid_width * state->grid_height))));
1251         tdens += dens;
1252         ndens++;
1253         printf ("density: %d%% (%d%%)\n", dens, (tdens / ndens));
1254         i = 0;
1255       }
1256   }
1257 #endif
1258
1259 }
1260
1261 \f
1262 char *progclass = "XMatrix";
1263
1264 char *defaults [] = {
1265   ".background:            black",
1266   ".foreground:            #00AA00",
1267   "*small:                 ",
1268   "*delay:                 10000",
1269   "*insert:                both",
1270   "*mode:                  Matrix",
1271   "*tracePhone:            (212) 555-0690",
1272   "*spinners:              5",
1273   "*density:               75",
1274   "*knockKnock:            False",
1275   "*geometry:              800x600",
1276   0
1277 };
1278
1279 XrmOptionDescRec options [] = {
1280   { "-small",           ".small",               XrmoptionNoArg, "True" },
1281   { "-large",           ".small",               XrmoptionNoArg, "False" },
1282   { "-delay",           ".delay",               XrmoptionSepArg, 0 },
1283   { "-top",             ".insert",              XrmoptionNoArg, "top" },
1284   { "-bottom",          ".insert",              XrmoptionNoArg, "bottom" },
1285   { "-both",            ".insert",              XrmoptionNoArg, "both" },
1286   { "-density",         ".density",             XrmoptionSepArg, 0 },
1287   { "-trace",           ".mode",                XrmoptionNoArg, "trace" },
1288   { "-crack",           ".mode",                XrmoptionNoArg, "crack"},
1289   { "-phone",           ".tracePhone",          XrmoptionSepArg, 0 },
1290   { "-dna",             ".mode",                XrmoptionNoArg, "DNA" },
1291   { "-binary",          ".mode",                XrmoptionNoArg, "binary" },
1292   { "-hexadecimal",     ".mode",                XrmoptionNoArg, "hexadecimal"},
1293   { "-knock-knock",     ".knockKnock",          XrmoptionNoArg, "True" },
1294   { 0, 0, 0, 0 }
1295 };
1296
1297
1298 void
1299 screenhack (Display *dpy, Window window)
1300 {
1301   m_state *state = init_matrix (dpy, window);
1302   int delay = get_integer_resource ("delay", "Integer");
1303   while (1)
1304     {
1305       draw_matrix (state);
1306       XSync (dpy, False);
1307       handle_events (state);
1308       if (delay) usleep (delay);
1309     }
1310 }