From http://www.jwz.org/xscreensaver/xscreensaver-5.22.tar.gz
[xscreensaver] / hacks / memscroller.c
1 /* xscreensaver, Copyright (c) 2002-2012 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  * Memscroller -- scrolls a dump of its own RAM across the screen.
12  */
13
14 #include "screenhack.h"
15 #include <stdio.h>
16
17 #ifdef HAVE_XSHM_EXTENSION
18 #include "xshm.h"
19 #endif
20
21 #undef countof
22 #define countof(x) (sizeof(x)/sizeof(*(x)))
23
24 #ifndef USE_IPHONE
25 # define READ_FILES
26 #endif
27
28 typedef struct {
29   int which;
30   XRectangle rect;
31   XImage *image;
32   int rez;
33   int speed;
34   int scroll_tick;
35   unsigned int value;
36   unsigned char *data;
37   int count_zero;
38 } scroller;
39
40 typedef struct {
41   Display *dpy;
42   Window window;
43   XWindowAttributes xgwa;
44   GC draw_gc, erase_gc, text_gc;
45   XFontStruct *fonts[6];
46   int border;
47
48   enum { SEED_RAM, SEED_RANDOM, SEED_FILE } seed_mode;
49   enum { DRAW_COLOR, DRAW_MONO } draw_mode;
50
51   char *filename;
52   FILE *in;
53
54   int nscrollers;
55   scroller *scrollers;
56
57 # ifdef HAVE_XSHM_EXTENSION
58   Bool shm_p;
59   XShmSegmentInfo shm_info;
60 # endif
61
62   int delay;
63
64 } state;
65
66
67 static void reshape_memscroller (state *st);
68
69
70 static void *
71 memscroller_init (Display *dpy, Window window)
72 {
73   int i;
74   XGCValues gcv;
75   state *st = (state *) calloc (1, sizeof (*st));
76   char *s;
77   st->dpy = dpy;
78   st->window = window;
79   st->delay = get_integer_resource (dpy, "delay", "Integer");
80
81   XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
82
83   /* Fill up the colormap with random colors.
84      We don't actually use these explicitly, but in 8-bit mode,
85      they will be used implicitly by the random image bits. */
86   {
87     int ncolors = 255;
88     XColor colors[256];
89     make_random_colormap (st->xgwa.screen, st->xgwa.visual, st->xgwa.colormap,
90                           colors, &ncolors, True, True, 0, False);
91   }
92
93   st->border = get_integer_resource (dpy, "borderSize", "BorderSize");
94
95   {
96     int i;
97     int nfonts = countof (st->fonts);
98     for (i = nfonts-1; i >= 0; i--)
99       {
100         char *fontname;
101         char res[20];
102         sprintf (res, "font%d", i+1);
103         fontname = get_string_resource (dpy, res, "Font");
104         /* Each resource can be a comma-separated list of font names.
105            We use the first one that exists. */
106         if (fontname && *fontname) 
107           {
108             char *f2 = strdup(fontname);
109             char *f, *token = f2;
110             while ((f = strtok(token, ",")) && !st->fonts[i])
111               {
112                 token = 0;
113                 while (*f == ' ' || *f == '\t') f++;
114                 st->fonts[i] = XLoadQueryFont (dpy, f);
115               }
116             free (f2);
117             if (!st->fonts[i] && i < nfonts-1)
118               {
119                 fprintf (stderr, "%s: unable to load font: \"%s\"\n",
120                          progname, fontname);
121                 st->fonts[i] = st->fonts[i+1];
122               }
123           }
124       }
125
126     if (!st->fonts[0])
127       st->fonts[0] = XLoadQueryFont (dpy, "fixed");
128
129     if (!st->fonts[0])
130       {
131         fprintf (stderr, "%s: unable to load any fonts!", progname);
132         exit (1);
133       }
134   }
135
136   gcv.line_width = st->border;
137
138   gcv.background = get_pixel_resource(st->dpy, st->xgwa.colormap,
139                                       "background", "Background");
140   gcv.foreground = get_pixel_resource(st->dpy, st->xgwa.colormap,
141                                       "textColor", "Foreground");
142   st->text_gc = XCreateGC (st->dpy, st->window,
143                            GCForeground|GCBackground, &gcv);
144
145   gcv.foreground = get_pixel_resource(st->dpy, st->xgwa.colormap,
146                                       "foreground", "Foreground");
147   st->draw_gc = XCreateGC (st->dpy, st->window,
148                            GCForeground|GCBackground|GCLineWidth,
149                            &gcv);
150   gcv.foreground = gcv.background;
151   st->erase_gc = XCreateGC (st->dpy, st->window,
152                             GCForeground|GCBackground, &gcv);
153
154
155   s = get_string_resource (dpy, "drawMode", "DrawMode");
156   if (!s || !*s || !strcasecmp (s, "color"))
157     st->draw_mode = DRAW_COLOR;
158   else if (!strcasecmp (s, "mono"))
159     st->draw_mode = DRAW_MONO;
160   else
161     {
162       fprintf (stderr, "%s: drawMode must be 'mono' or 'color', not '%s'\n",
163                progname, s);
164       exit (1);
165     }
166   if (s) free (s);
167   s = 0;
168
169
170 # ifdef READ_FILES
171   st->filename = get_string_resource (dpy, "filename", "Filename");
172 # endif
173
174   if (!st->filename ||
175       !*st->filename ||
176       !strcasecmp (st->filename, "(ram)") ||
177       !strcasecmp (st->filename, "(mem)") ||
178       !strcasecmp (st->filename, "(memory)"))
179     st->seed_mode = SEED_RAM;
180 # ifdef READ_FILES
181   else if (st->filename &&
182            (!strcasecmp (st->filename, "(rand)") ||
183             !strcasecmp (st->filename, "(random)")))
184     st->seed_mode = SEED_RANDOM;
185   else
186     st->seed_mode = SEED_FILE;
187 # else
188   st->seed_mode = SEED_RANDOM;
189 # endif
190
191   st->nscrollers = 3;
192   st->scrollers = (scroller *) calloc (st->nscrollers, sizeof(scroller));
193
194   for (i = 0; i < st->nscrollers; i++)
195     {
196       scroller *sc = &st->scrollers[i];
197       int max_height = 4096;
198
199       sc->which = i;
200       sc->speed = i+1;
201
202       sc->image = 0;
203 # ifdef HAVE_XSHM_EXTENSION
204       st->shm_p = get_boolean_resource (dpy, "useSHM", "Boolean");
205       if (st->shm_p)
206         {
207           sc->image = create_xshm_image (st->dpy, st->xgwa.visual,
208                                          st->xgwa.depth,
209                                          ZPixmap, 0, &st->shm_info,
210                                          1, max_height);
211           if (! sc->image)
212             st->shm_p = False;
213         }
214 # endif /* HAVE_XSHM_EXTENSION */
215
216       if (!sc->image)
217         sc->image = XCreateImage (st->dpy, st->xgwa.visual, st->xgwa.depth,
218                                   ZPixmap, 0, 0, 1, max_height, 8, 0);
219
220       if (sc->image && !sc->image->data)
221         sc->image->data = (char *)
222           malloc (sc->image->bytes_per_line * sc->image->height + 1);
223
224       if (!sc->image || !sc->image->data)
225         {
226           fprintf (stderr, "%s: out of memory (allocating 1x%d image)\n",
227                    progname, sc->image->height);
228           exit (1);
229         }
230     }
231
232   reshape_memscroller (st);
233   return st;
234 }
235
236
237 static void
238 reshape_memscroller (state *st)
239 {
240   int i;
241
242   XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
243
244   for (i = 0; i < st->nscrollers; i++)
245     {
246       scroller *sc = &st->scrollers[i];
247
248       if (i == 0)
249         {
250           sc->rez = 6;  /* #### */
251
252           sc->rect.width  = (((int) (st->xgwa.width * 0.8)
253                               / sc->rez) * sc->rez);
254           sc->rect.height = (((int) (st->xgwa.height * 0.3)
255                               / sc->rez) * sc->rez);
256
257           sc->rect.x = (st->xgwa.width  - sc->rect.width)  / 2;
258           sc->rect.y = (st->xgwa.height - sc->rect.height) / 2;
259         }
260       else
261         {
262           scroller *sc0 = &st->scrollers[i-1];
263           sc->rez = sc0->rez * 1.8;
264
265           sc->rect.x      = sc0->rect.x;
266           sc->rect.y      = (sc0->rect.y + sc0->rect.height + st->border
267                              + (st->border + 2) * 7);
268           sc->rect.width  = sc0->rect.width;
269           sc->rect.height = (((int) (st->xgwa.height * 0.1)
270                               / sc->rez) * sc->rez);
271         }
272
273       XDrawRectangle (st->dpy, st->window, st->draw_gc,
274                       sc->rect.x - st->border*2,
275                       sc->rect.y - st->border*2,
276                       sc->rect.width  + st->border*4,
277                       sc->rect.height + st->border*4);
278     }
279 }
280
281
282
283 # ifdef READ_FILES
284 static void
285 open_file (state *st)
286 {
287   if (st->in)
288     {
289       fclose (st->in);
290       st->in = 0;
291     }
292
293   st->in = fopen (st->filename, "r");
294   if (!st->in)
295     {
296       char buf[1024];
297       sprintf (buf, "%s: %s", progname, st->filename);
298       perror (buf);
299       exit (1);
300     }
301 }
302 #endif
303
304
305 static unsigned int
306 more_bits (state *st, scroller *sc)
307 {
308   static unsigned char *lomem = 0;
309   static unsigned char *himem = 0;
310   unsigned char r, g, b;
311
312   /* vv: Each incoming byte rolls through all 4 bytes of this (it is sc->value)
313          This is the number displayed at the top.
314      pv: the pixel color value.  incoming bytes land in R,G,B, or maybe just G.
315    */
316   unsigned int vv, pv;
317
318   unsigned int rmsk = st->scrollers[0].image->red_mask;
319   unsigned int gmsk = st->scrollers[0].image->green_mask;
320   unsigned int bmsk = st->scrollers[0].image->blue_mask;
321   unsigned int amsk = ~(rmsk | gmsk | bmsk);
322
323   vv = sc->value;
324
325   /* Pack RGB into a pixel according to the XImage component masks;
326      set the remaining bits to 1 for the benefit of HAVE_COCOA alpha.
327    */
328 # undef PACK
329 # define PACK() ((((r << 24) | (r << 16) | (r << 8) | r) & rmsk) | \
330                  (((g << 24) | (g << 16) | (g << 8) | g) & gmsk) | \
331                  (((b << 24) | (b << 16) | (b << 8) | b) & bmsk) | \
332                  amsk)
333
334   switch (st->seed_mode)
335     {
336     case SEED_RAM:
337       if (himem == 0)
338         {
339           lomem = (unsigned char *) progname; /* not first malloc, but early */
340           himem = (unsigned char *)           /* not last malloc, but late */
341             st->scrollers[st->nscrollers-1].image->data;
342         }
343
344       if (sc->data < lomem)
345         sc->data = lomem;
346
347 # ifdef HAVE_SBRK  /* re-get it each time through */
348       /* "The brk and sbrk functions are historical curiosities left over
349          from earlier days before the advent of virtual memory management."
350             -- sbrk(2) man page on MacOS
351        */
352       himem = ((unsigned char *) sbrk(0)) - (2 * sizeof(void *));
353 # endif
354
355       if (!lomem || !himem) 
356         {
357           /* bad craziness! give up! */
358           st->seed_mode = SEED_RANDOM;
359           return 0;
360         }
361
362       /* I don't understand what's going on there, but on MacOS X, we're
363          getting insane values for lomem and himem (both Xlib and HAVE_COCOA).
364          Does malloc() draw from more than one heap? */
365       if ((unsigned long) himem - (unsigned long) lomem > 0x0FFFFFFF) {
366 # if 0
367         fprintf (stderr, "%s: wonky: 0x%08x - 0x%08x = 0x%08x\n", progname,
368                  (unsigned int) himem,  (unsigned int) lomem,
369                  (unsigned int) himem - (unsigned int) lomem);
370 # endif
371         himem = lomem + 0xFFFF;
372       }
373
374       if (lomem >= himem) abort();
375
376     RETRY:
377       if (sc->data >= himem)
378         sc->data = lomem;
379
380       switch (st->draw_mode)
381         {
382         case DRAW_COLOR:
383           r = *sc->data++;
384           g = *sc->data++;
385           b = *sc->data++;
386           vv = (vv << 24) | (r << 16) | (g << 8) | b;
387           break;
388         case DRAW_MONO:
389           r = 0;
390           g = *sc->data++;
391           b = 0;
392           vv = (vv << 8) | g;
393           break;
394         default:
395           abort();
396         }
397
398       pv = PACK();
399
400       /* avoid having many seconds of blackness: truncate zeros at 24K.
401        */
402       if (vv == 0)
403         sc->count_zero++;
404       else
405         sc->count_zero = 0;
406       if (sc->count_zero > 1024 * (st->draw_mode == DRAW_COLOR ? 24 : 8))
407         goto RETRY;
408
409       break;
410
411     case SEED_RANDOM:
412       vv = random();
413       switch (st->draw_mode)
414         {
415         case DRAW_COLOR:
416           r = (vv >> 16) & 0xFF;
417           g = (vv >>  8) & 0xFF;
418           b = (vv      ) & 0xFF;
419           break;
420         case DRAW_MONO:
421           r = 0;
422           g = vv & 0xFF;
423           b = 0;
424           break;
425         default:
426           abort();
427         }
428       pv = PACK();
429       break;
430
431 # ifdef READ_FILES
432     case SEED_FILE:
433       {
434         int i;
435
436   /* this one returns only bytes from the file */
437 # define GETC(V) \
438             do { \
439               i = fgetc (st->in); \
440             } while (i == EOF \
441                      ? (open_file (st), 1) \
442                      : 0); \
443             V = i
444
445   /* this one returns a null at EOF -- else we hang on zero-length files */
446 # undef GETC
447 # define GETC(V) \
448             i = fgetc (st->in); \
449             if (i == EOF) { i = 0; open_file (st); } \
450             V = i
451
452         if (!st->in)
453           open_file (st);
454
455         switch (st->draw_mode)
456           {
457           case DRAW_COLOR:
458             GETC(r);
459             GETC(g);
460             GETC(b);
461             vv = (vv << 24) | (r << 16) | (g << 8) | b;
462             break;
463           case DRAW_MONO:
464             r = 0;
465             GETC(g);
466             b = 0;
467             vv = (vv << 8) | g;
468             break;
469           default:
470             abort();
471           }
472 # undef GETC
473         pv = PACK();
474       }
475       break;
476 # endif /* READ_FILES */
477
478     default:
479       abort();
480     }
481
482 # undef PACK
483
484   sc->value = vv;
485   return pv;
486 }
487
488
489 static void
490 draw_string (state *st)
491 {
492   char buf[40];
493   int direction, ascent, descent;
494   int bot = st->scrollers[0].rect.y;
495   const char *fmt = "%08X";
496   int i;
497
498   /* Draw the first font that fits.
499    */
500   for (i = 0; i < countof (st->fonts); i++)
501     {
502       XCharStruct overall;
503       int x, y, w, h;
504
505       if (! st->fonts[i]) continue;
506
507       sprintf (buf, fmt, 0);
508       XTextExtents (st->fonts[i], buf, strlen(buf), 
509                     &direction, &ascent, &descent, &overall);
510       sprintf (buf, "%08X", st->scrollers[0].value);
511
512       w = overall.width;
513       h = ascent + descent + 1;
514       x = (st->xgwa.width - w) / 2;
515       y = (bot - h) / 2;
516
517       if (y + h + 10 <= bot && x > -10)
518         {
519           XSetFont (st->dpy, st->text_gc, st->fonts[i]->fid);
520           XFillRectangle (st->dpy, st->window, st->erase_gc,
521                           x-w, y, w*3, h);
522           XDrawString (st->dpy, st->window, st->text_gc,
523                        x, y + ascent, buf, strlen(buf));
524           break;
525         }
526     }
527 }
528
529
530 static unsigned long
531 memscroller_draw (Display *dpy, Window window, void *closure)
532 {
533   state *st = (state *) closure;
534   int i;
535   draw_string (st);
536
537   for (i = 0; i < st->nscrollers; i++)
538     {
539       scroller *sc = &st->scrollers[i];
540       int j;
541
542       XCopyArea (st->dpy, st->window, st->window, st->draw_gc,
543                  sc->rect.x + sc->speed, sc->rect.y,
544                  sc->rect.width - sc->speed, sc->rect.height,
545                  sc->rect.x, sc->rect.y);
546
547       if (sc->scroll_tick == 0)
548         {
549           int top = ((sc->image->bytes_per_line * sc->rect.height) /
550                      (4 * sc->rez));
551           unsigned int *out = (unsigned int *) sc->image->data;
552           for (j = 0; j < top; j++)
553             {
554               unsigned int v = more_bits(st, sc);
555               int k;
556               for (k = 0; k < sc->rez; k++)
557                 *out++ = v;
558             }
559         }
560
561       sc->scroll_tick++;
562       if (sc->scroll_tick * sc->speed >= sc->rez)
563         sc->scroll_tick = 0;
564
565       for (j = 0; j < sc->speed; j++)
566         {
567 # ifdef HAVE_XSHM_EXTENSION
568           if (st->shm_p)
569             XShmPutImage (st->dpy, st->window, st->draw_gc, sc->image,
570                           0, 0,
571                           sc->rect.x + sc->rect.width - sc->image->width - j,
572                           sc->rect.y,
573                           sc->rect.width, sc->rect.height,
574                           False);
575           else
576 # endif /* HAVE_XSHM_EXTENSION */
577             XPutImage (st->dpy, st->window, st->draw_gc, sc->image,
578                        0, 0,
579                        sc->rect.x + sc->rect.width - sc->image->width - j,
580                        sc->rect.y,
581                        sc->rect.width, sc->rect.height);
582         }
583     }
584
585   return st->delay;
586 }
587
588
589 static void
590 memscroller_reshape (Display *dpy, Window window, void *closure, 
591                  unsigned int w, unsigned int h)
592 {
593   state *st = (state *) closure;
594   XClearWindow (st->dpy, st->window);
595   reshape_memscroller (st);
596 }
597
598 static Bool
599 memscroller_event (Display *dpy, Window window, void *closure, XEvent *event)
600 {
601   return False;
602 }
603
604
605 static void
606 memscroller_free (Display *dpy, Window window, void *closure)
607 {
608 }
609
610
611 static const char *memscroller_defaults [] = {
612   ".background:            black",
613   "*drawMode:              color",
614   "*fpsSolid:              true",
615   "*fpsTop:                true",
616   "*filename:              (RAM)",
617   ".textColor:             #00FF00",
618   ".foreground:            #00FF00",
619   "*borderSize:            2",
620
621 #if defined(HAVE_COCOA) && !defined(USE_IPHONE)
622   ".font1:                 OCR A Std 192, Lucida Console 192",
623   ".font2:                 OCR A Std 144, Lucida Console 144",
624   ".font3:                 OCR A Std 128, Lucida Console 128",
625   ".font4:                 OCR A Std 96,  Lucida Console 96",
626   ".font5:                 OCR A Std 48,  Lucida Console 48",
627   ".font6:                 OCR A Std 24,  Lucida Console 24",
628 #else  /* !HAVE_COCOA */
629   ".font1:                 -*-courier-bold-r-*-*-*-1440-*-*-m-*-*-*",
630   ".font2:                 -*-courier-bold-r-*-*-*-960-*-*-m-*-*-*",
631   ".font3:                 -*-courier-bold-r-*-*-*-480-*-*-m-*-*-*",
632   ".font4:                 -*-courier-bold-r-*-*-*-320-*-*-m-*-*-*",
633   ".font5:                 -*-courier-bold-r-*-*-*-180-*-*-m-*-*-*",
634   ".font6:                 fixed",
635 #endif /* !HAVE_COCOA */
636
637   "*delay:                 10000",
638   "*offset:                0",
639   0
640 };
641
642 static XrmOptionDescRec memscroller_options [] = {
643   { "-delay",           ".delay",               XrmoptionSepArg, 0 },
644   { "-font",            ".font",                XrmoptionSepArg, 0 },
645   { "-filename",        ".filename",            XrmoptionSepArg, 0 },
646   { "-color",           ".drawMode",            XrmoptionNoArg, "color"    },
647   { "-mono",            ".drawMode",            XrmoptionNoArg, "mono"     },
648   { "-ram",             ".filename",            XrmoptionNoArg, "(RAM)"    },
649   { "-random",          ".filename",            XrmoptionNoArg, "(RANDOM)" },
650   { 0, 0, 0, 0 }
651 };
652
653 XSCREENSAVER_MODULE ("MemScroller", memscroller)