File: gmDemographicsWidgets.py

package info (click to toggle)
gnumed-client 1.4.12%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 164,192 kB
  • ctags: 168,531
  • sloc: python: 88,281; sh: 765; makefile: 37
file content (1840 lines) | stat: -rw-r--r-- 62,056 bytes parent folder | download
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
"""Widgets dealing with patient demographics."""
#============================================================
__author__ = "R.Terry, SJ Tan, I Haywood, Carlos Moro <cfmoro1976@yahoo.es>"
__license__ = 'GPL v2 or later (details at http://www.gnu.org)'

# standard library
import sys
import sys
import codecs
import re as regex
import logging
import os
import datetime as pydt


import wx
import wx.wizard
import wx.lib.imagebrowser as wx_imagebrowser
import wx.lib.statbmp as wx_genstatbmp


# GNUmed specific
if __name__ == '__main__':
	sys.path.insert(0, '../../')
from Gnumed.pycommon import gmDispatcher
from Gnumed.pycommon import gmI18N
from Gnumed.pycommon import gmMatchProvider
from Gnumed.pycommon import gmPG2
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmCfg
from Gnumed.pycommon import gmDateTime
from Gnumed.pycommon import gmShellAPI
from Gnumed.pycommon import gmNetworkTools

from Gnumed.business import gmDemographicRecord
from Gnumed.business import gmPersonSearch
from Gnumed.business import gmPerson
from Gnumed.business import gmStaff

from Gnumed.wxpython import gmPhraseWheel
from Gnumed.wxpython import gmRegetMixin
from Gnumed.wxpython import gmAuthWidgets
from Gnumed.wxpython import gmPersonContactWidgets
from Gnumed.wxpython import gmEditArea
from Gnumed.wxpython import gmListWidgets
from Gnumed.wxpython import gmDateTimeInput
from Gnumed.wxpython import gmDataMiningWidgets
from Gnumed.wxpython import gmGuiHelpers


# constant defs
_log = logging.getLogger('gm.ui')


try:
	_('dummy-no-need-to-translate-but-make-epydoc-happy')
except NameError:
	_ = lambda x:x

#============================================================
# image tags related widgets
#------------------------------------------------------------
def edit_tag_image(parent=None, tag_image=None, single_entry=False):
	if tag_image is not None:
		if tag_image['is_in_use']:
			gmGuiHelpers.gm_show_info (
				aTitle = _('Editing tag'),
				aMessage = _(
					'Cannot edit the image tag\n'
					'\n'
					' "%s"\n'
					'\n'
					'because it is currently in use.\n'
				) % tag_image['l10n_description']
			)
			return False

	ea = cTagImageEAPnl(parent = parent, id = -1)
	ea.data = tag_image
	ea.mode = gmTools.coalesce(tag_image, 'new', 'edit')
	dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
	dlg.SetTitle(gmTools.coalesce(tag_image, _('Adding new tag'), _('Editing tag')))
	if dlg.ShowModal() == wx.ID_OK:
		dlg.Destroy()
		return True
	dlg.Destroy()
	return False
#------------------------------------------------------------
def manage_tag_images(parent=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()
	#------------------------------------------------------------
	def go_to_openclipart_org(tag_image):
		gmNetworkTools.open_url_in_browser(url = u'http://www.openclipart.org')
		gmNetworkTools.open_url_in_browser(url = u'http://commons.wikimedia.org/wiki/Category:Symbols_of_disabilities')
		gmNetworkTools.open_url_in_browser(url = u'http://www.duckduckgo.com')
		gmNetworkTools.open_url_in_browser(url = u'http://images.google.com')
		return True
	#------------------------------------------------------------
	def edit(tag_image=None):
		return edit_tag_image(parent = parent, tag_image = tag_image, single_entry = (tag_image is not None))
	#------------------------------------------------------------
	def delete(tag):
		if tag['is_in_use']:
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot delete this tag. It is in use.'), beep = True)
			return False

		return gmDemographicRecord.delete_tag_image(tag_image = tag['pk_tag_image'])
	#------------------------------------------------------------
	def refresh(lctrl):
		tags = gmDemographicRecord.get_tag_images(order_by = u'l10n_description')
		items = [ [
			t['l10n_description'],
			gmTools.bool2subst(t['is_in_use'], u'X', u''),
			u'%s' % t['size'],
			t['pk_tag_image']
		] for t in tags ]
		lctrl.set_string_items(items)
		lctrl.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE])
		lctrl.set_data(tags)
	#------------------------------------------------------------
	msg = _('\nTags with images registered with GNUmed.\n')

	tag = gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = msg,
		caption = _('Showing tags with images.'),
		columns = [_('Tag name'), _('In use'), _('Image size'), u'#'],
		single_selection = True,
		new_callback = edit,
		edit_callback = edit,
		delete_callback = delete,
		refresh_callback = refresh,
		left_extra_button = (_('WWW'), _('Go to www.openclipart.org for images.'), go_to_openclipart_org)
	)

	return tag
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgTagImageEAPnl

class cTagImageEAPnl(wxgTagImageEAPnl.wxgTagImageEAPnl, gmEditArea.cGenericEditAreaMixin):

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['tag_image']
			del kwargs['tag_image']
		except KeyError:
			data = None

		wxgTagImageEAPnl.wxgTagImageEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		self.__selected_image_file = None
	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):

		valid = True

		if self.mode == u'new':
			if self.__selected_image_file is None:
				valid = False
				gmDispatcher.send(signal = 'statustext', msg = _('Must pick an image file for a new tag.'), beep = True)
				self._BTN_pick_image.SetFocus()

		if self.__selected_image_file is not None:
			try:
				open(self.__selected_image_file).close()
			except StandardError:
				valid = False
				self.__selected_image_file = None
				gmDispatcher.send(signal = 'statustext', msg = _('Cannot open the image file [%s].') % self.__selected_image_file, beep = True)
				self._BTN_pick_image.SetFocus()

		if self._TCTRL_description.GetValue().strip() == u'':
			valid = False
			self.display_tctrl_as_valid(self._TCTRL_description, False)
			self._TCTRL_description.SetFocus()
		else:
			self.display_tctrl_as_valid(self._TCTRL_description, True)

		return (valid is True)
	#----------------------------------------------------------------
	def _save_as_new(self):

		dbo_conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Creating tag with image'))
		if dbo_conn is None:
			return False

		data = gmDemographicRecord.create_tag_image(description = self._TCTRL_description.GetValue().strip(), link_obj = dbo_conn)
		dbo_conn.close()

		data['filename'] = self._TCTRL_filename.GetValue().strip()
		data.save()
		data.update_image_from_file(filename = self.__selected_image_file)

		# must be done very late or else the property access
		# will refresh the display such that later field
		# access will return empty values
		self.data = data
		return True
	#----------------------------------------------------------------
	def _save_as_update(self):

		# this is somewhat fake as it never actually uses the gm-dbo conn
		# (although it does verify it)
		dbo_conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Updating tag with image'))
		if dbo_conn is None:
			return False
		dbo_conn.close()

		self.data['description'] = self._TCTRL_description.GetValue().strip()
		self.data['filename'] = self._TCTRL_filename.GetValue().strip()
		self.data.save()

		if self.__selected_image_file is not None:
			open(self.__selected_image_file).close()
			self.data.update_image_from_file(filename = self.__selected_image_file)
			self.__selected_image_file = None

		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._TCTRL_description.SetValue(u'')
		self._TCTRL_filename.SetValue(u'')
		self._BMP_image.SetBitmap(bitmap = wx.EmptyBitmap(100, 100))

		self.__selected_image_file = None

		self._TCTRL_description.SetFocus()
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._refresh_as_new()
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._TCTRL_description.SetValue(self.data['l10n_description'])
		self._TCTRL_filename.SetValue(gmTools.coalesce(self.data['filename'], u''))
		fname = self.data.export_image2file()
		if fname is None:
			self._BMP_image.SetBitmap(bitmap = wx.EmptyBitmap(100, 100))
		else:
			self._BMP_image.SetBitmap(bitmap = gmGuiHelpers.file2scaled_image(filename = fname, height = 100))

		self.__selected_image_file = None

		self._TCTRL_description.SetFocus()
	#----------------------------------------------------------------
	# event handlers
	#----------------------------------------------------------------
	def _on_pick_image_button_pressed(self, event):
		paths = gmTools.gmPaths()
		img_dlg = wx_imagebrowser.ImageDialog(parent = self, set_dir = paths.home_dir)
		img_dlg.Centre()
		if img_dlg.ShowModal() != wx.ID_OK:
			return

		self.__selected_image_file = img_dlg.GetFile()
		self._BMP_image.SetBitmap(bitmap = gmGuiHelpers.file2scaled_image(filename = self.__selected_image_file, height = 100))
		fdir, fname = os.path.split(self.__selected_image_file)
		self._TCTRL_filename.SetValue(fname)

