summaryrefslogtreecommitdiff
path: root/src/contacts-contact-pane.vala
blob: 1a8df8bb26b45624775c3054d34feb6fea0c3ca3 (plain)
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
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
/* -*- Mode: vala; indent-tabs-mode: t; c-basic-offset: 2; tab-width: 8 -*- */
/*
 * Copyright (C) 2011 Alexander Larsson <alexl@redhat.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, see <http://www.gnu.org/licenses/>.
 */

using Gtk;
using Folks;
using Gee;

public class Contacts.FieldRow : Contacts.Row {
  Clickable clickable;
  int start;
  bool has_child_focus;

  /* show_as_editable means we prelight, can_focus, show selected, etc.
     It doesn't mean we can't edit the row. For instance the
     Card row is editing when we're editing the full name, but
     thats not represented in the UI as editing the row. */
  protected bool show_as_editable;
  protected bool is_editing;

  public FieldRow(RowGroup group) {
    base (group);
    set_redraw_on_allocate (true); // Since we draw the focus rect

    clickable = new Clickable (this);
    clickable.set_focus_on_click (true);
    clickable.clicked.connect ( () => { this.clicked (); } );
    start = 0;

    /* This should really be in class construct, but that doesn't seem to work... */
    activate_signal = GLib.Signal.lookup ("activate-row", typeof (FieldRow));
  }

  public void set_editing (bool val) {
    is_editing = val;
  }

  public void reset () {
    start = 0;
  }

  public signal void clicked ();

  public override bool focus (DirectionType direction) {
    var row_can_focus = get_can_focus ();

    /* Non-focusable rows get the standard behvaiour */
    if (!row_can_focus)
      return base.focus (direction);

    /* Focusable rows have to also support focusable children,
       which is not supported by Container.focus(), so we
       work around that. */

    bool res = false;

    bool recurse_into = false;
    if (has_focus) {
      switch (direction) {
      case DirectionType.RIGHT:
      case DirectionType.TAB_FORWARD:
	recurse_into = true;
	break;
      }
    } else if (this.get_focus_child () != null) {
      recurse_into = true;
    } else {
      switch (direction) {
      case DirectionType.LEFT:
      case DirectionType.TAB_BACKWARD:
	recurse_into = true;
	break;
      }
    }

    if (recurse_into) {
      set_can_focus (false);
      res = base.focus (direction);
      set_can_focus (true);

      if (!res && !has_focus) {
	switch (direction) {
	case DirectionType.LEFT:
	case DirectionType.TAB_BACKWARD:
	  this.grab_focus ();
	  res = true;
	  break;
	}
      }
    } else {
      if (!has_focus) {
	this.grab_focus ();
	res = true;
      }
    }

    return res;
  }

  [CCode (action_signal = true)]
  public virtual signal void activate_row () {
    clickable.activate ();
  }

  public override void realize () {
    base.realize ();
    clickable.realize_for (event_window);
  }

  public override void unrealize () {
    base.unrealize ();
    clickable.unrealize ();
  }

  public override bool draw (Cairo.Context cr) {
    Allocation allocation;
    this.get_allocation (out allocation);

    var context = this.get_style_context ();

    context.save ();
    StateFlags state = 0;
    if (show_as_editable) {
      state = clickable.state & (StateFlags.ACTIVE | StateFlags.PRELIGHT);
      if (is_editing)
	state |= StateFlags.SELECTED;
    }
    context.set_state (state);
    if (state != 0)
      Gtk.render_background (context, cr,
			     0, 0, allocation.width, allocation.height);

    if (this.has_visible_focus ())
      Gtk.render_focus (context, cr, 0, 0, allocation.width, allocation.height);

    context.restore ();

    base.draw (cr);

    return true;
  }

  public override void parent_set (Widget? old_parent) {
    if (old_parent != null) {
      var old_parent_container = (old_parent as Container);
      old_parent_container.set_focus_child.disconnect (parent_set_focus_child);
    }

    var parent_container = (this.get_parent () as Container);
    has_child_focus = parent_container != null && parent_container.get_focus_child () == this;
    if (parent_container != null)
      parent_container.set_focus_child.connect (parent_set_focus_child);
  }

  public virtual signal void lost_child_focus () {
  }

  public void parent_set_focus_child (Container container, Widget? widget) {
    var old_has_child_focus = has_child_focus;
    has_child_focus = widget == this;

    if (old_has_child_focus && !has_child_focus) {
	  Idle.add(() => {
	      if (!has_child_focus)
		lost_child_focus ();
	      return false;
	    });
    }
  }

  public void pack (Widget w) {
    this.attach (w, 1, start++);
  }

  public void pack_label (string s) {
    var l = new Label (s);
    l.set_halign (Align.START);
    l.get_style_context ().add_class ("dim-label");
    pack (l);
  }

  public void pack_header (string s) {
    var l = new Label (s);
    l.set_markup (
      "<span font='24px'>%s</span>".printf (s));
    l.set_halign (Align.START);
    pack (l);
  }

  public Grid pack_header_in_grid (string s) {
    var grid = new Grid ();
    var l = new Label (s);
    l.set_markup (
      "<span font='24px'>%s</span>".printf (s));
    l.set_halign (Align.START);
    l.set_hexpand (true);

    grid.set_halign (Align.FILL);
    grid.add (l);

    pack (grid);

    return grid;
  }

  public Label pack_text (bool wrap = false) {
    var l = new Label ("");
    if (wrap) {
      l.set_line_wrap (true);
      l.set_line_wrap_mode (Pango.WrapMode.WORD_CHAR);
    } else {
      l.set_ellipsize (Pango.EllipsizeMode.END);
    }
    l.set_halign (Align.START);
    pack (l);
    return l;
  }

  public void pack_text_detail (out Label text_label, out Label detail_label, bool wrap = false) {
    var grid = new Grid ();

    var l = new Label ("");
    l.set_hexpand (true);
    l.set_halign (Align.START);
    if (wrap) {
      l.set_line_wrap (true);
      l.set_line_wrap_mode (Pango.WrapMode.WORD_CHAR);
    } else {
      l.set_ellipsize (Pango.EllipsizeMode.END);
    }
    grid.add (l);

    text_label = l;

    l = new Label ("");
    l.set_halign (Align.END);
    l.get_style_context ().add_class ("dim-label");
    detail_label = l;

    grid.set_halign (Align.FILL);
    grid.add (l);

    pack (grid);
  }

  public void pack_widget_detail_combo (Widget w, AbstractFieldDetails detail, TypeSet type_set, out TypeCombo combo) {
    var grid = new Grid ();
    grid.set_column_spacing (16);

    grid.add (w);

    combo = new TypeCombo (type_set);
    combo.set_hexpand (false);
    combo.set_halign (Align.END);
    combo.set_active (detail);

    grid.set_halign (Align.FILL);
    grid.add (combo);

    pack (grid);
  }


  public void pack_entry_detail_combo (string text, AbstractFieldDetails detail, TypeSet type_set, out Entry entry, out TypeCombo combo) {
    entry = new Entry ();
    entry.get_style_context ().add_class ("contact-entry");
    entry.set_text (text);
    entry.set_hexpand (true);
    entry.set_halign (Align.FILL);

    pack_widget_detail_combo (entry, detail, type_set, out combo);
  }

