File: DaliClockView.m

package info (click to toggle)
xdaliclock 2.48-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 17,328 kB
  • sloc: ansic: 8,377; sh: 3,522; objc: 2,029; makefile: 1,220; java: 1,044; javascript: 802; asm: 419; xml: 337; perl: 269; ruby: 5
file content (1781 lines) | stat: -rw-r--r-- 53,446 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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
/* xdaliclock - a melting digital clock
 * Copyright (c) 1991-2020 Jamie Zawinski <jwz@jwz.org>
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation.  No representations are made about the suitability of this
 * software for any purpose.  It is provided "as is" without express or
 * implied warranty.
 */

#import "DaliClockView.h"
#import "xdaliclock.h"

#import <sys/time.h>

#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
  /* In 10.5 and later, NSColor wants CGfloat args, but that type
     does not exist in 10.4. */
  typedef float CGFloat;
#endif


/* Some systems get flicker if we don't turn on OpenGL double-buffering.
   I have reports of flicker on 10.7.5 Macbooks, but I can't reproduce
   it on a 10.8.3 iMac-2010.
 */
#define DO_DOUBLE_BUFFER


/* On a 10.6 iMac-2008, I was seeing the behavior that a transparent
   Dali Clock window on top of iTunes playing videos would flicker.  At
   the time I believed that OpenGL double-buffering didn't fix it, but
   that alternating between two different texture IDs, and only writing
   to the one not currently on screen, did fix it.
*/
#undef DO_DOUBLE_TEXTURE


static void check_gl_error (const char *type);
static void log_gl_error (const char *type, GLenum error);

#ifdef USE_IPHONE
static void rgb_to_hsv (CGFloat r, CGFloat g, CGFloat b, 
                        CGFloat *h, CGFloat *s, CGFloat *v);
#endif /* USE_IPHONE */


@interface DaliClockView (ForwardDeclarations)
- (void)setForeground:(NSColor *)fg background:(NSColor *)bg;
- (void)clockTick;
- (void)colorTick;
- (void)dateTick;
@end


@implementation DaliClockView
{
  GLuint textures[2];

  NSTimer *clockTimer;
  NSTimer *colorTimer;
  NSTimer *dateTimer;
  NSTimer *countdownHomeStretchStartTimer;
  NSTimer *countdownHomeStretchEndTimer;
  float autoDateInterval;

  BOOL ownWindow;
  BOOL constrainSizes;
  BOOL usesCountdownTimer;
  BOOL usesHomeStretchTimer;
  NSDate *countdownDate;

  NSColor *fg;
  NSColor *bg;
  NSColor *initialForegroundColor;
  NSColor *initialBackgroundColor;
}

static NSUserDefaultsController *staticUserDefaultsController = 0;

+ (NSUserDefaultsController *)userDefaultsController
{
  return staticUserDefaultsController;
}

+ (void)setUserDefaultsController:(NSUserDefaultsController *)ctl
{
  if (staticUserDefaultsController &&
      staticUserDefaultsController != ctl)
    [staticUserDefaultsController release];
  staticUserDefaultsController = [ctl retain];
}


+ (void)registerDefaults:(NSUserDefaults *)defs
{
  /* Set the defaults for all preferences handled by DaliClockView.
     (AppController or DaliClockSaverView handles other preferences).
   */
  NSColor *deffg = [NSColor  blueColor];
  NSColor *defbg = [NSColor colorWithCalibratedHue:0.50
                                        saturation:1.00
                                        brightness:0.70   // cyan, but darker
# ifndef USE_IPHONE
                                             alpha:0.30   // and translucent
# else  /* USE_IPHONE */
                                             alpha:1.00
# endif /* USE_IPHONE */
                            ];

  // Default countdown date is "12 hours from now"
  NSDate *defdate = [NSDate dateWithTimeIntervalSinceNow:
                     (NSTimeInterval) 60 * 60 * 12];


  /* Try to determine the current locale's short date format, and set our
     dateStyle based on that.  We do this by creating an NSDate with a
     particular unambiguous date/time in the current time zone, having
     NSDateFormatter convert that to a string in the current locale, and
     parsing that string.  There doesn't seem to be any other way to get
     the answer to the questions, "what order are year, month and day 
     printed?", and "are hours printed mod 12 or 24?"
   */
  struct tm TM = { 0,0,13, 31,11,132, -1,-1,-1, 0, }; // 2032-12-31 13:00:00
  time_t tt = mktime (&TM);
  NSDate *test_date = [NSDate dateWithTimeIntervalSince1970:tt];
  NSDateFormatter *df = [[NSDateFormatter alloc] init];
  [df setFormatterBehavior:NSDateFormatterBehavior10_4];
  [df setDateStyle:NSDateFormatterShortStyle];
  [df setTimeStyle:NSDateFormatterNoStyle];

  NSString *test_str = [df stringFromDate:test_date];
  NSString *ds = ([test_str hasPrefix:@"12/"]   ? @"0" :  // MMDDYY
                  [test_str hasPrefix:@"31/"]   ? @"1" :  // DDMMYY
                  [test_str hasPrefix:@"32/"]   ? @"3" :  // YYMMDD
                  [test_str hasPrefix:@"2032/"] ? @"3" :  // YYMMDD
                  @"0");

  [df setDateStyle:NSDateFormatterNoStyle];
  [df setTimeStyle:NSDateFormatterShortStyle];
  test_str = [df stringFromDate:test_date];
  NSString *hs = ([test_str hasPrefix:@"13"] ? @"1" : @"0"); // 24- or 12 hour
  [df release];

  NSDictionary* extras = [NSDictionary dictionaryWithObjectsAndKeys:
    @"0", @"timeStyle",
    ds,   @"dateStyle",
    hs,   @"hourStyle",
    [NSArchiver archivedDataWithRootObject:deffg], @"initialForegroundColor",
    [NSArchiver archivedDataWithRootObject:defbg], @"initialBackgroundColor",
    @"10.0", @"cycleSpeed",
    @"NO", @"usesCountdownTimer",
    @"YES", @"usesHomeStretchTimer",
    defdate,@"countdownDate",
    nil];

  NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:100];
  [dict addEntriesFromDictionary:[defs dictionaryRepresentation]];
  [dict addEntriesFromDictionary:extras];
  [defs registerDefaults:dict];
}