#============================================================
def select_patient_tags(parent=None, patient=None):

	if parent is None:
		parent = wx.GetApp().GetTopWindow()
	#--------------------------------------------------------
	def refresh(lctrl):
		tags = patient.tags
		items = [ [
			t['l10n_description'],
			gmTools.coalesce(t['comment'], u'')
		] for t in tags ]
		lctrl.set_string_items(items)
		#lctrl.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
		lctrl.set_data(tags)
	#--------------------------------------------------------
	def delete(tag):
		do_delete = gmGuiHelpers.gm_show_question (
			title = _('Deleting patient tag'),
			question = _('Do you really want to delete this patient tag ?')
		)
		if not do_delete:
			return False
		patient.remove_tag(tag = tag['pk_identity_tag'])
		return True
	#--------------------------------------------------------
	def manage_available_tags(tag):
		manage_tag_images(parent = parent)
		return False
	#--------------------------------------------------------
	msg = _('Tags of patient: %s\n') % patient['description_gender']

	return gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = msg,
		caption = _('Showing patient tags'),
		columns = [_('Tag'), _('Comment')],
		single_selection = False,
		delete_callback = delete,
		refresh_callback = refresh,
		left_extra_button = (_('Manage'), _('Manage available tags.'), manage_available_tags)
	)
#============================================================
from Gnumed.wxGladeWidgets import wxgVisualSoapPresenterPnl

class cImageTagPresenterPnl(wxgVisualSoapPresenterPnl.wxgVisualSoapPresenterPnl):

	def __init__(self, *args, **kwargs):
		wxgVisualSoapPresenterPnl.wxgVisualSoapPresenterPnl.__init__(self, *args, **kwargs)
		self._SZR_bitmaps = self.GetSizer()
		self.__bitmaps = []

		self.__context_popup = wx.Menu()

		item = self.__context_popup.Append(-1, _('&Edit comment'))
		self.Bind(wx.EVT_MENU, self.__edit_tag, item)

		item = self.__context_popup.Append(-1, _('&Remove tag'))
		self.Bind(wx.EVT_MENU, self.__remove_tag, item)
	#--------------------------------------------------------
	# external API
	#--------------------------------------------------------
	def refresh(self, patient):

		self.clear()

		for tag in patient.get_tags(order_by = u'l10n_description'):
			fname = tag.export_image2file()
			if fname is None:
				_log.warning('cannot export image data of tag [%s]', tag['l10n_description'])
				continue
			img = gmGuiHelpers.file2scaled_image(filename = fname, height = 20)
			bmp = wx_genstatbmp.GenStaticBitmap(self, -1, img, style = wx.NO_BORDER)
			bmp.SetToolTipString(u'%s%s' % (
				tag['l10n_description'],
				gmTools.coalesce(tag['comment'], u'', u'\n\n%s')
			))
			bmp.tag = tag
			bmp.Bind(wx.EVT_RIGHT_UP, self._on_bitmap_rightclicked)
			# FIXME: add context menu for Delete/Clone/Add/Configure
			self._SZR_bitmaps.Add(bmp, 0, wx.LEFT | wx.RIGHT | wx.TOP | wx.BOTTOM, 1)		# | wx.EXPAND
			self.__bitmaps.append(bmp)

		self.GetParent().Layout()
	#--------------------------------------------------------
	def clear(self):
		while len(self._SZR_bitmaps.GetChildren()) > 0:
			self._SZR_bitmaps.Detach(0)
#		for child_idx in range(len(self._SZR_bitmaps.GetChildren())):
#			self._SZR_bitmaps.Detach(child_idx)
		for bmp in self.__bitmaps:
			bmp.Destroy()
		self.__bitmaps = []
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __remove_tag(self, evt):
		if self.__current_tag is None:
			return
		pat = gmPerson.gmCurrentPatient()
		if not pat.connected:
			return
		pat.remove_tag(tag = self.__current_tag['pk_identity_tag'])
	#--------------------------------------------------------
	def __edit_tag(self, evt):
		if self.__current_tag is None:
			return

		msg = _('Edit the comment on tag [%s]') % self.__current_tag['l10n_description']
		comment = wx.GetTextFromUser (
			message = msg,
			caption = _('Editing tag comment'),
			default_value = gmTools.coalesce(self.__current_tag['comment'], u''),
			parent = self
		)

		if comment == u'':
			return

		if comment.strip() == self.__current_tag['comment']:
			return

		if comment == u' ':
			self.__current_tag['comment'] = None
		else:
			self.__current_tag['comment'] = comment.strip()

		self.__current_tag.save()
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _on_bitmap_rightclicked(self, evt):
		self.__current_tag = evt.GetEventObject().tag
		self.PopupMenu(self.__context_popup, pos = wx.DefaultPosition)
		self.__current_tag = None