  public Entry pack_entry (string s) {
    var e = new Entry ();
    e.get_style_context ().add_class ("contact-entry");
    e.set_text (s);
    e.set_halign (Align.FILL);
    pack (e);
    return e;
  }

  public void left_add (Widget widget) {
    this.attach (widget, 0, 0);
    widget.set_halign (Align.END);
  }

  public void right_add (Widget widget) {
    this.attach (widget, 2, 0);
    widget.set_halign (Align.START);
  }

  public Button pack_delete_button () {
    var image = new Image.from_icon_name ("user-trash-symbolic", IconSize.MENU);
    var b = new Button();
    b.add (image);
    right_add (b);
    b.set_halign (Align.CENTER);
    return b;
  }


  public virtual signal bool enter_edit_mode () {
    return false;
  }

  public virtual signal void exit_edit_mode (bool save) {
  }
}

public abstract class Contacts.FieldSet : Grid {
  public class string label_name;
  public class string detail_name;
  public class string property_name;
  public class bool is_single_value;

  public PersonaSheet sheet { get; construct; }
  public int row_nr { get; construct; }
  public bool added;
  public bool saving;
  FieldRow label_row;
  protected ArrayList<DataFieldRow> data_rows = new ArrayList<DataFieldRow>();

  public abstract void populate ();
  public abstract DataFieldRow new_field ();

  construct {
    this.set_orientation (Orientation.VERTICAL);

    label_row = new FieldRow (sheet.pane.row_group);
    this.add (label_row);
    label_row.pack_label (label_name);
  }

  public void add_to_sheet () {
    if (!added) {
      sheet.attach (this, 0, row_nr, 1, 1);
      added = true;
    }
  }

  public void remove_from_sheet () {
    if (added) {
      sheet.remove (this);
      added = false;
    }
  }

  public bool reads_param (string param) {
    return param == property_name;
  }

  public bool is_empty () {
    return get_children ().length () == 1;
  }

  public void clear () {
    foreach (var row in data_rows) {
      row.destroy ();
    }
    data_rows.clear ();
  }

  public void add_row (DataFieldRow row) {
    this.add (row);
    data_rows.add (row);

    row.clicked.connect( () => {
	sheet.pane.enter_edit_mode (row);
      });

    row.update ();
  }

  public void remove_row (DataFieldRow row) {
    this.remove (row);
    data_rows.remove (row);
  }

  public virtual Value? get_value () {
    return null;
  }

  public void save () {
    var value = get_value ();
    if (value == null)
      warning ("Unimplemented get_value()");
    else {
      saving = true;
      sheet.pane.contact.set_persona_property.begin (sheet.persona, property_name, value,
						     (obj, result) => {
	  try {
	    var contact = obj as Contact;
	    contact.set_persona_property.end (result);
	    saving = false;
	  } catch (PropertyError e1) {
	    warning ("Unable to edit property '%s': %s", property_name, e1.message);
	  } catch (Error e2) {
	    warning ("Unable to create writeable persona: %s", e2.message);
	  }

						     });
    }
  }
}

public class Contacts.TitleFieldRow : FieldRow {
  PersonaSheet sheet;
  Grid grid;

  public TitleFieldRow (PersonaSheet sheet, string text) {
    base (sheet.pane.row_group);
    this.sheet = sheet;
    set_can_focus (true);

    grid = pack_header_in_grid (text);

    if (!sheet.persona.store.is_primary_store ||
	sheet.pane.contact.individual.personas.size > 1)
      show_as_editable = true;
  }

  Button? unlink_button;
  public override bool enter_edit_mode () {
    if (!show_as_editable)
      return false;

    this.set_can_focus (false);

    this.reset ();
    var b = new Button.with_label("Unlink");
    unlink_button = b;
    b.show ();
    grid.add (b);
    b.set_halign (Align.END);
    b.clicked.connect ( () => {
	unlink_persona.begin (sheet.pane.contact, sheet.persona, (obj, result) => {
	    unlink_persona.end (result);
	  });
      });

    return true;
  }

  public override void lost_child_focus () {
    if (sheet.pane.editing_row == this)
      sheet.pane.exit_edit_mode (true);
  }

  public override void exit_edit_mode (bool save) {
    unlink_button.destroy ();

    this.set_can_focus (true);
  }
}

public abstract class Contacts.DataFieldRow : FieldRow {
  public FieldSet field_set;
  protected Button? delete_button;

  public DataFieldRow (FieldSet field_set) {
    base (field_set.sheet.pane.row_group);
    set_editable (true);
    this.field_set = field_set;
  }

  public void set_editable (bool editable) {
    this.show_as_editable = editable;
    set_can_focus (editable);
  }

  public abstract void update ();
  public virtual void pack_edit_widgets () {
  }
  public virtual bool finish_edit_widgets (bool save) {
    return false;
  }

  public override bool enter_edit_mode () {
    if (!show_as_editable)
      return false;

    this.set_can_focus (false);
    foreach (var w in this.get_children ()) {
      w.hide ();
      w.set_data ("original-widget", true);
    }

    this.reset ();
    delete_button = this.pack_delete_button ();
    delete_button.clicked.connect ( () => {
	field_set.remove_row (this);
	field_set.save ();
      });

    this.pack_edit_widgets ();

    foreach (var w in this.get_children ()) {
      if (!w.get_data<bool> ("original-widget"))
	w.show_all ();
    }

    return true;
  }

  public override void lost_child_focus () {
    if (field_set.sheet.pane.editing_row == this)
      field_set.sheet.pane.exit_edit_mode (true);
  }

  public override void exit_edit_mode (bool save) {
    if (!show_as_editable)
      return;

    var had_child_focus = this.get_focus_child () != null;

    var changed = finish_edit_widgets (save);

    delete_button = null;
    foreach (var w in this.get_children ()) {
      if (!w.get_data<bool> ("original-widget"))
	w.destroy ();
    }

    update ();
    this.show_all ();
    this.set_can_focus (true);
    if (had_child_focus)
      this.grab_focus ();

    if (save && changed)
      field_set.save ();
  }

  public void setup_entry_for_edit (Entry entry, bool grab_focus = true) {
    if (grab_focus) {
      Utils.grab_widget_later (entry);
    }
    entry.activate.connect_after ( () => {
	field_set.sheet.pane.exit_edit_mode (true);
      });
    entry.key_press_event.connect ( (key_event) => {
	if (key_event.keyval == Gdk.Key.Escape) {
	  field_set.sheet.pane.exit_edit_mode (false);
	}
	return false;
      });
  }

  public void setup_text_view_for_edit (TextView text, bool grab_focus = true) {
    if (grab_focus) {
      Utils.grab_widget_later (text);
    }
    text.key_press_event.connect ( (key_event) => {
	if (key_event.keyval == Gdk.Key.Escape) {
	  field_set.sheet.pane.exit_edit_mode (false);
	}
	return false;
      });
  }
}

class Contacts.LinkFieldRow : DataFieldRow {
  public UrlFieldDetails details;
  Label text_label;
  LinkButton uri_button;
  Entry? entry;