- (void)bindPreferences
{
# ifndef USE_IPHONE
  NSUserDefaultsController *controller = staticUserDefaultsController;

  [self    bind:@"hourStyle"
       toObject:controller
    withKeyPath:@"values.hourStyle" options:nil];
  [self    bind:@"timeStyle"
       toObject:controller
    withKeyPath:@"values.timeStyle"
        options:nil];
  [self    bind:@"dateStyle"
       toObject:controller
    withKeyPath:@"values.dateStyle"
        options:nil];
  [self    bind:@"cycleSpeed"
       toObject:controller
    withKeyPath:@"values.cycleSpeed"
        options:nil];
  [self    bind:@"usesCountdownTimer"
       toObject:controller
    withKeyPath:@"values.usesCountdownTimer"
        options:nil];
  [self    bind:@"usesHomeStretchTimer"
       toObject:controller
    withKeyPath:@"values.usesHomeStretchTimer"
        options:nil];
  [self    bind:@"countdownDate"
       toObject:controller
    withKeyPath:@"values.countdownDate"
        options:nil];

  NSDictionary *colorBindingOptions =
    [NSDictionary dictionaryWithObject:@"NSUnarchiveFromData"
                                forKey:NSValueTransformerNameBindingOption];
  [self    bind:@"initialForegroundColor"
       toObject:controller
    withKeyPath:@"values.initialForegroundColor"
        options:colorBindingOptions];
  [self    bind:@"initialBackgroundColor"
       toObject:controller
    withKeyPath:@"values.initialBackgroundColor"
        options:colorBindingOptions];

# else  /* USE_IPHONE */

  // WTF, why don't we have bindings for this!!
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

  [self setHourStyle:(int)[defaults integerForKey:@"hourStyle"]];
  [self setTimeStyle:(int)[defaults integerForKey:@"timeStyle"]];
  [self setDateStyle:(int)[defaults integerForKey:@"dateStyle"]];
  [self setCycleSpeed:[defaults floatForKey:@"cycleSpeed"]];
  [self setUsesCountdownTimer:[defaults boolForKey:@"usesCountdownTimer"]];
  [self setUsesHomeStretchTimer:[defaults boolForKey:@"usesHomeStretchTimer"]];
  [self setCountdownDate:(NSDate *)[defaults objectForKey:@"countdownDate"]];

  /* Is it a problem that I'm using NSKeyedUnarchiver on an object
     that was created with NSArchiver instead of NSKeyedArchiver?
     Does the NSUnarchiveFromData NSValueTransformerNameBindingOption
     work with both NSArchiver and NSKeyedArchiver objects?
   */
  NSData *ifgd = [defaults objectForKey:@"initialForegroundColor"];
  NSData *ibgd = [defaults objectForKey:@"initialBackgroundColor"];
  UIColor *ifg = (ifgd ? [NSKeyedUnarchiver unarchiveObjectWithData:ifgd] : 0);
  UIColor *ibg = (ibgd ? [NSKeyedUnarchiver unarchiveObjectWithData:ibgd] : 0);
  if (! ifg) ifg = [UIColor whiteColor];  // This shouldn't happen...
  if (! ibg) ibg = [UIColor blackColor];
  [self setInitialForegroundColor:ifg];
  [self setInitialBackgroundColor:ibg];

  // So we can tell when we're docked.
  [UIDevice currentDevice].batteryMonitoringEnabled = YES;
# endif /* USE_IPHONE */
}


- (id)initWithFrame:(NSRect)rect
{
  // by default, we may change window background
  return [self initWithFrame:rect ownWindow:YES];
}


#ifdef USE_IPHONE
- (void)initFramebuffer
{

  if (gl_framebuffer)  glDeleteFramebuffersOES  (1, &gl_framebuffer);
  if (gl_renderbuffer) glDeleteRenderbuffersOES (1, &gl_renderbuffer);

  glGenFramebuffersOES  (1, &gl_framebuffer);
  glBindFramebufferOES  (GL_FRAMEBUFFER_OES,  gl_framebuffer);

  glGenRenderbuffersOES (1, &gl_renderbuffer);
  glBindRenderbufferOES (GL_RENDERBUFFER_OES, gl_renderbuffer);

// redundant?
//   glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_RGBA8_OES, w, h);
  [ogl_ctx renderbufferStorage:GL_RENDERBUFFER_OES
           fromDrawable:(CAEAGLLayer*)self.layer];

  glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES,  GL_COLOR_ATTACHMENT0_OES,
                                GL_RENDERBUFFER_OES, gl_renderbuffer);

  int err = glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES);
  switch (err) {
  case GL_FRAMEBUFFER_COMPLETE_OES:
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES:
    NSAssert (0, @"framebuffer incomplete attachment");
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES:
    NSAssert (0, @"framebuffer incomplete missing attachment");
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES:
    NSAssert (0, @"framebuffer incomplete dimensions");
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES:
    NSAssert (0, @"framebuffer incomplete formats");
    break;
  case GL_FRAMEBUFFER_UNSUPPORTED_OES:
    NSAssert (0, @"framebuffer unsupported");
    break;
/*
  case GL_FRAMEBUFFER_UNDEFINED:
    NSAssert (0, @"framebuffer undefined");
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
    NSAssert (0, @"framebuffer incomplete draw buffer");
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
    NSAssert (0, @"framebuffer incomplete read buffer");
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
    NSAssert (0, @"framebuffer incomplete multisample");
    break;
  case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
    NSAssert (0, @"framebuffer incomplete layer targets");
    break;
 */
  default:
    NSAssert (0, @"framebuffer incomplete, unknown error 0x%04X", err);
    break;
  }

  check_gl_error ("OES_init");
}
#endif // USE_IPHONE