#============================================================
#============================================================
class cKOrganizerSchedulePnl(gmDataMiningWidgets.cPatientListingPnl):

	def __init__(self, *args, **kwargs):

		kwargs['message'] = _("Today's KOrganizer appointments ...")
		kwargs['button_defs'] = [
			{'label': _('Reload'), 'tooltip': _('Reload appointments from KOrganizer')},
			{'label': u''},
			{'label': u''},
			{'label': u''},
			{'label': u'KOrganizer', 'tooltip': _('Launch KOrganizer')}
		]
		gmDataMiningWidgets.cPatientListingPnl.__init__(self, *args, **kwargs)

		self.fname = os.path.expanduser(os.path.join(gmTools.gmPaths().tmp_dir, 'korganizer2gnumed.csv'))
		self.reload_cmd = 'konsolekalendar --view --export-type csv --export-file %s' % self.fname

	#--------------------------------------------------------
	def _on_BTN_1_pressed(self, event):
		"""Reload appointments from KOrganizer."""
		self.reload_appointments()
	#--------------------------------------------------------
	def _on_BTN_5_pressed(self, event):
		"""Reload appointments from KOrganizer."""
		found, cmd = gmShellAPI.detect_external_binary(binary = 'korganizer')

		if not found:
			gmDispatcher.send(signal = 'statustext', msg = _('KOrganizer is not installed.'), beep = True)
			return

		gmShellAPI.run_command_in_shell(command = cmd, blocking = False)
	#--------------------------------------------------------
	def reload_appointments(self):
		try: os.remove(self.fname)
		except OSError: pass
		gmShellAPI.run_command_in_shell(command=self.reload_cmd, blocking=True)
		try:
			csv_file = codecs.open(self.fname , mode = 'rU', encoding = 'utf8', errors = 'replace')
		except IOError:
			gmDispatcher.send(signal = u'statustext', msg = _('Cannot access KOrganizer transfer file [%s]') % self.fname, beep = True)
			return

		csv_lines = gmTools.unicode_csv_reader (
			csv_file,
			delimiter = ','
		)
		# start_date, start_time, end_date, end_time, title (patient), ort, comment, UID
		self._LCTRL_items.set_columns ([
			_('Place'),
			_('Start'),
			u'',
			u'',
			_('Patient'),
			_('Comment')
		])
		items = []
		data = []
		for line in csv_lines:
			items.append([line[5], line[0], line[1], line[3], line[4], line[6]])
			data.append([line[4], line[7]])

		self._LCTRL_items.set_string_items(items = items)
		self._LCTRL_items.set_column_widths()
		self._LCTRL_items.set_data(data = data)
		self._LCTRL_items.patient_key = 0
	#--------------------------------------------------------
	# notebook plugins API
	#--------------------------------------------------------
	def repopulate_ui(self):
		self.reload_appointments()
#============================================================
# occupation related widgets / functions
#============================================================
def edit_occupation():

	pat = gmPerson.gmCurrentPatient()
	curr_jobs = pat.get_occupations()
	if len(curr_jobs) > 0:
		old_job = curr_jobs[0]['l10n_occupation']
		update = curr_jobs[0]['modified_when'].strftime('%m/%Y')
	else:
		old_job = u''
		update = u''

	msg = _(
		'Please enter the primary occupation of the patient.\n'
		'\n'
		'Currently recorded:\n'
		'\n'
		' %s (last updated %s)'
	) % (old_job, update)

	new_job = wx.GetTextFromUser (
		message = msg,
		caption = _('Editing primary occupation'),
		default_value = old_job,
		parent = None
	)
	if new_job.strip() == u'':
		return

	for job in curr_jobs:
		# unlink all but the new job
		if job['l10n_occupation'] != new_job:
			pat.unlink_occupation(occupation = job['l10n_occupation'])
	# and link the new one
	pat.link_occupation(occupation = new_job)

#------------------------------------------------------------
class cOccupationPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"SELECT distinct name, _(name) from dem.occupation where _(name) %(fragment_condition)s"
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 3, 5)
		gmPhraseWheel.cPhraseWheel.__init__ (
			self,
			*args,
			**kwargs
		)
		self.SetToolTipString(_("Type or select an occupation."))
		self.capitalisation_mode = gmTools.CAPS_FIRST
		self.matcher = mp

#============================================================
# identity widgets / functions
#============================================================
def document_death_of_patient(identity=None):
	pass

#------------------------------------------------------------
def disable_identity(identity=None):
	# ask user for assurance
	go_ahead = gmGuiHelpers.gm_show_question (
		_('Are you sure you really, positively want\n'
		  'to disable the following person ?\n'
		  '\n'
		  ' %s %s %s\n'
		  ' born %s\n'
		  '\n'
		  '%s\n'
		) % (
			identity['firstnames'],
			identity['lastnames'],
			identity['gender'],
			identity.get_formatted_dob(),
			gmTools.bool2subst (
				identity.is_patient,
				_('This patient DID receive care.'),
				_('This person did NOT receive care.')
			)
		),
		_('Disabling person')
	)
	if not go_ahead:
		return True

	# get admin connection
	conn = gmAuthWidgets.get_dbowner_connection (
		procedure = _('Disabling patient')
	)
	# - user cancelled
	if conn is False:
		return True
	# - error
	if conn is None:
		return False

	# now disable patient
	gmPG2.run_rw_queries(queries = [{'cmd': u"update dem.identity set deleted=True where pk=%s", 'args': [identity['pk_identity']]}])

	return True

#------------------------------------------------------------
# phrasewheels
#------------------------------------------------------------
class cLastnamePhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"SELECT distinct lastnames, lastnames from dem.names where lastnames %(fragment_condition)s order by lastnames limit 25"
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(3, 5, 9)
		gmPhraseWheel.cPhraseWheel.__init__ (
			self,
			*args,
			**kwargs
		)
		self.SetToolTipString(_("Type or select a last name (family name/surname)."))
		self.capitalisation_mode = gmTools.CAPS_NAMES
		self.matcher = mp
#------------------------------------------------------------
class cFirstnamePhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"""
			(SELECT distinct firstnames, firstnames from dem.names where firstnames %(fragment_condition)s order by firstnames limit 20)
				union
			(SELECT distinct name, name from dem.name_gender_map where name %(fragment_condition)s order by name limit 20)"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(3, 5, 9)
		gmPhraseWheel.cPhraseWheel.__init__ (
			self,
			*args,
			**kwargs
		)
		self.SetToolTipString(_("Type or select a first name (forename/Christian name/given name)."))
		self.capitalisation_mode = gmTools.CAPS_NAMES
		self.matcher = mp
#------------------------------------------------------------
class cNicknamePhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"""
			(SELECT distinct preferred, preferred from dem.names where preferred %(fragment_condition)s order by preferred limit 20)
				union
			(SELECT distinct firstnames, firstnames from dem.names where firstnames %(fragment_condition)s order by firstnames limit 20)
				union
			(SELECT distinct name, name from dem.name_gender_map where name %(fragment_condition)s order by name limit 20)"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(3, 5, 9)
		gmPhraseWheel.cPhraseWheel.__init__ (
			self,
			*args,
			**kwargs
		)
		self.SetToolTipString(_("Type or select an alias (nick name, preferred name, call name, warrior name, artist name)."))
		# nicknames CAN start with lower case !
		#self.capitalisation_mode = gmTools.CAPS_NAMES
		self.matcher = mp
#------------------------------------------------------------
class cTitlePhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"SELECT distinct title, title from dem.identity where title %(fragment_condition)s"
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 3, 9)
		gmPhraseWheel.cPhraseWheel.__init__ (
			self,
			*args,
			**kwargs
		)
		self.SetToolTipString(_("Type or select a title. Note that the title applies to the person, not to a particular name !"))
		self.matcher = mp