  public LinkFieldRow (FieldSet field_set, UrlFieldDetails details) {
    base (field_set);
    this.details = details;

    text_label = this.pack_text ();
    var image = new Image.from_icon_name ("web-browser" /* -symbolic */, IconSize.MENU);
    image.get_style_context ().add_class ("dim-label");
    uri_button = new LinkButton("");
    uri_button.remove (uri_button.get_child ());
    uri_button.set_relief (ReliefStyle.NONE);
    uri_button.add (image);
    this.right_add (uri_button);
  }

  public override void update () {
    text_label.set_text (Contact.format_uri_link_text (details));
    uri_button.set_uri (details.value);
  }

  public override void pack_edit_widgets () {
    entry = this.pack_entry (details.value);
    setup_entry_for_edit (entry);
  }

  public override bool finish_edit_widgets (bool save) {
    var old_details = details;
    var changed = entry.get_text () != details.value;
    if (save && changed)
      details = new UrlFieldDetails (entry.get_text (), old_details.parameters);
    entry = null;
    return changed;
  }
}

class Contacts.LinkFieldSet : FieldSet {
  class construct {
    label_name = _("Links");
    detail_name = _("Link");
    property_name = "urls";
  }

  public override void populate () {
    var details = sheet.persona as UrlDetails;
    if (details == null)
      return;

    var urls = details.urls;
    foreach (var url_details in urls) {
      var row = new LinkFieldRow (this, url_details);
      add_row (row);
    }
  }

  public override DataFieldRow new_field () {
    var row = new LinkFieldRow (this, new UrlFieldDetails (""));
    add_row (row);
    return row;
  }

  public override Value? get_value () {
    var details = sheet.persona as UrlDetails;
    if (details == null)
      return null;

    var new_details = new HashSet<UrlFieldDetails>();
    foreach (var row in data_rows) {
      var link_row = row as LinkFieldRow;
      new_details.add (link_row.details);
    }

    var value = Value(new_details.get_type ());
    value.set_object (new_details);

    return value;
  }
}

class Contacts.DetailedFieldRow<T> : DataFieldRow {
  public AbstractFieldDetails<string> _details;
  TypeSet type_set;
  Label text_label;
  Label detail_label;
  Entry? entry;
  TypeCombo? combo;

  public delegate AbstractFieldDetails<string> DataCreate(string s);
  DataCreate data_create;

  public T details { get { return (T)_details; } }

  public DetailedFieldRow (FieldSet field_set, AbstractFieldDetails<string> details, TypeSet type_set, owned DataCreate data_create) {
    base (field_set);
    this._details = details;
    this.type_set = type_set;
    this.data_create = (owned) data_create;
    this.pack_text_detail (out text_label, out detail_label);
  }

  public override void update () {
    text_label.set_text (_details.value);
    detail_label.set_text (type_set.format_type (_details));
  }

  public override void pack_edit_widgets () {
    this.pack_entry_detail_combo (_details.value, _details, type_set, out entry, out combo);
    setup_entry_for_edit (entry);
  }

  public override bool finish_edit_widgets (bool save) {
    var old_details = _details;
    bool changed = _details.value != entry.get_text () || combo.modified;
    if (save && changed) {
      _details = data_create (entry.get_text ());
      _details.parameters = old_details.parameters;
      combo.update_details (_details);
    }
    entry = null;
    combo = null;
    return changed;
  }
}

class Contacts.EmailFieldSet : FieldSet {
  class construct {
    label_name = _("Email");
    detail_name = _("Email");
    property_name = "email-addresses";
  }

  public override void populate () {
    var details = sheet.persona as EmailDetails;
    if (details == null)
      return;
    var emails = Contact.sort_fields<EmailFieldDetails>(details.email_addresses);
    foreach (var email in emails) {
      var row = new DetailedFieldRow<EmailFieldDetails> (this, email,TypeSet.general, (s) => { return new EmailFieldDetails (s); } );
      add_row (row);
    }
  }

  public override DataFieldRow new_field () {
    var row = new DetailedFieldRow<EmailFieldDetails> (this, new EmailFieldDetails("") ,TypeSet.general, (s) => { return new EmailFieldDetails (s); } );
    add_row (row);
    return row;
  }

  public override Value? get_value () {
    var details = sheet.persona as EmailDetails;
    if (details == null)
      return null;

    var new_details = new HashSet<EmailFieldDetails>();
    foreach (var row in data_rows) {
      var email_row = row as DetailedFieldRow<EmailFieldDetails>;
      new_details.add (email_row.details);
    }

    var value = Value(new_details.get_type ());
    value.set_object (new_details);

    return value;
  }
}

class Contacts.PhoneFieldSet : FieldSet {
  class construct {
    label_name = _("Phone");
    detail_name = _("Phone number");
    property_name = "phone-numbers";
  }
  public override void populate () {
    var details = sheet.persona as PhoneDetails;
    if (details == null)
      return;
    var phone_numbers = Contact.sort_fields<PhoneFieldDetails>(details.phone_numbers);
    foreach (var phone in phone_numbers) {
      var row = new DetailedFieldRow<PhoneFieldDetails> (this, phone,TypeSet.phone, (s) => { return new PhoneFieldDetails (s);} );
      add_row (row);
    }
  }

  public override DataFieldRow new_field () {
    var row = new DetailedFieldRow<PhoneFieldDetails> (this, new PhoneFieldDetails("") ,TypeSet.phone, (s) => { return new EmailFieldDetails (s); } );
    add_row (row);
    return row;
  }

  public override Value? get_value () {
    var details = sheet.persona as PhoneDetails;
    if (details == null)
      return null;

    var new_details = new HashSet<PhoneFieldDetails>();
    foreach (var row in data_rows) {
      var phone_row = row as DetailedFieldRow<PhoneFieldDetails>;
      new_details.add (phone_row.details);
    }

    var value = Value(new_details.get_type ());
    value.set_object (new_details);

    return value;
  }
}

class Contacts.ChatFieldRow : DataFieldRow {
  string protocol;
  ImFieldDetails details;

  Label text_label;

  public ChatFieldRow (FieldSet field_set, string protocol, ImFieldDetails details) {
    base (field_set);
    this.protocol = protocol;
    this.details = details;
    text_label = this.pack_text ();
    this.set_editable (false);
  }

  public override void update () {
    var im_persona = field_set.sheet.persona as Tpf.Persona;
    text_label.set_text (Contact.format_im_name (im_persona, protocol, details.value));
  }
}

class Contacts.ChatFieldSet : FieldSet {
  class construct {
    label_name = _("Chat");
    detail_name = _("Chat");
    property_name = "im-addresses";
  }
  public override void populate () {
    var details = sheet.persona as ImDetails;
    if (details == null)
      return;
    foreach (var protocol in details.im_addresses.get_keys ()) {
      foreach (var id in details.im_addresses[protocol]) {
	if (sheet.persona is Tpf.Persona) {
	  var row = new ChatFieldRow (this, protocol, id);
	  add_row (row);
	}
      }
    }
  }

  public override DataFieldRow new_field () {
    var row = new ChatFieldRow (this, "", new ImFieldDetails (""));
    add_row (row);
    return row;
  }
}

