aboutsummaryrefslogtreecommitdiffstats
path: root/calendar/gui/calendar-model.c
blob: 7168f2714b4938539db501ba0724445246befa1c (plain) (blame)
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
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */

/* Evolution calendar - Data model for ETable
 *
 * Copyright (C) 2000 Helix Code, Inc.
 *
 * Authors: Federico Mena-Quintero <federico@helixcode.com>
 *
 * 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 2 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */


#include <config.h>
#include <math.h>
#include <ctype.h>
#include <gnome.h>
#include <cal-util/timeutil.h>
#include "calendar-model.h"
#include "calendar-commands.h"

/* We need this for strptime. */
#define _XOPEN_SOURCE 500
#define __USE_XOPEN
#include <time.h>
#include <sys/time.h>
#undef _XOPEN_SOURCE
#undef __USE_XOPEN



/* Private part of the ECalendarModel structure */
struct _CalendarModelPrivate {
    /* Calendar client we are using */
    CalClient *client;

    /* Types of objects we are dealing with */
    CalObjType type;

    /* Array of pointers to calendar objects */
    GArray *objects;

    /* UID -> array index hash */
    GHashTable *uid_index_hash;

    /* Whether we display dates in 24-hour format. */
    gboolean use_24_hour_format;

    /* HACK: so that ETable can do its stupid append_row() thing */
    guint appending_row : 1;
};



static void calendar_model_class_init (CalendarModelClass *class);
static void calendar_model_init (CalendarModel *model);
static void calendar_model_destroy (GtkObject *object);

static int calendar_model_column_count (ETableModel *etm);
static int calendar_model_row_count (ETableModel *etm);
static void *calendar_model_value_at (ETableModel *etm, int col, int row);
static void calendar_model_set_value_at (ETableModel *etm, int col, int row, const void *value);
static gboolean calendar_model_is_cell_editable (ETableModel *etm, int col, int row);
static void calendar_model_append_row (ETableModel *etm, ETableModel *source, gint row);
static void *calendar_model_duplicate_value (ETableModel *etm, int col, const void *value);
static void calendar_model_free_value (ETableModel *etm, int col, void *value);
static void *calendar_model_initialize_value (ETableModel *etm, int col);
static gboolean calendar_model_value_is_empty (ETableModel *etm, int col, const void *value);
#if 0
static char * calendar_model_value_to_string (ETableModel *etm, int col, const void *value);
#endif
static void load_objects (CalendarModel *model);
static int remove_object (CalendarModel *model, const char *uid);
static void ensure_task_complete (CalComponent *comp,
                  time_t completed_date);
static void ensure_task_not_complete (CalComponent *comp);

static ETableModelClass *parent_class;



/**
 * calendar_model_get_type:
 * @void:
 *
 * Registers the #CalendarModel class if necessary, and returns the type ID
 * associated to it.
 *
 * Return value: The type ID of the #CalendarModel class.
 **/
GtkType
calendar_model_get_type (void)
{
    static GtkType calendar_model_type = 0;

    if (!calendar_model_type) {
        static GtkTypeInfo calendar_model_info = {
            "CalendarModel",
            sizeof (CalendarModel),
            sizeof (CalendarModelClass),
            (GtkClassInitFunc) calendar_model_class_init,
            (GtkObjectInitFunc) calendar_model_init,
            NULL, /* reserved_1 */
            NULL, /* reserved_2 */
            (GtkClassInitFunc) NULL
        };

        calendar_model_type = gtk_type_unique (E_TABLE_MODEL_TYPE, &calendar_model_info);
    }

    return calendar_model_type;
}

/* Class initialization function for the calendar table model */
static void
calendar_model_class_init (CalendarModelClass *class)
{
    GtkObjectClass *object_class;
    ETableModelClass *etm_class;

    object_class = (GtkObjectClass *) class;
    etm_class = (ETableModelClass *) class;

    parent_class = gtk_type_class (E_TABLE_MODEL_TYPE);

    object_class->destroy = calendar_model_destroy;

    etm_class->column_count = calendar_model_column_count;
    etm_class->row_count = calendar_model_row_count;
    etm_class->value_at = calendar_model_value_at;
    etm_class->set_value_at = calendar_model_set_value_at;
    etm_class->is_cell_editable = calendar_model_is_cell_editable;
    etm_class->append_row = calendar_model_append_row;
    etm_class->duplicate_value = calendar_model_duplicate_value;
    etm_class->free_value = calendar_model_free_value;
    etm_class->initialize_value = calendar_model_initialize_value;
    etm_class->value_is_empty = calendar_model_value_is_empty;
#if 0
    etm_class->value_to_string = calendar_model_value_to_string;
#endif
}

/* Object initialization function for the calendar table model */
static void
calendar_model_init (CalendarModel *model)
{
    CalendarModelPrivate *priv;

    priv = g_new0 (CalendarModelPrivate, 1);
    model->priv = priv;

    priv->objects = g_array_new (FALSE, TRUE, sizeof (CalComponent *));
    priv->uid_index_hash = g_hash_table_new (g_str_hash, g_str_equal);
    priv->use_24_hour_format = TRUE;
}

/* Called from g_hash_table_foreach_remove(), frees a stored UID->index
 * mapping.
 */
static gboolean
free_uid_index (gpointer key, gpointer value, gpointer data)
{
    int *idx;

    idx = value;
    g_free (idx);

    return TRUE;
}

/* Frees the objects stored in the calendar model */
static void
free_objects (CalendarModel *model)
{
    CalendarModelPrivate *priv;
    int i;

    priv = model->priv;

    g_hash_table_foreach_remove (priv->uid_index_hash, free_uid_index, NULL);

    for (i = 0; i < priv->objects->len; i++) {
        CalComponent *comp;

        comp = g_array_index (priv->objects, CalComponent *, i);
        g_assert (comp != NULL);
        gtk_object_unref (GTK_OBJECT (comp));
    }

    g_array_set_size (priv->objects, 0);
}