#------------------------------------------------------------
class cGenderSelectionPhraseWheel(gmPhraseWheel.cPhraseWheel):
	"""Let user select a gender."""

	_gender_map = None

	def __init__(self, *args, **kwargs):

		if cGenderSelectionPhraseWheel._gender_map is None:
			cmd = u"""
				SELECT tag, l10n_label, sort_weight
				from dem.v_gender_labels
				order by sort_weight desc"""
			rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd}], get_col_idx=True)
			cGenderSelectionPhraseWheel._gender_map = {}
			for gender in rows:
				cGenderSelectionPhraseWheel._gender_map[gender[idx['tag']]] = {
					'data': gender[idx['tag']],
					'field_label': gender[idx['l10n_label']],
					'list_label': gender[idx['l10n_label']],
					'weight': gender[idx['sort_weight']]
				}

		mp = gmMatchProvider.cMatchProvider_FixedList(aSeq = cGenderSelectionPhraseWheel._gender_map.values())
		mp.setThresholds(1, 1, 3)

		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.selection_only = True
		self.matcher = mp
		self.picklist_delay = 50
#------------------------------------------------------------
class cExternalIDTypePhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"""
			SELECT DISTINCT ON (list_label)
				pk AS data,
				name AS field_label,
				name || coalesce(' (' || issuer || ')', '') as list_label
			FROM dem.enum_ext_id_types
			WHERE name %(fragment_condition)s
			ORDER BY list_label
			LIMIT 25
		"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 3, 5)
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.SetToolTipString(_("Enter or select a type for the external ID."))
		self.matcher = mp
	#--------------------------------------------------------
	def _get_data_tooltip(self):
		if self.GetData() is None:
			return None
		return self._data.values()[0]['list_label']
#------------------------------------------------------------
class cExternalIDIssuerPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"""
SELECT distinct issuer, issuer
from dem.enum_ext_id_types
where issuer %(fragment_condition)s
order by issuer limit 25"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 3, 5)
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.SetToolTipString(_("Type or select an ID issuer."))
		self.capitalisation_mode = gmTools.CAPS_FIRST
		self.matcher = mp
#------------------------------------------------------------
# edit areas
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgExternalIDEditAreaPnl

class cExternalIDEditAreaPnl(wxgExternalIDEditAreaPnl.wxgExternalIDEditAreaPnl, gmEditArea.cGenericEditAreaMixin):
	"""An edit area for editing/creating external IDs.

	Does NOT act on/listen to the current patient.
	"""
	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['external_id']
			del kwargs['external_id']
		except:
			data = None

		wxgExternalIDEditAreaPnl.wxgExternalIDEditAreaPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.identity = None

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		self.__init_ui()
	#--------------------------------------------------------
	def __init_ui(self):
		self._PRW_type.add_callback_on_lose_focus(self._on_type_set)
	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):
		validity = True

		# do not test .GetData() because adding external
		# IDs will create types as necessary
		#if self._PRW_type.GetData() is None:
		if self._PRW_type.GetValue().strip() == u'':
			validity = False
			self._PRW_type.display_as_valid(False)
			self._PRW_type.SetFocus()
		else:
			self._PRW_type.display_as_valid(True)

		if self._TCTRL_value.GetValue().strip() == u'':
			validity = False
			self.display_tctrl_as_valid(tctrl = self._TCTRL_value, valid = False)
		else:
			self.display_tctrl_as_valid(tctrl = self._TCTRL_value, valid = True)

		return validity
	#----------------------------------------------------------------
	def _save_as_new(self):
		data = {}
		data['pk_type'] = None
		data['name'] = self._PRW_type.GetValue().strip()
		data['value'] = self._TCTRL_value.GetValue().strip()
		data['issuer'] = gmTools.none_if(self._PRW_issuer.GetValue().strip(), u'')
		data['comment'] = gmTools.none_if(self._TCTRL_comment.GetValue().strip(), u'')

		self.identity.add_external_id (
			type_name = data['name'],
			value = data['value'],
			issuer = data['issuer'],
			comment = data['comment']
		)

		self.data = data
		return True
	#----------------------------------------------------------------
	def _save_as_update(self):
		self.data['name'] = self._PRW_type.GetValue().strip()
		self.data['value'] = self._TCTRL_value.GetValue().strip()
		self.data['issuer'] = gmTools.none_if(self._PRW_issuer.GetValue().strip(), u'')
		self.data['comment'] = gmTools.none_if(self._TCTRL_comment.GetValue().strip(), u'')

		self.identity.update_external_id (
			pk_id = self.data['pk_id'],
			type = self.data['name'],
			value = self.data['value'],
			issuer = self.data['issuer'],
			comment = self.data['comment']
		)

		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_type.SetText(value = u'', data = None)
		self._TCTRL_value.SetValue(u'')
		self._PRW_issuer.SetText(value = u'', data = None)
		self._TCTRL_comment.SetValue(u'')
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._refresh_as_new()
		self._PRW_issuer.SetText(self.data['issuer'])
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_type.SetText(value = self.data['name'], data = self.data['pk_type'])
		self._TCTRL_value.SetValue(self.data['value'])
		self._PRW_issuer.SetText(self.data['issuer'])
		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], u''))
	#----------------------------------------------------------------
	# internal helpers
	#----------------------------------------------------------------
	def _on_type_set(self):
		"""Set the issuer according to the selected type.

		Matches are fetched from existing records in backend.
		"""
		pk_curr_type = self._PRW_type.GetData()
		if pk_curr_type is None:
			return True
		rows, idx = gmPG2.run_ro_queries(queries = [{
			'cmd': u"SELECT issuer from dem.enum_ext_id_types where pk = %s",
			'args': [pk_curr_type]
		}])
		if len(rows) == 0:
			return True
		wx.CallAfter(self._PRW_issuer.SetText, rows[0][0])
		return True

#============================================================
# identity widgets
#------------------------------------------------------------
def _empty_dob_allowed():
	allow_empty_dob = gmGuiHelpers.gm_show_question (
		_(
			'Are you sure you want to leave this person\n'
			'without a valid date of birth ?\n'
			'\n'
			'This can be useful for temporary staff members\n'
			'but will provoke nag screens if this person\n'
			'becomes a patient.\n'
		),
		_('Validating date of birth')
	)
	return allow_empty_dob
#------------------------------------------------------------
def _validate_dob_field(dob_prw):

	# valid timestamp ?
	if dob_prw.is_valid_timestamp(allow_empty = False):			# properly colors the field
		dob = dob_prw.date
		# but year also usable ?
		if (dob.year > 1899) and (dob < gmDateTime.pydt_now_here()):
			return True

		if dob.year < 1900:
			msg = _(
				'DOB: %s\n'
				'\n'
				'While this is a valid point in time Python does\n'
				'not know how to deal with it.\n'
				'\n'
				'We suggest using January 1st 1901 instead and adding\n'
				'the true date of birth to the patient comment.\n'
				'\n'
				'Sorry for the inconvenience %s'
			) % (dob, gmTools.u_frowning_face)
		else:
			msg = _(
				'DOB: %s\n'
				'\n'
				'Date of birth in the future !'
			) % dob
		gmGuiHelpers.gm_show_error (
			msg,
			_('Validating date of birth')
		)
		dob_prw.display_as_valid(False)
		dob_prw.SetFocus()
		return False

	# invalid timestamp but not empty
	if dob_prw.GetValue().strip() != u'':
		dob_prw.display_as_valid(False)
		gmDispatcher.send(signal = u'statustext', msg = _('Invalid date of birth.'))
		dob_prw.SetFocus()
		return False

	# empty DOB field
	dob_prw.display_as_valid(False)
	return True