class Contacts.BirthdayFieldRow : DataFieldRow {
  public DateTime details;
  Label text_label;
  SpinButton? day_spin;
  SpinButton? year_spin;
  ComboBoxText? combo;

  public BirthdayFieldRow (FieldSet field_set, DateTime details) {
    base (field_set);
    this.details = details;

    text_label = this.pack_text ();
    var image = new Image.from_icon_name ("preferences-system-date-and-time-symbolic", IconSize.MENU);
    image.get_style_context ().add_class ("dim-label");
    var button = new Button();
    button.set_relief (ReliefStyle.NONE);
    button.add (image);
    this.right_add (button);
  }

  public override void update () {
    text_label.set_text (details.to_local ().format ("%x"));
  }

  public override void pack_edit_widgets () {
    var bday = details.to_local ();
    var grid = new Grid ();
    grid.set_column_spacing (16);

    day_spin = new SpinButton.with_range (0, 31, 1);
    day_spin.set_digits (0);
    day_spin.numeric = true;
    day_spin.set_value ((double)bday.get_day_of_month ());
    grid.add (day_spin);

    setup_entry_for_edit (day_spin);

    combo = new ComboBoxText ();
    combo.append_text (_("January"));
    combo.append_text (_("February"));
    combo.append_text (_("March"));
    combo.append_text (_("April"));
    combo.append_text (_("May"));
    combo.append_text (_("June"));
    combo.append_text (_("July"));
    combo.append_text (_("August"));
    combo.append_text (_("September"));
    combo.append_text (_("October"));
    combo.append_text (_("November"));
    combo.append_text (_("December"));
    combo.set_active (bday.get_month () - 1);
    combo.get_style_context ().add_class ("contact-combo");
    grid.add (combo);

    year_spin = new SpinButton.with_range (1800, 3000, 1);
    year_spin.set_digits (0);
    year_spin.numeric = true;
    year_spin.set_value ((double)bday.get_year ());
    grid.add (year_spin);

    setup_entry_for_edit (year_spin, false);

    pack (grid);
  }

  public override bool finish_edit_widgets (bool save) {
    var old_details = details;

    var bday = new DateTime.local ((int)year_spin.get_value (),
				   combo.get_active () + 1,
				   (int)day_spin.get_value (),
				   0, 0, 0);
    bday = bday.to_utc ();

    var changed = !bday.equal (old_details);
    if (save && changed)
      details = bday;

    combo = null;
    day_spin = null;
    year_spin = null;
    return changed;
  }
}

class Contacts.BirthdayFieldSet : FieldSet {
  class construct {
    label_name = _("Birthday");
    detail_name = _("Birthday");
    property_name = "birthday";
    is_single_value = true;
  }
  public override void populate () {
    var details = sheet.persona as BirthdayDetails;
    if (details == null)
      return;

    DateTime? bday = details.birthday;
    if (bday != null) {
      var row = new BirthdayFieldRow (this, bday);
      add_row (row);
    }
  }

  public override DataFieldRow new_field () {
    var row = new BirthdayFieldRow (this, new DateTime.now_utc ());
    add_row (row);
    return row;
  }

  public override Value? get_value () {
    var details = sheet.persona as BirthdayDetails;
    if (details == null)
      return null;

    DateTime? new_details = null;
    foreach (var row in data_rows) {
      var bday_row = row as BirthdayFieldRow;
      new_details = bday_row.details;
    }

    var value = Value(typeof (DateTime));
    value.set_boxed (new_details);

    return value;
  }
}

class Contacts.StringFieldRow : DataFieldRow {
  public string value;
  Label text_label;
  Entry? entry;

  public StringFieldRow (FieldSet field_set, string value) {
    base (field_set);
    this.value = value;

    text_label = this.pack_text ();
  }

  public override void update () {
    text_label.set_text (value);
  }

  public override void pack_edit_widgets () {
    entry = this.pack_entry (value);
    setup_entry_for_edit (entry);
  }

  public override bool finish_edit_widgets (bool save) {
    var changed = entry.get_text () != value;
    if (save && changed)
      value = entry.get_text ();
    entry = null;
    return changed;
  }
}

class Contacts.NicknameFieldSet : FieldSet {
  class construct {
    label_name = _("Nickname");
    detail_name = _("Nickname");
    property_name = "nickname";
    is_single_value = true;
  }
  public override void populate () {
    var details = sheet.persona as NameDetails;
    if (details == null)
      return;

    if (is_set (details.nickname)) {
      var row = new StringFieldRow (this, details.nickname);
      add_row (row);
    }
  }

  public override DataFieldRow new_field () {
    var row = new StringFieldRow (this, "");
    add_row (row);
    return row;
  }

  public override Value? get_value () {
    var details = sheet.persona as NameDetails;
    if (details == null)
      return null;

    var value = Value(typeof (string));
    value.set_string ("");
    foreach (var row in data_rows) {
      var string_row = row as StringFieldRow;
      value.set_string (string_row.value);
    }

    return value;
  }
}

class Contacts.NoteFieldRow : DataFieldRow {
  public NoteFieldDetails details;
  Label text_label;
  TextView? text;

  public NoteFieldRow (FieldSet field_set, NoteFieldDetails details) {
    base (field_set);
    this.details = details;

    text_label = this.pack_text (true);
  }

  public override void update () {
    text_label.set_text (details.value);
  }

  public override void pack_edit_widgets () {
    text = new TextView ();
    text.get_style_context ().add_class ("contact-entry");
    text.set_hexpand (true);
    text.set_vexpand (true);
    var scrolled = new ScrolledWindow (null, null);
    scrolled.set_shadow_type (ShadowType.OUT);
    scrolled.add_with_viewport (text);

    pack (scrolled);

    delete_button.set_valign (Align.START);

    text.get_buffer ().set_text (details.value);
    text.get_buffer ().set_modified (false);

    setup_text_view_for_edit (text);
  }

  public override bool finish_edit_widgets (bool save) {
    var old_details = details;
    var changed = text.get_buffer (). get_modified ();
    if (save && changed) {
	TextIter start, end;
	text.get_buffer ().get_start_iter (out start);
	text.get_buffer ().get_end_iter (out end);
	var value = text.get_buffer ().get_text (start, end, true);
	details = new NoteFieldDetails (value, old_details.parameters);
    }
    text = null;

    return changed;
  }
}

class Contacts.NoteFieldSet : FieldSet {
  class construct {
    label_name = _("Note");
    detail_name = _("Note");
    property_name = "notes";
    is_single_value = true;
  }
  public override void populate () {
    var details = sheet.persona as NoteDetails;
    if (details == null)
      return;

    foreach (var note in details.notes) {
      var row = new NoteFieldRow (this, note);
      add_row (row);
    }
  }

  public override DataFieldRow new_field () {
    var row = new NoteFieldRow (this, new NoteFieldDetails (""));
    add_row (row);
    return row;
  }

  public override Value? get_value () {
    var details = sheet.persona as NoteDetails;
    if (details == null)
      return null;

    var new_details = new HashSet<NoteFieldDetails>();
    foreach (var row in data_rows) {
      var note_row = row as NoteFieldRow;
      new_details.add (note_row.details);
    }

    var value = Value(new_details.get_type ());
    value.set_object (new_details);

    return value;
  }
}