- (id)initWithFrame:(NSRect)rect ownWindow:(BOOL)own_p
{
  self = [super initWithFrame:rect];
  if (! self) return nil;

  ownWindow = own_p;

  memset (&config, 0, sizeof(config));

  config.max_fps = 30;

# ifndef USE_IPHONE
  // Tell the color selector widget to show the "opacity" slider.
  [[NSColorPanel sharedColorPanel] setShowsAlpha:YES];
# endif /* !USE_IPHONE */

# ifdef USE_IPHONE
  [self initGestures];
# endif /* USE_IPHONE */

  // initialize the fonts and bitmaps
  //
  [self setFrameSize:[self frame].size];
  [self bindPreferences];

  [self clockTick];
  [self colorTick];


  // Initialize the OpenGL context.
  //
# ifndef USE_IPHONE

  NSOpenGLContext *ctx = ogl_ctx;
  if (! ctx) {

    NSOpenGLPixelFormatAttribute attrs[] = {
      NSOpenGLPFAColorSize, 24,
      NSOpenGLPFAAlphaSize, 8,
      NSOpenGLPFADepthSize, 0, //16,  we don't need a depth buffer at all.
#  ifdef DO_DOUBLE_BUFFER
      NSOpenGLPFADoubleBuffer,
#  endif
      0 };

    NSOpenGLPixelFormat *pixfmt = 
      [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];

    NSAssert (pixfmt, @"unable to create NSOpenGLPixelFormat");

    ctx = [[NSOpenGLContext alloc] 
            initWithFormat:pixfmt
              shareContext:nil];
    ogl_ctx = ctx;
//    [pixfmt release]; // #### ???
  }

  // Sync refreshes to the vertical blanking interval
  GLint r = 1;
  [ctx setValues:&r forParameter:NSOpenGLCPSwapInterval];
//  check_gl_error ("NSOpenGLCPSwapInterval");  // SEGV sometimes. Too early?

  // Make window transparency possible
  r = NO;
  [ogl_ctx setValues:&r forParameter:NSOpenGLCPSurfaceOpacity];
//  check_gl_error ("init opacity");


  [ctx makeCurrentContext];
  check_gl_error ("makeCurrentContext");

  // Get device pixels instead of points, for Retina displays.
  self.wantsBestResolutionOpenGLSurface = YES;

  // Clear frame buffer ASAP, else there are bits left over from other apps.
  // #### On 10.7, this causes GL_INVALID_FRAMEBUFFER_OPERATION.
  // In Dali Clock but not XScreenSaver?
  //  glClearColor (0, 0, 0, 1);
  //  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  //  check_gl_error ("init clear");


  // Enable multi-threading, if possible.  This runs most OpenGL commands
  // and GPU management on a second CPU.
  {
#   ifndef  kCGLCEMPEngine
#    define kCGLCEMPEngine 313  // Added in MacOS 10.4.8 + XCode 2.4.
#   endif
    CGLContextObj cctx = CGLGetCurrentContext();
    CGLError err = CGLEnable (cctx, kCGLCEMPEngine);
    if (err != kCGLNoError) {
      NSLog (@"enabling multi-threaded OpenGL failed: %d", err);
    }
  }

  {
    GLboolean d = 0;
    glGetBooleanv (GL_DOUBLEBUFFER, &d);
    if (d)
      glDrawBuffer (GL_BACK);
    else
      glDrawBuffer (GL_FRONT);

    /* WTF?  Sometimes we get "invalid operation" when doing GL_FRONT,
       which means the front buffer doesn't exist!  But that's a lie,
       because on ignoring the error, everything works.  So, just flush
       errors here.
     */
    // check_gl_error ("init drawBuffer");
    while (glGetError() != GL_NO_ERROR)
      ;
  }

  check_gl_error ("init");

# else  // USE_IPHONE

  if (!ogl_ctx) {

    CAEAGLLayer *eagl_layer = (CAEAGLLayer *) self.layer;
    eagl_layer.opaque = TRUE;
    eagl_layer.drawableProperties = 
      [NSDictionary dictionaryWithObjectsAndKeys:
       kEAGLColorFormatRGBA8,           kEAGLDrawablePropertyColorFormat,
       [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking,
       nil];

    // Without this, the GL frame buffer is half the screen resolution!
    eagl_layer.contentsScale = [UIScreen mainScreen].scale;

    ogl_ctx = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
  }

  if (!ogl_ctx) {
    [self release];
    return 0;
  }

  [EAGLContext setCurrentContext: ogl_ctx];

  [self initFramebuffer];
# endif // USE_IPHONE

# ifdef DO_DOUBLE_TEXTURE
  glGenTextures (2, textures);
# else
  glGenTextures (1, textures);
# endif

  check_gl_error ("glGenTextures");

  return self;
}


/* Called when the View is resized.
 */
- (void)setFrameSize:(NSSize)newSize
{
# ifndef USE_IPHONE
  [ogl_ctx clearDrawable];  // need this to cause the vp change to stick
  [super setFrameSize:newSize];

  /* If the user is interactively resizing the window, don't regenerate
     the bitmap until we're done.  (We will just scale whatever image is
     already on the window instead, which reduces flicker when the
     target bitmap size shifts over a boundary).
   */
  if ([self inLiveResize]) return;
# endif /* USE_IPHONE */

  int ow = config.width;
  int oh = config.height;

# if defined(USE_IPHONE) && defined(__IPHONE_4_0)
  /* Make sure we are dealing with real pixels, not "virtual" pixels. */
  if ([self respondsToSelector:@selector(contentScaleFactor)]) {
    double s = [self contentScaleFactor];
    newSize.width  *= s;
    newSize.height *= s;
  }
# endif /* __IPHONE_4_0 */

  float sscale = 2.5;   // use the next-larger bitmap

  config.width  = newSize.width  * sscale;
  config.height = newSize.height * sscale;

  render_bitmap_size (&config, 
                      &config.width, &config.height,
                      &config.width2, &config.height2);

  if (config.render_state && (ow == config.width && oh == config.height))
    return;  // nothing to do

  /* When the window is resized, re-create the bitmaps for the largest
     font that will now fit in the window.
   */
  if (config.bitmap) free (config.bitmap);
  config.bitmap = 0;

  if (config.render_state)
    render_free (&config);
  render_init (&config);

# ifdef USE_IPHONE
  // Orientation changes resize the window (swapping W and H) so we need
  // to get a new framebuffer that matches the current shape of the window,
  // or else the aspect ratio goes wonky.
  if (gl_framebuffer)
    [self initFramebuffer];
  if (aboutBox)
    [self aboutOff];

# endif
}


#ifdef USE_IPHONE

- (void)setFrame:(NSRect)r
{
  [super setFrame:r];
  [self setFrameSize:r.size];
}


+ (Class) layerClass
{
    return [CAEAGLLayer class];
}


/* Gestures
 */


- (void)initGestures
{
  UITapGestureRecognizer *dtap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(handleDoubleTap)];
  dtap.numberOfTapsRequired = 2;
  [self addGestureRecognizer: dtap];
  [dtap release];

  UITapGestureRecognizer *stap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(handleTap)];
  stap.numberOfTapsRequired = 1;
  [stap requireGestureRecognizerToFail: dtap];
  [self addGestureRecognizer: stap];
  [stap release];
 
  UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]
                                  initWithTarget:self
                                  action:@selector(handlePan:)];
  [self addGestureRecognizer: pan];
  [pan release];
 
  UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]
                                      initWithTarget:self
                                      action:@selector(handlePinch:)];
  [self addGestureRecognizer: pinch];
  [pinch release];
}


- (void) handleTap
{
  // Single tap: briefly display date and credits.

  config.display_date_p = 1;
  [NSTimer scheduledTimerWithTimeInterval:2.0
           target:self
           selector:@selector(dateOff)
           userInfo:nil
           repeats:NO];
  [NSTimer scheduledTimerWithTimeInterval:3.5
           target:self
           selector:@selector(aboutOff)
           userInfo:nil
           repeats:NO];
  [self aboutClick:nil];
}


- (void) handleDoubleTap
{
  // Double tap: toggle 24 hour mode.

  config.display_date_p = 0;
  // Change it only if hours currently visible;
  // In seconds-only mode, this is a mis-tap.
  if (config.time_mode != SS)
    [self setHourStyle: ![self hourStyle]];

  // Save prefs
  NSUserDefaults *controller = [NSUserDefaults standardUserDefaults];
  [controller setObject:[NSNumber numberWithInt:[self hourStyle]]
              forKey:@"hourStyle"];
  [controller synchronize];
}


- (void) pinch:(BOOL)in
{
  config.display_date_p = 0;
  if (in) {					// Pinch in: smaller digits
    if ([self timeStyle] == SS)        [self setTimeStyle:HHMM];
    else if ([self timeStyle] == HHMM) [self setTimeStyle:HHMMSS];

  } else {					// Pinch out: larger digits
    if ([self timeStyle] == HHMMSS)    [self setTimeStyle:HHMM];
    else if ([self timeStyle] == HHMM) [self setTimeStyle:SS];
  }

  // Save prefs
  NSUserDefaults *controller = [NSUserDefaults standardUserDefaults];
  [controller setObject:[NSNumber numberWithInt:[self timeStyle]]
              forKey:@"timeStyle"];
  [controller synchronize];
}


- (void) handlePinch:(UIPinchGestureRecognizer *)sender
{
  if (sender.state == UIGestureRecognizerStateEnded)
    [self pinch: ([sender scale] < 1)];
}