#------------------------------------------------------------
def _validate_tob_field(ctrl):

	val = ctrl.GetValue().strip()

	if val == u'':
		return True

	converted, hours = gmTools.input2int(val[:2], 0, 23)
	if not converted:
		return False

	converted, minutes = gmTools.input2int(val[3:5], 0, 59)
	if not converted:
		return False

	return True

#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgIdentityEAPnl

class cIdentityEAPnl(wxgIdentityEAPnl.wxgIdentityEAPnl, gmEditArea.cGenericEditAreaMixin):
	"""An edit area for editing/creating title/gender/dob/dod etc."""

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['identity']
			del kwargs['identity']
		except KeyError:
			data = None

		wxgIdentityEAPnl.wxgIdentityEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

#		self.__init_ui()
	#----------------------------------------------------------------
#	def __init_ui(self):
#		# adjust phrasewheels etc
	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):

		has_error = False

		if self._PRW_gender.GetData() is None:
			self._PRW_gender.SetFocus()
			has_error = True

		if self.data is not None:
			if not _validate_dob_field(self._PRW_dob):
				has_error = True

		# TOB validation
		if _validate_tob_field(self._TCTRL_tob):
			self.display_ctrl_as_valid(ctrl = self._TCTRL_tob, valid = True)
		else:
			has_error = True
			self.display_ctrl_as_valid(ctrl = self._TCTRL_tob, valid = False)

		if not self._PRW_dod.is_valid_timestamp(allow_empty = True):
			gmDispatcher.send(signal = u'statustext', msg = _('Invalid date of death.'))
			self._PRW_dod.SetFocus()
			has_error = True

		return (has_error is False)
	#----------------------------------------------------------------
	def _save_as_new(self):
		# not used yet
		return False
	#----------------------------------------------------------------
	def _save_as_update(self):

		if self._PRW_dob.GetValue().strip() == u'':
			if not _empty_dob_allowed():
				return False
			self.data['dob'] = None
		else:
			self.data['dob'] = self._PRW_dob.GetData()
		self.data['dob_is_estimated'] = self._CHBOX_estimated_dob.GetValue()
		val = self._TCTRL_tob.GetValue().strip()
		if val == u'':
			self.data['tob'] = None
		else:
			self.data['tob'] = pydt.time(int(val[:2]), int(val[3:5]))
		self.data['gender'] = self._PRW_gender.GetData()
		self.data['title'] = gmTools.none_if(self._PRW_title.GetValue().strip(), u'')
		self.data['deceased'] = self._PRW_dod.GetData()
		self.data['comment'] = gmTools.none_if(self._TCTRL_comment.GetValue().strip(), u'')

		self.data.save()
		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		pass
	#----------------------------------------------------------------
	def _refresh_from_existing(self):

		self._LBL_info.SetLabel(u'ID: #%s' % (
			self.data.ID
			# FIXME: add 'deleted' status
		))
		if self.data['dob'] is None:
			val = u''
		else:
			val = gmDateTime.pydt_strftime (
				self.data['dob'],
				format = '%Y-%m-%d',
				accuracy = gmDateTime.acc_minutes
			)
		self._PRW_dob.SetText(value = val, data = self.data['dob'])
		self._CHBOX_estimated_dob.SetValue(self.data['dob_is_estimated'])
		if self.data['tob'] is None:
			self._TCTRL_tob.SetValue(u'')
		else:
			self._TCTRL_tob.SetValue(self.data['tob'].strftime('%H:%M'))
		if self.data['deceased'] is None:
			val = u''
		else:
			val = gmDateTime.pydt_strftime (
				self.data['deceased'],
				format = '%Y-%m-%d %H:%M',
				accuracy = gmDateTime.acc_minutes
			)
		self._PRW_dod.SetText(value = val, data = self.data['deceased'])
		self._PRW_gender.SetData(self.data['gender'])
		#self._PRW_ethnicity.SetValue()
		self._PRW_title.SetText(gmTools.coalesce(self.data['title'], u''))
		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], u''))
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		pass
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgPersonNameEAPnl

class cPersonNameEAPnl(wxgPersonNameEAPnl.wxgPersonNameEAPnl, gmEditArea.cGenericEditAreaMixin):
	"""An edit area for editing/creating names of people.

	Does NOT act on/listen to the current patient.
	"""
	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['name']
			identity = gmPerson.cIdentity(aPK_obj = data['pk_identity'])
			del kwargs['name']
		except KeyError:
			data = None
			identity = kwargs['identity']
			del kwargs['identity']

		wxgPersonNameEAPnl.wxgPersonNameEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.__identity = identity

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		#self.__init_ui()
	#----------------------------------------------------------------
#	def __init_ui(self):
#		# adjust phrasewheels etc
	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):
		validity = True

		if self._PRW_lastname.GetValue().strip() == u'':
			validity = False
			self._PRW_lastname.display_as_valid(False)
			self._PRW_lastname.SetFocus()
		else:
			self._PRW_lastname.display_as_valid(True)

		if self._PRW_firstname.GetValue().strip() == u'':
			validity = False
			self._PRW_firstname.display_as_valid(False)
			self._PRW_firstname.SetFocus()
		else:
			self._PRW_firstname.display_as_valid(True)

		return validity
	#----------------------------------------------------------------
	def _save_as_new(self):

		first = self._PRW_firstname.GetValue().strip()
		last = self._PRW_lastname.GetValue().strip()
		active = self._CHBOX_active.GetValue()

		try:
			data = self.__identity.add_name(first, last, active)
		except gmPG2.dbapi.IntegrityError as exc:
			_log.exception('cannot save new name')
			exc = make_pg_exception_fields_unicode(exc)
			gmGuiHelpers.gm_show_error (
				aTitle = _('Adding name'),
				aMessage = _(
					'Cannot add this name to the patient !\n'
					'\n'
					' %s'
				) % exc.u_pgerror
#				) % str(exc)
			)
			return False

		old_nick = self.__identity['active_name']['preferred']
		new_nick = gmTools.none_if(self._PRW_nick.GetValue().strip(), u'')
		if active:
			data['preferred'] = gmTools.coalesce(new_nick, old_nick)
		else:
			data['preferred'] = new_nick
		data['comment'] = gmTools.none_if(self._TCTRL_comment.GetValue().strip(), u'')
		data.save()

		self.data = data
		return True
	#----------------------------------------------------------------
	def _save_as_update(self):
		"""The knack here is that we can only update a few fields.

		Otherwise we need to clone the name and update that.
		"""
		first = self._PRW_firstname.GetValue().strip()
		last = self._PRW_lastname.GetValue().strip()
		active = self._CHBOX_active.GetValue()

		current_name = self.data['firstnames'].strip() + self.data['lastnames'].strip()
		new_name = first + last

		# editable fields only ?
		if new_name == current_name:
			self.data['active_name'] = self._CHBOX_active.GetValue()
			self.data['preferred'] = gmTools.none_if(self._PRW_nick.GetValue().strip(), u'')
			self.data['comment'] = gmTools.none_if(self._TCTRL_comment.GetValue().strip(), u'')
			self.data.save()
		# else clone name and update that
		else:
			try:
				name = self.__identity.add_name(first, last, active)
			except gmPG2.dbapi.IntegrityError as exc:
				_log.exception('cannot clone name when editing existing name')
				exc = make_pg_exception_fields_unicode(exc)
				gmGuiHelpers.gm_show_error (
					aTitle = _('Editing name'),
					aMessage = _(
						'Cannot clone a copy of this name !\n'
						'\n'
						' %s'
					) % exc.u_pgerror
#					) % str(exc)
				)
				return False
			name['preferred'] = gmTools.none_if(self._PRW_nick.GetValue().strip(), u'')
			name['comment'] = gmTools.none_if(self._TCTRL_comment.GetValue().strip(), u'')
			name.save()
			self.data = name

		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_firstname.SetText(value = u'', data = None)
		self._PRW_lastname.SetText(value = u'', data = None)
		self._PRW_nick.SetText(value = u'', data = None)
		self._TCTRL_comment.SetValue(u'')
		self._CHBOX_active.SetValue(False)

		self._PRW_firstname.SetFocus()
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._refresh_as_new()
		self._PRW_firstname.SetText(value = u'', data = None)
		self._PRW_nick.SetText(gmTools.coalesce(self.data['preferred'], u''))

		self._PRW_lastname.SetFocus()
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_firstname.SetText(self.data['firstnames'])
		self._PRW_lastname.SetText(self.data['lastnames'])
		self._PRW_nick.SetText(gmTools.coalesce(self.data['preferred'], u''))
		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], u''))
		self._CHBOX_active.SetValue(self.data['active_name'])

		self._TCTRL_comment.SetFocus()