class Contacts.AddressFieldRow : DataFieldRow {
  public PostalAddressFieldDetails details;
  Label? text_label[8];
  Label detail_label;
  Entry? entry[7];
  TypeCombo? combo;

  public AddressFieldRow (FieldSet field_set, PostalAddressFieldDetails details) {
    base (field_set);
    this.details = details;
    this.pack_text_detail (out text_label[0], out detail_label);
    for (int i = 1; i < text_label.length; i++) {
      text_label[i] = this.pack_text (true);
    }
  }

  public override void update () {
    detail_label.set_text (TypeSet.general.format_type (details));

    string[] strs = Contact.format_address (details.value);
    for (int i = 0; i < text_label.length; i++) {
      if (i < strs.length && strs[i] != null) {
	text_label[i].set_text (strs[i]);
	text_label[i].show ();
	text_label[i].set_no_show_all (false);
      } else {
	text_label[i].hide ();
	text_label[i].set_no_show_all (true);
      }
    }
  }

  public override void pack_edit_widgets () {

    var grid = new Box (Orientation.VERTICAL, 0);
    grid.set_hexpand (true);
    grid.set_halign (Align.FILL);

    for (int i = 0; i < entry.length; i++) {
      string postal_part;
      details.value.get (Contact.postal_element_props[i], out postal_part);
      entry[i] = new Entry ();
      entry[i].set_hexpand (true);
      if (postal_part != null)
	entry[i].set_text (postal_part);
      entry[i].set ("placeholder-text", Contact.postal_element_names[i]);
      entry[i].get_style_context ().add_class ("contact-entry");
      entry[i].get_style_context ().add_class ("contact-postal-entry");
      grid.add (entry[i]);

      setup_entry_for_edit (entry[i], i == 0);
    }

    this.pack_widget_detail_combo (grid, details, TypeSet.general, out combo);
    delete_button.set_valign (Align.START);
    var size_group = new SizeGroup (SizeGroupMode.VERTICAL);
    size_group.add_widget (delete_button);
    size_group.add_widget (combo);

  }

  public override bool finish_edit_widgets (bool save) {
    var old_details = details;

    bool changed = combo.modified;
    for (int i = 0; i < entry.length; i++) {
      string postal_part;
      details.value.get (Contact.postal_element_props[i], out postal_part);
      if (entry[i].get_text () != postal_part) {
	changed = true;
	break;
      }
    }

    if (save && changed) {
      var new_value = new PostalAddress (details.value.po_box,
					 details.value.extension,
					 details.value.street,
					 details.value.locality,
					 details.value.region,
					 details.value.postal_code,
					 details.value.country,
					 details.value.address_format,
					 details.value.uid);
      for (int i = 0; i < entry.length; i++)
	new_value.set (Contact.postal_element_props[i], entry[i].get_text ());
      details = new PostalAddressFieldDetails(new_value, old_details.parameters);
      combo.update_details (details);
    }

    for (int i = 0; i < entry.length; i++)
      entry[i] = null;
    combo = null;

    return changed;
  }
}

class Contacts.AddressFieldSet : FieldSet {
  class construct {
    label_name = _("Addresses");
    detail_name = _("Address");
    property_name = "postal-addresses";
  }
  public override void populate () {
    var details = sheet.persona as PostalAddressDetails;
    if (details == null)
      return;

    foreach (var addr in details.postal_addresses) {
      var row = new AddressFieldRow (this, addr);
      add_row (row);
    }
  }

  public override DataFieldRow new_field () {
    var row = new AddressFieldRow (this,
				   new PostalAddressFieldDetails (
				     new PostalAddress (null,
							null,
							null,
							null,
							null,
							null,
							null,
							null,
							null)));
    add_row (row);
    return row;
  }

  public override Value? get_value () {
    var details = sheet.persona as PostalAddressDetails;
    if (details == null)
      return null;

    var new_details = new HashSet<PostalAddressFieldDetails>();
    foreach (var row in data_rows) {
      var addr_row = row as AddressFieldRow;
      new_details.add (addr_row.details);
    }

    var value = Value(new_details.get_type ());
    value.set_object (new_details);

    return value;
  }
}

public class Contacts.PersonaSheet : Grid {
  public ContactPane pane;
  public Persona persona;
  FieldRow header;
  FieldRow footer;

  static Type[] field_set_types = {
    typeof(LinkFieldSet),
    typeof(EmailFieldSet),
    typeof(PhoneFieldSet),
    typeof(ChatFieldSet),
    typeof(BirthdayFieldSet),
    typeof(NicknameFieldSet),
    typeof(AddressFieldSet),
    typeof(NoteFieldSet)
    /* More:
       company/department/profession/title/manager/assistant
    */
  };
  FieldSet? field_sets[8]; // This is really the size of field_set_types

  public PersonaSheet(ContactPane pane, Persona persona) {
    assert (field_sets.length == field_set_types.length);

    this.pane = pane;
    this.persona = persona;

    this.set_orientation (Orientation.VERTICAL);
    this.set_row_spacing (16);

    int row_nr = 0;

    bool editable =
      Contact.persona_has_writable_property (persona, "email-addresses") &&
      Contact.persona_has_writable_property (persona, "phone-numbers") &&
      Contact.persona_has_writable_property (persona, "postal-addresses");

    if (!persona.store.is_primary_store) {
      header = new TitleFieldRow (this, Contact.format_persona_store_name_for_contact (persona.store));
      this.attach (header, 0, row_nr++, 1, 1);

      header.clicked.connect ( () => {
	  this.pane.enter_edit_mode (header);
	});

      if (!editable) {
	var image = new Image.from_icon_name ("changes-prevent-symbolic", IconSize.MENU);

	image.get_style_context ().add_class ("dim-label");
	image.set_valign (Align.CENTER);
	header.left_add (image);
      }
    }

    for (int i = 0; i < field_set_types.length; i++) {
      var field_set = (FieldSet) Object.new(field_set_types[i], sheet: this, row_nr: row_nr++);
      field_sets[i] = field_set;

      field_set.populate ();
      if (!field_set.is_empty ())
	field_set.add_to_sheet ();
    }

    if (editable) {
      footer = new FieldRow (pane.row_group);
      this.attach (footer, 0, row_nr++, 1, 1);

      var b = new Button.with_label ("Add detail...");
      b.set_halign (Align.START);
      b.clicked.connect (add_detail);
      footer.pack (b);
    }

    persona.notify.connect(persona_notify_cb);
  }

  ~PersonaSheet() {
    persona.notify.disconnect(persona_notify_cb);
  }

