-
Notifications
You must be signed in to change notification settings - Fork 1
/
foocal
executable file
·1188 lines (1131 loc) · 40.9 KB
/
foocal
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
#!/usr/bin/perl
# vi:set sw=2 ai sm:
#
# Copyright 2016-2018, 2021 by Ambrose Li <ambrose.li@gmail.com>
# The primary purpose of this script is to figure out the year number in the Chinese system
# so that I can name my CV's without having to look up two web pages.
# Everything else is just for kicks =P
#
# This script doesn't really do a lot of calculations itself; it just gathers the information
# from elsewhere (e.g., hebcal, or the HKO) and presents it.
#
# http://www.hko.gov.hk/gts/time/calendar/text/T2016e.txt
# http://www.hko.gov.hk/gts/time/calendar/text/T2016c.txt
# www.hko.gov.hk/gts/time/stemsandbranches.htm
#
# https://scitechvista.nat.gov.tw/zh-tw/articles/c/9/7/10/1/998.htm
# see https://stackoverflow.com/questions/6162484/why-does-modern-perl-avoid-utf-8-by-default for these crazy hacks
# THERE ARE MORE CRAZY HACKS THERE FOR MORE COMPLEX PROJECTS!!
use v5.12; # minimal for unicode string feature
use v5.14; # //u modifier
use utf8;
use open qw( :encoding(UTF-8) :std );
use charnames qw( :full :short );
use feature "unicode_strings";
use warnings qw( FATAL utf8 );
use Encode qw( encode decode );
@ARGV = map { decode("UTF-8", $_) } @ARGV if grep /\P{ASCII}/ => @ARGV;
use strict;
use integer;
use POSIX;
use DateTime;
use vars qw( $use_datetime_event_sunrise );
use vars qw( $use_datetime_astro_sunrise );
use vars qw( $use_astro_sunrise );
BEGIN {
if (!eval { require DateTime::Astro::Sunrise; }) {
$use_datetime_event_sunrise = 1;
require DateTime::Event::Sunrise;
} elsif (!eval { require DateTime::Astro::Sunrise; }) {
$use_datetime_astro_sunrise = 1;
require DateTime::Astro::Sunrise;
} elsif (!eval { require Astro::Sunrise; }) {
$use_astro_sunrise = 1;
require Astro::Sunrise;
} else {
die "Cannot find a usable Sunrise package";
}
}
use Getopt::Long;
use Data::Dumper;
use vars qw( $fake );
use vars qw( $debug );
use vars qw( $enable_seconds );
use vars qw( $enable_nonproportional_watches );
use vars qw( $enable_qing_quarters );
use vars qw( $enable_hebcal );
use vars qw( $enable_planetary $planetary_omit_details );
use vars qw( $enable_chinese $lang );
use vars qw( $enable_decaminutes $enable_minutes );
use vars qw( $enable_4th_hebrew_watch );
use vars qw( $decimals );
use vars qw( $sysline_mode );
use vars qw( $genmon_mode );
$enable_hebcal = 1;
$decimals = 2;
use vars qw( $now );
$now = time; # so that everything can be synchronized
use vars qw( $coords );
use vars qw( $representation );
$representation = 'name';
use vars qw( $lat $lon );
use vars qw( @planets );
@planets = (
{
'name' => {'zh' => '日', 'en' => 'Sun'},
'icon' => '☉',
'article' => {'en' => 'the'},
},
{
'name' => {'zh' => '月', 'en' => 'Moon'},
'icon' => '☽',
'article' => {'en' => 'the'},
},
{
'name' => {'zh' => '火', 'en' => 'Mars'},
'icon' => '♂',
},
{
'name' => {'zh' => '水', 'en' => 'Mercury'},
'icon' => '☿',
},
{
'name' => {'zh' => '木', 'en' => 'Jupiter'},
'icon' => '♃',
},
{
'name' => {'zh' => '金', 'en' => 'Venus'},
'icon' => '♀',
},
{
'name' => {'zh' => '土', 'en' => 'Saturn'},
'icon' => '♄',
},
);
use vars qw( @stems @branches );
@stems = (
{
'zh' => '甲',
'en' => 'Jia',
'yue@latn' => 'ˉgap',
},
{
'zh' => '乙',
'en' => 'Yi',
'yue@latn' => 'ˍjyt',
},
{
'zh' => '丙',
'en' => 'Bing',
'yue@latn' => 'ˊbiŋ',
},
{
'zh' => '丁',
'en' => 'Ding',
'yue@latn' => 'ˈdiŋ',
},
{
'zh' => '戊',
'en' => 'Wu',
'yue@latn' => 'ˍmou',
},
{
'zh' => '己',
'en' => 'Ji',
'yue@latn' => 'ˊgei',
},
{
'zh' => '庚',
'en' => 'Geng',
'yue@latn' => 'ˈgɐŋ',
},
{
'zh' => '辛',
'en' => 'Xin',
'yue@latn' => 'ˈsɐn',
},
{
'zh' => '壬',
'en' => 'Ren',
'yue@latn' => 'ˌjɐm',
},
{
'zh' => '癸',
'en' => 'Gui',
'yue@latn' => 'ˉgwɐi',
},
);
# Note that apparently the hours have names in the Han dynasty
# Cf. http://www.oldkids.cn/group/post_detail.php?did=669531
@branches = (
{
'zh' => '子',
'en' => 'Zi',
'yue@latn' => 'ˊdzi',
'name' => {'zh' => '鼠', 'en' => 'Mouse'},
'icon' => '🐁',
'han_hour' => '夜半',
},
{
# feminine year
'zh' => '丑',
'en' => 'Chou',
'yue@latn' => 'ˊtsɐu',
'name' => {'zh' => '牛', 'en' => 'Cow'},
'icon' => '🐄',
'han_hour' => '雞鳴',
},
{
'zh' => '寅',
'en' => 'Yin',
'yue@latn' => 'ˌjɐn',
'name' => {'zh' => '虎', 'en' => 'Tiger'},
'icon' => '🐅',
'han_hour' => '平旦',
},
{
# feminine year
'zh' => '卯',
'en' => 'Mao',
'yue@latn' => 'ˏmɐu',
'name' => {'zh' => '兔', 'en' => 'Rabbit'},
'icon' => '🐇',
'han_hour' => '日出',
},
{
'zh' => '辰',
'en' => 'Chen',
'yue@latn' => 'ˌsɐn',
'name' => {'zh' => '龍', 'en' => 'Dragon'},
'icon' => '🐉',
'han_hour' => '食時',
},
{
# feminine year
'zh' => '巳',
'en' => 'Si',
'yue@latn' => 'ˍdzi',
'name' => {'zh' => '蛇', 'en' => 'Snake'},
'icon' => '🐍',
'han_hour' => '隅中',
},
{
'zh' => '午',
'en' => 'Wu',
'yue@latn' => 'ˏŋ',
'name' => {'zh' => '馬', 'en' => 'Horse'},
'icon' => '🐎',
'han_hour' => '日中',
},
{
# feminine year
'zh' => '未',
'en' => 'Wei',
'yue@latn' => 'ˍmei',
'name' => {'zh' => '羊', 'en' => 'Sheep'},
'icon' => '🐐',
'han_hour' => '日昳',
},
{
'zh' => '申',
'en' => 'Shen',
'yue@latn' => 'ˈsɐn',
'name' => {'zh' => '猴', 'en' => 'Monkey'},
'icon' => '🐒',
'han_hour' => '晡時',
},
{
# feminine year
'zh' => '酉',
'en' => 'You',
'yue@latn' => 'ˏjɐu',
'name' => {'zh' => '雞', 'en' => 'Chicken'},
'icon' => '🐔',
'han_hour' => '日入',
},
{
'zh' => '戌',
'en' => 'Xu',
'yue@latn' => 'ˈsœt',
'name' => {'zh' => '狗', 'en' => 'Dog'},
'icon' => '🐕',
'han_hour' => '黄昏',
},
{
# feminine year
'zh' => '亥',
'en' => 'Hai',
'yue@latn' => 'ˍhɔi',
'name' => {'zh' => '豬', 'en' => 'Pig'},
'icon' => '🐖',
'han_hour' => '人定',
},
);
# We don't use the weird "meaningful" names found in https://zh.wikipedia.org/wiki/希伯來曆
# even though they are short, because first, they're weird and unrecognizable, and also because
# according to the next link the meanings are also wrong.
#
# Note that it's easier to run months starting from Nisan because then Adar II would be just 13
# (cf. http://www.yashanet.com/library/hebrew-days-and-months.html ) but that gets weird if
# the year number increments at Tishrei
#
# Or we could in theory do what some programmers do and make Adar II 8 so in a non-leap year
# after 7 we'd get 9 (cf. https://www.qppstudio.net/webhelp_xv4/jewish-month-numbers.htm )
#
# But in theory Adar I is the leap month, not Adar II, so actually no matter what we do it gets weird
use vars qw( %hebrew_months );
%hebrew_months = (
'Nisan' => {
'zh' => '七',
'en' => 'Nisan',
'xx' => '7',
},
'Iyyar' => {
'zh' => '八',
'en' => 'Iyyar',
'xx' => '8',
},
'Sivan' => {
'zh' => '九',
'en' => 'Sivan',
'xx' => '9',
},
'Tamuz' => {
'zh' => '十',
'en' => 'Tammuz',
'xx' => '10',
},
'Av' => {
'zh' => '11',
'en' => 'Av',
'xx' => '11',
},
'Elul' => {
'zh' => '12',
'en' => 'Elul',
'xx' => '12',
},
'Tishrei' => {
'zh' => '正',
'en' => 'Tishrei',
'xx' => '1',
},
'Cheshvan' => {
'zh' => '二',
'en' => 'Cheshvan',
'xx' => '2',
},
'Kislev' => {
'zh' => '三',
'en' => 'Kislev',
'xx' => '3',
},
'Tevet' => {
'zh' => '四',
'en' => 'Tevet',
'xx' => '4',
},
"Sh'vat" => {
'zh' => '五',
'en' => 'Shevat',
'xx' => '5',
},
'Adar I' => {
'zh' => '閏六',
'en' => 'Adar I',
'xx' => '6a',
},
'Adar' => {
'zh' => '六',
'en' => 'Adar II',
'xx' => '6b',
},
);
sub stem_name ($) {
my($n) = @_;
my $use_yue_latn = $lang eq 'en';
my $key = $use_yue_latn? 'yue@latn': $lang;
return $stems[$n - 1]->{$key};
}
sub branch_name ($) {
my($n) = @_;
my $use_yue_latn = $lang eq 'en';
my $key = $use_yue_latn? 'yue@latn': $lang;
return $branches[$n - 1]->{$key};
}
sub stem_branch_name ($) {
my($year) = @_;
$year -= 1;
$year %= 60;
my $use_yue_latn = $lang eq 'en';
my $key = $use_yue_latn? 'yue@latn': $lang;
return sprintf('%s%s%s', $stems[$year%10]->{$key}, (($enable_chinese || $use_yue_latn)? '': '-'), $branches[$year%12]->{$key});
}
sub get_representation ($;$$) {
my($s, $specific_representation, $use_article) = @_;
my $prefix = $use_article && defined $s->{'article'}->{$lang}? sprintf('%s ', $s->{'article'}->{$lang}): '';
my $base = (defined $specific_representation? $specific_representation: $representation) =~ /^icon/? $s->{'icon'}: $s->{'name'}->{$lang};
return $prefix . $base;
}
sub start_of_day ($) {
my($t) = @_;
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime $t;
return mktime(0, 0, 0, $mday, $mon, $year);
}
sub yesterday ($) {
my($t) = @_;
return start_of_day(start_of_day($t) - 12*3600);
}
sub tomorrow ($) {
my($t) = @_;
return start_of_day(start_of_day($t) + 36*3600);
}
sub estimate_sunrise ($) {
my($t) = @_;
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime $t;
my $tmp;
if ($use_datetime_event_sunrise) {
my $dt = DateTime->new(year => $year + 1900, month => $mon + 1, day => $mday);
my $sunrise = DateTime::Event::Sunrise->new(latitude => $lat, longitude => $lon, precise => 1);
$tmp = $sunrise->sunrise_sunset_span($dt)->start;
} elsif ($use_datetime_astro_sunrise) {
my $dt = DateTime->new(year => $year + 1900, month => $mon + 1, day => $mday);
my $sunrise = DateTime::Astro::Sunrise->new($lat, $lon, undef, 1);
$tmp = ($sunrise->sunrise($dt))[0];
} else {
no integer;
my $tz = ($2 + $3/60) * ($1 eq '-'? -1: 1) if POSIX::strftime('%z', localtime $t) =~ /^([-\+])(\d\d)(\d\d)$/;
my($sunrise, $sunset) = Astro::Sunrise::sunrise(year => $year + 1900, month => $mon + 1, day => $mday,
lon => $lon, lat => $lat, $tz, $isdst);
$tmp = $sunrise;
}
return $tmp->strftime('%s');
}
sub estimate_sunset ($) {
my($t) = @_;
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime $t;
my $dt = DateTime->new(year => $year + 1900, month => $mon + 1, day => $mday);
my $tmp;
if ($use_datetime_event_sunrise) {
my $sunrise = DateTime::Event::Sunrise->new(latitude => $lat, longitude => $lon, precise => 1);
$tmp = $sunrise->sunrise_sunset_span($dt)->end;
} elsif ($use_datetime_astro_sunrise) {
my $sunrise = DateTime::Astro::Sunrise->new($lat, $lon, undef, 1);
$tmp = ($sunrise->sunrise($dt))[1];
} else {
# this should be the same as the else case in estimate_sunrise except the last line
no integer;
my $tz = ($2 + $3/60) * ($1 eq '-'? -1: 1) if POSIX::strftime('%z', localtime $t) =~ /^([-\+])(\d\d)(\d\d)$/;
my($sunrise, $sunset) = Astro::Sunrise::sunrise(year => $year + 1900, month => $mon + 1, day => $mday,
lon => $lon, lat => $lat, $tz, $isdst);
$tmp = $sunset;
}
return $tmp->strftime('%s');
}
sub trim ($) {
my($s) = @_;
$s =~ s/^\s+//;
$s =~ s/\s+$//;
return $s;
}
sub ordinal ($) {
my($n) = @_;
my $det1 = $n%10;
my $det2 = int($n/10)%10;
return sprintf '%d%s', $n, ($det2 == 1? 'th': $det1 == 1? 'st': $det1 == 2? 'nd': $det1 == 3? 'rd': 'th');
}
sub guess_city () {
my $input = '/etc/localtime';
my $det = readlink $input;
die "$input: $!\n" unless defined $det;
return $1 if $det =~ /([^\/]+)$/s;
}
sub guess_coordinates () {
my $it;
my $city = guess_city;
print STDERR "guessed city=($city)\n" if $debug;
my @cmd = qw(hebcal cities);
print STDERR 'DEBUG: running: ', join(' ', @cmd), "\n" if $debug;
my $pid = open(INPUT, '-|');
die "$0: guess_coordinates: $cmd[0]: fork: $!\n" unless defined $pid;
if ($pid) {
my $re = quotemeta $city;
for (;;) {
my $s = scalar <INPUT>;
last unless defined $s;
chomp;
if ($s =~ /^$re \((\d+)d(\d+)' ([NS]) lat, (\d+)d(\d+)' [EW] long/) {
no integer;
$it = {
'lat' => ($1 + $2/60)*($3 eq 'N'? 1: -1),
'lon' => ($4 + $5/60)*($6 eq 'E'? 1: -1),
};
}
last if defined $it;
}
close INPUT;
} else {
exec {$cmd[0]} @cmd;
die "$0: guess_coordinates: $cmd[0]: exec: $!\n";
}
return $it;
}
use vars qw( %chinese_digits );
%chinese_digits = (
'一' => 1,
'二' => 2,
'三' => 3,
'四' => 4,
'五' => 5,
'六' => 6,
'七' => 7,
'八' => 8,
'九' => 9,
'十' => 10,
'廿' => 20,
'卅' => 30,
);
sub parse_chinese_number ($) {
my($s) = @_;
my($tens, $units) = ($chinese_digits{$1}, $chinese_digits{$2}) if $s =~ /^(\S?)(\S)$/;
return ($units == 10 && defined $tens)? $tens*10: $tens + $units;
}
sub read_ini ($) {
my($input) = @_;
my $it;
local(*INPUT, $.);
if (open(INPUT, '<:utf8', $input)) {
for (my $section;;) {
my $s = scalar <INPUT>;
last unless defined $s;
chomp $s;
if ($s =~ /^\s*(?:[#\%;]|$)/) {
;
} elsif ($s =~ /^\s*\[\s*([^\[\]]+?)\s*\]\s*$/) {
$section = $1;
} elsif ($s =~ /^\s*([^=]+?)\s*=\s*(.*)/) {
if (defined $section) {
$it->{$section}->{$1} = $2;
} else {
$it->{$1} = $2;
}
} else {
warn "$input:$.: Warning: Unknown input \"$s\"\n";
}
}
close INPUT;
}
return $it;
}
sub read_xfce_cache () {
my $input = "$ENV{HOME}/.config/xfce4/panel/weather-17.rc";
my $dir = "$ENV{HOME}/.cache/xfce4/weather";
my $it;
my $rc = read_ini $input;
if (defined $rc) {
($lat, $lon) = ($rc->{'lat'}, $rc->{'lon'});
$input = sprintf('%s/weatherdata_%s_%s_%s', $dir, $lat, $lon, $rc->{'msl'});
my $data = read_ini $input;
for (my $i = 0;; $i += 1) {
my $key = "astrodata$i";
my $det = $data->{$key};
last unless defined $det;
my($yyyy, $mm, $dd) = ($1, $2, $3) if $det->{'day'} =~ /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
if (defined $dd) {
my $midnight = mktime(0, 0, 0, $dd, $mm - 1, $yyyy - 1900);
if ($midnight) {
for my $key (keys %$det) {
my $val = $det->{$key};
if ($val =~ /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/) {
$val = mktime($6, $5, $4, $3, $2 - 1, $1 - 1900); # mktime assumes local time so the result is wrong
die "Internal error: mktime failed for \"$val\"\n" unless defined $val;
my $z = POSIX::strftime('%z', localtime $now); # try to figure out timezone offset
if ($z =~ /^-(\d\d)(\d\d)$/) {
$val -= $1 * 3600 + $2 * 60;
} elsif ($z =~ /^\+(\d\d)(\d\d)$/) {
$val += $1 * 3600 + $2 * 60;
} else {
die "Internal error: Unknown timezone offset \"$z\"\n";
}
} elsif ($val eq 'true') {
$val = 1;
} elsif ($val eq 'false') {
$val = 0;
}
$it->{$midnight}->{$key} = $val;
}
}
}
}
}
return $it;
}
sub read_page ($;$) {
my($url, $cache) = @_;
my $it;
my $cache_valid = defined $cache && -f $cache;
my $input = $cache_valid? $cache: '-|';
my $output = $cache_valid? '-': $cache;
my @cmd = ('/usr/bin/wget', '-q', '-O', $output, $url);
my $pid = open(INPUT, $input);
die "$0: read_page: fork: $!\n" if !$cache_valid && !defined $pid;
@cmd = (@cmd, '-U', $fake) if defined $fake;
if ($cache_valid || (defined $pid && $pid)) {
binmode(INPUT, ':encoding(BIG5)') if $enable_chinese;
for (;;) {
my $s = scalar <INPUT>;
last unless defined $s;
$it .= $s;
}
close INPUT;
} elsif (defined $pid) {
exec {$cmd[0]} @cmd;
die "$0: read_page: exec: $!\n";
}
return $it;
}
sub read_cached_page ($;$) {
my($url, $cache) = @_;
return read_page $url, $cache;
}
sub read_hko_conversion_table () {
my $t = $now;
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime $t;
my $dir = "$ENV{HOME}/Documents/calendar";
my $basename = sprintf('T%04d%s.txt', $year + 1900, ($enable_chinese? 'c': 'e'));
my $input = "$dir/$basename";
mkdir $dir unless -d $dir;
return [read_cached_page("http://www.hko.gov.hk/gts/time/calendar/text/$basename", $input), $t];
}
# Quarters are weird. See https://zh.wikipedia.org/wiki/%E5%88%BB
# and http://yywz.snnu.edu.cn/show.aspx?id=697&cid=26
# Apparently the old Chinese system also used proportional hours... so we'll need to refactor things here at some point
# http://www.twword.com/wiki/%E5%B9%B2%E6%94%AF%E7%B4%80%E6%B3%95
sub determine_chinese_date () {
my($data, $t) = @{( read_hko_conversion_table )};
my $it;
my($header, $headings, @data) = split(/\r?\n/, $data);
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime $t;
my $midnight = start_of_day $t;
my $deciday;
($headings, @data) = @data if !$headings; # Chinese data file
# NOTE: according to one source (forgot which), although Zi spans [2300, 0100), the new day stil starts at 0000. Very odd :-/
# therefore the old adjustment for [2300, 0000) has been deleted
if (defined $coords) {
my $t = $now;
my $today = start_of_day $t;
my $yesterday = yesterday $t;
my $tomorrow = tomorrow $t;
my($daybreak, $slice_start, $slice_end, $starting_hour);
# Proportional hour is used in a very early system (Spring and Autumn Period / Warring States),
# but I don't even have an idea when the day starts (probably day before night) so we'll arbitrarily use sunrise as cutoff
if ($t < estimate_sunrise($today)) {
$daybreak = estimate_sunrise($yesterday);
$slice_start = estimate_sunset($yesterday);
$slice_end = estimate_sunrise($today);
$starting_hour = 6;
} elsif ($t < estimate_sunset($today)) {
$daybreak = estimate_sunrise($today);
$slice_start = $daybreak;
$slice_end = estimate_sunset($today);
$starting_hour = 1;
} else {
$daybreak = estimate_sunrise($today);
$slice_start = estimate_sunset($today);
$slice_end = estimate_sunrise($tomorrow);
$starting_hour = 6;
}
if ($slice_start && $slice_end) {
no integer;
my $slice = ($slice_end - $slice_start)/5;
$deciday = $starting_hour + ($t - $slice_start)/$slice;
}
}
if (@data) {
my($chk, $stem, $branch, $animal) = ($1, $2, $3, $4) if ($enable_chinese? $header =~ /(\d+)\((.)(.)\s*-\s*肖(.)\)/: $header =~ / of (\d+)\s*\((\w+)-(\w+)\s.*?year of the (\w+)\)/i);
#2016年1月1日 廿二 星期五
#2016年1月2日 廿三 星期六
#2016年1月3日 廿四 星期日
#2016年1月4日 廿五 星期一
#2016年1月5日 廿六 星期二
if (!defined $animal) {
warn "Internal error: Can't find animal in conversion table\n";
} elsif ($chk != $year + 1900) {
die "Internal error: Unexpected year $chk in conversion table\n";
} else {
# Figure out the primary year number of the conversion table
my $reference_year_number;
for (my $det = 0; $det < 60; $det += 1) {
my($i, $j) = ($det%10, $det%12);
$reference_year_number = $det + 1 if lc $stems[$i]->{$lang} eq lc $stem && lc $branches[$j]->{$lang} eq lc $branch;
last if defined $reference_year_number;
}
# Find the column alignments
my $c_greg = index($headings, $enable_chinese? '公曆日期': 'Gregorian date');
my $c_lunar = index($headings, $enable_chinese? '農曆日期': 'Lunar date');
my $c_wday = index($headings, $enable_chinese? '星期': 'Day-of-week');
my $c_term = index($headings, $enable_chinese? '節氣': 'Solar terms');
die "Internal error: Cannot find Gregorian date heading\n" unless defined $c_greg;
die "Internal error: Cannot find Lunar date heading\n" unless defined $c_lunar;
die "Internal error: Cannot find Day-of-week heading\n" unless defined $c_wday;
die "Internal error: Cannot find Solar terms heading\n" unless defined $c_term;
my $w_greg = $c_lunar - $c_greg;
my $w_lunar = $c_wday - $c_lunar;
my $w_wday = $c_term - $c_wday;
# Find today's date in the conversion table
my $target = sprintf(($enable_chinese? '%d年%d月%d日': '%d/%d/%d'), $year + 1900, $mon + 1, $mday);
my($current_year, $current_month, $current_day);
my($year, $month, $day, $solar_term);
for my $data (@data) {
my $greg_i = trim substr($data, $c_greg, $w_greg);
my $lunar_i = trim substr($data, $c_lunar, $w_lunar);
my $wday_i = trim substr($data, $c_wday, $w_wday);
my $solar_i = trim substr($data, $c_term);
print STDERR "DEBUG: greg_i=($greg_i), lunar_i=($lunar_i), wday_i=($wday_i), solar_i=($solar_i)\n" if $debug;
last if defined $year && defined $month && defined $day;
if ($lunar_i =~ /^\d+$/) {
$current_day = $lunar_i + 0;
} elsif ($lunar_i =~ /^(\d+)(?:st|nd|rd|th) Lunar Month/) {
$current_day = 1;
$current_month = $1 + 0;
$current_year = $reference_year_number if $current_month == 1;
} elsif ($lunar_i =~ /^初(\S+)/ || $lunar_i =~ /^((?!初)\S+)(?<!月)$/) {
$current_day = parse_chinese_number $1;
print STDERR "DEBUG: input day ($1), parsed $current_day\n" if $debug;
} elsif ($lunar_i =~ /^(\S+)月/) {
$current_month = ($1 eq '正')? 1: parse_chinese_number $1;
$current_year = $reference_year_number if $current_month == 1;
}
($year, $month, $day, $solar_term) = ($current_year, $current_month, $current_day, $solar_i) if $greg_i eq $target;
$month = $current_month - 1 if defined $day && !defined $month && defined $current_month;
$year = $current_year - 1 if defined $day && !defined $year && defined $current_year;
}
undef $solar_term unless $solar_term;
my $relative_chinese_hour = eval { no integer; ($t - ($midnight - 3600))/7200 };
my $chinese_hour = $relative_chinese_hour + 1;
my $quarter;
my $centiday = eval { no integer; ($t - $midnight)/864 };
if ($enable_qing_quarters) {
$quarter = $min/15 + 1;
$quarter += 4 if $hour%2 == 0;
} else {
# NOTE: traditionally these aren't quarters, but number of centiday marks past the beginning of the hour
no integer;
my $reporting_origin = (($chinese_hour - 1.5) * 7200)/864;
$reporting_origin -= 100 if $reporting_origin > $centiday;
$quarter = $centiday - int($reporting_origin);
$quarter -=100 if $quarter >= 100;
}
$it = [$year, $month, $day, $solar_term, $chinese_hour, $quarter, $centiday, $deciday, $wday, eval { no integer; $relative_chinese_hour < 0.5 }];
}
}
return $it;
}
sub format_chinese_date ($) {
my($data) = @_;
my $it;
my $tooltip;
my($year, $month, $day, $solar_term, $chinese_hour, $quarter, $centiday, $deciday, $wday, $note_needed) = @$data;
if (defined $year) {
my $minute = eval { no integer; ($centiday*60)%60 };
my $decaminute = $minute/10;
$minute %= 10 if $enable_decaminutes;
if ($enable_chinese && !$sysline_mode) {
$it .= sprintf '%s(%s)年%s月%s日', stem_branch_name($year), get_representation($branches[($year - 1)%12]), $month, $day;
if ($enable_decaminutes) {
$it .= sprintf '%d刻', $centiday;
$it .= sprintf '%d小刻', $decaminute if $decaminute;
$it .= sprintf '%d分', $minute if $minute && $enable_minutes;
} elsif ($enable_minutes) {
$it .= sprintf '%d刻', $centiday;
$it .= sprintf '%d分', $minute if $minute;
} else {
$it .= sprintf '%.*f刻', $decimals, $centiday;
}
$it .= sprintf ' (%s)', $solar_term if defined $solar_term;
$it .= sprintf '(%s時', $branches[$chinese_hour - 1]->{$lang};
$it .= $quarter < 5? '初': '正';
if ($enable_qing_quarters) {
$it .= ('初', '一', '二', '三')[($quarter - 1)%4];
$it .= '刻';
}
$it .= ')';
} else {
$it .= '<i>' if $genmon_mode && $note_needed;
$it .= sprintf '%s/%s/%s', $year, $month, $day;
$it .= '</i>' if $genmon_mode && $note_needed;
$tooltip .= sprintf('%s, ', ($wday? sprintf('%d-past-the-week', $wday): 'Day of the week'));
$tooltip .= sprintf('%s of month %s, year %d (%s)%s in the current sexagenary cycle',
ordinal($day), $month, $year, stem_branch_name($year), ($note_needed? '†': '')) if $genmon_mode;
my($prime, $dprime) = $genmon_mode? ('′', '″'): ("'", '"');
if ($enable_decaminutes) {
$it .= sprintf '+%d˟', $centiday; # U+02df
$it .= sprintf "%d%s", $decaminute, $prime;
$it .= sprintf '%d%s', $minute, $dprime if $enable_minutes;
} elsif ($enable_minutes) {
$it .= sprintf '+%d˟', $centiday; # U+02df
$it .= sprintf "%d%s", $minute, $prime;
} else {
$it .= sprintf '+%.*f', $decimals, $centiday;
}
if ($genmon_mode) {
$tooltip .= sprintf ' (%s)', $solar_term if defined $solar_term;
$tooltip .= sprintf ', %.*f centiday%s', $decimals, $centiday, (eval { no integer; $centiday == 1 }? '': 's');
$tooltip .= ' past midnight (';
}
if (!$sysline_mode && !$genmon_mode) {
$it .= sprintf(' (%s, %s)', stem_branch_name($year), get_representation($branches[($year - 1)%12]));
}
$it .= sprintf ' (%s)', $solar_term if defined $solar_term;
if ($enable_qing_quarters) {
$it .= sprintf ' %d%s%d', $chinese_hour, ($quarter < 5? 'a': 'b'), ($quarter - 1) % 4;
}
if (!$sysline_mode) {
$it .= sprintf ' (%s', branch_name($chinese_hour);
$it .= sprintf '+%d', $quarter if $quarter;
$it .= ')';
$tooltip .= sprintf '%d centiday mark%s past ', $quarter, ($quarter == 1? '': 's') if $quarter;
$tooltip .= sprintf '%s hour (%s)', ordinal($chinese_hour), branch_name($chinese_hour);
}
}
if (defined $deciday) {
my $div = eval { no integer; fmod($deciday - 1, 5) + 1 };
if ($genmon_mode) {
$it .= sprintf(' %s%.*f', ($deciday < 6? '☼': '☽'), $decimals, $div);
$tooltip .= ', ';
my $relative_deciday = eval { no integer; fmod($deciday - 1, 5) };
my $moitie = ($deciday < 6? 'day': 'night');
$tooltip .= sprintf('%.*f deciday%s* into the %s', $decimals, $relative_deciday, (eval { no integer; $relative_deciday == 1}? '': 's'), $moitie);
$tooltip .= sprintf(($deciday < 6? ', %stime %s deciday*': ''), $moitie, ordinal(($deciday - 1)%5 + 1));
} elsif ($sysline_mode) {
$it .= sprintf(' %s+%d', ($deciday < 6? 'd': 'e'), $div);
} elsif ($enable_chinese) {
$it .= sprintf(' %s:%s', ($deciday < 6? '晝': '夜'), (qw(朝 禺 中 晡 夕 甲 乙 丙 丁 戊)[$deciday - 1]));
} else {
$it .= sprintf(' %s+%d', ($deciday < 6? 'morning': 'evening'), $div);
}
}
my($watch, $subwatch);
if ($enable_nonproportional_watches) {
if ($chinese_hour >= 11 || $chinese_hour <= 3) {
$watch = (($chinese_hour - 10) + 12)%12;
$subwatch = eval { no integer; int(($quarter - 1)*5/8) };
}
} elsif (defined $deciday && $deciday >= 6) {
$watch = $deciday - 5;
$subwatch = eval { no integer; int(5*($deciday - int($deciday)) + 1); };
}
if (defined $watch) {
$it .= '(' unless $genmon_mode;
if ($enable_chinese && !$sysline_mode) {
$it .= sprintf('%d更', $watch);
$it .= sprintf('%d點', $subwatch) if $subwatch;
} elsif ($sysline_mode || $genmon_mode) {
$it .= ' ' if $genmon_mode;
$it .= $watch if $sysline_mode || $genmon_mode;
$it .= 'w' if $sysline_mode || $subwatch;
$it .= $subwatch if $subwatch;
$tooltip .= sprintf ', %s fifth of %s watch', ordinal($subwatch), ordinal($watch) if $genmon_mode;
$tooltip .= '*' if $genmon_mode && !$enable_nonproportional_watches;
} else {
$it .= sprintf('%d past ', $subwatch) if $subwatch;
$it .= sprintf('%s watch', $watch);
}
$it .= ')' unless $genmon_mode;
}
$tooltip .= ')' if $genmon_mode;
}
return wantarray? ($it, $tooltip): $it;
}
# A useless system described by https://en.wikipedia.org/wiki/Planetary_hours
# and http://www.renaissanceastrology.com/3rdplanetaryorder.html
# Alas, according to http://www.chabad.org/calendar/zmanim_cdo/aid/143790/jewish/Halachic-Times-Zmanim.htm
# and http://www.agapebiblestudy.com/charts/jewishtimedivision.htm
# this weird system is actually identical to the Hebrew system :-/
sub determine_planetary_hour () {
my $it;
if (defined $coords) {
my $t = $now;
my $today = start_of_day $t;
my $yesterday = yesterday $t;
my $tomorrow = tomorrow $t;
my($daybreak, $slice_start, $slice_end, $starting_hour);
if ($t < estimate_sunrise($today)) {
$daybreak = estimate_sunrise($yesterday);
$slice_start = estimate_sunset($yesterday);
$slice_end = estimate_sunrise($today);
$starting_hour = 13;
} elsif ($t < estimate_sunset($today)) {
$daybreak = estimate_sunrise($today);
$slice_start = $daybreak;
$slice_end = estimate_sunset($today);
$starting_hour = 1;
} else {
$daybreak = estimate_sunrise($today);
$slice_start = estimate_sunset($today);
$slice_end = estimate_sunrise($tomorrow);
$starting_hour = 13;
}
if ($slice_start && $slice_end) {
no integer;
my $slice = ($slice_end - $slice_start)/12;
my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime $daybreak;
$it = [$starting_hour + ($t - $slice_start)/$slice, $wday, ($daybreak < $today)];
}
}
return $it;
}
# A useless system described by https://en.wikipedia.org/wiki/Planetary_hours
# and http://www.renaissanceastrology.com/3rdplanetaryorder.html
sub format_planetary_hour ($) {
my($data) = @_;
my $it;
my $tooltip;
if (defined $data) {
my($planetary_hour, $wday, $note_needed) = @$data;
no integer;
my $m = int(60*($planetary_hour - 1))%60 + 1;
my $s = int(3600*($planetary_hour - 1))%60 + 1;
my $fmt = $enable_seconds? '+%02d:%02d:%02d': '+%02d:%02d%0.0s';
unless ($planetary_omit_details) {
$it .= '<i>' if $genmon_mode && $note_needed;
$it .= $wday + 1;
$it .= '</i>' if $genmon_mode && $note_needed;
$it .= sprintf($fmt, $planetary_hour, $m, $s);
}
my $style = $sysline_mode? 'icon': $representation;
local $representation = $style;
$fmt = ($sysline_mode || $genmon_mode)? '%s': '(%s)';
$fmt = " $fmt" unless $planetary_omit_details;
$it .= sprintf($fmt, get_representation($planets[($wday + 5*(int($planetary_hour) - 1))%7]));
$tooltip .= sprintf 'day of %s%s, ',
get_representation($planets[$wday%7], 'name', 1), # same as formula below with hour = 1 (so entire term reduces to 0)
($note_needed? '§': '');
$tooltip .= sprintf '%s hour* (of %s), %.*f hour%s* past sunrise',
ordinal($planetary_hour),
get_representation($planets[($wday + 5*(int($planetary_hour) - 1))%7], 'name', 1),
$decimals, eval { no integer; $planetary_hour - 1 }, (eval { no integer; $planetary_hour - 1 == 1 }? '': 's');
}
return wantarray? ($it, $tooltip): $it;
}
# The Hebrew system uses a different starting time (sunset)
# Cf https://www.britannica.com/science/calendar/Ancient-and-religious-calendar-systems
# https://zh.wikipedia.org/wiki/希伯來曆
# but apparently it's supposed to use the weird hour divisions too
# Cf http://kehillatisrael.net/hcal/zmanim.html [dead link as of 20210608]
# Although the day number is supposed to change at 6pm (?!)
# Cf http://www.jewfaq.org/calendr2.htm
sub determine_hebrew_date () {
my $it;
if (defined $coords) {
my $t = $now;
my $today = start_of_day $t;
my $yesterday = yesterday $t;
my $tomorrow = tomorrow $t;
my($daybreak, $slice_start, $slice_end, $starting_hour);
if ($t < estimate_sunrise($today)) {
$daybreak = estimate_sunset($yesterday);
$slice_start = $daybreak;
$slice_end = estimate_sunrise($today);
$starting_hour = 1;
} elsif ($t < estimate_sunset($today)) {
$daybreak = estimate_sunset($yesterday);
$slice_start = estimate_sunrise($today);
$slice_end = estimate_sunset($today);
$starting_hour = 13;
} else {
$daybreak = estimate_sunset($today);
$slice_start = estimate_sunset($today);
$slice_end = estimate_sunrise($tomorrow);
$starting_hour = 1;
}
if ($slice_start && $slice_end) {
no integer;
my $slice = ($slice_end - $slice_start)/12;
print STDERR "DEBUG: daybreak=$daybreak, slice_start=$slice_start, slice_end=$slice_end\n" if $debug;
# hebcal expects secular-style midnight cutoffs, but traditional reckoning cuts off at sundown
# so we need to calculate wday using $daybreak, but hand hebcal a secular date ($daybreak + 43200, say)
my $wday = (localtime($daybreak))[6]; # correct in traditional reckoning
my($sec, $min, $hour, $mday, $mon, $unix_year, $unix_wday) = localtime($daybreak + 43200); # correct in secular reckoning
my $hebcal = -f '/usr/bin/hebcal'? '/usr/bin/hebcal': '/usr/local/bin/hebcal';
my @cmd = ($hebcal, '-T',
'-l', eval { no integer; sprintf('%d,%d', $lat, int(60*$lat)%60) },
'-L', eval { no integer; sprintf('%d,%d', $lon, int(60*$lon)%60) }, $mon + 1, $mday, $unix_year + 1900);