#------------------------------------------------------------
# list manager
#------------------------------------------------------------
class cPersonNamesManagerPnl(gmListWidgets.cGenericListManagerPnl):
	"""A list for managing a person's names.

	Does NOT act on/listen to the current patient.
	"""
	def __init__(self, *args, **kwargs):

		try:
			self.__identity = kwargs['identity']
			del kwargs['identity']
		except KeyError:
			self.__identity = None

		gmListWidgets.cGenericListManagerPnl.__init__(self, *args, **kwargs)

		self.new_callback = self._add_name
		self.edit_callback = self._edit_name
		self.delete_callback = self._del_name
		self.refresh_callback = self.refresh

		self.__init_ui()
		self.refresh()
	#--------------------------------------------------------
	# external API
	#--------------------------------------------------------
	def refresh(self, *args, **kwargs):
		if self.__identity is None:
			self._LCTRL_items.set_string_items()
			return

		names = self.__identity.get_names()
		self._LCTRL_items.set_string_items (
			items = [ [
					gmTools.bool2str(n['active_name'], 'X', ''),
					n['lastnames'],
					n['firstnames'],
					gmTools.coalesce(n['preferred'], u''),
					gmTools.coalesce(n['comment'], u'')
				] for n in names ]
		)
		self._LCTRL_items.set_column_widths()
		self._LCTRL_items.set_data(data = names)
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_items.set_columns(columns = [
			_('Active'),
			_('Lastname'),
			_('Firstname(s)'),
			_('Preferred Name'),
			_('Comment')
		])
	#--------------------------------------------------------
	def _add_name(self):
		#ea = cPersonNameEAPnl(self, -1, name = self.__identity.get_active_name())
		ea = cPersonNameEAPnl(self, -1, identity = self.__identity)
		dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea, single_entry = True)
		dlg.SetTitle(_('Adding new name'))
		if dlg.ShowModal() == wx.ID_OK:
			dlg.Destroy()
			return True
		dlg.Destroy()
		return False
	#--------------------------------------------------------
	def _edit_name(self, name):
		ea = cPersonNameEAPnl(self, -1, name = name)
		dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea, single_entry = True)
		dlg.SetTitle(_('Editing name'))
		if dlg.ShowModal() == wx.ID_OK:
			dlg.Destroy()
			return True
		dlg.Destroy()
		return False
	#--------------------------------------------------------
	def _del_name(self, name):

		if len(self.__identity.get_names()) == 1:
			gmDispatcher.send(signal = u'statustext', msg = _('Cannot delete the only name of a person.'), beep = True)
			return False

		if name['active_name']:
			gmDispatcher.send(signal = u'statustext', msg = _('Cannot delete the active name of a person.'), beep = True)
			return False

		go_ahead = gmGuiHelpers.gm_show_question (
			_(	'It is often advisable to keep old names around and\n'
				'just create a new "currently active" name.\n'
				'\n'
				'This allows finding the patient by both the old\n'
				'and the new name (think before/after marriage).\n'
				'\n'
				'Do you still want to really delete\n'
				"this name from the patient ?"
			),
			_('Deleting name')
		)
		if not go_ahead:
			return False

		self.__identity.delete_name(name = name)
		return True
	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_identity(self):
		return self.__identity

	def _set_identity(self, identity):
		self.__identity = identity
		self.refresh()

	identity = property(_get_identity, _set_identity)
#------------------------------------------------------------
class cPersonIDsManagerPnl(gmListWidgets.cGenericListManagerPnl):
	"""A list for managing a person's external IDs.

	Does NOT act on/listen to the current patient.
	"""
	def __init__(self, *args, **kwargs):

		try:
			self.__identity = kwargs['identity']
			del kwargs['identity']
		except KeyError:
			self.__identity = None

		gmListWidgets.cGenericListManagerPnl.__init__(self, *args, **kwargs)

		self.new_callback = self._add_id
		self.edit_callback = self._edit_id
		self.delete_callback = self._del_id
		self.refresh_callback = self.refresh

		self.__init_ui()
		self.refresh()
	#--------------------------------------------------------
	# external API
	#--------------------------------------------------------
	def refresh(self, *args, **kwargs):
		if self.__identity is None:
			self._LCTRL_items.set_string_items()
			return

		ids = self.__identity.get_external_ids()
		self._LCTRL_items.set_string_items (
			items = [ [
					i['name'],
					i['value'],
					gmTools.coalesce(i['issuer'], u''),
					gmTools.coalesce(i['comment'], u'')
				] for i in ids
			]
		)
		self._LCTRL_items.set_column_widths()
		self._LCTRL_items.set_data(data = ids)
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_items.set_columns(columns = [
			_('ID type'),
			_('Value'),
			_('Issuer'),
			_('Comment')
		])
	#--------------------------------------------------------
	def _add_id(self):
		ea = cExternalIDEditAreaPnl(self, -1)
		ea.identity = self.__identity
		dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea)
		dlg.SetTitle(_('Adding new external ID'))
		if dlg.ShowModal() == wx.ID_OK:
			dlg.Destroy()
			return True
		dlg.Destroy()
		return False
	#--------------------------------------------------------
	def _edit_id(self, ext_id):
		ea = cExternalIDEditAreaPnl(self, -1, external_id = ext_id)
		ea.identity = self.__identity
		dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea, single_entry = True)
		dlg.SetTitle(_('Editing external ID'))
		if dlg.ShowModal() == wx.ID_OK:
			dlg.Destroy()
			return True
		dlg.Destroy()
		return False
	#--------------------------------------------------------
	def _del_id(self, ext_id):
		go_ahead = gmGuiHelpers.gm_show_question (
			_(	'Do you really want to delete this\n'
				'external ID from the patient ?'),
			_('Deleting external ID')
		)
		if not go_ahead:
			return False
		self.__identity.delete_external_id(pk_ext_id = ext_id['pk_id'])
		return True
	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_identity(self):
		return self.__identity

	def _set_identity(self, identity):
		self.__identity = identity
		self.refresh()

	identity = property(_get_identity, _set_identity)