/* Destroy handler for the calendar table model */
static void
calendar_model_destroy (GtkObject *object)
{
    CalendarModel *model;
    CalendarModelPrivate *priv;

    g_return_if_fail (object != NULL);
    g_return_if_fail (IS_CALENDAR_MODEL (object));

    model = CALENDAR_MODEL (object);
    priv = model->priv;

    /* Free the calendar client interface object */

    if (priv->client) {
        gtk_signal_disconnect_by_data (GTK_OBJECT (priv->client), model);
        gtk_object_unref (GTK_OBJECT (priv->client));
        priv->client = NULL;
    }

    /* Free the uid->index hash data and the array of UIDs */

    free_objects (model);

    g_hash_table_destroy (priv->uid_index_hash);
    priv->uid_index_hash = NULL;

    g_array_free (priv->objects, TRUE);
    priv->objects = NULL;

    /* Free the private structure */

    g_free (priv);
    model->priv = NULL;

    if (GTK_OBJECT_CLASS (parent_class)->destroy)
        (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
}



/* ETableModel methods */

/* column_count handler for the calendar table model */
static int
calendar_model_column_count (ETableModel *etm)
{
    return CAL_COMPONENT_FIELD_NUM_FIELDS;
}

/* row_count handler for the calendar table model */
static int
calendar_model_row_count (ETableModel *etm)
{
    CalendarModel *model;
    CalendarModelPrivate *priv;

    model = CALENDAR_MODEL (etm);
    priv = model->priv;

    return priv->objects->len;
}

/* Creates a nice string representation of a time value */
static char*
get_time_t (CalendarModel *model, time_t *t, gboolean skip_midnight)
{
    static char buffer[64];
    struct tm *tmp_tm;
    char *format;

    if (*t <= 0) {
        buffer[0] = '\0';
    } else {
        tmp_tm = localtime (t);

        if (skip_midnight && tmp_tm->tm_hour == 0
            && tmp_tm->tm_min == 0 && tmp_tm->tm_sec == 0)
            /* strftime format of a weekday and a date. */
            format = _("%a %m/%d/%Y");
        else if (model->priv->use_24_hour_format)
            /* strftime format of a weekday, a date and a time,
               in 24-hour format. */
            format = _("%a %m/%d/%Y %H:%M:%S");
        else
            /* strftime format of a weekday, a date and a time,
               in 12-hour format. */
            format = _("%a %m/%d/%Y %I:%M:%S %p");
            
        strftime (buffer, sizeof (buffer), format, tmp_tm);
    }

    return buffer;
}

/* Builds a string based on the list of CATEGORIES properties of a calendar
 * component.
 */
static char *
get_categories (CalComponent *comp)
{
    const char *categories;

    cal_component_get_categories (comp, &categories);

    return g_strdup (categories);
}

/* Returns a string based on the CLASSIFICATION property of a calendar component */
static char *
get_classification (CalComponent *comp)
{
    CalComponentClassification classif;

    cal_component_get_classification (comp, &classif);

    switch (classif) {
    case CAL_COMPONENT_CLASS_NONE:
        return "";

    case CAL_COMPONENT_CLASS_PUBLIC:
        return _("Public");

    case CAL_COMPONENT_CLASS_PRIVATE:
        return _("Private");

    case CAL_COMPONENT_CLASS_CONFIDENTIAL:
        return _("Confidential");

    case CAL_COMPONENT_CLASS_UNKNOWN:
        return _("Unknown");

    default:
        g_assert_not_reached ();
        return NULL;
    }
}

/* Builds a string for the COMPLETED property of a calendar component */
static char *
get_completed   (CalendarModel *model,
         CalComponent  *comp)
{
    struct icaltimetype *completed;
    time_t t;

    cal_component_get_completed (comp, &completed);

    if (!completed)
        t = 0;
    else {
        t = icaltime_as_timet (*completed);
        cal_component_free_icaltimetype (completed);
    }

    return get_time_t (model, &t, FALSE);
}

/* Builds a string for and frees a date/time value */
static char *
get_and_free_datetime (CalendarModel *model, CalComponentDateTime dt)
{
    time_t t;

    if (!dt.value)
        t = 0;
    else
        t = icaltime_as_timet (*dt.value);

    cal_component_free_datetime (&dt);

    return get_time_t (model, &t, FALSE);
}

/* Builds a string for the DTEND property of a calendar component */
static char *
get_dtend (CalendarModel *model, CalComponent *comp)
{
    CalComponentDateTime dt;

    cal_component_get_dtend (comp, &dt);
    return get_and_free_datetime (model, dt);
}

/* Builds a string for the DTSTART property of a calendar component */
static char *
get_dtstart (CalendarModel *model, CalComponent *comp)
{
    CalComponentDateTime dt;

    cal_component_get_dtstart (comp, &dt);
    return get_and_free_datetime (model, dt);
}

/* Builds a string for the DUE property of a calendar component */
static char *
get_due (CalendarModel *model, CalComponent *comp)
{
    CalComponentDateTime dt;

    cal_component_get_due (comp, &dt);
    return get_and_free_datetime (model, dt);
}

/* Builds a string for the GEO property of a calendar component */
static char*
get_geo (CalComponent *comp)
{
    struct icalgeotype *geo;
    static gchar buf[32];

    cal_component_get_geo (comp, &geo);

    if (!geo)
        buf[0] = '\0';
    else {
        g_snprintf (buf, sizeof (buf), "%g %s, %g %s",
                fabs (geo->lat),
                geo->lat >= 0.0 ? _("N") : _("S"),
                fabs (geo->lon),
                geo->lon >= 0.0 ? _("E") : _("W"));
        cal_component_free_geo (geo);
    }

    return buf;
}

/* Builds a string for the PERCENT property of a calendar component */
static char *
get_percent (CalComponent *comp)
{
    int *percent;
    static char buf[32];

    cal_component_get_percent (comp, &percent);

    if (!percent)
        buf[0] = '\0';
    else {
        g_snprintf (buf, sizeof (buf), "%d%%", *percent);
        cal_component_free_percent (percent);
    }

    return buf;
}

/* Builds a string for the PRIORITY property of a calendar component */
static char *
get_priority (CalComponent *comp)
{
    int *priority;
    static char buf[32];

    cal_component_get_priority (comp, &priority);

    if (!priority)
        buf[0] = '\0';
    else {
        g_snprintf (buf, sizeof (buf), "%d", *priority);
        cal_component_free_priority (priority);
    }

    return buf;
}

/* Builds a string for the SUMMARY property of a calendar component */
static char *
get_summary (CalComponent *comp)
{
    CalComponentText summary;

    cal_component_get_summary (comp, &summary);

    if (summary.value)
        return (char *) summary.value;
    else
        return "";
}

/* Builds a string for the TRANSPARENCY property of a calendar component */
static char *
get_transparency (CalComponent *comp)
{
    CalComponentTransparency transp;

    cal_component_get_transparency (comp, &transp);

    switch (transp) {
    case CAL_COMPONENT_TRANSP_NONE:
        return "";

    case CAL_COMPONENT_TRANSP_TRANSPARENT:
        return _("Transparent");

    case CAL_COMPONENT_TRANSP_OPAQUE:
        return _("Opaque");

    case CAL_COMPONENT_TRANSP_UNKNOWN:
        return _("Unknown");

    default:
        g_assert_not_reached ();
        return NULL;
    }
}

/* Builds a string for the URL property of a calendar component */
static char *
get_url (CalComponent *comp)
{
    const char *url;

    cal_component_get_url (comp, &url);

    if (url)
        return (char *) url;
    else
        return "";
}

/* Returns whether the completion date has been set on a component */
static gboolean
get_is_complete (CalComponent *comp)
{
    struct icaltimetype *t;
    gboolean retval;

    cal_component_get_completed (comp, &t);
    retval = (t != NULL);

    if (retval)
        cal_component_free_icaltimetype (t);

    return retval;
}

/* Returns whether a calendar component is overdue.
 *
 * FIXME: This will only get called when the component is scrolled into the
 * ETable.  There should be some sort of dynamic update thingy for if a component
 * becomes overdue while it is being viewed.
 */
static gboolean
get_is_overdue (CalComponent *comp)
{
    CalComponentDateTime dt;
    gboolean retval;

    cal_component_get_due (comp, &dt);

    /* First, do we have a due date? */

    if (!dt.value)
        retval = FALSE;
    else {
        time_t t;

        /* Second, is it already completed? */

        if (get_is_complete (comp)) {
            retval = FALSE;
            goto out;
        }

        /* Third, are we overdue as of right now? */

        t = icaltime_as_timet (*dt.value);

        if (t < time (NULL))
            retval = TRUE;
        else
            retval = FALSE;
    }

 out:

    cal_component_free_datetime (&dt);

    return retval;
}

/* value_at handler for the calendar table model */
static void *
calendar_model_value_at (ETableModel *etm, int col, int row)
{
    CalendarModel *model;
    CalendarModelPrivate *priv;
    CalComponent *comp;

    model = CALENDAR_MODEL (etm);
    priv = model->priv;

    g_return_val_if_fail (col >= 0 && col < CAL_COMPONENT_FIELD_NUM_FIELDS, NULL);
    g_return_val_if_fail (row >= 0 && row < priv->objects->len, NULL);

    comp = g_array_index (priv->objects, CalComponent *, row);
    g_assert (comp != NULL);

    switch (col) {
    case CAL_COMPONENT_FIELD_CATEGORIES:
        return get_categories (comp);

    case CAL_COMPONENT_FIELD_CLASSIFICATION:
        return get_classification (comp);

    case CAL_COMPONENT_FIELD_COMPLETED:
        return get_completed (model, comp);

    case CAL_COMPONENT_FIELD_DTEND:
        return get_dtend (model, comp);

    case CAL_COMPONENT_FIELD_DTSTART:
        return get_dtstart (model, comp);

    case CAL_COMPONENT_FIELD_DUE:
        return get_due (model, comp);

    case CAL_COMPONENT_FIELD_GEO:
        return get_geo (comp);

    case CAL_COMPONENT_FIELD_PERCENT:
        return get_percent (comp);

    case CAL_COMPONENT_FIELD_PRIORITY:
        return get_priority (comp);

    case CAL_COMPONENT_FIELD_SUMMARY:
        return get_summary (comp);

    case CAL_COMPONENT_FIELD_TRANSPARENCY:
        return get_transparency (comp);

    case CAL_COMPONENT_FIELD_URL:
        return get_url (comp);

    case CAL_COMPONENT_FIELD_HAS_ALARMS:
        return GINT_TO_POINTER (cal_component_has_alarms (comp));

    case CAL_COMPONENT_FIELD_ICON:
        /* FIXME: Also support 'Assigned to me' & 'Assigned to someone
           else'. */
        if (cal_component_has_recurrences (comp))
            return GINT_TO_POINTER (1);
        else {
            icalcomponent *ical_comp;

            ical_comp = cal_component_get_icalcomponent (comp);
            if (icalcomponent_get_first_property (ical_comp,
                                  ICAL_ATTENDEE_PROPERTY) != NULL)
            {
                return GINT_TO_POINTER (2); /* Task-assigned */
            }
            else {
                return GINT_TO_POINTER (0);
            }
        }
    case CAL_COMPONENT_FIELD_COMPLETE:
        return GINT_TO_POINTER (get_is_complete (comp));

    case CAL_COMPONENT_FIELD_RECURRING:
        return GINT_TO_POINTER (cal_component_has_recurrences (comp));

    case CAL_COMPONENT_FIELD_OVERDUE:
        return GINT_TO_POINTER (get_is_overdue (comp));

    case CAL_COMPONENT_FIELD_COLOR:
        if (get_is_overdue (comp))
            return "red";
        else
            return NULL;

    default:
        g_message ("calendar_model_value_at(): Requested invalid column %d", col);
        return NULL;
    }
}

/* Returns whether a string is NULL, empty, or full of whitespace */
static gboolean
string_is_empty (const char *value)
{
    const char *p;
    gboolean empty = TRUE;

    if (value) {
        p = value;
        while (*p) {
            if (!isspace (*p)) {
                empty = FALSE;
                break;
            }
            p++;
        }
    }
    return empty;
}


/* FIXME: We need to set the "transient_for" property for the dialog, but
   the model doesn't know anything about the windows. */
static void
show_date_warning (CalendarModel *model)
{
    GtkWidget *dialog;
    char buffer[64], message[256], *format;
    time_t t;
    struct tm *tmp_tm;

    t = time (NULL);
    tmp_tm = localtime (&t);

    if (model->priv->use_24_hour_format)
        /* strftime format of a weekday, a date and a time, 24-hour. */
        format = _("%a %m/%d/%Y %H:%M:%S");
    else
        /* strftime format of a weekday, a date and a time, 12-hour. */
        format = _("%a %m/%d/%Y %I:%M:%S %p");

    strftime (buffer, sizeof (buffer), format, tmp_tm);

    g_snprintf (message, 256,
            _("The date must be entered in the format: \n\n%s"),
            buffer);

    dialog = gnome_message_box_new (message,
                    GNOME_MESSAGE_BOX_ERROR,
                    GNOME_STOCK_BUTTON_OK, NULL);
    gtk_widget_show (dialog);
}

/* Builds a list of categories from a comma-delimited string */
static GSList *
categories_from_string (const char *value)
{
    GSList *list;
    const char *categ_start;
    const char *categ_end;
    const char *p;

    if (!value)
        return NULL;

    list = NULL;

    categ_start = categ_end = NULL;

    for (p = value; *p; p++) {
        if (categ_start) {
            if (*p == ',') {
                char *c;

                c = g_strndup (categ_start, categ_end - categ_start + 1);
                list = g_slist_prepend (list, c);

                categ_start = categ_end = NULL;
            } else if (!isspace (*p))
                categ_end = p;
        } else if (!isspace (*p) && *p != ',')
            categ_start = categ_end = p;
    }

    if (categ_start) {
        char *c;

        c = g_strndup (categ_start, categ_end - categ_start + 1);
        list = g_slist_prepend (list, c);
    }

    return g_slist_reverse (list);
}

/* Sets the list of categories from a comma-delimited string */
static void
set_categories (CalComponent *comp, const char *value)
{
    GSList *list;
    GSList *l;

    list = categories_from_string (value);

    cal_component_set_categories_list (comp, list);

    for (l = list; l; l = l->next) {
        char *s;

        s = l->data;
        g_free (s);
    }

    g_slist_free (list);
}

/* Parses a time value entered by the user; returns -1 if it could not be
 * parsed.  Returns 0 for an empty time.
 */
static time_t
parse_time (const char *value)
{
    struct tm discard_tm, date_tm, time_tm;
    struct tm *today_tm;
    time_t t;
    const char *pos, *parse_end;
    char *format[4];
    gboolean parsed_date = FALSE, parsed_time = FALSE;
    gint i;

    if (string_is_empty (value))
        return 0;

    pos = value;

    /* Skip any whitespace. */
    while (isspace (*pos))
        pos++;

    /* Skip any weekday name, full or abbreviated. */
    parse_end = strptime (pos, "%a ", &discard_tm);
    if (parse_end)
        pos = parse_end;

    memset (&date_tm, 0, sizeof (date_tm));
    /* strptime format for a date. */
    parse_end = strptime (pos, _("%m/%d/%Y"), &date_tm);
    if (parse_end) {
        pos = parse_end;
        parsed_date = TRUE;
    }

    /* Skip any whitespace. */
    while (isspace (*pos))
        pos++;

    /* Skip any weekday name, full or abbreviated, again. */
    parse_end = strptime (pos, "%a ", &discard_tm);
    if (parse_end)
        pos = parse_end;


    /* strptime format for a time of day, in 12-hour format.
       If it is is not appropriate in the locale set to an empty string. */
    format[0] = _("%I:%M:%S %p%n");

    /* strptime format for a time of day, in 24-hour format. */
    format[1] = _("%H:%M:%S%n");

    /* strptime format for time of day, without seconds, 12-hour format.
       If it is is not appropriate in the locale set to an empty string. */
    format[2] = _("%I:%M %p%n");

    /* strptime format for time of day, without seconds 24-hour format. */
    format[3] = _("%H:%M%n");

    for (i = 0; i < sizeof (format) / sizeof (format[0]); i++) {
        memset (&time_tm, 0, sizeof (time_tm));
        parse_end = strptime (pos, format[i], &time_tm);
        if (parse_end) {
            pos = parse_end;
            parsed_time = TRUE;
            break;
        }
    }

    /* Skip any whitespace. */
    while (isspace (*pos))
        pos++;

    /* If we haven't already parsed a date, try again. */
    if (!parsed_date) {
        memset (&date_tm, 0, sizeof (date_tm));
        /* strptime format for a date. */
        parse_end = strptime (pos, _("%m/%d/%Y"), &date_tm);
        if (parse_end) {
            pos = parse_end;
            parsed_date = TRUE;
        }
    }

    /* If we don't have a date or a time it must be invalid. */
    if (!parsed_date && !parsed_time)
        return -1;


    if (parsed_date) {
        /* If a 2-digit year was used we use the current century. */
        if (date_tm.tm_year < 0) {
            t = time (NULL);
            today_tm = localtime (&t);

            /* This should convert it into a value from 0 to 99. */
            date_tm.tm_year += 1900;

            /* Now add on the century. */
            date_tm.tm_year += today_tm->tm_year
                - (today_tm->tm_year % 100);
        }
    } else {
        /* If we didn't get a date we use the current day. */
        t = time (NULL);
        today_tm = localtime (&t);
        date_tm.tm_mday = today_tm->tm_mday;
        date_tm.tm_mon  = today_tm->tm_mon;
        date_tm.tm_year = today_tm->tm_year;
    }

    if (parsed_time) {
        date_tm.tm_hour = time_tm.tm_hour;
        date_tm.tm_min = time_tm.tm_min;
        date_tm.tm_sec = time_tm.tm_sec;
    } else {
        date_tm.tm_hour = 0;
        date_tm.tm_min = 0;
        date_tm.tm_sec = 0;
    }


    date_tm.tm_isdst = -1;
    return mktime (&date_tm);
}

/* Called to set the "Date Completed" field. We also need to update the
   Status and Percent fields to make sure they match. */
static void
set_completed (CalendarModel *model, CalComponent *comp, const char *value)
{
    time_t t;

    t = parse_time (value);
    if (t == -1) {
        show_date_warning (model);
    } else if (t == 0) {
        ensure_task_not_complete (comp);
    } else {
        ensure_task_complete (comp, t);
    }
}

/* Sets a CalComponentDateTime value */
static void
set_datetime (CalendarModel *model, CalComponent *comp, const char *value,
          void (* set_func) (CalComponent *comp, CalComponentDateTime *dt))
{
    time_t t;

    t = parse_time (value);
    if (t == -1) {
        show_date_warning (model);
        return;
    } else if (t == 0) {
        (* set_func) (comp, NULL);
        return;
    } else {
        CalComponentDateTime dt;
        struct icaltimetype itt;

        itt = icaltime_from_timet (t, FALSE, TRUE);
        dt.value = &itt;
        dt.tzid = NULL;

        (* set_func) (comp, &dt);
    }
}

/* FIXME: We need to set the "transient_for" property for the dialog, but the
 * model doesn't know anything about the windows.
 */
static void
show_geo_warning (void)
{
    GtkWidget *dialog;

    dialog = gnome_message_box_new (_("The geographical position must be entered "
                      "in the format: \n\n45.436845,125.862501"),
                    GNOME_MESSAGE_BOX_ERROR,
                    GNOME_STOCK_BUTTON_OK, NULL);
    gtk_widget_show (dialog);
}

/* Sets the geographical position value of a component */
static void
set_geo (CalComponent *comp, const char *value)
{
    double latitude, longitude;
    int matched;
    struct icalgeotype geo;

    if (string_is_empty (value)) {
        cal_component_set_geo (comp, NULL);
        return;
    }

    matched = sscanf (value, "%lg , %lg", &latitude, &longitude);

    if (matched != 2) {
        show_geo_warning ();
        return;
    }

    geo.lat = latitude;
    geo.lon = longitude;
    cal_component_set_geo (comp, &geo);
}

/* FIXME: We need to set the "transient_for" property for the dialog, but the
 * model doesn't know anything about the windows.
 */
static void
show_percent_warning (void)
{
    GtkWidget *dialog;

    dialog = gnome_message_box_new (_("The percent value must be between 0 and 100, inclusive"),
                    GNOME_MESSAGE_BOX_ERROR,
                    GNOME_STOCK_BUTTON_OK, NULL);
    gtk_widget_show (dialog);
}

/* Sets the percent value of a calendar component */
static void
set_percent (CalComponent *comp, const char *value)
{
    int matched, percent;

    if (string_is_empty (value)) {
        cal_component_set_percent (comp, NULL);
        ensure_task_not_complete (comp);
        return;
    }

    matched = sscanf (value, "%i", &percent);

    if (matched != 1 || percent < 0 || percent > 100) {
        show_percent_warning ();
        return;
    }

    cal_component_set_percent (comp, &percent);

    if (percent == 100)
        ensure_task_complete (comp, -1);
    else
        ensure_task_not_complete (comp);
}

/* FIXME: We need to set the "transient_for" property for the dialog, but the
 * model doesn't know anything about the windows.  */
static void
show_priority_warning (void)
{
    GtkWidget *dialog;

    dialog = gnome_message_box_new (_("The priority must be between 1 and 9, inclusive"),
                    GNOME_MESSAGE_BOX_ERROR,
                    GNOME_STOCK_BUTTON_OK, NULL);
    gtk_widget_show (dialog);
}

/* Sets the priority of a calendar component */
static void
set_priority (CalComponent *comp, const char *value)
{
    int matched, priority;

    if (string_is_empty (value)) {
        cal_component_set_priority (comp, NULL);
        return;
    }

    matched = sscanf (value, "%i", &priority);

    if (matched != 1 || priority < 1 || priority > 9) {
        show_priority_warning ();
        return;
    }

    cal_component_set_priority (comp, &priority);
}

/* Sets the summary of a calendar component */
static void
set_summary (CalComponent *comp, const char *value)
{
    CalComponentText text;

    if (string_is_empty (value)) {
        cal_component_set_summary (comp, NULL);
        return;
    }

    text.value = value;
    text.altrep = NULL; /* FIXME: should we preserve the old ALTREP? */

    cal_component_set_summary (comp, &text);
}

/* Sets the URI of a calendar component */
static void
set_url (CalComponent *comp, const char *value)
{
    if (string_is_empty (value)) {
        cal_component_set_url (comp, NULL);
        return;
    }

    cal_component_set_url (comp, value);
}

/* Called to set the checkbutton field which indicates whether a task is
   complete. */
static void
set_complete (CalComponent *comp, const void *value)
{
    gint state = GPOINTER_TO_INT (value);

    if (state) {
        ensure_task_complete (comp, -1);
    } else {
        ensure_task_not_complete (comp);
    }
}

/* set_value_at handler for the calendar table model */
static void
calendar_model_set_value_at (ETableModel *etm, int col, int row, const void *value)
{
    CalendarModel *model;
    CalendarModelPrivate *priv;
    CalComponent *comp;

    model = CALENDAR_MODEL (etm);
    priv = model->priv;

    g_return_if_fail (col >= 0 && col < CAL_COMPONENT_FIELD_NUM_FIELDS);
    g_return_if_fail (row >= 0 && row < priv->objects->len);

    comp = g_array_index (priv->objects, CalComponent *, row);
    g_assert (comp != NULL);

    switch (col) {
    case CAL_COMPONENT_FIELD_CATEGORIES:
        set_categories (comp, value);
        break;

    /* FIXME: CLASSIFICATION requires an option menu cell renderer */

    case CAL_COMPONENT_FIELD_COMPLETED:
        set_completed (model, comp, value);
        break;

    case CAL_COMPONENT_FIELD_DTEND:
        /* FIXME: Need to reset dtstart if dtend happens before it */
        set_datetime (model, comp, value, cal_component_set_dtend);
        break;

    case CAL_COMPONENT_FIELD_DTSTART:
        /* FIXME: Need to reset dtend if dtstart happens after it */
        set_datetime (model, comp, value, cal_component_set_dtstart);
        break;

    case CAL_COMPONENT_FIELD_DUE:
        set_datetime (model, comp, value, cal_component_set_due);
        break;

    case CAL_COMPONENT_FIELD_GEO:
        set_geo (comp, value);
        break;

    case CAL_COMPONENT_FIELD_PERCENT:
        set_percent (comp, value);
        break;

    case CAL_COMPONENT_FIELD_PRIORITY:
        set_priority (comp, value);
        break;

    case CAL_COMPONENT_FIELD_SUMMARY:
        set_summary (comp, value);
        break;

    /* FIXME: TRANSPARENCY requires an option menu cell renderer */

    case CAL_COMPONENT_FIELD_URL:
        set_url (comp, value);
        break;

    case CAL_COMPONENT_FIELD_COMPLETE:
        set_complete (comp, value);
        break;

    default:
        g_message ("calendar_model_set_value_at(): Requested invalid column %d", col);
        break;
    }

    /* FIXME: this is an ugly HACK.  ETable needs a better API for the
     * "click here to add an element" thingy.
     */
    if (priv->appending_row)
        return;

    if (!cal_client_update_object (priv->client, comp))
        g_message ("calendar_model_set_value_at(): Could not update the object!");
}

/* is_cell_editable handler for the calendar table model */
static gboolean
calendar_model_is_cell_editable (ETableModel *etm, int col, int row)
{
    CalendarModel *model;
    CalendarModelPrivate *priv;

    model = CALENDAR_MODEL (etm);
    priv = model->priv;

    g_return_val_if_fail (col >= 0 && col < CAL_COMPONENT_FIELD_NUM_FIELDS, FALSE);

    /* FIXME: We can't check this as 'click-to-add' passes row 0. */
    /*g_return_val_if_fail (row >= 0 && row < priv->objects->len, FALSE);*/

    switch (col) {
    case CAL_COMPONENT_FIELD_CATEGORIES:
    case CAL_COMPONENT_FIELD_COMPLETED:
    case CAL_COMPONENT_FIELD_DTEND:
    case CAL_COMPONENT_FIELD_DTSTART:
    case CAL_COMPONENT_FIELD_DUE:
    case CAL_COMPONENT_FIELD_GEO:
    case CAL_COMPONENT_FIELD_PERCENT:
    case CAL_COMPONENT_FIELD_PRIORITY:
    case CAL_COMPONENT_FIELD_SUMMARY:
    case CAL_COMPONENT_FIELD_URL:
    case CAL_COMPONENT_FIELD_COMPLETE:
        return TRUE;

    default:
        return FALSE;
    }
}

/* append_row handler for the calendar model */
static void
calendar_model_append_row (ETableModel *etm, ETableModel *source, gint row)
{
    CalendarModel *model;
    CalendarModelPrivate *priv;
    CalComponent *comp;
    int *new_idx, col;
    const char *uid;

    model = CALENDAR_MODEL (etm);
    priv = model->priv;

    /* This is a HACK */
    priv->appending_row = TRUE;

    /* FIXME: This should support other types of components, but for now it
     * is only used for the task list.
     */
    comp = cal_component_new ();
    cal_component_set_new_vtype (comp, CAL_COMPONENT_TODO);

    cal_component_get_uid (comp, &uid);

    g_array_append_val (priv->objects, comp);
    new_idx = g_new (int, 1);
    *new_idx = priv->objects->len - 1;
    g_hash_table_insert (priv->uid_index_hash, (char *) uid, new_idx);

    /* Notify the views about the new row. I think we have to do that here,
       or the views may become confused when they start getting
       "row_changed" or "cell_changed" signals for this new row. */
    e_table_model_row_inserted (etm, *new_idx);

    for (col = 0; col < CAL_COMPONENT_FIELD_NUM_FIELDS; col++) {
        const void *val;

        if (!e_table_model_is_cell_editable (etm, col, *new_idx))
            continue;

        val = e_table_model_value_at(source, col, row);
        e_table_model_set_value_at (etm, col, *new_idx, val);
    }

    /* This is the end of the HACK */
    priv->appending_row = FALSE;

    if (!cal_client_update_object (priv->client, comp)) {
        /* FIXME: Show error dialog. */
        g_message ("calendar_model_append_row(): Could not add new object!");
        remove_object (model, uid);
        e_table_model_row_deleted (etm, *new_idx);
    }
}

/* Duplicates a string value */
static char *
dup_string (const char *value)
{
    return g_strdup (value);
}

/* duplicate_value handler for the calendar table model */
static void *
calendar_model_duplicate_value (ETableModel *etm, int col, const void *value)
{
    g_return_val_if_fail (col >= 0 && col < CAL_COMPONENT_FIELD_NUM_FIELDS, NULL);

    /* They are almost all dup_string()s for now, but we'll have real fields
     * later.
     */

    switch (col) {
    case CAL_COMPONENT_FIELD_CATEGORIES:
        return dup_string (value);

    case CAL_COMPONENT_FIELD_CLASSIFICATION:
        return (void *) value;

    case CAL_COMPONENT_FIELD_COMPLETED:
    case CAL_COMPONENT_FIELD_DTEND:
    case CAL_COMPONENT_FIELD_DTSTART:
    case CAL_COMPONENT_FIELD_DUE:
    case CAL_COMPONENT_FIELD_GEO:
    case CAL_COMPONENT_FIELD_PERCENT:
    case CAL_COMPONENT_FIELD_PRIORITY:
    case CAL_COMPONENT_FIELD_SUMMARY:
        return dup_string (value);

    case CAL_COMPONENT_FIELD_TRANSPARENCY:
        return (void *) value;

    case CAL_COMPONENT_FIELD_URL:
        return dup_string (value);

    case CAL_COMPONENT_FIELD_HAS_ALARMS:
    case CAL_COMPONENT_FIELD_ICON:
    case CAL_COMPONENT_FIELD_COMPLETE:
    case CAL_COMPONENT_FIELD_RECURRING:
    case CAL_COMPONENT_FIELD_OVERDUE:
    case CAL_COMPONENT_FIELD_COLOR:
        return (void *) value;

    default:
        g_message ("calendar_model_duplicate_value(): Requested invalid column %d", col);
        return NULL;
    }
}

/* free_value handler for the calendar table model */
static void
calendar_model_free_value (ETableModel *etm, int col, void *value)
{
    g_return_if_fail (col >= 0 && col < CAL_COMPONENT_FIELD_NUM_FIELDS);

    switch (col) {
    case CAL_COMPONENT_FIELD_CATEGORIES:
        g_free (value);

    case CAL_COMPONENT_FIELD_CLASSIFICATION:
        return;

    case CAL_COMPONENT_FIELD_COMPLETED:
    case CAL_COMPONENT_FIELD_DTEND:
    case CAL_COMPONENT_FIELD_DTSTART:
    case CAL_COMPONENT_FIELD_DUE:
    case CAL_COMPONENT_FIELD_GEO:
    case CAL_COMPONENT_FIELD_PERCENT:
    case CAL_COMPONENT_FIELD_PRIORITY:
    case CAL_COMPONENT_FIELD_SUMMARY:
        g_free (value);

    case CAL_COMPONENT_FIELD_TRANSPARENCY:
        return;

    case CAL_COMPONENT_FIELD_URL:
        g_free (value);

    case CAL_COMPONENT_FIELD_HAS_ALARMS:
    case CAL_COMPONENT_FIELD_ICON:
    case CAL_COMPONENT_FIELD_COMPLETE:
    case CAL_COMPONENT_FIELD_RECURRING:
    case CAL_COMPONENT_FIELD_OVERDUE:
    case CAL_COMPONENT_FIELD_COLOR:
        return;

    default:
        g_message ("calendar_model_free_value(): Requested invalid column %d", col);
        return;
    }
}

/* Initializes a string value */
static char *
init_string (void)
{
    return g_strdup ("");
}

/* initialize_value handler for the calendar table model */
static void *
calendar_model_initialize_value (ETableModel *etm, int col)
{
    g_return_val_if_fail (col >= 0 && col < CAL_COMPONENT_FIELD_NUM_FIELDS, NULL);

    switch (col) {
    case CAL_COMPONENT_FIELD_CATEGORIES:
        return init_string ();

    case CAL_COMPONENT_FIELD_CLASSIFICATION:
        return NULL;

    case CAL_COMPONENT_FIELD_COMPLETED:
    case CAL_COMPONENT_FIELD_DTEND:
    case CAL_COMPONENT_FIELD_DTSTART:
    case CAL_COMPONENT_FIELD_DUE:
    case CAL_COMPONENT_FIELD_GEO:
    case CAL_COMPONENT_FIELD_PERCENT:
    case CAL_COMPONENT_FIELD_PRIORITY:
    case CAL_COMPONENT_FIELD_SUMMARY:
        return init_string ();

    case CAL_COMPONENT_FIELD_TRANSPARENCY:
        return NULL;

    case CAL_COMPONENT_FIELD_URL:
        return init_string ();

    case CAL_COMPONENT_FIELD_HAS_ALARMS:
    case CAL_COMPONENT_FIELD_ICON:
    case CAL_COMPONENT_FIELD_COMPLETE:
    case CAL_COMPONENT_FIELD_RECURRING:
    case CAL_COMPONENT_FIELD_OVERDUE:
    case CAL_COMPONENT_FIELD_COLOR:
        return NULL;

    default:
        g_message ("calendar_model_initialize_value(): Requested invalid column %d", col);
        return NULL;
    }
}

/* value_is_empty handler for the calendar model. This should return TRUE
   unless a significant value has been set. The 'click-to-add' feature
   checks all fields to see if any are not empty and if so it adds a new
   row, so we only want to return FALSE if we have a useful object. */
static gboolean
calendar_model_value_is_empty (ETableModel *etm, int col, const void *value)
{
    g_return_val_if_fail (col >= 0 && col < CAL_COMPONENT_FIELD_NUM_FIELDS, TRUE);

    switch (col) {
    case CAL_COMPONENT_FIELD_CATEGORIES:
    case CAL_COMPONENT_FIELD_CLASSIFICATION: /* actually goes here, not by itself */
    case CAL_COMPONENT_FIELD_COMPLETED:
    case CAL_COMPONENT_FIELD_DTEND:
    case CAL_COMPONENT_FIELD_DTSTART:
    case CAL_COMPONENT_FIELD_DUE:
    case CAL_COMPONENT_FIELD_GEO:
    case CAL_COMPONENT_FIELD_PERCENT:
    case CAL_COMPONENT_FIELD_PRIORITY:
    case CAL_COMPONENT_FIELD_SUMMARY:
    case CAL_COMPONENT_FIELD_TRANSPARENCY:
    case CAL_COMPONENT_FIELD_URL:
        return string_is_empty (value);

    case CAL_COMPONENT_FIELD_HAS_ALARMS:
    case CAL_COMPONENT_FIELD_ICON:
    case CAL_COMPONENT_FIELD_COMPLETE:
    case CAL_COMPONENT_FIELD_RECURRING:
    case CAL_COMPONENT_FIELD_OVERDUE:
    case CAL_COMPONENT_FIELD_COLOR:
        return TRUE;

    default:
        g_message ("calendar_model_value_is_empty(): Requested invalid column %d", col);
        return TRUE;
    }
}



/**
 * calendar_model_new:
 *
 * Creates a new calendar model.  It must be told about the calendar client
 * interface object it will monitor with calendar_model_set_cal_client().
 *
 * Return value: A newly-created calendar model.
 **/
CalendarModel *
calendar_model_new (void)
{
    return CALENDAR_MODEL (gtk_type_new (TYPE_CALENDAR_MODEL));
}


/* Callback used when a calendar is loaded into the server */
static void
cal_loaded_cb (CalClient *client,
           CalClientLoadStatus status,
           CalendarModel *model)
{
    g_return_if_fail (IS_CALENDAR_MODEL (model));

    e_table_model_pre_change (E_TABLE_MODEL (model));

    if (status == CAL_CLIENT_LOAD_SUCCESS)
        load_objects (model);

    e_table_model_changed (E_TABLE_MODEL (model));
}


/* Removes an object from the model and updates all the indices that follow.
 * Returns the index of the object that was removed, or -1 if no object with
 * such UID was found.
 */
static int
remove_object (CalendarModel *model, const char *uid)
{
    CalendarModelPrivate *priv;
    int *idx;
    CalComponent *orig_comp;
    int i;
    int n;

    priv = model->priv;

    /* Find the index of the object to be removed */

    idx = g_hash_table_lookup (priv->uid_index_hash, uid);
    if (!idx)
        return -1;

    orig_comp = g_array_index (priv->objects, CalComponent *, *idx);
    g_assert (orig_comp != NULL);

    /* Decrease the indices of all the objects that follow in the array */

    for (i = *idx + 1; i < priv->objects->len; i++) {
        CalComponent *comp;
        int *comp_idx;
        const char *comp_uid;

        comp = g_array_index (priv->objects, CalComponent *, i);
        g_assert (comp != NULL);

        cal_component_get_uid (comp, &comp_uid);

        comp_idx = g_hash_table_lookup (priv->uid_index_hash, comp_uid);
        g_assert (comp_idx != NULL);

        (*comp_idx)--;
        g_assert (*comp_idx >= 0);
    }

    /* Remove this object from the array and hash */

    g_hash_table_remove (priv->uid_index_hash, uid);
    g_array_remove_index (priv->objects, *idx);

    gtk_object_unref (GTK_OBJECT (orig_comp));

    n = *idx;
    g_free (idx);

    return n;
}

/* Returns whether a component's type matches the types we support */
static gboolean
matches_type (CalObjType type, CalComponentVType vtype)
{
    return ((vtype == CAL_COMPONENT_EVENT && (type & CALOBJ_TYPE_EVENT))
        || (vtype == CAL_COMPONENT_TODO && (type & CALOBJ_TYPE_TODO))
        || (vtype == CAL_COMPONENT_JOURNAL && (type & CALOBJ_TYPE_JOURNAL)));
}

/* Callback used when an object is updated in the server */
static void
obj_updated_cb (CalClient *client, const char *uid, gpointer data)
{
    CalendarModel *model;
    CalendarModelPrivate *priv;
    int orig_idx;
    CalComponent *new_comp;
    CalComponentVType new_comp_vtype;
    const char *new_comp_uid;
    int *new_idx;
    CalClientGetStatus status;

    model = CALENDAR_MODEL (data);
    priv = model->priv;

    orig_idx = remove_object (model, uid);

    status = cal_client_get_object (priv->client, uid, &new_comp);

    switch (status) {
    case CAL_CLIENT_GET_SUCCESS:
        /* Check if we are interested in this type of object */

        new_comp_vtype = cal_component_get_vtype (new_comp);
        if (!matches_type (priv->type, new_comp_vtype)) {
            gtk_object_unref (GTK_OBJECT (new_comp));
            break;
        }

        /* Insert the object into the model */

        cal_component_get_uid (new_comp, &new_comp_uid);

        if (orig_idx == -1) {
            /* The object not in the model originally, so we just append it */

            g_array_append_val (priv->objects, new_comp);

            new_idx = g_new (int, 1);
            *new_idx = priv->objects->len - 1;

            g_hash_table_insert (priv->uid_index_hash, (char *) new_comp_uid, new_idx);
            e_table_model_row_inserted (E_TABLE_MODEL (model), *new_idx);
        } else {
            int i;

            /* Insert the new version of the object in its old position */

            g_array_insert_val (priv->objects, orig_idx, new_comp);

            new_idx = g_new (int, 1);
            *new_idx = orig_idx;
            g_hash_table_insert (priv->uid_index_hash, (char *) new_comp_uid, new_idx);

            /* Increase the indices of all subsequent objects */

            for (i = orig_idx + 1; i < priv->objects->len; i++) {
                CalComponent *comp;
                int *comp_idx;
                const char *comp_uid;

                comp = g_array_index (priv->objects, CalComponent *, i);
                g_assert (comp != NULL);

                cal_component_get_uid (comp, &comp_uid);

                comp_idx = g_hash_table_lookup (priv->uid_index_hash, comp_uid);
                g_assert (comp_idx != NULL);

                (*comp_idx)++;
            }

            e_table_model_row_changed (E_TABLE_MODEL (model), *new_idx);
        }

        break;

    case CAL_CLIENT_GET_NOT_FOUND:
        /* Nothing; the object may have been removed from the server.  We just
         * notify that the old object was deleted.
         */
        if (orig_idx != -1)
            e_table_model_row_deleted (E_TABLE_MODEL (model), orig_idx);

        break;

    case CAL_CLIENT_GET_SYNTAX_ERROR:
        g_message ("obj_updated_cb(): Syntax error when getting object `%s'", uid);

        /* Same notification as above */
        if (orig_idx != -1)
            e_table_model_row_deleted (E_TABLE_MODEL (model), orig_idx);

        break;

    default:
        g_assert_not_reached ();
    }
}

/* Callback used when an object is removed in the server */
static void
obj_removed_cb (CalClient *client, const char *uid, gpointer data)
{
    CalendarModel *model;
    int idx;

    model = CALENDAR_MODEL (data);

    idx = remove_object (model, uid);

    if (idx != -1)
        e_table_model_row_deleted (E_TABLE_MODEL (model), idx);
}

/* Loads the required objects from the calendar client */
static void
load_objects (CalendarModel *model)
{
    CalendarModelPrivate *priv;
    GList *uids;
    GList *l;

    priv = model->priv;

    if (!cal_client_is_loaded (priv->client))
        return;

    uids = cal_client_get_uids (priv->client, priv->type);

    for (l = uids; l; l = l->next) {
        char *uid;
        CalComponent *comp;
        const char *comp_uid;
        CalClientGetStatus status;
        CalComponentVType comp_vtype;
        int *idx;

        uid = l->data;
        status = cal_client_get_object (priv->client, uid, &comp);

        switch (status) {
        case CAL_CLIENT_GET_SUCCESS:
            break;

        case CAL_CLIENT_GET_NOT_FOUND:
            /* Nothing; the object may have been removed from the server */
            continue;

        case CAL_CLIENT_GET_SYNTAX_ERROR:
            g_message ("load_objects(): Syntax error when getting object `%s'", uid);
            continue;

        default:
            g_assert_not_reached ();
        }

        /* Check if we are interested in this type of object */

        comp_vtype = cal_component_get_vtype (comp);
        if (!matches_type (priv->type, comp_vtype)) {
            gtk_object_unref (GTK_OBJECT (comp));
            continue;
        }

        /* Insert the object into the model */

        idx = g_new (int, 1);

        g_array_append_val (priv->objects, comp);
        *idx = priv->objects->len - 1;

        cal_component_get_uid (comp, &comp_uid);
        g_hash_table_insert (priv->uid_index_hash, (char *) comp_uid, idx);
    }

    cal_obj_uid_list_free (uids);
}

/**
 * calendar_model_get_cal_client:
 * @model: A calendar model.
 * 
 * Queries the calendar client interface object that a calendar model is using.
 * 
 * Return value: A calendar client interface object.
 **/
CalClient *
calendar_model_get_cal_client (CalendarModel *model)
{
    CalendarModelPrivate *priv;

    g_return_val_if_fail (model != NULL, NULL);
    g_return_val_if_fail (IS_CALENDAR_MODEL (model), NULL);

    priv = model->priv;

    return priv->client;
}


/**
 * calendar_model_set_cal_client:
 * @model: A calendar model.
 * @client: A calendar client interface object.
 * @type: Type of objects to present.
 *
 * Sets the calendar client interface object that a calendar model will monitor.
 * It also sets the types of objects this model will present to an #ETable.
 **/
void
calendar_model_set_cal_client (CalendarModel *model, CalClient *client, CalObjType type)
{
    CalendarModelPrivate *priv;

    g_return_if_fail (model != NULL);
    g_return_if_fail (IS_CALENDAR_MODEL (model));

    if (client)
        g_return_if_fail (IS_CAL_CLIENT (client));

    priv = model->priv;

    if (priv->client == client && priv->type == type)
        return;

    e_table_model_pre_change (E_TABLE_MODEL(model));

    if (client)
        gtk_object_ref (GTK_OBJECT (client));

    if (priv->client) {
        gtk_signal_disconnect_by_data (GTK_OBJECT (priv->client), model);
        gtk_object_unref (GTK_OBJECT (priv->client));
    }

    free_objects (model);

    priv->client = client;
    priv->type = type;

    if (priv->client) {
        if (!cal_client_is_loaded (priv->client))
            gtk_signal_connect (GTK_OBJECT (priv->client), "cal_loaded",
                        GTK_SIGNAL_FUNC (cal_loaded_cb), model);

        gtk_signal_connect (GTK_OBJECT (priv->client), "obj_updated",
                    GTK_SIGNAL_FUNC (obj_updated_cb), model);
        gtk_signal_connect (GTK_OBJECT (priv->client), "obj_removed",
                    GTK_SIGNAL_FUNC (obj_removed_cb), model);

        load_objects (model);
    }

    e_table_model_changed (E_TABLE_MODEL (model));
}


void
calendar_model_mark_task_complete (CalendarModel *model,
                   gint row)
{
    CalendarModelPrivate *priv;
    CalComponent *comp;

    g_return_if_fail (model != NULL);
    g_return_if_fail (IS_CALENDAR_MODEL (model));

    priv = model->priv;

    g_return_if_fail (row >= 0 && row < priv->objects->len);

    comp = g_array_index (priv->objects, CalComponent *, row);
    g_assert (comp != NULL);

    ensure_task_complete (comp, -1);

    if (!cal_client_update_object (priv->client, comp))
        g_message ("calendar_model_mark_task_complete(): Could not update the object!");
}


/**
 * calendar_model_get_component:
 * @model: A calendar model.
 * @row: Row number of sought calendar component.
 * 
 * Queries a calendar component from a calendar model based on its row number.
 * 
 * Return value: The sought calendar component.
 **/
CalComponent *
calendar_model_get_component (CalendarModel *model,
                   gint       row)
{
    CalendarModelPrivate *priv;

    g_return_val_if_fail (model != NULL, NULL);
    g_return_val_if_fail (IS_CALENDAR_MODEL (model), NULL);

    priv = model->priv;

    g_return_val_if_fail (row >= 0 && row < priv->objects->len, NULL);

    return g_array_index (priv->objects, CalComponent *, row);
}


/* This makes sure a task is marked as complete.
   It makes sure the "Date Completed" property is set. If the completed_date
   is not -1, then that is used, otherwise if the "Date Completed" property
   is not already set it is set to the current time.
   It makes sure the percent is set to 100, and that the status is "Completed".
   Note that this doesn't update the component on the client. */
static void
ensure_task_complete (CalComponent *comp,
              time_t completed_date)
{
    struct icaltimetype *old_completed = NULL;
    struct icaltimetype new_completed;
    int *old_percent, new_percent;
    gboolean set_completed = TRUE;

    /* Date Completed. */
    if (completed_date == -1) {
        cal_component_get_completed (comp, &old_completed);

        if (old_completed) {
            cal_component_free_icaltimetype (old_completed);
            set_completed = FALSE;
        } else {
            completed_date = time (NULL);
        }
    }

    if (set_completed) {
        new_completed = icaltime_from_timet (completed_date, FALSE, TRUE);
        cal_component_set_completed (comp, &new_completed);
    }

    /* Percent. */
    cal_component_get_percent (comp, &old_percent);
    if (!old_percent || *old_percent != 100) {
        new_percent = 100;
        cal_component_set_percent (comp, &new_percent);
    }
    if (old_percent)
        cal_component_free_percent (old_percent);
}


/* This makes sure a task is marked as incomplete. It clears the
   "Date Completed" property. If the percent is set to 100 it removes it,
   and if the status is "Completed" it sets it to "Needs Action".
   Note that this doesn't update the component on the client. */
static void
ensure_task_not_complete (CalComponent *comp)
{
    icalproperty_status old_status;
    int *old_percent;

    /* Date Completed. */
    cal_component_set_completed (comp, NULL);

    /* Percent. */
    cal_component_get_percent (comp, &old_percent);
    if (old_percent && *old_percent == 100)
        cal_component_set_percent (comp, NULL);
    if (old_percent)
        cal_component_free_percent (old_percent);

    /* Status. */
    cal_component_get_status (comp, &old_status);
    if (old_status == ICAL_STATUS_COMPLETED)
        cal_component_set_status (comp, ICAL_STATUS_NEEDSACTION);
}


/* Whether we use 24 hour format to display the times. */
gboolean
calendar_model_get_use_24_hour_format (CalendarModel *model)
{
    g_return_val_if_fail (IS_CALENDAR_MODEL (model), TRUE);

    return model->priv->use_24_hour_format;
}


void
calendar_model_set_use_24_hour_format (CalendarModel *model,
                       gboolean       use_24_hour_format)
{
    g_return_if_fail (IS_CALENDAR_MODEL (model));

    if (model->priv->use_24_hour_format != use_24_hour_format) {
        model->priv->use_24_hour_format = use_24_hour_format;
        /* Get the views to redraw themselves. */
        e_table_model_changed (E_TABLE_MODEL (model));
    }
}