  private void add_detail () {
    var title = _("Add contact data to %s\n").printf (pane.contact.display_name);
    var dialog = new Dialog.with_buttons ("",
					  (Window) pane.get_toplevel (),
					  DialogFlags.MODAL | DialogFlags.DESTROY_WITH_PARENT,
					  Stock.CANCEL, ResponseType.CANCEL,
					  Stock.OK, ResponseType.OK);

    dialog.set_resizable (false);
    dialog.set_default_response (ResponseType.OK);

    var tree_view = new TreeView ();
    var store = new ListStore (2, typeof (string), typeof (FieldSet));
    tree_view.set_model (store);
    tree_view.set_headers_visible (false);
    tree_view.get_selection ().set_mode (SelectionMode.BROWSE);

    var column = new Gtk.TreeViewColumn ();
    tree_view.append_column (column);

    var renderer = new Gtk.CellRendererText ();
    column.pack_start (renderer, false);
    column.add_attribute (renderer, "text", 0);

    var scrolled = new ScrolledWindow(null, null);
    scrolled.set_size_request (340, 300);
    scrolled.set_policy (PolicyType.NEVER, PolicyType.AUTOMATIC);
    scrolled.set_vexpand (true);
    scrolled.set_hexpand (true);
    scrolled.set_shadow_type (ShadowType.IN);
    scrolled.add (tree_view);

    var grid = new Grid ();
    grid.set_orientation (Orientation.VERTICAL);
    grid.set_row_spacing (6);

    var l = new Label (title);
    l.set_halign (Align.START);

    grid.add (l);
    grid.add (scrolled);

    var box = dialog.get_content_area () as Box;
    box.pack_start (grid, true, true, 0);
    grid.set_border_width (6);

    TreeIter iter;

    for (int i = 0; i < field_set_types.length; i++) {
      var field_set = field_sets[i];
      if (!(field_set is ChatFieldSet) &&
	  Contact.persona_has_writable_property (persona, field_set.property_name) &&
	  (field_set.is_empty () || !field_set.is_single_value)) {
	store.append (out iter);
	store.set (iter, 0, field_set.detail_name, 1, field_set);
      }
    }

    dialog.show_all ();
    dialog.response.connect ( (response) => {
	if (response == ResponseType.OK) {
	  FieldSet field_set;
	  TreeIter iter2;

	  if (tree_view.get_selection() .get_selected (null, out iter2)) {
	    store.get (iter2, 1, out field_set);

	    var row = field_set.new_field ();
	    field_set.show_all ();
	    field_set.add_to_sheet ();
	    pane.enter_edit_mode (row);
	  }
	}
	dialog.destroy ();
      });
  }

  private void persona_notify_cb (ParamSpec pspec) {
    var name = pspec.get_name ();
    foreach (var field_set in field_sets) {
      if (field_set.reads_param (name) && !field_set.saving) {
	field_set.clear ();
	field_set.populate ();

	if (field_set.is_empty ())
	  field_set.remove_from_sheet ();
	else {
	  field_set.show_all ();
	  field_set.add_to_sheet ();
	}
      }
    }
  }
}


public class Contacts.ContactPane : ScrolledWindow {
  private Store contacts_store;
  private Grid top_grid;
  private FieldRow card_row;
  private Grid card_grid;
  private Grid personas_grid;
  public RowGroup row_group;
  public FieldRow? editing_row;

  public Button email_button;
  public Button chat_button;
  public Button call_button;
  public Gtk.Menu context_menu;
  private Gtk.MenuItem link_menu_item;
  private Gtk.MenuItem delete_menu_item;

  public Contact? contact;

  const int PROFILE_SIZE = 128;

 private async Persona? set_persona_property (Persona persona,
					       string property_name,
					       Value value) throws GLib.Error, PropertyError {
    if (persona is FakePersona) {
      var fake = persona as FakePersona;
      return yield fake.make_real_and_set (property_name, value);
    } else {
      persona.set_data ("contacts-unedited", true);
      yield Contact.set_persona_property (persona, property_name, value);
      return null;
    }
  }

  /* Tries to set the property on all persons that have it writeable, and
   * if none, creates a new persona and writes to it, returning the new
   * persona.
   */
  private async Persona? set_individual_property (Contact contact,
						  string property_name,
						  Value value) throws GLib.Error, PropertyError {
    bool did_set = false;
    // Need to make a copy here as it could change during the yields
    var personas_copy = contact.individual.personas.to_array ();
    foreach (var p in personas_copy) {
      if (property_name in p.writeable_properties) {
	did_set = true;
	yield Contact.set_persona_property (p, property_name, value);
      }
    }

    if (!did_set) {
      var fake = new FakePersona (contact);
      return yield fake.make_real_and_set (property_name, value);
    }
    return null;
  }

  public void update_card () {
    foreach (var w in card_grid.get_children ()) {
      w.destroy ();
    }

    if (contact == null)
      return;

    var menu = new AvatarMenu (contact);
    menu.icon_set.connect ( (icon) => {
	Value v = Value (icon.get_type ());
	v.set_object (icon);
	set_individual_property.begin (contact,
				       "avatar", v, () => {
				       });
      });

    var image_frame = new ContactFrame (PROFILE_SIZE, menu);
    contact.keep_widget_uptodate (image_frame,  (w) => {
	(w as ContactFrame).set_image (contact.individual, contact);
      });

    card_grid.attach (image_frame,  0, 0, 1, 3);
    card_grid.set_column_spacing (16);

    var l = new Label (null);
    l.set_hexpand (true);
    l.set_halign (Align.START);
    l.set_valign (Align.START);
    l.set_margin_top (4);
    l.set_ellipsize (Pango.EllipsizeMode.END);
    l.xalign = 0.0f;

    contact.keep_widget_uptodate (l,  (w) => {
	(w as Label).set_markup ("<span font='24'>" + contact.display_name + "</span>");
      });

    var event_box = new EventBox ();
    event_box.set_margin_top (4);
    event_box.set_visible_window (false);

    var clickable = new Clickable (event_box);
    event_box.realize.connect_after ( (event) => {
	Gdk.Window window = null;
	foreach (var win in event_box.get_window ().get_children ()) {
	  Widget *w = null;
	  win.get_user_data (out w);
	  if (w == event_box) {
	    window = win;
	  }
	}
	clickable.realize_for (window);
      });
    event_box.unrealize.connect_after ( (event) => {
	clickable.unrealize ();
      });
    clickable.clicked.connect ( () => {
	this.enter_edit_mode (card_row);
      });

    var id1 = card_row.enter_edit_mode.connect_after ( () => {
	event_box.remove (l);
	var entry = new Entry ();
	entry.set_text (contact.display_name);
	entry.set_hexpand (true);
	entry.show ();
	entry.override_font (Pango.FontDescription.from_string ("24px"));
	event_box.add (entry);
	Utils.grab_widget_later (entry);

	entry.activate.connect_after ( () => {
	    exit_edit_mode (true);
	  });
	entry.key_press_event.connect ( (key_event) => {
	    if (key_event.keyval == Gdk.Key.Escape) {
	      exit_edit_mode (false);
	    }
	    return false;
	  });

	return true;
      });

    var id2 = card_row.exit_edit_mode.connect ( (save) => {
	Entry entry = event_box.get_child () as Entry;
	bool changed = entry.get_text () != contact.display_name;

	if (save && changed) {
	  // Things look better if we update immediately, rather than after the setting has
	  // been applied
	  l.set_markup ("<span font='24'>" + entry.get_text () + "</span>");

	  Value v = Value (typeof (string));
	  v.set_string (entry.get_text ());
	  set_individual_property.begin (contact,
					 "full-name", v,
					 (obj, result) => {
					   try {
					     var p = set_individual_property.end (result);
					   } catch (Error e) {
					     warning ("Unable to create writeable persona: %s", e.message);
					   }
					 });
	}

	event_box.remove (entry);
	event_box.add (l);
      });

    var id3 = card_row.lost_child_focus.connect ( () => {
	if (editing_row == card_row)
	  exit_edit_mode (true);
      });

    event_box.destroy.connect ( () => {
	card_row.disconnect (id1);
	card_row.disconnect (id2);
	card_row.disconnect (id3);
      });

    event_box.add (l);
    card_grid.attach (event_box,  1, 0, 1, 1);

    var merged_presence = contact.create_merged_presence_widget ();
    merged_presence.set_halign (Align.START);
    merged_presence.set_valign (Align.START);
    merged_presence.set_vexpand (true);
    card_grid.attach (merged_presence,  1, 1, 1, 1);

    var box = new Box (Orientation.HORIZONTAL, 0);
    box.set_margin_bottom (4 + 8);
    box.set_halign (Align.START);

    box.get_style_context ().add_class ("linked");
    var image = new Image.from_icon_name ("mail-unread-symbolic", IconSize.MENU);
    var b = new Button ();
    b.add (image);
    box.pack_start (b, true, true, 0);
    email_button = b;
    email_button.set_size_request (82, 32);
    email_button.clicked.connect (send_email);

    image = new Image.from_icon_name ("user-available-symbolic", IconSize.MENU);
    b = new Button ();
    b.add (image);
    box.pack_start (b, true, true, 0);
    chat_button = b;
    chat_button.set_size_request (82, 32);
    chat_button.clicked.connect (start_chat);

    image = new Image.from_icon_name ("call-start-symbolic", IconSize.MENU);
    b = new Button ();
    b.add (image);
    box.pack_start (b, true, true, 0);
    call_button = b;
    call_button.set_size_request (82, 32);
    call_button.clicked.connect (start_call);

    card_grid.attach (box,  1, 2, 1, 1);

    card_grid.show_all ();

    update_buttons ();
  }