#------------------------------------------------------------
# integrated panels
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgPersonIdentityManagerPnl

class cPersonIdentityManagerPnl(wxgPersonIdentityManagerPnl.wxgPersonIdentityManagerPnl):
	"""A panel for editing identity data for a person.

	- provides access to:
	  - identity EA
	  - name list manager
	  - external IDs list manager

	Does NOT act on/listen to the current patient.
	"""
	def __init__(self, *args, **kwargs):

		wxgPersonIdentityManagerPnl.wxgPersonIdentityManagerPnl.__init__(self, *args, **kwargs)

		self.__identity = None
		self.refresh()
	#--------------------------------------------------------
	# external API
	#--------------------------------------------------------
	def refresh(self):
		self._PNL_names.identity = self.__identity
		self._PNL_ids.identity = self.__identity
		# this is an Edit Area:
		self._PNL_identity.mode = 'new'
		self._PNL_identity.data = self.__identity
		if self.__identity is not None:
			self._PNL_identity.mode = 'edit'
			self._PNL_identity._refresh_from_existing()
	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_identity(self):
		return self.__identity

	def _set_identity(self, identity):
		self.__identity = identity
		self.refresh()

	identity = property(_get_identity, _set_identity)
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _on_save_identity_details_button_pressed(self, event):
		if not self._PNL_identity.save():
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot save identity. Incomplete information.'), beep = True)
		#self._PNL_identity.refresh()
	#--------------------------------------------------------
	def _on_reload_identity_button_pressed(self, event):
		self._PNL_identity.refresh()

#============================================================
from Gnumed.wxGladeWidgets import wxgPersonSocialNetworkManagerPnl

class cPersonSocialNetworkManagerPnl(wxgPersonSocialNetworkManagerPnl.wxgPersonSocialNetworkManagerPnl):
	def __init__(self, *args, **kwargs):

		wxgPersonSocialNetworkManagerPnl.wxgPersonSocialNetworkManagerPnl.__init__(self, *args, **kwargs)

		self.__identity = None
		self._PRW_provider.selection_only = False
		self.refresh()
	#--------------------------------------------------------
	# external API
	#--------------------------------------------------------
	def refresh(self):

		tt = _('Link another person in this database as the emergency contact:\n\nEnter person name part or identifier and hit <enter>.')

		if self.__identity is None:
			self._TCTRL_er_contact.SetValue(u'')
			self._TCTRL_person.person = None
			self._TCTRL_person.SetToolTipString(tt)

			self._PRW_provider.SetText(value = u'', data = None)
			return

		self._TCTRL_er_contact.SetValue(gmTools.coalesce(self.__identity['emergency_contact'], u''))
		if self.__identity['pk_emergency_contact'] is not None:
			ident = gmPerson.cIdentity(aPK_obj = self.__identity['pk_emergency_contact'])
			self._TCTRL_person.person = ident
			tt = u'%s\n\n%s\n\n%s' % (
				tt,
				ident['description_gender'],
				u'\n'.join([
					u'%s: %s%s' % (
						c['l10n_comm_type'],
						c['url'],
						gmTools.bool2subst(c['is_confidential'], _(' (confidential !)'), u'', u'')
					)
					for c in ident.get_comm_channels()
				])
			)
		else:
			self._TCTRL_person.person = None

		self._TCTRL_person.SetToolTipString(tt)

		if self.__identity['pk_primary_provider'] is None:
			self._PRW_provider.SetText(value = u'', data = None)
		else:
			self._PRW_provider.SetData(data = self.__identity['pk_primary_provider'])
	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_identity(self):
		return self.__identity

	def _set_identity(self, identity):
		self.__identity = identity
		self.refresh()

	identity = property(_get_identity, _set_identity)
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _on_save_button_pressed(self, event):
		if self.__identity is not None:
			self.__identity['emergency_contact'] = self._TCTRL_er_contact.GetValue().strip()
			if self._TCTRL_person.person is not None:
				self.__identity['pk_emergency_contact'] = self._TCTRL_person.person.ID
			if self._PRW_provider.GetValue().strip == u'':
				self.__identity['pk_primary_provider'] = None
			else:
				self.__identity['pk_primary_provider'] = self._PRW_provider.GetData()

			self.__identity.save()
			gmDispatcher.send(signal = 'statustext', msg = _('Emergency data and primary provider saved.'), beep = False)

		event.Skip()
	#--------------------------------------------------------
	def _on_reload_button_pressed(self, event):
		self.refresh()
	#--------------------------------------------------------
	def _on_remove_contact_button_pressed(self, event):
		event.Skip()

		if self.__identity is None:
			return

		self._TCTRL_person.person = None

		self.__identity['pk_emergency_contact'] = None
		self.__identity.save()
	#--------------------------------------------------------
	def _on_button_activate_contact_pressed(self, event):
		ident = self._TCTRL_person.person
		if ident is not None:
			from Gnumed.wxpython import gmPatSearchWidgets
			gmPatSearchWidgets.set_active_patient(patient = ident, forced_reload = False)

		event.Skip()

#============================================================
# patient demographics editing classes
#============================================================
class cPersonDemographicsEditorNb(wx.Notebook):
	"""Notebook displaying demographics editing pages:

		- Identity (as per Jim/Rogerio 12/2011)
		- Contacts (addresses, phone numbers, etc)
		- Social network (significant others, GP, etc)

	Does NOT act on/listen to the current patient.
	"""
	#--------------------------------------------------------
	def __init__(self, parent, id):

		wx.Notebook.__init__ (
			self,
			parent = parent,
			id = id,
			style = wx.NB_TOP | wx.NB_MULTILINE | wx.NO_BORDER,
			name = self.__class__.__name__
		)

		self.__identity = None
		self.__do_layout()
		self.SetSelection(0)
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	def refresh(self):
		"""Populate fields in pages with data from model."""
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			page.identity = self.__identity

		return True
	#--------------------------------------------------------
	# internal API
	#--------------------------------------------------------
	def __do_layout(self):
		"""Build patient edition notebook pages."""

		# identity page
		new_page = cPersonIdentityManagerPnl(self, -1)
		new_page.identity = self.__identity
		self.AddPage (
			page = new_page,
			text = _('Identity'),
			select = False
		)

		# contacts page
		new_page = gmPersonContactWidgets.cPersonContactsManagerPnl(self, -1)
		new_page.identity = self.__identity
		self.AddPage (
			page = new_page,
			text = _('Contacts'),
			select = True
		)

		# social network page
		new_page = cPersonSocialNetworkManagerPnl(self, -1)
		new_page.identity = self.__identity
		self.AddPage (
			page = new_page,
			text = _('Social network'),
			select = False
		)
	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_identity(self):
		return self.__identity

	def _set_identity(self, identity):
		self.__identity = identity

	identity = property(_get_identity, _set_identity)