// I couldn't get Swipe to work, but Pan works fine.
- (void) handlePan:(UIPanGestureRecognizer *)sender
{
  CGPoint translate = [sender translationInView: self];
  if (sender.state != UIGestureRecognizerStateEnded)
    ;
  else if (fabs (translate.x) > fabs (translate.y))	// Horizontal
    [self pinch: (translate.x > 0)];
  else							// Vertical
    [self pinch: (translate.y > 0)];
}


- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
  if (event.type == UIEventSubtypeMotionShake) {
    config.test_hack = '0' + (random() % 11);  /* 0-9 or SPC */
  }
}


/* We need this to respond to "shake" gestures
 */
- (BOOL)canBecomeFirstResponder {
  return YES;
}
 

#else /* !USE_IPHONE */


/* The top-level window is sometimes transparent.
 */
- (BOOL)isOpaque
{
  return NO;
}


/* Called when the user starts interactively resizing the window.
 */
- (void)viewWillStartLiveResize
{
}


/* Called when the user is done interactively sizing the window.
 */
- (void)viewDidEndLiveResize
{
  // Resize the frame one last time, now that we're finished dragging.
  [self setFrameSize:[self frame].size];
}


/* Announce our willingness to accept keyboard input.
 */
- (BOOL)acceptsFirstResponder
{
  return YES;
}

/* Display date when mouse clicked in window.
 */
- (void)mouseDown:(NSEvent *)ev
{
  config.display_date_p = 1;
}


/* Back to time display shortly after mouse released.
 */
- (void)mouseUp:(NSEvent *)ev
{
  float delay = 2.0;  // seconds
  if (config.display_date_p)
    [NSTimer scheduledTimerWithTimeInterval:delay
                                     target:self
                                   selector:@selector(dateOff)
                                   userInfo:nil
                                    repeats:NO];
}


/* Typing Ctrl-0 through Ctrl-9 and Ctrl-hyphen are a debugging hack.
 */
- (void)keyDown:(NSEvent *)ev
{
  NSString *ns = [ev charactersIgnoringModifiers];
  if (! [ns canBeConvertedToEncoding:NSASCIIStringEncoding])
    goto FAIL;
  const char *s = [ns cStringUsingEncoding:NSASCIIStringEncoding];
  if (! s) goto FAIL;
  if (strlen(s) != 1) goto FAIL;
  if (! ([ev modifierFlags] & NSControlKeyMask)) goto FAIL;
  if (*s == '-' || (*s >= '0' && *s <= '9'))
    config.test_hack = *s;
  else goto FAIL;
  return;
FAIL:
  [super keyDown:ev];
}

#endif /* !USE_IPHONE */


- (void)dateOff
{
  config.display_date_p = 0;
}

# ifdef USE_IPHONE
- (void)aboutOff
{
  if (aboutBox) {
    CABasicAnimation *anim = 
      [CABasicAnimation animationWithKeyPath:@"opacity"];
    anim.duration     = 0.3;
    anim.repeatCount  = 1;
    anim.autoreverses = NO;
    anim.fromValue    = [NSNumber numberWithFloat: 1];
    anim.toValue      = [NSNumber numberWithFloat: 0];
//  anim.delegate     = self;
    aboutBox.layer.opacity = 0;
    [aboutBox.layer addAnimation:anim forKey:@"animateOpacity"];
  }
}


- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
  if (! aboutBox) return;
  [aboutBox removeFromSuperview];
  aboutBox = 0;
}

# endif /* USE_IPHONE */


/* This is called from the timer (and other places) to change the colors.
 */
- (void)setForeground:(NSColor *)new_fg background:(NSColor *)new_bg
{
  if (fg != new_fg) {
    if (fg) [fg release];
# ifdef USE_IPHONE
    fg = [new_fg retain];
# else  /* !USE_IPHONE */
    fg = [[new_fg colorUsingColorSpaceName:NSCalibratedRGBColorSpace] retain];
# endif /* !USE_IPHONE */
  }
  if (bg != new_bg) {
    if (bg) [bg release];
# ifdef USE_IPHONE
    bg = [new_bg retain];
# else  /* !USE_IPHONE */
    bg = [[new_bg colorUsingColorSpaceName:NSCalibratedRGBColorSpace] retain];
# endif /* !USE_IPHONE */
  }

# ifdef USE_IPHONE
//    [self drawRect:[self frame]];
# else  /* !USE_IPHONE */
  [self setNeedsDisplay:TRUE];
# endif /* !USE_IPHONE */
}


#if 0
#ifndef USE_IPHONE
- (void)viewDidMoveToWindow
{
  // Make window's background transparent so that the GL background works.
  // But only do this if our creator has said that it's ok for us to diddle
  // the background color of the window we are running on.
  //
  // #### For some reason we are now getting "invalid context 0" errors
  //      inside AppController:[window setContentView:view] when doing
  //      this here.  So, this code was moved to inside of colorTick,
  //      which means the window flickers at startup (initially has a
  //      solid background color, then turns transparent.)  Bleh.
  //
  if (ownWindow) {
    [[self window] setBackgroundColor:[NSColor clearColor]];
    [[self window] setOpaque:NO];
    [[NSColor clearColor] set];
    NSRectFill ([self frame]);
  }
}
#endif /* !USE_IPHONE */
#endif /* 0 */



/**************************************************************************
 **************************************************************************

   The big kahuna refresh method.  Draw the current contents of the bitmap
   onto the window.  Sounds easy, doesn't it?

 **************************************************************************
 **************************************************************************/

