File: gmPatPicWidgets.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 (200 lines) | stat: -rw-r--r-- 6,573 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
"""GNUmed patient picture widget."""

#=====================================================================
__author__  = "R.Terry <rterry@gnumed.net>,\
			   I.Haywood <i.haywood@ugrad.unimelb.edu.au>,\
			   K.Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = "GPL v2 or later"

# standard lib
import sys, os, os.path, logging


# 3rd party
import wx, wx.lib.imagebrowser


# GNUmed
from Gnumed.pycommon import gmDispatcher, gmTools, gmI18N, gmDateTime
from Gnumed.business import gmDocuments, gmPerson
from Gnumed.wxpython import gmGuiHelpers


_log = logging.getLogger('gm.ui')


ID_AcquirePhoto = wx.NewId()
ID_ImportPhoto = wx.NewId()
ID_Refresh = wx.NewId()

#=====================================================================
class cPatientPicture(wx.StaticBitmap):
	"""A patient picture control ready for display.
		with popup menu to import/export
		remove or Acquire from a device
	"""
	def __init__(self, *args, **kwargs):

		wx.StaticBitmap.__init__(self, *args, **kwargs)

		paths = gmTools.gmPaths(app_name = u'gnumed', wx = wx)
		self.__fallback_pic_name = os.path.join(paths.system_app_data_dir, 'bitmaps', 'empty-face-in-bust.png')
		self.__desired_width = 50
		self.__desired_height = 54
		self.__pat = gmPerson.gmCurrentPatient()

		self.__init_ui()
		self.__register_events()
	#-----------------------------------------------------------------
	# event handling
	#-----------------------------------------------------------------
	def __register_events(self):
		# wxPython events
		wx.EVT_RIGHT_UP(self, self._on_RightClick_photo)
		wx.EVT_MENU(self, ID_AcquirePhoto, self._on_AcquirePhoto)
		wx.EVT_MENU(self, ID_ImportPhoto, self._on_ImportPhoto)
		wx.EVT_MENU(self, ID_Refresh, self._on_refresh_from_backend)

		# dispatcher signals
		gmDispatcher.connect(receiver=self._on_post_patient_selection, signal = u'post_patient_selection')
	#-----------------------------------------------------------------
	def _on_post_patient_selection(self):
		self.__reload_photo()
	#-----------------------------------------------------------------
	def _on_RightClick_photo(self, event):
		if not self.__pat.connected:
			gmDispatcher.send(signal='statustext', msg=_('No active patient.'))
			return False
		self.PopupMenu(self.__photo_menu, event.GetPosition())
	#-----------------------------------------------------------------
	def _on_refresh_from_backend(self, evt):
		self.__reload_photo()
	#-----------------------------------------------------------------
	def _on_ImportPhoto(self, event):
		"""Import an existing photo."""

		# get from file system
		imp_dlg = wx.lib.imagebrowser.ImageDialog(parent = self, set_dir = os.path.expanduser('~'))
		imp_dlg.Centre()
		if imp_dlg.ShowModal() != wx.ID_OK:
			return

		self.__import_pic_into_db(fname = imp_dlg.GetFile())
		self.__reload_photo()
	#-----------------------------------------------------------------
	def _on_AcquirePhoto(self, event):

		# get from image source
		from Gnumed.pycommon import gmScanBackend

		try:
			fnames = gmScanBackend.acquire_pages_into_files (
				delay = 5,
				calling_window = self
			)
		except OSError:
			_log.exception('problem acquiring image from source')
			gmGuiHelpers.gm_show_error (
				aMessage = _(
					'No image could be acquired from the source.\n\n'
					'This may mean the scanner driver is not properly installed.\n\n'
					'On Windows you must install the TWAIN Python module\n'
					'while on Linux and MacOSX it is recommended to install\n'
					'the XSane package.'
				),
				aTitle = _('Acquiring photo')
			)
			return

		if fnames is False:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Patient photo could not be acquired from source.'),
				aTitle = _('Acquiring photo')
			)
			return

		if len(fnames) == 0:		# no pages scanned
			return

		self.__import_pic_into_db(fname=fnames[0])
		self.__reload_photo()
	#-----------------------------------------------------------------
	# internal API
	#-----------------------------------------------------------------
	def __init_ui(self):
		# pre-make context menu
		self.__photo_menu = wx.Menu()
		self.__photo_menu.Append(ID_Refresh, _('Refresh from database'))
		self.__photo_menu.AppendSeparator()
		self.__photo_menu.Append(ID_AcquirePhoto, _("Acquire from imaging device"))
		self.__photo_menu.Append(ID_ImportPhoto, _("Import from file"))

		self.__set_pic_from_file()
	#-----------------------------------------------------------------
	def __import_pic_into_db(self, fname=None):

		docs = gmDocuments.search_for_documents(patient_id = self.__pat.ID, type_id = gmDocuments.MUGSHOT)
		if len(docs) == 0:
			emr = self.__pat.get_emr()
			epi = emr.add_episode(episode_name = u'administrative')
			enc = emr.active_encounter
			doc = gmDocuments.create_document (
				document_type = gmDocuments.MUGSHOT,
				episode = epi['pk_episode'],
				encounter = enc['pk_encounter']
			)
		else:
			doc = docs[0]

		obj = doc.add_part(file=fname)
		return True
	#-----------------------------------------------------------------
	def __reload_photo(self):
		"""(Re)fetch patient picture from DB."""

		doc_folder = self.__pat.get_document_folder()
		photo = doc_folder.get_latest_mugshot()

		if photo is None:
			fname = None
			self.SetToolTipString (_(
				'Patient picture.\n'
				'\n'
				'Right-click for context menu.'
			))
#			gmDispatcher.send(signal='statustext', msg=_('Cannot get most recent patient photo from database.'))
		else:
			fname = photo.export_to_file()
			self.SetToolTipString (_(
				'Patient picture (%s).\n'
				'\n'
				'Right-click for context menu.'
			) % gmDateTime.pydt_strftime(photo['date_generated'], '%b %Y'))

		return self.__set_pic_from_file(fname)
	#-----------------------------------------------------------------
	def __set_pic_from_file(self, fname=None):
		if fname is None:
			fname = self.__fallback_pic_name
		try:
			img_data = wx.Image(fname, wx.BITMAP_TYPE_ANY)
			img_data.Rescale(self.__desired_width, self.__desired_height)
			bmp_data = wx.BitmapFromImage(img_data)
		except:
			_log.exception('cannot set patient picture from [%s]', fname)
			gmDispatcher.send(signal='statustext', msg=_('Cannot set patient picture from [%s].') % fname)
			return False
		del img_data
		self.SetBitmap(bmp_data)
		self.__pic_name = fname

		return True

#====================================================
# main
#----------------------------------------------------
if __name__ == "__main__":
	app = wx.PyWidgetTester(size = (200, 200))
	app.SetWidget(cPatientPicture, -1)
	app.MainLoop()
#====================================================