  public void update_buttons () {
    if (contact == null)
      return;

    var emails = contact.individual.email_addresses;
    email_button.set_sensitive (!emails.is_empty);

    var ims = contact.individual.im_addresses;
    var im_keys = ims.get_keys ();
    bool found_im = false;
    bool callable = false;
    PresenceType max_presence = 0;
    foreach (var protocol in im_keys) {
      foreach (var id in ims[protocol]) {
	var im_persona = contact.find_im_persona (protocol, id.value);
	if (im_persona != null) {
	  var type = im_persona.presence_type;
	  if (type != PresenceType.UNSET &&
	      type != PresenceType.ERROR &&
	      type != PresenceType.OFFLINE) {
	    found_im = true;
	    if (type > max_presence)
	      max_presence = type;
	  }
	}

	if (contact.is_callable (protocol, id.value) != null)
	  callable = true;
      }
    }

    if (contacts_store.can_call) {
      var phones = contact.individual.phone_numbers;
      if (!phones.is_empty)
	callable = true;
    }

    string icon;
    if (found_im)
      icon = Contact.presence_to_icon_symbolic (max_presence);
    else
      icon = "user-available-symbolic";
    (chat_button.get_child () as Image).set_from_icon_name (icon, IconSize.MENU);
    chat_button.set_sensitive (found_im);

    if (callable)
      call_button.show ();
    else
      call_button.hide ();
  }

  public void update_personas () {
    foreach (var w in personas_grid.get_children ()) {
      w.destroy ();
    }

    if (contact == null)
      return;

    var personas = contact.get_personas_for_display ();

    foreach (var p in personas) {
      var sheet = new PersonaSheet(this, p);
      personas_grid.add (sheet);
    }

    personas_grid.show_all ();
  }

  public void show_contact (Contact? new_contact, bool edit=false) {
    if (contact == new_contact)
      return;

    if (contact != null && editing_row != null)
      exit_edit_mode (true);

    if (contact != null) {
      contact.personas_changed.disconnect (personas_changed_cb);
      contact.changed.disconnect (contact_changed_cb);
    }

    contact = new_contact;

    update_card ();
    update_personas ();

    bool can_remove = false;
    bool can_remove_all = true;

    if (contact != null) {
      contact.personas_changed.connect (personas_changed_cb);
      contact.changed.connect (contact_changed_cb);

      foreach (var p in contact.individual.personas) {
	if (p.store.can_remove_personas == MaybeBool.TRUE &&
	    !(p is Tpf.Persona)) {
	  can_remove = true;
	} else {
	  can_remove_all = false;
	}
      }
    }

    can_remove_all = can_remove && can_remove_all;

    delete_menu_item.set_sensitive (can_remove_all);
    link_menu_item.set_sensitive (contact != null);
  }

  private void personas_changed_cb (Contact contact) {
    update_personas ();
  }

  private void contact_changed_cb (Contact contact) {
    update_buttons ();
  }

  public void enter_edit_mode (FieldRow row) {
    if (editing_row != row) {
      exit_edit_mode (true);
      editing_row = null;
      if (row.enter_edit_mode ()) {
	editing_row = row;
	editing_row.set_editing (true);
      }
    }
  }

  public void exit_edit_mode (bool save) {
    if (editing_row != null) {
      editing_row.exit_edit_mode (save);
      editing_row.set_editing (false);
    }

    editing_row = null;
  }

  private Dialog pick_one_dialog (string title, TreeModel model, out TreeSelection selection) {
    var dialog = new Dialog.with_buttons (title,
					  (Window) this.get_toplevel (),
					  DialogFlags.MODAL | DialogFlags.DESTROY_WITH_PARENT,
					  Stock.CANCEL, ResponseType.CANCEL,
					  Stock.OK, ResponseType.OK);

    dialog.set_resizable (false);
    dialog.set_default_response (ResponseType.OK);

    var tree_view = new TreeView ();
    tree_view.set_model (model);
    tree_view.set_headers_visible (false);
    tree_view.get_selection ().set_mode (SelectionMode.BROWSE);

    var column = new Gtk.TreeViewColumn ();
    tree_view.append_column (column);

    var renderer = new Gtk.CellRendererText ();
    column.pack_start (renderer, false);
    column.add_attribute (renderer, "text", 0);

    var scrolled = new ScrolledWindow(null, null);
    scrolled.set_size_request (340, 300);
    scrolled.set_policy (PolicyType.NEVER, PolicyType.AUTOMATIC);
    scrolled.set_vexpand (true);
    scrolled.set_hexpand (true);
    scrolled.set_shadow_type (ShadowType.IN);
    scrolled.add (tree_view);

    var grid = new Grid ();
    grid.set_orientation (Orientation.VERTICAL);
    grid.set_row_spacing (6);

    var l = new Label (title);
    l.set_halign (Align.START);

    grid.add (l);
    grid.add (scrolled);

    var box = dialog.get_content_area () as Box;
    box.pack_start (grid, true, true, 0);
    grid.set_border_width (6);

    dialog.show_all ();

    selection = tree_view.get_selection ();
    return dialog;
  }