- (void)drawRect:(NSRect)rect
{
  NSRect framerect = [self frame];
  NSRect torect;

  /**************************************************************************
     Compute the desired size and rotation of the destination rectangle.
   **************************************************************************/

  if (config.width <= 0 || config.height <= 0) abort();

  if (!fg || !bg) return; // Called too early somehow?

# ifdef USE_IPHONE

  double s = 1;  /* Retina scale factor */

#  if defined(__IPHONE_4_0)
  /* Make sure we are dealing with real pixels, not "virtual" pixels. */
  if ([self respondsToSelector:@selector(contentScaleFactor)]) {
    s = [self contentScaleFactor];
    framerect.size.width  *= s;
    framerect.size.height *= s;
  }
#  endif /* __IPHONE_4_0 */

# else // !USE_IPHONE

  CGFloat s = self.window.backingScaleFactor;
  framerect.size.width  *= s;
  framerect.size.height *= s;

# endif // !USE_IPHONE

  float img_aspect = (float) config.width / (float) config.height;
  float win_aspect = framerect.size.width / (float) framerect.size.height;

  // Scale the image to fill the window without changing its aspect ratio.
  //
  if (win_aspect > img_aspect) {
    torect.size.height = framerect.size.height;
    torect.size.width  = framerect.size.height * img_aspect;
  } else {
    torect.size.width  = framerect.size.width;
    torect.size.height = framerect.size.width / img_aspect;
  }


  /**************************************************************************
     Choose the size of the texture
   **************************************************************************/

  char err[100];
  int retries = 0;

  while (1) {	// Loop trying smaller sizes

    strcpy (err, "glTexImage2D");

    // The animation slows down a lot if we use truly gigantic numbers,
    // so limit the number size in screensaver-mode.  Note that this
    // limits the size of the output quad, not the size of the texture.
    //
    if (constrainSizes) {
      int maxh = (config.time_mode == SS ? 512 : /*256*/ 200);
      maxh *= s;
      if (torect.size.height > maxh) {
        torect.size.height = maxh;
        torect.size.width  = maxh * img_aspect;
      }
    }

    // put a 10% margin between the numbers and the edge of the window.
    torect.size.width  *= 0.9;
    torect.size.height *= 0.9;

    // center it in the window
    //
    torect.origin.x = (framerect.size.width  - torect.size.width ) / 2;
    torect.origin.y = (framerect.size.height - torect.size.height) / 2;

    // Don't allow the top of the number to be off screen (iPhone 5, sec only)
    //
    if (torect.origin.x < 0) {
      float r = ((torect.size.width + torect.origin.x) / torect.size.width);
      torect.size.width  *= r;
      torect.size.height *= r;
      torect.origin.x = (framerect.size.width  - torect.size.width ) / 2;
      torect.origin.y = (framerect.size.height - torect.size.height) / 2;
    }


  /**************************************************************************
     Set the current GL context before talking to OpenGL
   **************************************************************************/

# ifdef USE_IPHONE
  [EAGLContext setCurrentContext:ogl_ctx];
  glBindFramebufferOES(GL_FRAMEBUFFER_OES, gl_framebuffer);
# else /* !USE_IPHONE */
  [ogl_ctx makeCurrentContext];
  [ogl_ctx setView:self];
  [ogl_ctx update];
# endif /* !USE_IPHONE */


  /**************************************************************************
     Bind the bitmap to a texture
   **************************************************************************/

    // We alternate between two different texture IDs, only writing to the one
    // that is not currently on screen.  If we don't do this, then the window
    // flickers if it is above another window that has video playing in it.

    // Drawing with GL_LUMINANCE_ALPHA means that only the "ink" pixels of the
    // digits are written into the color buffer, and are multiplied by by the
    // prevailing glColor.

    sprintf (err + strlen(err), " #%d %dx%d", 
             retries, config.width2, config.height2);

    if (! config.bitmap) abort();
    glBindTexture (GL_TEXTURE_2D, textures[0]);
    glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA,
                  config.width2, config.height2, 0,
                  GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, config.bitmap);

    GLenum errn = glGetError();
    if (errn == GL_NO_ERROR) {			// Texture succeeded.
      break;
    } else if (errn == GL_INVALID_VALUE) {	// Texture too large. Retry.

      log_gl_error (err, errn);
      retries++;

      // Reduce the target size of the texture.
      // If it's insanely small, abort.

      unsigned int ow = config.width2;
      unsigned int oh = config.height2;
      int toosmall = 20;
      int size_tries = 0;

      while (config.height2 > toosmall &&
             ow == config.width2 &&
             oh == config.height2) {
        config.height -= 4;
        render_bitmap_size (&config, 
                            &config.width, &config.height,
                            &config.width2, &config.height2);
        if (size_tries++ > 2000) abort();  // sanity
      }

      if (config.height2 <= toosmall) abort();

      // Must re-render if size changed.
      if (config.bitmap) free (config.bitmap);
      config.bitmap = 0;
      if (config.render_state) render_free (&config);
      render_init (&config);

    } else if (errn != GL_NO_ERROR) {		// Unknown error.
      log_gl_error (err, errn);
      abort();
    }
  }

  if (retries > 0)
    NSLog (@"%s: Succeeded: %s", progname, err);


  /**************************************************************************
     Finish texture initialization
   **************************************************************************/

# ifdef DO_DOUBLE_TEXTURE
  GLuint swap = textures[0];
  textures[0] = textures[1];
  textures[1] = swap;
# endif

  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  check_gl_error ("glTexParameteri");

  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable (GL_BLEND);
  glEnable (GL_TEXTURE_2D);


  /**************************************************************************
     Set the viewport and projection matrix
   **************************************************************************/

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glViewport (0, 0, framerect.size.width, framerect.size.height);
  glOrtho (0, framerect.size.width, 0, framerect.size.height, -1, 1);
  check_gl_error ("gOrtho");

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();


  /**************************************************************************
     Set the foreground and background colors
   **************************************************************************/

  CGFloat fgr, fgg, fgb, fga;
  CGFloat bgr, bgg, bgb, bga;
# ifndef USE_IPHONE
  [fg getRed:&fgr green:&fgg blue:&fgb alpha:&fga];
  [bg getRed:&bgr green:&bgg blue:&bgb alpha:&bga];
# else  /* USE_IPHONE */
  const CGFloat *rgba;
  rgba = CGColorGetComponents ([fg CGColor]);
  fgr = rgba[0]; fgg = rgba[1]; fgb = rgba[2]; fga = rgba[3];
  rgba = CGColorGetComponents ([bg CGColor]);
  bgr = rgba[0]; bgg = rgba[1]; bgb = rgba[2]; bga = 1;  // rgba[3];
# endif /* USE_IPHONE */

  glClearColor (bgr, bgg, bgb, bga);
  glColor4f (fgr, fgg, fgb, fga);
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  check_gl_error ("clear");


  /**************************************************************************
     Create the quad
   **************************************************************************/

  GLfloat qx = torect.origin.x;
  GLfloat qy = torect.origin.y;
  GLfloat qw = torect.size.width;
  GLfloat qh = torect.size.height;
  GLfloat tw = (GLfloat) config.width  / config.width2;
  GLfloat th = (GLfloat) config.height / config.height2;

  if (config.left_offset != 0)
    glTranslatef (-qw * ((GLfloat) config.left_offset / config.width),
                  0, 0);

# ifndef USE_IPHONE
  glBegin (GL_QUADS);
  glTexCoord2f (0,  0);  glVertex3f (qx,    qy,    0);
  glTexCoord2f (tw, 0);  glVertex3f (qx+qw, qy,    0);
  glTexCoord2f (tw, th); glVertex3f (qx+qw, qy+qh, 0);
  glTexCoord2f (0,  th); glVertex3f (qx,    qy+qh, 0);
  glEnd();
  check_gl_error ("quad");
# else /* USE_IPHONE */

  GLfloat vertices[] = {
    qx,    qy,    0,
    qx+qw, qy,    0,
    qx,    qy+qh, 0,
    qx+qw, qy+qh, 0
  };
  GLfloat texCoords[] = {
    0,  0,
    tw, 0,
    0,  th,
    tw, th
  };
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  check_gl_error ("client state");

  glVertexPointer(3, GL_FLOAT, 0, vertices);
  glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  check_gl_error ("draw arrays");

# endif /* USE_IPHONE */

  /**************************************************************************
     Flush bits to the screen.
   **************************************************************************/

  glFinish();

# ifndef USE_IPHONE
  [ogl_ctx flushBuffer];
  check_gl_error ("finish");
# else /* USE_IPHONE */
  glBindRenderbufferOES (GL_RENDERBUFFER_OES, gl_renderbuffer);
  [ogl_ctx presentRenderbuffer:GL_RENDERBUFFER_OES];
  check_gl_error ("finish");