#============================================================
# old occupation widgets
#============================================================
# FIXME: support multiple occupations
# FIXME: redo with wxGlade

class cPatOccupationsPanel(wx.Panel):
	"""Page containing patient occupations edition fields.
	"""
	def __init__(self, parent, id, ident=None):
		"""
		Creates a new instance of BasicPatDetailsPage
		@param parent - The parent widget
		@type parent - A wx.Window instance
		@param id - The widget id
		@type id - An integer
		"""
		wx.Panel.__init__(self, parent, id)
		self.__ident = ident
		self.__do_layout()
	#--------------------------------------------------------
	def __do_layout(self):
		PNL_form = wx.Panel(self, -1)
		# occupation
		STT_occupation = wx.StaticText(PNL_form, -1, _('Occupation'))
		self.PRW_occupation = cOccupationPhraseWheel(parent = PNL_form,	id = -1)
		self.PRW_occupation.SetToolTipString(_("primary occupation of the patient"))
		# known since
		STT_occupation_updated = wx.StaticText(PNL_form, -1, _('Last updated'))
		self.TTC_occupation_updated = wx.TextCtrl(PNL_form, -1, style = wx.TE_READONLY)

		# layout input widgets
		SZR_input = wx.FlexGridSizer(cols = 2, rows = 5, vgap = 4, hgap = 4)
		SZR_input.AddGrowableCol(1)				
		SZR_input.Add(STT_occupation, 0, wx.SHAPED)
		SZR_input.Add(self.PRW_occupation, 1, wx.EXPAND)
		SZR_input.Add(STT_occupation_updated, 0, wx.SHAPED)
		SZR_input.Add(self.TTC_occupation_updated, 1, wx.EXPAND)
		PNL_form.SetSizerAndFit(SZR_input)

		# layout page
		SZR_main = wx.BoxSizer(wx.VERTICAL)
		SZR_main.Add(PNL_form, 1, wx.EXPAND)
		self.SetSizer(SZR_main)
	#--------------------------------------------------------
	def set_identity(self, identity):
		return self.refresh(identity=identity)
	#--------------------------------------------------------
	def refresh(self, identity=None):
		if identity is not None:
			self.__ident = identity
		jobs = self.__ident.get_occupations()
		if len(jobs) > 0:
			self.PRW_occupation.SetText(jobs[0]['l10n_occupation'])
			self.TTC_occupation_updated.SetValue(jobs[0]['modified_when'].strftime('%m/%Y'))
		return True
	#--------------------------------------------------------
	def save(self):
		if self.PRW_occupation.IsModified():
			new_job = self.PRW_occupation.GetValue().strip()
			jobs = self.__ident.get_occupations()
			for job in jobs:
				if job['l10n_occupation'] == new_job:
					continue
				self.__ident.unlink_occupation(occupation = job['l10n_occupation'])
			self.__ident.link_occupation(occupation = new_job)
		return True
#============================================================
class cNotebookedPatEditionPanel(wx.Panel, gmRegetMixin.cRegetOnPaintMixin):
	"""Patient demographics plugin for main notebook.

	Hosts another notebook with pages for Identity, Contacts, etc.

	Acts on/listens to the currently active patient.
	"""
	#--------------------------------------------------------
	def __init__(self, parent, id):
		wx.Panel.__init__ (self, parent = parent, id = id, style = wx.NO_BORDER)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)
		self.__do_layout()
		self.__register_interests()
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __do_layout(self):
		"""Arrange widgets."""
		self.__patient_notebook = cPersonDemographicsEditorNb(self, -1)

		szr_main = wx.BoxSizer(wx.VERTICAL)
		szr_main.Add(self.__patient_notebook, 1, wx.EXPAND)
		self.SetSizerAndFit(szr_main)
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		gmDispatcher.connect(signal = u'pre_patient_selection', receiver = self._on_pre_patient_selection)
		gmDispatcher.connect(signal = u'post_patient_selection', receiver = self._on_post_patient_selection)
	#--------------------------------------------------------
	def _on_pre_patient_selection(self):
		self._schedule_data_reget()
	#--------------------------------------------------------
	def _on_post_patient_selection(self):
		self._schedule_data_reget()
	# reget mixin API
	#--------------------------------------------------------
	def _populate_with_data(self):
		"""Populate fields in pages with data from model."""
		pat = gmPerson.gmCurrentPatient()
		if pat.connected:
			self.__patient_notebook.identity = pat
		else:
			self.__patient_notebook.identity = None
		self.__patient_notebook.refresh()
		return True
#============================================================
#============================================================
if __name__ == "__main__":

	#--------------------------------------------------------
	def test_organizer_pnl():
		app = wx.PyWidgetTester(size = (600, 400))
		app.SetWidget(cKOrganizerSchedulePnl)
		app.MainLoop()
	#--------------------------------------------------------
	def test_person_names_pnl():
		app = wx.PyWidgetTester(size = (600, 400))
		widget = cPersonNamesManagerPnl(app.frame, -1)
		widget.identity = activate_patient()
		app.frame.Show(True)
		app.MainLoop()
	#--------------------------------------------------------
	def test_person_ids_pnl():
		app = wx.PyWidgetTester(size = (600, 400))
		widget = cPersonIDsManagerPnl(app.frame, -1)
		widget.identity = activate_patient()
		app.frame.Show(True)
		app.MainLoop()
	#--------------------------------------------------------
	def test_pat_ids_pnl():
		app = wx.PyWidgetTester(size = (600, 400))
		widget = cPersonIdentityManagerPnl(app.frame, -1)
		widget.identity = activate_patient()
		app.frame.Show(True)
		app.MainLoop()
	#--------------------------------------------------------
	def test_name_ea_pnl():
		app = wx.PyWidgetTester(size = (600, 400))
		app.SetWidget(cPersonNameEAPnl, name = activate_patient().get_active_name())
		app.MainLoop()
	#--------------------------------------------------------
	def test_cPersonDemographicsEditorNb():
		app = wx.PyWidgetTester(size = (600, 400))
		widget = cPersonDemographicsEditorNb(app.frame, -1)
		widget.identity = activate_patient()
		widget.refresh()
		app.frame.Show(True)
		app.MainLoop()
	#--------------------------------------------------------
	def activate_patient():
		patient = gmPersonSearch.ask_for_patient()
		if patient is None:
			print "No patient. Exiting gracefully..."
			sys.exit(0)
		from Gnumed.wxpython import gmPatSearchWidgets
		gmPatSearchWidgets.set_active_patient(patient=patient)
		return patient
	#--------------------------------------------------------
	if len(sys.argv) > 1 and sys.argv[1] == 'test':

		gmI18N.activate_locale()
		gmI18N.install_domain(domain='gnumed')
		gmPG2.get_connection()

#		app = wx.PyWidgetTester(size = (400, 300))
#		app.SetWidget(cNotebookedPatEditionPanel, -1)
#		app.frame.Show(True)
#		app.MainLoop()

		# phrasewheels
#		test_organizer_pnl()

		# identity related widgets
		#test_person_names_pnl()
		test_person_ids_pnl()
		#test_pat_ids_pnl()
		#test_name_ea_pnl()

		#test_cPersonDemographicsEditorNb()

#============================================================