-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathffalarms.vala
2507 lines (2245 loc) · 62.5 KB
/
ffalarms.vala
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
/* ffalarms -- finger friendly alarms
* Copyright (C) 2009-2010 Łukasz Pankowski <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Elm;
using Ecore;
using Posix;
using ICal;
[DBus (name = "org.freedesktop.DBus")]
interface FreeDesktopBus : GLib.Object
{
public abstract string get_name_owner(string name) throws IOError;
}
T get_proxy_sync_for_name_owner<T>(BusType bus_type, string name, string path)
throws IOError, DBusError
{
FreeDesktopBus bus = Bus.get_proxy_sync(bus_type, "org.freedesktop.DBus", "/");
return Bus.get_proxy_sync(bus_type, bus.get_name_owner(name), path);
}
[DBus (name = "org.freesmartphone.Device.Display")]
interface Display : GLib.Object
{
public abstract int get_brightness() throws IOError;
public abstract void set_brightness(int value) throws IOError;
}
[DBus (name = "org.freesmartphone.Time.Alarm")]
interface FsoAlarm : GLib.Object
{
public abstract void
add_alarm(string dbus_name, int time) throws IOError;
public abstract void
set_alarm(string dbus_name, int time) throws IOError;
}
[DBus (name = "org.freesmartphone.Usage")]
interface Usage : GLib.Object
{
public abstract void request_resource(string name) throws IOError;
public abstract void release_resource(string name) throws IOError;
}
namespace Ffalarms {
public const string VERSION = "0.4";
public const string EDJE_FILE = "/usr/share/ffalarms/ffalarms.edj";
public const string ALARM_SH = "/usr/share/ffalarms/alarm.sh";
public const string ATD_CONTACT_ERR =
"Could not contact atd daemon, the alarm may not work";
public const string AMIXER = "amixer";
public const string DBUS_NAME = "org.openmoko.projects.ffalarms.alarm";
public errordomain MyError {
CONFIG, ERR;
}
void die(string msg)
{
printerr("%s: %s\n", Environment.get_prgname(), msg);
Posix.exit(1);
}
string expand_home(string s)
{
if (s.has_prefix("~/"))
return Path.build_filename(Environment.get_home_dir(), s.substring(2));
else
return s;
}
time_t next_hm(int hour, int minute)
{
var now = time_t();
var t = GLib.Time.local(now); t.hour=hour; t.minute=minute; t.second=0;
var timestamp = t.mktime();
if (timestamp <= now) {
t.day += 1;
timestamp = t.mktime(); // also normalizes Time
}
if (t.hour != hour) {
t.hour = hour;
timestamp = t.mktime();
}
return timestamp;
}
void set_alarm_inner(time_t timestamp, Config cfg, Component e)
throws MyError, FileError
{
string alarm_cmd = cfg.alarm_cmd();
int repeat = cfg.repeat;
string alarm_sh, player = alarm_cmd.chug().split(" ", 2)[0];
Posix.Stat st;
foreach (unowned string cmd in new string[] {AMIXER, player})
if (Environment.find_program_in_path(cmd) == null)
throw new MyError.CONFIG("command %s not found".printf(cmd));
var trig = Path.build_filename(cfg.at_spool, "trigger");
if (stat(trig, out st) != 0 || !S_ISFIFO(st.st_mode))
throw new MyError.CONFIG(
"Could not contact atd daemon, the alarm was not set");
var filename = Path.build_filename(
cfg.at_spool, "%ld.ffalarms.%s".printf(
timestamp, Uri.escape_string(e.get_uid(), "@", false)));
FileUtils.get_contents(cfg.alarm_script, out alarm_sh);
var header = """FFALARMS_UID=%s
FFALARMS_ATD_SCRIPT="$0"
export FFALARMS_UID FFALARMS_ATD_SCRIPT""".printf(Shell.quote(e.get_uid()));
int fd = open(filename, O_CREAT | O_EXCL);
if (fd == -1)
return; // XXX tmp silently ignored to schedule next alarms
close(fd);
if (lstat(filename, out st) != 0 || !S_ISREG(st.st_mode))
return; // XXX tmp silently ignored to schedule next alarms
close(fd);
FileUtils.set_contents(
filename, alarm_sh.printf(header, repeat, Shell.quote(alarm_cmd)));
FileUtils.chmod(filename, 0755);
fd = open(trig, O_WRONLY | O_NONBLOCK);
bool atd_error = (fd == -1 || fstat(fd, out st) != 0 ||
!S_ISFIFO(st.st_mode) || write(fd, "\n", 1) != 1);
if (fd != -1)
close(fd);
if (atd_error)
throw new MyError.CONFIG(ATD_CONTACT_ERR);
}
void schedule_alarms(Config cfg, Component? alarms=null) throws MyError
{
// We schedule one occurence for each alarm as we do not yet have
// a concept of unacknowledged past alarms
Component alarms_;
if (alarms == null)
alarms = alarms_ = list_alarms(cfg);
var scheduled_alarms = list_scheduled_alarms(cfg);
foreach (var c in alarms.begin_component()) {
var next = next_alarm_as_utc(c);
if (! next.is_null_time()) {
var t = next.as_timet();
foreach (var a in scheduled_alarms)
if (a.timestamp == t && a.uid == c.get_uid()) {
t = 0; // already scheduled
break;
}
if (t != 0)
try {
set_alarm_inner(t, cfg, c);
} catch (FileError e) {
throw new MyError.ERR(e.message);
}
}
}
}
unowned ICal.TimeZone local_tz()
{
string s = Environment.get_variable("TZ");
try {
if (s == null)
// XXX quick hack: the format is more complicated
FileUtils.get_contents("/etc/timezone", out s);
} catch (FileError e) {
s = "UTC";
}
return ICal.TimeZone.get_builtin_timezone(s.strip());
}
// XXX may return time_t
ICal.Time next_alarm_as_utc(Component c)
{
unowned ICal.TimeZone tz = local_tz();
unowned ICal.TimeZone utc = ICal.TimeZone.get_utc_timezone();
var t = time_t();
var utc_now = ICal.Time.from_timet_with_zone(t, false, utc);
ICal.Time tz_now = ICal.Time.from_timet_with_zone(t, false, tz);
ICal.Time next = ICal.Time.null_time(); // silent Vala false positive error
unowned Property p = c.get_first_property(PropertyKind.RRULE);
if (p == null) {
next = c.get_dtstart();
} else {
var iter = new RecurIterator(p.get_rrule(), c.get_dtstart());
do {
next = iter.next();
} while (next.compare(tz_now) < 0);
}
if (!next.is_utc() && next.zone == null)
ICal.Time.set_timezone(ref next, tz);
ICal.TimeZone.convert_time(ref next, tz, utc);
next.set_timezone(ref next, utc);
return (next.compare (utc_now) >= 0) ? next : ICal.Time.null_time();
}
void write_alarms(Component alarms, Config cfg) throws MyError
{
var fn = cfg.get_alarms_filename();
var tmp_fn = "%s.new.%ld".printf(fn, getpid());
var f = FileStream.open(tmp_fn, "w");
foreach (var c in alarms.begin_component())
f.puts(c.as_ical_string());
f = null;
FileUtils.rename(tmp_fn, fn);
}
void set_alarm(time_t timestamp, Config cfg, string? rrule, string? summary)
throws MyError, FileError
{
Component x = list_alarms(cfg);
Component c = new Component.vevent();
c.set_dtstart(ICal.Time.from_timet_with_zone(timestamp, false, local_tz()));
c.set_uid("%08x.%08x@%s".printf((uint) time_t(), Random.next_int(),
Environment.get_host_name()));
if (rrule != null)
c.add_property(new Property.rrule(Recurrence.from_string(rrule)));
if (summary != null && !Regex.match_simple("^\\s*$", summary))
c.set_summary(summary);
x.add_component((owned) c);
write_alarms(x, cfg);
schedule_alarms(cfg);
}
void modify_alarm(time_t timestamp, Config cfg,
string? rrule, string? summary, string uid)
throws MyError, FileError
{
Component x = list_alarms(cfg);
unowned Component c = null;
foreach (var c1 in x.begin_component())
if (c1.get_uid() == uid) {
c = c1;
break;
}
if (c == null)
throw new MyError.ERR("Could not find alarm with the given uid");
c.set_dtstart(ICal.Time.from_timet_with_zone(timestamp, false, local_tz()));
unowned Property p_rrule = c.get_first_property(PropertyKind.RRULE);
if (rrule != null) {
Recurrence r = Recurrence.from_string(rrule);
if (p_rrule != null)
p_rrule.set_rrule(r);
else
c.add_property(new Property.rrule(r));
} else if (p_rrule != null) {
c.remove_property(p_rrule);
}
if (summary != null && !Regex.match_simple("^\\s*$", summary)) {
c.set_summary(summary);
} else {
unowned Property p = c.get_first_property(PropertyKind.SUMMARY);
if (p != null)
c.remove_property(p);
}
delete_scheduled_alarm(c.get_uid(), cfg);
write_alarms(x, cfg);
schedule_alarms(cfg);
}
struct AlarmInfo
{
public time_t timestamp;
public string filename;
public string localtime;
public string uid;
}
Component list_alarms(Config cfg) throws MyError
{
FileStream f = FileStream.open(cfg.get_alarms_filename(), "r");
if (f != null) {
var p = new Parser();
p.set_gen_data(f);
Component c = p.parse((LineGenFunc) FileStream.gets);
if (c == null) {
return new Component(ComponentKind.XROOT);
} else if (c.isa() == ComponentKind.XROOT) {
return c;
} else {
Component x = new Component(ComponentKind.XROOT);
x.add_component((owned) c);
return x;
}
} else {
return new Component(ComponentKind.XROOT);
}
}
[Compact]
class NextAlarm
{
public unowned Component comp;
public ICal.Time next;
static Regex rrule_re;
public string to_string(string summary_prefix=" ")
{
var sb = new StringBuilder(GLib.Time.local(next.as_timet())
.format("%a %b %d %X %Y"));
unowned Property p = comp.get_first_property(PropertyKind.RRULE);
if (p != null)
sb.append_printf(" (%s)", rrule_str(p));
unowned string s = comp.get_summary();
if (s != null && s.length > 0)
sb.append_printf("%s%s", summary_prefix, s);
return sb.str;
}
public string get_label(string part)
{
if (part == "elm.text") {
var sb = new StringBuilder(GLib.Time.local(next.as_timet())
.format("%a %b %d %X %Y"));
unowned Property p = comp.get_first_property(PropertyKind.RRULE);
if (p != null)
sb.append_printf(" (%s)", rrule_str(p));
return sb.str;
} else {
return comp.get_summary() ?? "";
}
}
static string rrule_str(Property p)
{
var s = p.as_ical_string().strip();
MatchInfo m;
if (rrule_re == null)
try {
rrule_re = new Regex("RRULE:FREQ=([A-Z]+)$");
} catch (RegexError e) {
assert_not_reached();
}
if (rrule_re.match(s, 0, out m))
return m.fetch(1).down();
else
return s;
}
}
/**
* NOTE: if alarms parameter is deleted, result is no longer valid
*/
NextAlarm[] list_future_alarms(Component alarms)
{
var arr = new NextAlarm[0];
foreach (var c in alarms.begin_component(ComponentKind.ANY)) {
var next = next_alarm_as_utc(c);
if (! next.is_null_time())
arr += new NextAlarm() { comp=c, next=next };
}
Posix.qsort_r(arr, arr.length, sizeof(NextAlarm),
(a, b) => (((NextAlarm **)a)[0])->next.compare(
(((NextAlarm **)b)[0])->next), null);
return arr;
}
SList<AlarmInfo?> list_scheduled_alarms(Config cfg)
throws MyError
{
Regex re, re_uid;
try {
re = new Regex("^[0-9]+[.]ffalarms[.]");
re_uid = new Regex("^FFALARMS_UID=([^ ]+)");
} catch (RegexError e) {
assert_not_reached();
}
var dir = opendir(cfg.at_spool);
if (dir == null)
throw new MyError.CONFIG("Could not list spool directory: %s",
cfg.at_spool);
var lst = new SList<AlarmInfo?>();
unowned DirEnt de;
MatchInfo m;
while ((de = readdir(dir)) != null) {
unowned string s = (string) de.d_name;
time_t t = int.parse(s);
string uid;
if (re.match(s)) {
var f = FileStream.open(Path.build_filename(cfg.at_spool, s), "r");
if (f != null) {
string line;
while ((line = f.read_line()) != null) {
if (line.has_prefix("#!") ||
line.has_prefix("##ffalarms##"))
continue;
if (! line.has_prefix("FFALARMS_"))
break;
if (re_uid.match(line, 0, out m))
try {
uid = Shell.unquote(m.fetch(1));
} catch (ShellError e) {
uid = m.fetch(1);
}
}
}
lst.append(AlarmInfo() { timestamp=t, filename=s, uid=uid,
localtime=GLib.Time.local(t).format("%a %b %d %X %Y")});
}
}
lst.sort((aa, bb) => {
time_t a = ((AlarmInfo *) aa)->timestamp;
time_t b = ((AlarmInfo *) bb)->timestamp;
return (a < b) ? -1 : (a == b) ? 0 : 1;
});
return lst;
}
// Return nth tok (indices start with 0) where tokens are delimitied
// by any number of spaces or null if not found
unowned string? nth_token(string buf, int nth)
{
bool prev_tok = false, tok;
int n = -1;
for (char *p = (char *) buf; *p != '\0'; p++) {
tok = *p != ' ';
if (tok != prev_tok) {
prev_tok = tok;
if (tok && ++n == nth)
return (string?) p;
}
}
return null;
}
bool kill_running_alarms(string at_spool)
{
Regex alarm_cmd;
string line;
bool result = false;
MatchInfo m;
Posix.Stat st;
FileStream? f = (FileStream) FILE.popen("ps -ef", "r");
if (f == null) {
error("could not exec ps");
return false;
}
try {
alarm_cmd = new Regex("^/bin/sh ([0-9]+[.]ffalarms[.][0-9]+)");
} catch (RegexError e) {
assert_not_reached();
}
while ((line = f.read_line()) != null) {
if (alarm_cmd.match(nth_token(line, 7), 0, out m)) {
int alarm_pid = int.parse(nth_token(line, 1));
if (stat(Path.build_filename(
at_spool, "x%s.%d".printf(
m.fetch(1), alarm_pid)), out st) == 0)
if (kill(alarm_pid, SIGTERM) == 0)
result = true;
}
}
return result;
}
void delete_scheduled_alarm(string uid, Config cfg) throws MyError
{
foreach (var a in list_scheduled_alarms(cfg))
if (a.uid == uid) {
var filename = Path.build_filename(cfg.at_spool, a.filename);
if (unlink(filename) != 0) {
Posix.Stat st;
if (Posix.errno == ENOENT)
throw new MyError.ERR("%s: %s\n".printf(
filename, Posix.strerror(Posix.errno)));
if (stat(Path.build_filename(
cfg.at_spool, "x%s".printf(a.filename)), out st) == 0 &&
! kill_running_alarms(cfg.at_spool))
throw new MyError.ERR("No alarm was running");
}
}
}
/**
* NOTE: you have to call schedule_alarms after a call (or calls) to
* delete_alarm
*/
void delete_alarm(string uid, Config cfg) throws MyError
{
Component alarms = list_alarms(cfg);
foreach (unowned Component c in alarms.begin_component())
if (c.get_uid() == uid) {
delete_scheduled_alarm(c.get_uid(), cfg);
// XXX libical.vapi: we should free the component memory
alarms.remove_component(c);
write_alarms(alarms, cfg);
break;
}
}
/**
* NOTE: you have to call schedule_alarms after a call (or calls) to
* acknowledge_alarm
*/
void acknowledge_alarm(string uid, time_t t, Config cfg) throws MyError
{
Component alarms = list_alarms(cfg);
foreach (unowned Component c in alarms.begin_component())
if (c.get_uid() == uid) {
unowned Property p = c.get_first_property(PropertyKind.RRULE);
if (p == null) {
delete_alarm(uid, cfg);
} else if (t != 0) {
// we hold newest acknowlendged instance of the
// recurring alarm in the RECURRENCE-ID
var time = ICal.Time.from_timet_with_zone(t, false, local_tz());
var prev = c.get_recurrenceid();
if (prev.is_null_time() || time.compare(prev) > 0) {
c.set_recurrenceid(time);
write_alarms(alarms, cfg);
}
}
return;
}
}
public void display_alarms_list(Config cfg) throws MyError
{
GLib.stdout.printf("# Alarms:\n");
var alarms = list_alarms(cfg);
foreach (unowned NextAlarm a in list_future_alarms(alarms))
GLib.stdout.printf("%s %s (dtstart:%s)\n",
a.comp.get_uid(), a.to_string("\n "),
a.comp.get_dtstart().as_ical_string());
GLib.stdout.printf("# Scheduled:\n");
foreach (unowned AlarmInfo? a in list_scheduled_alarms(cfg))
GLib.stdout.printf("%11ld %s%s\n", a.timestamp, a.localtime,
(a.uid != null) ? " (%s)".printf(a.uid) : "");
}
class CheckGroup
{
public unowned Box? bx;
public GLib.List<unowned Check?> checks;
public CheckGroup(Win parent, string[] names)
{
bx = Box.add(parent);
checks = new GLib.List<unowned Check?>();
foreach (var s in names) {
unowned Check? ck = Check.add(parent);
ck.style_set("toggle");
ck.text_set(s);
ck.size_hint_align_set(0.0, 0.0);
ck.show();
ck.state_set(true);
bx.pack_end(ck);
checks.append(ck);
}
}
}
class BaseWin
{
protected Win win;
protected unowned Frame? frame(string label, Elm.Object? content)
{
unowned Frame? fr = Frame.add(win);
unowned Frame? result = fr;
fr.text_set(label);
fr.text_set(label);
fr.content_set(content);
fr.size_hint_align_set(-1.0, 0.0);
fr.show();
return result;
}
protected unowned Frame? pad(string style)
{
unowned Frame? fr = Frame.add(win);
unowned Frame? result = fr;
fr.style_set(style);
fr.size_hint_align_set(-1.0, 0.0);
fr.show();
return result;
}
}
class Calendar
{
public unowned Table? tb;
public delegate void DateFunc(Date date);
public DateFunc date_clicked_cb;
Date first;
Date today;
int first_weekday;
const int DAY_BTNS_CNT = 37;
GLib.List<unowned Button?> day_btns = new GLib.List<unowned Button?>();
HashTable<unowned Evas.Object,int> day_btns_to_idx;
unowned Label? cur_month;
public const string[] days = {
"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" };
public Calendar(Win parent)
{
tb = Table.add(parent);
tb.size_hint_weight_set(1.0, 1.0);
tb.size_hint_align_set(-1, -1);
var tm = GLib.Time.local(time_t());
today = Date();
today.set_dmy((DateDay)tm.day, tm.month + 1,
(DateYear)(1900 + tm.year));
cur_month = Label.add(parent);
tb.pack(cur_month, 1, 0, 5, 1);
cur_month.show();
unowned Button? b = Button.add(parent);
b.text_set("<");
b.smart_callback_add("clicked", prev_month);
tb.pack(b, 0, 0, 1, 1);
b.show();
b = Button.add(parent);
b.text_set(">");
b.smart_callback_add("clicked", next_month);
tb.pack(b, 6, 0, 1, 1);
b.show();
for (int i = 0; i < 7; ++i)
{
unowned Label? lb = Label.add(parent);
lb.text_set(days[i]);
tb.pack(lb, i, 1, 1, 1);
lb.show();
}
day_btns_to_idx = new HashTable<unowned Evas.Object,int>(null, null);
for (int i = 0; i < DAY_BTNS_CNT; ++i)
{
b = Button.add(parent);
b.smart_callback_add("clicked", day_button_cb);
tb.pack(b, i % 7, i / 7 + 2, 1, 1);
day_btns_to_idx.insert(b, i);
day_btns.append(b);
}
set_month(today.get_month(), today.get_year());
tb.show();
}
public void prev_month()
{
first.subtract_months(1);
set_month(first.get_month(), first.get_year());
}
public void next_month()
{
first.add_months(1);
set_month(first.get_month(), first.get_year());
}
public void set_month(DateMonth month, DateYear year)
{
first.set_dmy(1, month, year);
int wday = first_weekday = first.get_weekday() % 7;
int dim = first.get_month().get_days_in_month(first.get_year());
char[] s = new char[100];
first.strftime(s, "<b>%B %Y<b>");
cur_month.text_set((string) s);
for (int i = 0; i < DAY_BTNS_CNT; i++)
{
int j = i - wday;
if (j >= 0 && j < dim) {
day_btns.nth_data(i).text_set((j + 1).to_string());
day_btns.nth_data(i).show();
} else {
day_btns.nth_data(i).hide();
}
}
if (today.get_month() == month && today.get_year() == year) {
int j = today.get_day() - 1;
day_btns.nth_data(j + wday).text_set("[%d]".printf(j + 1));
}
}
void day_button_cb(Evas.Object o, void* event_info)
{
Date date = first;
date.set_day((DateDay)(day_btns_to_idx.lookup(o) - first_weekday + 1));
if (date_clicked_cb != null)
date_clicked_cb(date);
}
}
class CalendarWin : BaseWin
{
public Calendar cal;
public CalendarWin(Win? parent, Calendar.DateFunc? date_clicked_cb=null)
{
win = new Win(parent, "calendar", WinType.BASIC);
win.smart_callback_add("delete,request", close);
win.title_set("Calendar");
unowned Bg? bg = Bg.add(win);
bg.size_hint_weight_set(1.0, 1.0);
win.resize_object_add(bg);
bg.show();
unowned Box? bx = Box.add(win);
bx.size_hint_weight_set(1.0, 1.0);
win.resize_object_add(bx);
bx.show();
cal = new Calendar(win);
cal.date_clicked_cb = date_clicked_cb;
cal.tb.size_hint_align_set(0.5, 0.5);
unowned Button? b = Button.add(win);
b.size_hint_align_set(-1, -1);
b.smart_callback_add("clicked", close);
b.text_set("Close");
cal.tb.pack(b, 2, 7, 5, 1);
b.show();
bx.pack_end(cal.tb);
}
public void show()
{
win.show();
}
public void close()
{
win = null;
}
}
class AddAlarm : BaseWin
{
unowned Bg? bg;
unowned Box? bx;
unowned Naviframe? pager;
Buttons btns;
unowned Layout? lt;
unowned Edje.Object edje;
int hour = -1;
int minute = 0;
bool showing_options = false;
public delegate void SetAlarm(time_t timestamp,
string? recur, string? summary);
SetAlarm set_alarm;
Recurrence recur;
bool recur_editable = true;
string summary;
public AddAlarm()
{
recur.clear(ref recur);
}
public void show(Win parent, string edje_file, SetAlarm set_alarm)
{
// NOTE do not use parent to avoid window decorations
win = new Win(null, "add", WinType.BASIC);
win.title_set("Add alarm");
win.smart_callback_add("delete,request", () => { this.win = null; });
this.set_alarm = set_alarm;
bg = Bg.add(win);
bg.size_hint_weight_set(1.0, 1.0);
win.resize_object_add(bg);
bg.show();
bx = Box.add(win);
bx.size_hint_weight_set(1.0, 1.0);
win.resize_object_add(bx);
bx.show();
pager = Naviframe.add(win);
pager.size_hint_weight_set(1.0, 1.0);
pager.size_hint_align_set(-1.0, -1.0);
bx.pack_end(pager);
pager.show();
lt = Layout.add(win);
lt.file_set(edje_file, "clock-group");
lt.size_hint_weight_set(1.0, 1.0);
lt.size_hint_align_set(-1.0, -1.0);
unowned Elm.NaviframeItem it;
it = pager.item_push("", null, null, lt, null);
it.title_visible_set(false);
lt.show();
btns = new Buttons(win);
btns.add("Add", this.add);
btns.add("Options", flip_page);
btns.add("Close", this.close);
bx.pack_end(btns.box);
edje = (Edje.Object) lt.edje_get();
edje.signal_callback_add("clicked", "hour-*", this.set_hour);
edje.signal_callback_add("clicked", "minute-*", this.set_minute);
win.resize(480, 640);
win.show();
}
public void set_data(Component c)
{
win.title_set("Edit alarm");
btns.buttons.nth_data(0).text_set("Save");
this.summary = c.get_summary();
var t = c.get_dtstart();
date.set_dmy((DateDay)t.day, t.month, (DateMonth)t.year);
this.hour = t.hour;
this.minute = t.minute;
edje.signal_emit("%d".printf(hour), "set-hour");
edje.signal_emit("%d".printf(minute), "set-minute");
unowned Property p = c.get_first_property(PropertyKind.RRULE);
if (p != null) {
recur = p.get_rrule();
recur_editable = (freq_cb(recur.freq) &&
recur.until.is_null_time() &&
recur.count == 0 &&
recur.interval == 1 &&
recur.by_second[0] == Recurrence.ARRAY_MAX &&
recur.by_minute[0] == Recurrence.ARRAY_MAX &&
recur.by_hour[0] == Recurrence.ARRAY_MAX &&
recur.by_month_day[0] == Recurrence.ARRAY_MAX &&
recur.by_year_day[0] == Recurrence.ARRAY_MAX &&
recur.by_week_no[0] == Recurrence.ARRAY_MAX &&
recur.by_month_day[0] == Recurrence.ARRAY_MAX &&
recur.by_set_pos[0] == Recurrence.ARRAY_MAX);
}
}
void flip_page()
{
if (options == null) {
build_options();
unowned Elm.NaviframeItem it;
it = pager.item_push("", null, null, options, null);
it.title_visible_set(false);
}
if (showing_options) {
cl.time_get(out hour, out minute, null);
edje.signal_emit("%d".printf(hour), "set-hour");
edje.signal_emit("%d".printf(minute), "set-minute");
} else {
cl.time_set((hour != -1) ? hour : 0, minute, 0);
}
pager.item_simple_promote((showing_options) ? (Elm.Object) lt : options);
showing_options = ! showing_options;
}
void set_hour(Edje.Object obj, string sig, string src)
{
int h = int.parse(src.split("-")[1]);
if (h >= 0 && h < 24)
this.hour = h;
}
void set_minute(Edje.Object obj, string sig, string src)
{
int m = int.parse(src.split("-")[1]);
if (m >= 0 && m < 60)
this.minute = m;
}
public void add()
{
if (showing_options)
cl.time_get(out hour, out minute, null);
if (options != null) {
if (recur_editable) {
int i = 0, j = 0;
foreach (unowned Check? ck in wd.checks) {
if (ck.state_get())
recur.by_day[j++] = recur_weekdays[i];
i++;
}
recur.by_day[(j < 7) ? j : 0] = Recurrence.ARRAY_MAX;
}
summary = Entry.markup_to_utf8(this.summary_e.entry_get());
if (summary != null)
summary = summary.strip();
}
if (this.hour != -1) {
time_t timestamp;
if (date.valid()) {
GLib.Time t;
date.to_time(out t);
t.hour = hour;
t.minute = minute;
t.second = 0;
timestamp = t.mktime();
} else {
timestamp = next_hm(this.hour, this.minute);
}
this.set_alarm(timestamp, recur.as_string(ref recur), summary);
close();
}
}
public void close()
{
win = null;
}
unowned Scroller? options;
unowned Clock? cl;
unowned Entry? summary_e;
unowned Hoversel? freq;
/* unowned Hoversel? repeat; */
CheckGroup wd;
Date date;
unowned Button? date_b;
CalendarWin cal;
const string[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"};
const RecurrenceWeekday[] recur_weekdays = {
RecurrenceWeekday.MONDAY,
RecurrenceWeekday.TUESDAY,
RecurrenceWeekday.WEDNESDAY,
RecurrenceWeekday.THURSDAY,
RecurrenceWeekday.FRIDAY,
RecurrenceWeekday.SATURDAY,
RecurrenceWeekday.SUNDAY
};
public void build_options()
{
unowned Box? bx = Box.add(win);
bx.size_hint_weight_set(1.0, 0.0);
bx.show();
summary_e = Entry.add(win);
summary_e.single_line_set(true);
if (summary != null)
this.summary_e.entry_set(Entry.utf8_to_markup(summary));
summary_e.size_hint_weight_set(1.0, 1.0);
summary_e.show();
unowned Scroller? sc = Scroller.add(win);
sc.policy_set(ScrollerPolicy.OFF, ScrollerPolicy.OFF);
sc.content_min_limit(false, true);
sc.size_hint_align_set(-1.0, -1.0);
sc.content_set(summary_e);
sc.show();
bx.pack_end(frame("Summary", sc));
unowned Box? bx1 = Box.add(win);
date_b = Button.add(win);
date_b.size_hint_align_set(-1.0, -1.0);
if (date.valid())
set_date_close_calendar(date);