# endif /* USE_IPHONE */
}


/* When this timer goes off, we re-generate the bitmap
   and mark the display as invalid.
*/
- (void)clockTick
{
  if (clockTimer && [clockTimer isValid]) {
    [clockTimer invalidate];
    clockTimer = 0;
  }

  if (config.max_fps <= 0) abort();

# ifndef USE_IPHONE
  NSWindow *w = [self window];
  if (w && ![w isMiniaturized])   // noop if no window yet, or if iconified.
# else  /* USE_IPHONE */
  if (! screenLocked)
# endif /* USE_IPHONE */
  {
    render_once (&config);
    // [[self window] invalidateShadow]; // windows with shadows flicker...

    [self drawRect:[self frame]];
  }

# ifdef USE_IPHONE
  // Never automatically turn the screen off if we are docked.
  [UIApplication sharedApplication].idleTimerDisabled =
    ([UIDevice currentDevice].batteryState != UIDeviceBatteryStateUnplugged);
# endif /* USE_IPHONE */


  // re-schedule the timer according to current fps.
  // Schedule it in two run loop modes so that the timer fires even
  // during liveResize.
  //
  float delay = 0.9 / config.max_fps;

# ifdef USE_IPHONE
  if (screenLocked) delay = 0.25;  // only wake up 4x/second.
# endif /* USE_IPHONE */

  clockTimer = [NSTimer timerWithTimeInterval:delay
                                       target:self
                                     selector:@selector(clockTick)
                                     userInfo:nil
                                      repeats:NO];
  NSRunLoop *L = [NSRunLoop currentRunLoop];
  [L addTimer:clockTimer forMode:NSDefaultRunLoopMode];
# ifndef USE_IPHONE
  [L addTimer:clockTimer forMode:NSEventTrackingRunLoopMode];
# endif /* !USE_IPHONE */
}


/* When this timer goes off, we re-pick the foreground/background colors,
   and mark the display as invalid.
 */
- (void)colorTick
{
  if (colorTimer && [colorTimer isValid]) {
    [colorTimer invalidate];
    colorTimer = 0;
  }

# ifndef USE_IPHONE
  // See comment in viewDidMoveToWindow -- doing this there caused errors.
  // 
  if ([self window] && ownWindow) {
    ownWindow = 0; // only do it once
    [[self window] setBackgroundColor:[NSColor clearColor]];
    [[self window] setOpaque:NO];
    // Not sure why I was doing this, but this causes the System Preferences
    // window to have random black areas drawn on it.
    //  [[NSColor clearColor] set];
    //  NSRectFill ([self frame]);
  }
# endif /* !USE_IPHONE */

  if (config.max_cps <= 0) return;   // cycling is turned off, do nothing

  if ([self window]		     // do nothing if no window yet
# ifdef USE_IPHONE
      && !screenLocked
# endif /* USE_IPHONE */
      ) {
    CGFloat h, s, v, a;
    NSColor *fg2, *bg2;
    float tick = 1.0 / 360.0;   // cycle H by one degree per tick

# ifdef USE_IPHONE
    const CGFloat *rgba = CGColorGetComponents([fg CGColor]);
    rgb_to_hsv (rgba[0], rgba[1], rgba[2], &h, &s, &v);
    h /= 360.0;
    a = rgba[3];
# else  /* !USE_IPHONE */
    [fg getHue:&h saturation:&s brightness:&v alpha:&a];
# endif /* !USE_IPHONE */

    h += tick;
    while (h > 1.0) h -= 1.0;
    fg2 = [NSColor colorWithCalibratedHue:h saturation:s brightness:v alpha:a];

# ifdef USE_IPHONE
    rgba = CGColorGetComponents([bg CGColor]);
    rgb_to_hsv (rgba[0], rgba[1], rgba[2], &h, &s, &v);
    h /= 360.0;
    a = rgba[3];
# else  /* !USE_IPHONE */
    [bg getHue:&h saturation:&s brightness:&v alpha:&a];
# endif /* !USE_IPHONE */

    h += tick * 0.91;   // cycle bg slightly slower than fg, for randomosity.
    while (h > 1.0) h -= 1.0;
    bg2 = [NSColor colorWithCalibratedHue:h saturation:s brightness:v alpha:a];

    [self setForeground:fg2 background:bg2];

# ifdef USE_IPHONE
    /* Every time we tick the color, write the current colors into
       preferences so that the next time the app starts up, the color
       cycle begins where it left off.  (Maybe this is dumb.)
     */
    NSUserDefaults *controller = [NSUserDefaults standardUserDefaults];
    [controller setObject:[NSArchiver archivedDataWithRootObject:fg]
                forKey:@"initialForegroundColor"];
    [controller setObject:[NSArchiver archivedDataWithRootObject:bg]
                forKey:@"initialBackgroundColor"];
# endif /* USE_IPHONE */
  }

  /* re-schedule the timer according to current fps.
     Schedule it in two run loop modes so that the timer fires even
     during liveResize.
   */
  float delay = 1.0 / config.max_cps;

# ifdef USE_IPHONE
  if (screenLocked) delay = 0.25;  // only wake up 4x/second.
# endif /* USE_IPHONE */

  colorTimer = [NSTimer timerWithTimeInterval:delay
                                       target:self
                                     selector:@selector(colorTick)
                                     userInfo:nil
                                      repeats:NO];
  NSRunLoop *L = [NSRunLoop currentRunLoop];
  [L addTimer:colorTimer forMode:NSDefaultRunLoopMode];
# ifndef USE_IPHONE
  [L addTimer:colorTimer forMode:NSEventTrackingRunLoopMode];
# endif /* !USE_IPHONE */
}


/* When this timer goes off, we switch to "show date" mode.
 */
- (void)dateTick
{
  if (dateTimer && [dateTimer isValid]) {
    [dateTimer invalidate];
    dateTimer = 0;
  }

  if (autoDateInterval <= 0) return;

  BOOL was_on = config.display_date_p;

  if (config.time_mode != SS)		// don't auto-date in secs-only mode
    config.display_date_p = !was_on;

  /* re-schedule the timer according to current fps.
   */
  float delay = autoDateInterval;
  if (!was_on) delay = 3.0;
  dateTimer = [NSTimer scheduledTimerWithTimeInterval:delay
                                               target:self
                                             selector:@selector(dateTick)
                                             userInfo:nil
                                              repeats:NO];
}


static NSTimeInterval countdown_homestretch_interval = 30;

