File: xxRoot.cc

package info (click to toggle)
xtide 2.9.5-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 2,996 kB
  • ctags: 2,141
  • sloc: cpp: 20,379; sh: 1,044; makefile: 224; yacc: 114; lex: 58
file content (860 lines) | stat: -rw-r--r-- 26,781 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
// $Id: xxRoot.cc 2652 2007-09-03 01:26:10Z flaterco $

/*  xxRoot  XTide "root" window (control panel, top-level logic)

    Copyright (C) 1998  David Flater.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "xtide.hh"
#include "xxGraphMode.hh"
#include "xxDisclaimer.hh"
#include "xxLocationList.hh"
#include "xxGlobe.hh"
#include "xxMap.hh"
#include "xxHorizDialog.hh"
#include "xxUnsignedChooser.hh"
#include "xxMultiChoice.hh"
#include "xxErrorBox.hh"
#include "xxHelpBox.hh"
#include "xxTextMode.hh"


static void errorCallback (const Dstr &errorMessage, Error::ErrType fatality) {
  Global::root->newErrorBox (errorMessage, fatality);
}


static void dismissCallback (Widget w unusedParameter,
                             XtPointer client_data unusedParameter,
                             XtPointer call_data unusedParameter) {
  Global::root->unrealize();
}


static void applyCallback (Widget w unusedParameter,
                           XtPointer client_data unusedParameter,
                           XtPointer call_data unusedParameter) {
  Global::root->apply (xxRoot::justApply);
}


static void changeUserDefaults (const Settings &newUserDefaults) {
  Global::settings = Settings();
  Global::settings.applyXResources();
  Global::settings.apply (newUserDefaults);
  Global::settings.applyCommandLine();
  Global::settings.fixUpDeprecatedSettings();
  xxX::installColors();
}


void xxRoot::apply (ApplyProtocol protocol) {

  // Build new settings for ~/.xtide.xml.
  Settings newUserDefaults;
  newUserDefaults.nullify();

  // There are several ways to implement this, all of which involve
  // messy nested logic because the association between dialog classes
  // and configurable interpretations is not simple.  This way at
  // least has no duplicated code and at most two redundant
  // operations (the failed dynamic casts).

  for (BetterMap<const Dstr, xxRedrawable*>::iterator it = dialogs.begin();
       it != dialogs.end();
       ++it) {
    xxRedrawable *redrawable (it->second);
    assert (redrawable);
    assert (newUserDefaults.count(it->first) == 1);
    Configurable &configurable (newUserDefaults[it->first]);
    assert (!configurable.caption.isNull());
    assert (configurable.kind == Configurable::settingKind);

    xxMultiChoice *multiChoice (dynamic_cast<xxMultiChoice*>(redrawable));
    if (multiChoice) {
      const unsigned choice (multiChoice->choice());
      switch (configurable.interpretation) {
      case Configurable::booleanInterp:
	switch (choice) {
	case 0:
	  configurable.isNull = false;
	  configurable.c = 'y';
	  break;
	case 1:
	  configurable.isNull = false;
	  configurable.c = 'n';
	  break;
	case 2:
	  break;
	default:
	  assert (false);
	}
	break;
      case Configurable::glDoubleInterp:
        assert (choice < 14);
	switch (choice) {
	case 12:
	  configurable.isNull = false;
	  configurable.d = 360.0;
	  break;
	case 13:
	  break;
	default:
	  configurable.isNull = false;
	  configurable.d = (double)choice * 30.0 - 180.0;
	  break;
	}
	break;
      case Configurable::unitInterp:
	switch (choice) {
	case 0:
	  configurable.isNull = false;
	  configurable.s = "ft";
	  break;
	case 1:
	  configurable.isNull = false;
	  configurable.s = "m";
	  break;
	case 2:
	  configurable.isNull = false;
	  configurable.s = "x";
	  break;
	case 3:
	  break;
	default:
	  assert (false);
	}
	break;
      default:
        assert (false);
      }

    } else {
      xxUnsignedChooser *unsignedChooser (
                                 dynamic_cast<xxUnsignedChooser*>(redrawable));
      if (unsignedChooser) {
        const unsigned choice (unsignedChooser->choice());
        assert (configurable.interpretation == Configurable::posIntInterp);
	if (choice != UINT_MAX) {
          assert (choice > 0);
	  configurable.isNull = false;
	  configurable.u = choice;
	}
      } else {
        xxHorizDialog *horizDialog (dynamic_cast<xxHorizDialog*>(redrawable));
        assert (horizDialog);
        const Dstr value (horizDialog->val());
	switch (configurable.interpretation) {
	case Configurable::posDoubleInterp:
	case Configurable::nonnegativeDoubleInterp:
	  {
	    Global::GetDoubleReturn gdr (Global::getDouble (
                                                   value,
                                                   configurable.interpretation,
						   configurable.d));
            switch (gdr) {
            case Global::inputNotOK:
              return;
            case Global::emptyInput:
              break;
            case Global::inputOK:
              configurable.isNull = false;
              break;
            default:
              assert (false);
            }
	  }
	  break;
	case Configurable::colorInterp:
	  if (value.length()) {
	    // Sanity check color
	    uint8_t r, g, b;
	    if (!(Colors::parseColor (value, r, g, b, Error::nonfatal)))
	      return;
	    configurable.isNull = false;
	    configurable.s = value;
	  }
	  break;
	case Configurable::timeFormatInterp:
	  if (value.length()) {
	    // Sanity check strftime format string
	    if (value.strchr('"') != -1 ||
                value.strchr('>') != -1 ||
		value.strchr('<') != -1) {
	      Global::barf (Error::XMLPARSE,
                            "Please don't use nasty characters like \", >, and < in your date/time formats.",
                            Error::nonfatal);
	      return;
	    }
	    configurable.isNull = false;
	    configurable.s = value;
	  }
	  break;
	case Configurable::eventMaskInterp:
	  if (value.length()) {
	    if (!Global::isValidEventMask (value)) {
	      Global::barf (Error::BAD_EVENTMASK, Error::nonfatal);
	      return;
	    }
	    configurable.isNull = false;
	    configurable.s = value;
	  }
	  break;
	default:
	  assert (false);
	}
      }
    }
  }

  changeUserDefaults (newUserDefaults);
  globalRedraw();

  // Provided that the world did not explode as a result of applying those
  // settings, only then might they be saved.
  if (protocol == applyAndSave)
    newUserDefaults.save();
}


static void saveCallback (Widget w unusedParameter,
                          XtPointer client_data unusedParameter,
                          XtPointer call_data unusedParameter) {
  Global::root->apply (xxRoot::applyAndSave);
}


static void helpCallback (Widget w unusedParameter,
                          XtPointer client_data unusedParameter,
                          XtPointer call_data unusedParameter) {
  Dstr helpstring ("\
XTide Control Panel\n\
\n\
The Control Panel is used to change global XTide settings.  These settings\n\
take precedence over compiled-in defaults and X application defaults, but\n\
they are overridden by settings made on the command line.  Therefore, any\n\
settings that you make in the Control Panel will not have any visible effect\n\
if you have also made these settings on the command line.\n\
\n\
Some settings have dialog boxes for you to type in; others have pull-down\n\
menus or '+' and '-' controls.  In each case, there is a way to leave the\n\
field blank if you want to keep the inherited settings.  Either delete all\n\
text in the dialog box, or choose the \"(blank)\" option on the pull-down\n\
menu, or lay on the '-' button until the field reads \"(blank)\".\n\
\n\
The settings identified as \"default\" settings (widths, heights, and\n\
aspect ratio) will not affect existing windows.  Widths and heights will\n\
affect all new windows; aspect ratio will only affect new windows that\n\
are created from the location chooser.  (This is because the aspect is\n\
preserved from one tide window to any new windows that it spawns.)\n\
\n\
Use the Apply button to apply the new settings to the current XTide session\n\
without making them permanent.  Use Save to make them permanent.\n\
\n\
If necessary, resize the Control Panel to keep all of the settings visible.\n\
\n\
About colors:  When entering colors, use either standard X11 color names\n\
or 24-bit hex specs of the form rgb:hh/hh/hh.  Do not use more or less bits;\n\
it will not work.\n\
\n\
About the event mask:  Events to suppress (p = phase of moon, S =\n\
sunrise, s = sunset, M = moonrise, m = moonset), or x to suppress\n\
none.  E.g, to suppress all sun and moon events, set eventmask to the\n\
value pSsMm.\n\
\n\
About date/time formats:  Please refer to the man page for strftime to see\n\
how these formats work.  Here is how to get XTide to use 24-hour time instead\n\
of AM/PM:\n\
   Hour format  %H\n\
   Time format  %H:%M %Z");
  (void) Global::root->newHelpBox (helpstring);
}


// This function is passed to Settings::applyXResources.

static XrmDatabase database;
static const bool getResource (const Dstr &name, Dstr &val_out) {
  Dstr n1 ("xtide*"), n2 ("XTide*");
  n1 += name;
  n2 += name;
  XrmValue xv;
  char *str_type[20]; // Waste.
  if (XrmGetResource (database, n1.aschar(), n2.aschar(), str_type, &xv)) {
    val_out = (char *)xv.addr;
    return true;
  }
  return false;
}


xxRoot::xxRoot (int argc, char **argv):
  xxWindow (argc, argv),
  popupCount(0) {

  setTitle ("Control Panel");

  // Switches recognized by X11 are removed from the command line by
  // the xxWidget constructor.
  database = XtScreenDatabase (xxX::screen);
  Global::settings.applyXResources (getResource);
  Global::settings.applyUserDefaults();
  Global::settings.applyCommandLine (argc, argv);
  Global::settings.fixUpDeprecatedSettings();
  xxX::installColors();

  Global::setErrorCallback (&errorCallback);

  {
    // Can't do this until after the settings have been processed.
    Arg args[2] =  {
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]}
    };
    XtSetValues (popup->widget(), args, 2);
  }{
    // Slightly different than what xxWindow would provide.
    Arg formArgs[3] =  {
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNvSpace, (XtArgVal)0}
    };
    Widget formWidget = XtCreateManagedWidget ("", formWidgetClass,
      popup->widget(), formArgs, 3);
    container = xxX::wrap (formWidget);
  }{
    Arg labelArgs[6] =  {
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNleft, (XtArgVal)XawChainLeft},
      {XtNright, (XtArgVal)XawChainLeft},
      {XtNtop, (XtArgVal)XawChainTop},
      {XtNbottom, (XtArgVal)XawChainTop}
    };
    Widget labelWidget = XtCreateManagedWidget (
      "-------------- XTide Control Panel --------------",
      labelWidgetClass, container->widget(), labelArgs, 6);
    label = new xxWidget (labelWidget);
  }{
    Arg vpArgs[9] =  {
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNallowVert, (XtArgVal)1},
      {XtNforceBars, (XtArgVal)1},
      {XtNfromVert, (XtArgVal)label->widget()},
      {XtNleft, (XtArgVal)XawChainLeft},
      {XtNright, (XtArgVal)XawChainRight},
      {XtNtop, (XtArgVal)XawChainTop},
      {XtNbottom, (XtArgVal)XawChainBottom}
    };

    Widget viewportWidget = XtCreateManagedWidget ("", viewportWidgetClass,
      container->widget(), vpArgs, 9);
    viewport = new xxWidget (viewportWidget);

    require (scrollbarWidget = XtNameToWidget (viewportWidget, "vertical"));
    Arg sbArgs[2] = {
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]}
    };
    XtSetValues (scrollbarWidget, sbArgs, 2);
  }{
    Arg boxArgs[4] =  {
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNvSpace, (XtArgVal)0},
      {XtNorientation, (XtArgVal)XtorientVertical}
    };
    Widget boxWidget = XtCreateManagedWidget ("", boxWidgetClass,
      viewport->widget(), boxArgs, 4);
    viewBox = new xxWidget (boxWidget);
  }

  // Get current settings, but convert the deprecated ones.
  Settings settings;
  settings.nullify();
  settings.applyUserDefaults();
  settings.fixUpDeprecatedSettings();

  static constString toggleChoices[] = {"Yes",
                                        "No",
                                        "(blank)",
                                        NULL};

  static constString unitsChoices[] = {"Feet",
                                       "Meters",
                                       "No preference",
                                       "(blank)",
                                       NULL};

  static constString glChoices[] = {"180",
                                    "150 W",
                                    "120 W",
                                    "90 W",
                                    "60 W",
                                    "30 W",
                                    "0",
                                    "30 E",
                                    "60 E",
                                    "90 E",
                                    "120 E",
                                    "150 E",
                                    "Max stations",
                                    "(blank)",
                                    NULL};

  // Create all of the dialogs.
  for (ConfigurablesMap::iterator it = settings.begin();
       it != settings.end();
       ++it) {
    Configurable &configurable (it->second);
    if (!configurable.caption.isNull()) {
      if (configurable.kind == Configurable::settingKind) {
	switch (configurable.interpretation) {
	case Configurable::booleanInterp:
	  {
	    unsigned firstChoice;
	    if (configurable.isNull)
	      firstChoice = 2;
	    else if (configurable.c == 'n')
	      firstChoice = 1;
	    else
	      firstChoice = 0;
	    dialogs[it->first] = new xxMultiChoice (
						*viewBox,
	                                        configurable.caption.aschar(),
                                                toggleChoices,
                                                firstChoice);
	  }
	  break;
	case Configurable::posIntInterp:
	  dialogs[it->first] = new xxUnsignedChooser (
                                                *viewBox,
	                                        configurable.caption.aschar(),
						configurable.u,
						configurable.isNull,
						configurable.minValue);
	  break;
	case Configurable::posDoubleInterp:
	case Configurable::nonnegativeDoubleInterp:
	  {
	    char temp[80];
	    if (configurable.isNull)
	      strcpy (temp, "");
	    else
	      sprintf (temp, "%0.2f", configurable.d);
	    dialogs[it->first] = new xxHorizDialog (
                                                *viewBox,
	                                        configurable.caption.aschar(),
						temp);
	  }
	  break;
	case Configurable::glDoubleInterp:
	  {
	    unsigned firstChoice = 13;
	    if (!configurable.isNull) {
	      if (configurable.d == 360.0)
		firstChoice = 12;
	      else
		firstChoice = (unsigned) ((configurable.d + 180.0) / 30.0);
	    }
	    dialogs[it->first] = new xxMultiChoice (
                                                *viewBox,
	                                        configurable.caption.aschar(),
						glChoices,
						firstChoice);
	  }
	  break;
	case Configurable::colorInterp:     // deliberate fall through
	case Configurable::eventMaskInterp: // deliberate fall through
	case Configurable::timeFormatInterp:
	  dialogs[it->first] = new xxHorizDialog (
                           *viewBox,
			   configurable.caption.aschar(),
			   configurable.isNull ? "" : configurable.s.aschar());
	  break;
	case Configurable::unitInterp:
	  {
	    unsigned firstChoice;
	    if (configurable.isNull)
	      firstChoice = 3;
	    else if (configurable.s == "ft")
	      firstChoice = 0;
	    else if (configurable.s == "m")
	      firstChoice = 1;
	    else
	      firstChoice = 2;
	    dialogs[it->first] = new xxMultiChoice (
                                                *viewBox,
						configurable.caption.aschar(),
						unitsChoices,
						firstChoice);
	  }
	  break;
	default:
	  assert (false);
	}
      }
    }
  }

  {
    Arg applyArgs[9] =  {
      {XtNvisual, (XtArgVal)xxX::visual},
      {XtNcolormap, (XtArgVal)xxX::colormap},
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::button]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNfromVert, (XtArgVal)viewport->widget()},
      {XtNleft, (XtArgVal)XawChainLeft},
      {XtNright, (XtArgVal)XawChainLeft},
      {XtNtop, (XtArgVal)XawChainBottom},
      {XtNbottom, (XtArgVal)XawChainBottom}
    };
    Widget buttonWidget = XtCreateManagedWidget ("Apply", commandWidgetClass,
      container->widget(), applyArgs, 9);
    XtAddCallback (buttonWidget, XtNcallback, applyCallback,
     (XtPointer)this);
    applyButton = new xxWidget (buttonWidget);
  }{
    Arg saveArgs[10] =  {
      {XtNvisual, (XtArgVal)xxX::visual},
      {XtNcolormap, (XtArgVal)xxX::colormap},
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::button]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNfromVert, (XtArgVal)viewport->widget()},
      {XtNfromHoriz, (XtArgVal)applyButton->widget()},
      {XtNleft, (XtArgVal)XawChainLeft},
      {XtNright, (XtArgVal)XawChainLeft},
      {XtNtop, (XtArgVal)XawChainBottom},
      {XtNbottom, (XtArgVal)XawChainBottom}
    };
    Widget buttonWidget = XtCreateManagedWidget ("Save", commandWidgetClass,
      container->widget(), saveArgs, 10);
    XtAddCallback (buttonWidget, XtNcallback, saveCallback,
     (XtPointer)this);
    saveButton = new xxWidget (buttonWidget);
  }{
    Arg buttonArgs[10] =  {
      {XtNvisual, (XtArgVal)xxX::visual},
      {XtNcolormap, (XtArgVal)xxX::colormap},
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::button]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNfromVert, (XtArgVal)viewport->widget()},
      {XtNfromHoriz, (XtArgVal)saveButton->widget()},
      {XtNleft, (XtArgVal)XawChainLeft},
      {XtNright, (XtArgVal)XawChainLeft},
      {XtNtop, (XtArgVal)XawChainBottom},
      {XtNbottom, (XtArgVal)XawChainBottom}
    };
    Widget buttonWidget = XtCreateManagedWidget ("Dismiss", commandWidgetClass,
      container->widget(), buttonArgs, 10);
    XtAddCallback (buttonWidget, XtNcallback, dismissCallback,
     (XtPointer)this);
    dismissButton = new xxWidget (buttonWidget);
  }{
    Arg buttonArgs[10] =  {
      {XtNvisual, (XtArgVal)xxX::visual},
      {XtNcolormap, (XtArgVal)xxX::colormap},
      {XtNbackground, (XtArgVal)xxX::pixels[Colors::button]},
      {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]},
      {XtNfromVert, (XtArgVal)viewport->widget()},
      {XtNfromHoriz, (XtArgVal)dismissButton->widget()},
      {XtNleft, (XtArgVal)XawChainLeft},
      {XtNright, (XtArgVal)XawChainLeft},
      {XtNtop, (XtArgVal)XawChainBottom},
      {XtNbottom, (XtArgVal)XawChainBottom}
    };
    Widget buttonWidget = XtCreateManagedWidget ("?", commandWidgetClass,
      container->widget(), buttonArgs, 10);
    XtAddCallback (buttonWidget, XtNcallback, helpCallback,
      (XtPointer)this);
    helpButton = new xxWidget (buttonWidget);
  }

  obeyMouseWheel (popup->widget());
  obeyMouseWheel (scrollbarWidget);
}


void xxRoot::dup() {
  ++popupCount;
}


void xxRoot::dup (xxWindow *child) {
  dup();
  children.insert (child);
}


void xxRoot::release () {
  assert (popupCount > 0);
  if (--popupCount == 0)
    exit (0);
}


void xxRoot::release (xxWindow *child) {
  release ();
  children.erase (child);
}


void xxRoot::globalRedraw() {
  for (std::set<xxWindow*>::iterator it = children.begin();
       it != children.end();
       ++it)
    (*it)->globalRedraw();

  for (BetterMap<const Dstr, xxRedrawable*>::iterator it = dialogs.begin();
       it != dialogs.end();
       ++it)
    it->second->globalRedraw();

  Arg buttonArgs[2] =  {
    {XtNbackground, (XtArgVal)xxX::pixels[Colors::button]},
    {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]}
  };
  assert (applyButton);
  XtSetValues (applyButton->widget(), buttonArgs, 2);
  assert (saveButton);
  XtSetValues (saveButton->widget(), buttonArgs, 2);
  assert (helpButton);
  XtSetValues (helpButton->widget(), buttonArgs, 2);
  assert (dismissButton);
  XtSetValues (dismissButton->widget(), buttonArgs, 2);

  Arg args[2] =  {
    {XtNbackground, (XtArgVal)xxX::pixels[Colors::background]},
    {XtNforeground, (XtArgVal)xxX::pixels[Colors::foreground]}
  };
  assert (label);
  XtSetValues (label->widget(), args, 2);
  assert (viewBox);
  XtSetValues (viewBox->widget(), args, 2);
  assert (viewport);
  XtSetValues (viewport->widget(), args, 2);
  assert (container.get());
  XtSetValues (container->widget(), args, 2);
  assert (popup.get());
  XtSetValues (popup->widget(), args, 2);
  XtSetValues (scrollbarWidget, args, 2);
}


void xxRoot::run() {
  if (!Global::disclaimerDisabled()) {
    (void) new xxDisclaimer (*popup);
    handleXEvents (returnWhenIdle);
  }

  if (Global::settings["l"].isNull)
    newChooser ();
  else
    commandLineWindows ();

  handleXEvents (loopForever);
}


xxHelpBox * const xxRoot::newHelpBox (const Dstr &help) {
  return new xxHelpBox (*popup, help);
}


xxGraphMode * const xxRoot::newGraph (Station *station, Timestamp t) {
  return new xxGraphMode (*popup, station, t);
}


xxGraphMode * const xxRoot::newGraph (const StationRef &stationRef) {
  return newGraph (stationRef.load(), (time_t)time(NULL));
}


xxTextMode * const xxRoot::newPlain (Station *station, Timestamp t) {
  return new xxTextMode (*popup, station, Mode::plain, t);
}


xxTextMode * const xxRoot::newRaw (Station *station, Timestamp t) {
  return new xxTextMode (*popup, station, Mode::raw, t);
}


xxTextMode * const xxRoot::newMediumRare (Station *station, Timestamp t) {
  return new xxTextMode (*popup, station, Mode::mediumRare, t);
}


xxClock * const xxRoot::newClock (Station *station,
				  xxClock::ButtonsStyle buttonsStyle) {
  return new xxClock (*popup, station, buttonsStyle);
}


xxClock * const xxRoot::newClock (Station *station) {
  return newClock (station,
                   (Global::settings["cb"].c == 'n' ? xxClock::noButtons :
                                                      xxClock::buttons));
}


void xxRoot::commandLineWindows () {
  Settings &settings (Global::settings);
  Timestamp t ((time_t)time(NULL));
  Mode::Mode mode;
  {
    const Configurable &m (settings["m"]);
    if (m.isNull)
      mode = Mode::clock;
    else
      mode = (Mode::Mode)m.c;
  }{
    const Configurable &l (settings["l"]);
    DstrVector::const_iterator it (l.v.begin());
    DstrVector::const_iterator stop (l.v.end());
    while (it != stop) {
      StationRef *stationRef (Global::stationIndex().getStationRefByName(*it));
      if (stationRef) {
        const Configurable &b (settings["b"]);
	if (!b.isNull) {
	  t = Timestamp (b.s, stationRef->timezone);
	  if (t.isNull())
	    Global::cant_mktime (b.s, stationRef->timezone, Error::fatal);
	}
        Station *station (stationRef->load());
	xxWindow *d (NULL);
	if (mode == Mode::graph)
	  d = newGraph (station, t);
	else if (mode == Mode::plain)
	  d = newPlain (station, t);
	else if (mode == Mode::raw)
	  d = newRaw (station, t);
	else if (mode == Mode::mediumRare)
	  d = newMediumRare (station, t);
	else if (mode == Mode::about) {
          d = newAbout (station);
          delete station;
	} else
	  d = newClock (station);
        assert (d);

	// Apply -geometry to first one only.
	if (it == l.v.begin())
	  d->move (settings["X"].s);

      } else {
	Dstr details ("Could not find: ");
	details += *it;
	Global::barf (Error::STATION_NOT_FOUND, details);
      }
      ++it;
    }
  }
}


void xxRoot::newChooser () {
  if (Global::settings["fe"].c == 'n')
    (void) new xxGlobe (*popup);
  else
    (void) new xxMap (*popup);
}


void xxRoot::newMap () {
  (void) new xxMap (*popup);
}


void xxRoot::newGlobe () {
  (void) new xxGlobe (*popup);
}


xxHelpBox * const xxRoot::newAbout (const Station *station) {
  assert (station);
  Dstr verbiage;
  station->aboutMode (verbiage, Format::text, "ISO-8859-1");
  return newHelpBox (verbiage);
}


void xxRoot::newErrorBox (const Dstr &errmsg, Error::ErrType fatality) {
  static bool snakeBit (false); // Hide double-barfs.
  if (!snakeBit)
    (void) new xxErrorBox (*popup, errmsg, fatality);
  if (fatality == Error::fatal) {
    snakeBit = true;

    // This is a bad thing.  We have to grind crank on the X server to
    // get the error box to appear, but this might also cause
    // previously queued events to do stuff--possibly even leading to
    // another fatal error.  The callback that led to the current sad
    // state of affairs is being held hostage on the stack and did not
    // get to finish whatever it was doing.
    handleXEvents (xxRoot::loopForever);
  }
}


// Similar to, but critically different from, xxWindow::realize.
void xxRoot::realize() {
  if (!_isRealized) {
    Widget popupWidget (popup->widget());
    XtRealizeWidget (popupWidget);
    XSetWMProtocols (xxX::display, XtWindow(popupWidget), &xxX::killAtom, 1);
    _isRealized = true;
    setTitle_NET_WM();
    dup();
  }
}


// Similar to, but critically different from, xxWindow::unrealize.
void xxRoot::unrealize() {
  if (_isRealized) {
    XtUnrealizeWidget (popup->widget());
    _isRealized = false;
    release();

    // Since the window vanishes, the Dismiss button misses the
    // LeaveWindow event.  The next time the window is realized,
    // Dismiss is still stuck in a set and/or highlighted state.
    // This fixes that.
    XtCallActionProc (dismissButton->widget(), "reset", NULL, NULL, 0);
  }
}


xxWindow * const xxRoot::dismiss() {
  unrealize();
  // ISO/IEC 14882:2003 5.3.5 specifies that deleting a null pointer
  // shall have no effect.
  return NULL;
}


void xxRoot::handleXEvents (HandleXEventsReturnProtocol protocol) {
  XEvent foo;
  while (XtAppPending(xxX::appContext) || (protocol == loopForever)) {
    XtAppNextEvent (xxX::appContext, &foo);
    XtDispatchEvent (&foo);
  }
}

// Cleanup2006 Done