  public void send_email () {
    var emails = contact.individual.email_addresses;
    if (emails.is_empty)
      return;
    if (emails.size == 1) {
      foreach (var email in emails) {
	var email_addr = email.value;
	Utils.compose_mail (email_addr);
      }
    } else {
      TreeIter iter;

      var store = new ListStore (1, typeof (string));
      foreach (var email in emails) {
	var email_addr = email.value;
	store.append (out iter);
	store.set (iter, 0, email_addr);
      }

      TreeSelection selection;
      var dialog = pick_one_dialog (_("Select email address"), store, out selection);
      dialog.response.connect ( (response) => {
	  if (response == ResponseType.OK) {
	    string email2;
	    TreeIter iter2;

	    if (selection.get_selected (null, out iter2)) {
	      store.get (iter2, 0, out email2);
	      Utils.compose_mail (email2);
	    }
	  }
	  dialog.destroy ();
	});
    }
  }

  struct CallValue {
    string phone_nr;
    string protocol;
    string id;
    string name;
  }

  public void start_call () {
    var ims = contact.individual.im_addresses;
    var im_keys = ims.get_keys ();
    var call_targets = new ArrayList<CallValue?>();
    foreach (var protocol in im_keys) {
      foreach (var id in ims[protocol]) {
	var im_persona = contact.find_im_persona (protocol, id.value);
	if (im_persona != null &&
	    contact.is_callable (protocol, id.value) != null) {
	  var type = im_persona.presence_type;
	  if (type != PresenceType.UNSET &&
	      type != PresenceType.ERROR &&
	      type != PresenceType.OFFLINE) {
	    CallValue? value = { null, protocol, id.value, Contact.format_im_name (im_persona, protocol, id.value) };
	    call_targets.add (value);
	  }
	}
      }
    }

    if (contacts_store.can_call) {
      var phones = contact.individual.phone_numbers;
      foreach (var phone in phones) {
	CallValue? value = { phone.value, null, null, phone.value };
	call_targets.add (value);
      }
    }


    if (call_targets.is_empty)
      return;

    if (call_targets.size == 1) {
      foreach (var value in call_targets) {
	if (value.phone_nr != null)
	  Utils.start_call (value.phone_nr, this.contacts_store.calling_accounts);
	else {
	  var account = contact.is_callable (value.protocol, value.id);
	  Utils.start_call_with_account (value.id, account);
	}
      }
    } else {
      var store = new ListStore (2, typeof (string), typeof (CallValue?));
      foreach (var value in call_targets) {
	TreeIter iter;
	store.append (out iter);
	store.set (iter, 0, value.name, 1, value);
      }
      TreeSelection selection;
      var dialog = pick_one_dialog (_("Select what to call"), store, out selection);
      dialog.response.connect ( (response) => {
	  if (response == ResponseType.OK) {
	    CallValue? value2;
	    TreeIter iter2;

	    if (selection.get_selected (null, out iter2)) {
	      store.get (iter2, 1, out value2);
	      if (value2.phone_nr != null)
		Utils.start_call (value2.phone_nr, this.contacts_store.calling_accounts);
	      else {
		var account = contact.is_callable (value2.protocol, value2.id);
		Utils.start_call_with_account (value2.id, account);
	      }
	    }
	  }
	  dialog.destroy ();
	});
    }
  }

  struct ImValue {
    string protocol;
    string id;
    string name;
  }

  public void start_chat () {
    var ims = contact.individual.im_addresses;
    var im_keys = ims.get_keys ();
    var online_personas = new ArrayList<ImValue?>();
    if (contact != null) {
      foreach (var protocol in im_keys) {
	foreach (var id in ims[protocol]) {
	  var im_persona = contact.find_im_persona (protocol, id.value);
	  if (im_persona != null) {
	    var type = im_persona.presence_type;
	    if (type != PresenceType.UNSET &&
		type != PresenceType.ERROR &&
		type != PresenceType.OFFLINE) {
	      ImValue? value = { protocol, id.value, Contact.format_im_name (im_persona, protocol, id.value) };
	      online_personas.add (value);
	    }
	  }
	}
      }
    }

    if (online_personas.is_empty)
      return;

    if (online_personas.size == 1) {
      foreach (var value in online_personas) {
	Utils.start_chat (contact, value.protocol, value.id);
      }
    } else {
      var store = new ListStore (2, typeof (string), typeof (ImValue?));
      foreach (var value in online_personas) {
	TreeIter iter;
	store.append (out iter);
	store.set (iter, 0, value.name, 1, value);
      }
      TreeSelection selection;
      var dialog = pick_one_dialog (_("Select chat account"), store, out selection);
      dialog.response.connect ( (response) => {
	  if (response == ResponseType.OK) {
	    ImValue? value2;
	    TreeIter iter2;

	    if (selection.get_selected (null, out iter2)) {
	      store.get (iter2, 1, out value2);
	      Utils.start_chat (contact, value2.protocol, value2.id);
	    }
	  }
	  dialog.destroy ();
	});
    }
  }

  public ContactPane (Store contacts_store) {
    this.get_style_context ().add_class ("contacts-content");
    this.set_shadow_type (ShadowType.IN);

    this.contacts_store = contacts_store;
    row_group = new RowGroup(3);
    row_group.set_column_min_width (0, 32);
    row_group.set_column_min_width (1, 400);
    row_group.set_column_max_width (1, 450);
    row_group.set_column_min_width (2, 32);
    row_group.set_column_spacing (0, 8);
    row_group.set_column_spacing (1, 8);

    this.set_hexpand (true);
    this.set_vexpand (true);
    this.set_policy (PolicyType.NEVER, PolicyType.AUTOMATIC);

    top_grid = new Grid ();
    top_grid.set_orientation (Orientation.VERTICAL);
    top_grid.set_margin_top (10);
    top_grid.set_margin_bottom (10);
    top_grid.set_row_spacing (20);
    this.add_with_viewport (top_grid);
    top_grid.set_focus_vadjustment (this.get_vadjustment ());

    var viewport = this.get_child ();
    viewport.button_press_event.connect ( (event) => {
	if (event.button == 3) {
	  context_menu.popup (null, null, null, event.button, event.time);
	  return true;
	}
	return false;
      });

    this.get_child().get_style_context ().add_class ("contacts-main-view");
    this.get_child().get_style_context ().add_class ("view");

    card_row = new FieldRow (row_group);
    top_grid.add (card_row);
    card_grid = new Grid ();
    card_grid.set_vexpand (false);
    card_row.pack (card_grid);

    personas_grid = new Grid ();
    personas_grid.set_orientation (Orientation.VERTICAL);
    personas_grid.set_row_spacing (40);
    top_grid.add (personas_grid);

    top_grid.show_all ();

    context_menu = new Gtk.Menu ();
    link_menu_item = Utils.add_menu_item (context_menu,_("Add/Remove Linked Contacts..."));
    link_menu_item.activate.connect (link_contact);
    link_menu_item.set_sensitive (false);
    //Utils.add_menu_item (context_menu,_("Send..."));
    delete_menu_item = Utils.add_menu_item (context_menu,_("Delete"));
    delete_menu_item.activate.connect (delete_contact);
    delete_menu_item.set_sensitive (false);
  }

  void link_contact () {
    var dialog = new LinkDialog (contact);
    dialog.show_all ();
  }

  public signal void will_delete (Contact contact);

  void delete_contact () {
    if (contact != null) {
      contact.hide ();
      this.will_delete (contact);
    }
  }
}