- (void)updateCountdown
{
  config.countdown = (usesCountdownTimer
                      ? [countdownDate timeIntervalSince1970]
                      : 0);

  if (countdownHomeStretchStartTimer) {
    if ([countdownHomeStretchStartTimer isValid])
      [countdownHomeStretchStartTimer invalidate];
    [countdownHomeStretchStartTimer release];
    countdownHomeStretchStartTimer = 0;
  }

  if (countdownHomeStretchEndTimer) {
    if ([countdownHomeStretchEndTimer isValid])
      [countdownHomeStretchEndTimer invalidate];
    [countdownHomeStretchEndTimer release];
    countdownHomeStretchEndTimer = 0;
  }

  [self countdownHomeStretch];

  if (usesCountdownTimer && usesHomeStretchTimer) {

    NSDate *now = [NSDate date];
    NSDate *start =
      [NSDate dateWithTimeInterval: -countdown_homestretch_interval
                         sinceDate: countdownDate];
    NSDate *end =
      [NSDate dateWithTimeInterval: countdown_homestretch_interval
                         sinceDate: countdownDate];
    NSTimeInterval delay1 = [start timeIntervalSinceDate: now];
    NSTimeInterval delay2 = [end   timeIntervalSinceDate: now];

    delay1 -= 1.5;  // start a little earlier

    if (delay1 > 0) {
      countdownHomeStretchStartTimer =
        [NSTimer timerWithTimeInterval:delay1
                                target:self
                              selector:@selector(countdownHomeStretch)
                              userInfo:nil
                               repeats:NO];
      [countdownHomeStretchStartTimer retain];
      // Without this, the timer doesn't fire...
      NSRunLoop *L = [NSRunLoop currentRunLoop];
      [L addTimer:countdownHomeStretchStartTimer forMode:NSDefaultRunLoopMode];
    }

    if (delay2 > 0) {
      countdownHomeStretchEndTimer =
        [NSTimer timerWithTimeInterval:delay2
                                target:self
                              selector:@selector(countdownHomeStretch)
                              userInfo:nil
                               repeats:NO];
      [countdownHomeStretchEndTimer retain];
      // Without this, the timer doesn't fire...
      NSRunLoop *L = [NSRunLoop currentRunLoop];
      [L addTimer:countdownHomeStretchEndTimer forMode:NSDefaultRunLoopMode];
    }
  }
}


- (void)countdownHomeStretch
{
  if (!usesCountdownTimer) return;

  NSTimeInterval secs = [countdownDate timeIntervalSinceNow];
  if (usesHomeStretchTimer &&
      secs >= -countdown_homestretch_interval &&
      secs <   countdown_homestretch_interval) {
    [self setTimeStyle:SS];
  } else {
    [self setTimeStyle:HHMMSS];
  }
}


# ifdef USE_IPHONE

- (void)showBlurb:(NSString *)text
{
  CGRect frame = [self frame];
  // CGFloat rot;
  int size = ([self frame].size.width >= 768 ? 24 : 14);
  UIFont *font = [UIFont boldSystemFontOfSize: size];
  // #### sizeWithFont deprecated as of iOS 7; use boundingRectWithSize.
  CGSize tsize = [text sizeWithFont:font
                  constrainedToSize:CGSizeMake(frame.size.width,
                                               frame.size.height)];

  // Don't know how to find inner margin of UITextView.
  CGFloat margin = 10;
  tsize.width  += margin * 4;
  tsize.height += margin * 2;

  frame = CGRectMake (0, 0, tsize.width, tsize.height);
  CGRect frame2 = frame;

  frame.origin.x = ([self frame].size.width  - tsize.width) / 2;
  frame.origin.y =  [self frame].size.height - tsize.height;

  if (aboutBox)
    [aboutBox removeFromSuperview];
  
  /* The aboutBox is just a view that applies rotation.
     Inside that is aboutText, pre-rotated, which draws the text.
     (We used to set the transformation on the UITextView itself,
     but that stopped working in iOS 7.)
     Finally inside that is a CALayer that applies dropshadows to the text.
   */
  aboutBox = [[UIView alloc] init];
  [aboutBox setFrame:frame];
  // aboutBox.transform = CGAffineTransformMakeRotation (rot);
  
  UITextView *aboutText = [[UITextView alloc] initWithFrame:frame2];
 // aboutText.transform = CGAffineTransformMakeRotation (rot);
  aboutText.font = font;
  aboutText.textAlignment = NSTextAlignmentCenter;
  aboutText.showsHorizontalScrollIndicator = NO;
  aboutText.showsVerticalScrollIndicator = NO;
  aboutText.scrollEnabled = NO;
  aboutText.textColor = [UIColor whiteColor];  // fg?
  aboutText.backgroundColor = [UIColor clearColor];
  aboutText.text = text;
  aboutText.editable = NO;

  // Too subtle?
  CALayer *textLayer = (CALayer *)[aboutText.layer.sublayers objectAtIndex:0];
  textLayer.shadowColor   = [UIColor blackColor].CGColor;
  textLayer.shadowOffset  = CGSizeMake(0, 0);
  textLayer.shadowOpacity = 1;
  textLayer.shadowRadius  = 2;
  CABasicAnimation *anim =
    [CABasicAnimation animationWithKeyPath:@"opacity"];
  anim.duration     = 0.3;
  anim.repeatCount  = 1;
  anim.autoreverses = NO;
  anim.fromValue    = [NSNumber numberWithFloat:0.0];
  anim.toValue      = [NSNumber numberWithFloat:1.0];
  [aboutText.layer addAnimation:anim forKey:@"animateOpacity"];

  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                  initWithTarget:self
                                  action:@selector(handleAboutTap)];
  [aboutBox addGestureRecognizer: tap];
  [tap release];

  [aboutBox addSubview:aboutText];
  [[self superview] addSubview:aboutBox];
}

- (void) handleAboutTap
{
  // Find the URL in the "about" text, and load it in Safari.
  NSDictionary *info = [[NSBundle bundleForClass:[self class]] infoDictionary];
  NSString *s = [info objectForKey:@"CFBundleGetInfoString"];
  NSRange r = [s rangeOfString:@"http://" options:0];
  if (r.location == NSNotFound)
    return;
  s = [s substringFromIndex: r.location];
  r = [s rangeOfCharacterFromSet:
           [NSCharacterSet whitespaceAndNewlineCharacterSet]];
  if (r.location != NSNotFound)
    s = [s substringToIndex: r.location];
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString: s]];
}

#endif /* USE_IPHONE */


/* The About button in the menu bar or preferences sheet.
 */
- (IBAction)aboutClick:(id)sender
{
  NSBundle *nsb = [NSBundle bundleForClass:[self class]];
  NSAssert1 (nsb, @"no bundle for class %@", [self class]);

  NSDictionary *info = [nsb infoDictionary];
# ifndef USE_IPHONE
  NSString *name = @"Dali Clock";
  NSString *vers = [info objectForKey:@"CFBundleVersion"];

  NSString *ver2 = [info objectForKey:@"CFBundleShortVersionString"];
  NSString *icon = [info objectForKey:@"CFBundleIconFile"];
  NSString *cred_file = [nsb pathForResource:@"Credits" ofType:@"html"];
  NSAttributedString *cred = [[[NSAttributedString alloc]
                                initWithPath:cred_file
                                documentAttributes:(NSDictionary **)NULL]
                               autorelease];
  NSString *icon_file = [nsb pathForResource:icon ofType:@"icns"];
  NSImage *iimg = [[NSImage alloc] initWithContentsOfFile:icon_file];

  NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
    name, @"ApplicationName",
    vers, @"Version",
    ver2, @"ApplicationVersion",
    @"",  @"Copyright",
    cred, @"Credits",
    iimg, @"ApplicationIcon",
    nil];

  [[NSApplication sharedApplication]
    orderFrontStandardAboutPanelWithOptions:dict];

# else  /* USE_IPHONE */
  NSString *vers = [info objectForKey:@"CFBundleGetInfoString"];
  vers = [vers stringByReplacingOccurrencesOfString:@", "  withString:@"\n"];
  vers = [vers stringByReplacingOccurrencesOfString:@".\n" withString:@"\n"];
  [self showBlurb:vers];
# endif /* USE_IPHONE */
}


// hint for XCode popup menu
#pragma mark accessors

/* [ken] if you (1) only wanted these for bindings purposes (true) and
   (2) they were dumb methods that just manipulated ivars of the same
   name (not true, they mostly write into config), then we would not
   have to write them.  I use the freeware Accessorizer to give me
   accessor templates.
 */
- (int)hourStyle { return !config.twelve_hour_p; }
- (void)setHourStyle:(int)aHourStyle
{
  config.twelve_hour_p = !aHourStyle;
}


- (int)timeStyle { return config.time_mode; }
- (void)setTimeStyle:(int)aTimeStyle
{
  if (config.time_mode != aTimeStyle) {
    config.time_mode = aTimeStyle;
    config.width++;  // kludge: force regeneration of bitmap
    [self setFrameSize:[self frame].size];
  }
}


- (int)dateStyle { return config.date_mode; }
- (void)setDateStyle:(int)aDateStyle
{
  config.date_mode = aDateStyle;
}


- (float)cycleSpeed { return (float)config.max_cps; }
- (void)setCycleSpeed:(float)aCycleSpeed
{
  if (config.max_cps != aCycleSpeed) {
    config.max_cps = (int)aCycleSpeed;
    if (config.max_cps < 0.0001) {
      [self setForeground:initialForegroundColor
               background:initialBackgroundColor];
    } else {
      [self colorTick];
    }
  }
}


- (int)usesCountdownTimer { return usesCountdownTimer; }
- (void)setUsesCountdownTimer:(int)flag
{
  if (usesCountdownTimer != flag) {

    // If we're in the home stretch while turning off countdown, pop out.
    NSTimeInterval secs = [countdownDate timeIntervalSinceNow];
    if (!flag &&
        usesHomeStretchTimer &&
        secs >= -countdown_homestretch_interval &&
        secs <   countdown_homestretch_interval) {
      [self setTimeStyle:HHMMSS];
    }

    usesCountdownTimer = flag;
    [self updateCountdown];
  }
}


- (int)usesHomeStretchTimer { return usesHomeStretchTimer; }
- (void)setUsesHomeStretchTimer:(int)flag
{
  if (usesHomeStretchTimer != flag) {
    usesHomeStretchTimer = flag;
    [self updateCountdown];
  }
}


- (NSDate *)countdownDate { return [[countdownDate retain] autorelease]; }
- (void)setCountdownDate:(NSDate *)aCountdownDate
{
  if (countdownDate != aCountdownDate) {
    [countdownDate release];
    countdownDate = [aCountdownDate retain];
    [self updateCountdown];
  }
}


- (NSColor *)initialForegroundColor
{
  return [[initialForegroundColor retain] autorelease];
}


- (void)setInitialForegroundColor:(NSColor *)c
{
  if (initialForegroundColor != c) {
    if (initialForegroundColor)
      [initialForegroundColor release];
    initialForegroundColor = (c ? [c retain] : 0);
    [self setForeground:initialForegroundColor
             background:initialBackgroundColor];
  }
}


- (NSColor *)initialBackgroundColor
{
  return [[initialBackgroundColor retain] autorelease];
}


- (void)setInitialBackgroundColor:(NSColor *)c
{
  if (initialBackgroundColor != c) {
    if (initialBackgroundColor)
      [initialBackgroundColor release];
    initialBackgroundColor = (c ? [c retain] : 0);
    [self setForeground:initialForegroundColor
             background:initialBackgroundColor];
  }
}


- (void)setConstrainSizes:(BOOL)constrain_p;
{
  constrainSizes = constrain_p;
}


- (void)setAutoDate:(float)interval
{
  autoDateInterval = interval;

  config.display_date_p = 1;
  [self dateTick];
  config.display_date_p = 0;
}

#ifdef USE_IPHONE
- (void)setScreenLocked:(BOOL)locked
{
  screenLocked = locked;

  // Reset the auto-date timer every time the screen is locked/unlocked,
  // so that it never happens while the user is active.
  [self setAutoDate:autoDateInterval];
}
#endif /* USE_IPHONE */


@end


#ifdef USE_IPHONE
static void
rgb_to_hsv (CGFloat R, CGFloat G, CGFloat B,
	    CGFloat *h, CGFloat *s, CGFloat *v)
{
  CGFloat H, S, V;
  CGFloat cmax, cmin;
  CGFloat cmm;
  int imax;
  cmax = R; cmin = G; imax = 1;
  if  ( cmax < G ) { cmax = G; cmin = R; imax = 2; }
  if  ( cmax < B ) { cmax = B; imax = 3; }
  if  ( cmin > B ) { cmin = B; }
  cmm = cmax - cmin;
  V = cmax;
  if (cmm == 0)
    S = H = 0;
  else
    {
      S = cmm / cmax;
      if       (imax == 1)    H =       (G - B) / cmm;
      else  if (imax == 2)    H = 2.0 + (B - R) / cmm;
      else /*if (imax == 3)*/ H = 4.0 + (R - G) / cmm;
      if (H < 0) H += 6.0;
    }
  *h = (H * 60.0);
  *s = S;
  *v = V;
}
#endif /* USE_IPHONE */



/* Prints the GL error to the system log.
 */
static void
log_gl_error (const char *type, GLenum err)
{
  char buf[100];
  const char *e;

# ifndef  GL_TABLE_TOO_LARGE_EXT
#  define GL_TABLE_TOO_LARGE_EXT 0x8031
# endif
# ifndef  GL_TEXTURE_TOO_LARGE_EXT
#  define GL_TEXTURE_TOO_LARGE_EXT 0x8065
# endif
# ifndef  GL_INVALID_FRAMEBUFFER_OPERATION
#  define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506
# endif

  switch (err) {
    case GL_NO_ERROR:              return;
    case GL_INVALID_ENUM:          e = "invalid enum";      break;
    case GL_INVALID_VALUE:         e = "invalid value";     break;
    case GL_INVALID_OPERATION:     e = "invalid operation"; break;
    case GL_STACK_OVERFLOW:        e = "stack overflow";    break;
    case GL_STACK_UNDERFLOW:       e = "stack underflow";   break;
    case GL_OUT_OF_MEMORY:         e = "out of memory";     break;
    case GL_TABLE_TOO_LARGE_EXT:   e = "table too large";   break;
    case GL_TEXTURE_TOO_LARGE_EXT: e = "texture too large"; break;
    case GL_INVALID_FRAMEBUFFER_OPERATION: e = "invalid framebuffer op"; break;
    default:
      e = buf; sprintf (buf, "unknown GL error 0x%04x", (int) err); break;
  }

  NSLog (@"%s: GL error in %s: %s", progname, type, e);
}


/* Log a GL error and abort. */
static void
check_gl_error (const char *type)
{
  GLenum err = glGetError();
  if (err == GL_NO_ERROR) return;
  log_gl_error (type, err);
  abort();
}