1
2 """GNUmed GUI client.
3
4 This contains the GUI application framework and main window
5 of the all signing all dancing GNUmed Python Reference
6 client. It relies on the <gnumed.py> launcher having set up
7 the non-GUI-related runtime environment.
8
9 This source code is protected by the GPL licensing scheme.
10 Details regarding the GPL are available at http://www.gnu.org
11 You may use and share it as long as you don't deny this right
12 to anybody else.
13
14 copyright: authors
15 """
16
17 __version__ = "$Revision: 1.491 $"
18 __author__ = "H. Herb <hherb@gnumed.net>,\
19 K. Hilbert <Karsten.Hilbert@gmx.net>,\
20 I. Haywood <i.haywood@ugrad.unimelb.edu.au>"
21 __license__ = 'GPL (details at http://www.gnu.org)'
22
23
24 import sys, time, os, cPickle, zlib, locale, os.path, datetime as pyDT
25 import webbrowser, shutil, logging, urllib2, subprocess, glob
26
27
28
29
30 if not hasattr(sys, 'frozen'):
31 import wxversion
32 wxversion.ensureMinimal('2.8-unicode', optionsRequired=True)
33
34 try:
35 import wx
36 import wx.lib.pubsub
37 except ImportError:
38 print "GNUmed startup: Cannot import wxPython library."
39 print "GNUmed startup: Make sure wxPython is installed."
40 print 'CRITICAL ERROR: Error importing wxPython. Halted.'
41 raise
42
43
44
45 version = int(u'%s%s' % (wx.MAJOR_VERSION, wx.MINOR_VERSION))
46 if (version < 28) or ('unicode' not in wx.PlatformInfo):
47 print "GNUmed startup: Unsupported wxPython version (%s: %s)." % (wx.VERSION_STRING, wx.PlatformInfo)
48 print "GNUmed startup: wxPython 2.8+ with unicode support is required."
49 print 'CRITICAL ERROR: Proper wxPython version not found. Halted.'
50 raise ValueError('wxPython 2.8+ with unicode support not found')
51
52
53
54 from Gnumed.pycommon import gmCfg, gmPG2, gmDispatcher, gmGuiBroker, gmI18N
55 from Gnumed.pycommon import gmExceptions, gmShellAPI, gmTools, gmDateTime
56 from Gnumed.pycommon import gmHooks, gmBackendListener, gmCfg2, gmLog2
57
58 from Gnumed.business import gmPerson, gmClinicalRecord, gmSurgery, gmEMRStructItems
59
60 from Gnumed.exporters import gmPatientExporter
61
62 from Gnumed.wxpython import gmGuiHelpers, gmHorstSpace, gmEMRBrowser
63 from Gnumed.wxpython import gmDemographicsWidgets, gmEMRStructWidgets
64 from Gnumed.wxpython import gmPatSearchWidgets, gmAllergyWidgets, gmListWidgets
65 from Gnumed.wxpython import gmProviderInboxWidgets, gmCfgWidgets, gmExceptionHandlingWidgets
66 from Gnumed.wxpython import gmNarrativeWidgets, gmPhraseWheel, gmMedicationWidgets
67 from Gnumed.wxpython import gmStaffWidgets, gmDocumentWidgets, gmTimer, gmMeasurementWidgets
68 from Gnumed.wxpython import gmFormWidgets, gmSnellen, gmVaccWidgets
69
70 try:
71 _('dummy-no-need-to-translate-but-make-epydoc-happy')
72 except NameError:
73 _ = lambda x:x
74
75 _cfg = gmCfg2.gmCfgData()
76 _provider = None
77 _scripting_listener = None
78
79 _log = logging.getLogger('gm.main')
80 _log.info(__version__)
81 _log.info('wxPython GUI framework: %s %s' % (wx.VERSION_STRING, wx.PlatformInfo))
82
83
84 icon_serpent = \
85 """x\xdae\x8f\xb1\x0e\x83 \x10\x86w\x9f\xe2\x92\x1blb\xf2\x07\x96\xeaH:0\xd6\
86 \xc1\x85\xd5\x98N5\xa5\xef?\xf5N\xd0\x8a\xdcA\xc2\xf7qw\x84\xdb\xfa\xb5\xcd\
87 \xd4\xda;\xc9\x1a\xc8\xb6\xcd<\xb5\xa0\x85\x1e\xeb\xbc\xbc7b!\xf6\xdeHl\x1c\
88 \x94\x073\xec<*\xf7\xbe\xf7\x99\x9d\xb21~\xe7.\xf5\x1f\x1c\xd3\xbdVlL\xc2\
89 \xcf\xf8ye\xd0\x00\x90\x0etH \x84\x80B\xaa\x8a\x88\x85\xc4(U\x9d$\xfeR;\xc5J\
90 \xa6\x01\xbbt9\xceR\xc8\x81e_$\x98\xb9\x9c\xa9\x8d,y\xa9t\xc8\xcf\x152\xe0x\
91 \xe9$\xf5\x07\x95\x0cD\x95t:\xb1\x92\xae\x9cI\xa8~\x84\x1f\xe0\xa3ec"""
92
94 """GNUmed client's main windows frame.
95
96 This is where it all happens. Avoid popping up any other windows.
97 Most user interaction should happen to and from widgets within this frame
98 """
99
100 - def __init__(self, parent, id, title, size=wx.DefaultSize):
101 """You'll have to browse the source to understand what the constructor does
102 """
103 wx.Frame.__init__(self, parent, id, title, size, style = wx.DEFAULT_FRAME_STYLE)
104
105 self.__gb = gmGuiBroker.GuiBroker()
106 self.__pre_exit_callbacks = []
107 self.bar_width = -1
108 self.menu_id2plugin = {}
109
110 _log.info('workplace is >>>%s<<<', gmSurgery.gmCurrentPractice().active_workplace)
111
112 self.__setup_main_menu()
113 self.setup_statusbar()
114 self.SetStatusText(_('You are logged in as %s%s.%s (%s). DB account <%s>.') % (
115 gmTools.coalesce(_provider['title'], ''),
116 _provider['firstnames'][:1],
117 _provider['lastnames'],
118 _provider['short_alias'],
119 _provider['db_user']
120 ))
121
122 self.__set_window_title_template()
123 self.__update_window_title()
124 self.__set_window_icon()
125
126 self.__register_events()
127
128 self.LayoutMgr = gmHorstSpace.cHorstSpaceLayoutMgr(self, -1)
129 self.vbox = wx.BoxSizer(wx.VERTICAL)
130 self.vbox.Add(self.LayoutMgr, 10, wx.EXPAND | wx.ALL, 1)
131
132 self.SetAutoLayout(True)
133 self.SetSizerAndFit(self.vbox)
134
135
136
137
138
139 self.__set_GUI_size()
140
142
143 icon_bmp_data = wx.BitmapFromXPMData(cPickle.loads(zlib.decompress(icon_serpent)))
144 icon = wx.EmptyIcon()
145 icon.CopyFromBitmap(icon_bmp_data)
146 self.SetIcon(icon)
147
149 """Try to get previous window size from backend."""
150
151 cfg = gmCfg.cCfgSQL()
152
153
154 width = int(cfg.get2 (
155 option = 'main.window.width',
156 workplace = gmSurgery.gmCurrentPractice().active_workplace,
157 bias = 'workplace',
158 default = 800
159 ))
160
161
162 height = int(cfg.get2 (
163 option = 'main.window.height',
164 workplace = gmSurgery.gmCurrentPractice().active_workplace,
165 bias = 'workplace',
166 default = 600
167 ))
168
169 dw = wx.DisplaySize()[0]
170 dh = wx.DisplaySize()[1]
171
172 _log.info('display size: %s:%s' % (wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X), wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)))
173 _log.debug('display size: %s:%s %s mm', dw, dh, str(wx.DisplaySizeMM()))
174 _log.debug('previous GUI size [%s:%s]', width, height)
175
176
177 if width > dw:
178 _log.debug('adjusting GUI width from %s to %s', width, dw)
179 width = dw
180
181 if height > dh:
182 _log.debug('adjusting GUI height from %s to %s', height, dh)
183 height = dh
184
185
186 if width < 100:
187 _log.debug('adjusting GUI width to minimum of 100 pixel')
188 width = 100
189 if height < 100:
190 _log.debug('adjusting GUI height to minimum of 100 pixel')
191 height = 100
192
193 _log.info('setting GUI to size [%s:%s]', width, height)
194
195 self.SetClientSize(wx.Size(width, height))
196
198 """Create the main menu entries.
199
200 Individual entries are farmed out to the modules.
201 """
202 global wx
203 self.mainmenu = wx.MenuBar()
204 self.__gb['main.mainmenu'] = self.mainmenu
205
206
207 menu_gnumed = wx.Menu()
208
209 self.menu_plugins = wx.Menu()
210 menu_gnumed.AppendMenu(wx.NewId(), _('&Go to plugin ...'), self.menu_plugins)
211
212 ID = wx.NewId()
213 menu_gnumed.Append(ID, _('Check for updates'), _('Check for new releases of the GNUmed client.'))
214 wx.EVT_MENU(self, ID, self.__on_check_for_updates)
215
216 item = menu_gnumed.Append(-1, _('Announce downtime'), _('Announce database maintenance downtime to all connected clients.'))
217 self.Bind(wx.EVT_MENU, self.__on_announce_maintenance, item)
218
219
220 menu_gnumed.AppendSeparator()
221
222
223 menu_config = wx.Menu()
224 menu_gnumed.AppendMenu(wx.NewId(), _('Preferences ...'), menu_config)
225
226 item = menu_config.Append(-1, _('List configuration'), _('List all configuration items stored in the database.'))
227 self.Bind(wx.EVT_MENU, self.__on_list_configuration, item)
228
229
230 menu_cfg_db = wx.Menu()
231 menu_config.AppendMenu(wx.NewId(), _('Database ...'), menu_cfg_db)
232
233 ID = wx.NewId()
234 menu_cfg_db.Append(ID, _('Language'), _('Configure the database language'))
235 wx.EVT_MENU(self, ID, self.__on_configure_db_lang)
236
237 ID = wx.NewId()
238 menu_cfg_db.Append(ID, _('Welcome message'), _('Configure the database welcome message (all users).'))
239 wx.EVT_MENU(self, ID, self.__on_configure_db_welcome)
240
241
242 menu_cfg_client = wx.Menu()
243 menu_config.AppendMenu(wx.NewId(), _('Client parameters ...'), menu_cfg_client)
244
245 ID = wx.NewId()
246 menu_cfg_client.Append(ID, _('Export chunk size'), _('Configure the chunk size used when exporting BLOBs from the database.'))
247 wx.EVT_MENU(self, ID, self.__on_configure_export_chunk_size)
248
249 ID = wx.NewId()
250 menu_cfg_client.Append(ID, _('Temporary directory'), _('Configure the directory to use as scratch space for temporary files.'))
251 wx.EVT_MENU(self, ID, self.__on_configure_temp_dir)
252
253 item = menu_cfg_client.Append(-1, _('Email address'), _('The email address of the user for sending bug reports, etc.'))
254 self.Bind(wx.EVT_MENU, self.__on_configure_user_email, item)
255
256
257 menu_cfg_ui = wx.Menu()
258 menu_config.AppendMenu(wx.NewId(), _('User interface ...'), menu_cfg_ui)
259
260
261 menu_cfg_doc = wx.Menu()
262 menu_cfg_ui.AppendMenu(wx.NewId(), _('Document handling ...'), menu_cfg_doc)
263
264 ID = wx.NewId()
265 menu_cfg_doc.Append(ID, _('Review dialog'), _('Configure review dialog after document display.'))
266 wx.EVT_MENU(self, ID, self.__on_configure_doc_review_dialog)
267
268 ID = wx.NewId()
269 menu_cfg_doc.Append(ID, _('UUID display'), _('Configure unique ID dialog on document import.'))
270 wx.EVT_MENU(self, ID, self.__on_configure_doc_uuid_dialog)
271
272 ID = wx.NewId()
273 menu_cfg_doc.Append(ID, _('Empty documents'), _('Whether to allow saving documents without parts.'))
274 wx.EVT_MENU(self, ID, self.__on_configure_partless_docs)
275
276
277 menu_cfg_update = wx.Menu()
278 menu_cfg_ui.AppendMenu(wx.NewId(), _('Update handling ...'), menu_cfg_update)
279
280 ID = wx.NewId()
281 menu_cfg_update.Append(ID, _('Auto-check'), _('Whether to auto-check for updates at startup.'))
282 wx.EVT_MENU(self, ID, self.__on_configure_update_check)
283
284 ID = wx.NewId()
285 menu_cfg_update.Append(ID, _('Check scope'), _('When checking for updates, consider latest branch, too ?'))
286 wx.EVT_MENU(self, ID, self.__on_configure_update_check_scope)
287
288 ID = wx.NewId()
289 menu_cfg_update.Append(ID, _('URL'), _('The URL to retrieve version information from.'))
290 wx.EVT_MENU(self, ID, self.__on_configure_update_url)
291
292
293 menu_cfg_pat_search = wx.Menu()
294 menu_cfg_ui.AppendMenu(wx.NewId(), _('Person ...'), menu_cfg_pat_search)
295
296 ID = wx.NewId()
297 menu_cfg_pat_search.Append(ID, _('Birthday reminder'), _('Configure birthday reminder proximity interval.'))
298 wx.EVT_MENU(self, ID, self.__on_configure_dob_reminder_proximity)
299
300 ID = wx.NewId()
301 menu_cfg_pat_search.Append(ID, _('Immediate source activation'), _('Configure immediate activation of single external person.'))
302 wx.EVT_MENU(self, ID, self.__on_configure_quick_pat_search)
303
304 ID = wx.NewId()
305 menu_cfg_pat_search.Append(ID, _('Initial plugin'), _('Configure which plugin to show right after person activation.'))
306 wx.EVT_MENU(self, ID, self.__on_configure_initial_pat_plugin)
307
308 item = menu_cfg_pat_search.Append(-1, _('Default region'), _('Configure the default province/region/state for person creation.'))
309 self.Bind(wx.EVT_MENU, self.__on_cfg_default_region, item)
310
311 item = menu_cfg_pat_search.Append(-1, _('Default country'), _('Configure the default country for person creation.'))
312 self.Bind(wx.EVT_MENU, self.__on_cfg_default_country, item)
313
314
315 menu_cfg_soap_editing = wx.Menu()
316 menu_cfg_ui.AppendMenu(wx.NewId(), _('Progress notes handling ...'), menu_cfg_soap_editing)
317
318 ID = wx.NewId()
319 menu_cfg_soap_editing.Append(ID, _('Multiple new episodes'), _('Configure opening multiple new episodes on a patient at once.'))
320 wx.EVT_MENU(self, ID, self.__on_allow_multiple_new_episodes)
321
322
323 menu_cfg_ext_tools = wx.Menu()
324 menu_config.AppendMenu(wx.NewId(), _('External tools ...'), menu_cfg_ext_tools)
325
326
327
328
329
330 item = menu_cfg_ext_tools.Append(-1, _('MI/stroke risk calc cmd'), _('Set the command to start the CV risk calculator.'))
331 self.Bind(wx.EVT_MENU, self.__on_configure_acs_risk_calculator_cmd, item)
332
333 ID = wx.NewId()
334 menu_cfg_ext_tools.Append(ID, _('OOo startup time'), _('Set the time to wait for OpenOffice to settle after startup.'))
335 wx.EVT_MENU(self, ID, self.__on_configure_ooo_settle_time)
336
337 item = menu_cfg_ext_tools.Append(-1, _('Measurements URL'), _('URL for measurements encyclopedia.'))
338 self.Bind(wx.EVT_MENU, self.__on_configure_measurements_url, item)
339
340 item = menu_cfg_ext_tools.Append(-1, _('Drug data source'), _('Select the drug data source.'))
341 self.Bind(wx.EVT_MENU, self.__on_configure_drug_data_source, item)
342
343 item = menu_cfg_ext_tools.Append(-1, _('FreeDiams path'), _('Set the path for the FreeDiams binary.'))
344 self.Bind(wx.EVT_MENU, self.__on_configure_freediams_cmd, item)
345
346 item = menu_cfg_ext_tools.Append(-1, _('Visual SOAP editor'), _('Set the command for calling the visual progress note editor.'))
347 self.Bind(wx.EVT_MENU, self.__on_configure_visual_soap_cmd, item)
348
349
350 menu_cfg_emr = wx.Menu()
351 menu_config.AppendMenu(wx.NewId(), _('EMR ...'), menu_cfg_emr)
352
353 item = menu_cfg_emr.Append(-1, _('Medication list template'), _('Select the template for printing a medication list.'))
354 self.Bind(wx.EVT_MENU, self.__on_cfg_medication_list_template, item)
355
356
357 menu_cfg_encounter = wx.Menu()
358 menu_cfg_emr.AppendMenu(wx.NewId(), _('Encounter ...'), menu_cfg_encounter)
359
360 ID = wx.NewId()
361 menu_cfg_encounter.Append(ID, _('Edit on patient change'), _('Edit encounter details on changing of patients.'))
362 wx.EVT_MENU(self, ID, self.__on_cfg_enc_pat_change)
363
364 ID = wx.NewId()
365 menu_cfg_encounter.Append(ID, _('Minimum duration'), _('Minimum duration of an encounter.'))
366 wx.EVT_MENU(self, ID, self.__on_cfg_enc_min_ttl)
367
368 ID = wx.NewId()
369 menu_cfg_encounter.Append(ID, _('Maximum duration'), _('Maximum duration of an encounter.'))
370 wx.EVT_MENU(self, ID, self.__on_cfg_enc_max_ttl)
371
372 ID = wx.NewId()
373 menu_cfg_encounter.Append(ID, _('Minimum empty age'), _('Minimum age of an empty encounter before considering for deletion.'))
374 wx.EVT_MENU(self, ID, self.__on_cfg_enc_empty_ttl)
375
376 ID = wx.NewId()
377 menu_cfg_encounter.Append(ID, _('Default type'), _('Default type for new encounters.'))
378 wx.EVT_MENU(self, ID, self.__on_cfg_enc_default_type)
379
380
381 menu_cfg_episode = wx.Menu()
382 menu_cfg_emr.AppendMenu(wx.NewId(), _('Episode ...'), menu_cfg_episode)
383
384 ID = wx.NewId()
385 menu_cfg_episode.Append(ID, _('Dormancy'), _('Maximum length of dormancy after which an episode will be considered closed.'))
386 wx.EVT_MENU(self, ID, self.__on_cfg_epi_ttl)
387
388
389 menu_master_data = wx.Menu()
390 menu_gnumed.AppendMenu(wx.NewId(), _('&Master data ...'), menu_master_data)
391
392 item = menu_master_data.Append(-1, _('Workplace profiles'), _('Manage the plugins to load per workplace.'))
393 self.Bind(wx.EVT_MENU, self.__on_configure_workplace, item)
394
395 menu_master_data.AppendSeparator()
396
397 item = menu_master_data.Append(-1, _('&Document types'), _('Manage the document types available in the system.'))
398 self.Bind(wx.EVT_MENU, self.__on_edit_doc_types, item)
399
400 item = menu_master_data.Append(-1, _('&Form templates'), _('Manage templates for forms and letters.'))
401 self.Bind(wx.EVT_MENU, self.__on_manage_form_templates, item)
402
403 item = menu_master_data.Append(-1, _('&Text expansions'), _('Manage keyword based text expansion macros.'))
404 self.Bind(wx.EVT_MENU, self.__on_manage_text_expansion, item)
405
406 menu_master_data.AppendSeparator()
407
408 item = menu_master_data.Append(-1, _('&Encounter types'), _('Manage encounter types.'))
409 self.Bind(wx.EVT_MENU, self.__on_manage_encounter_types, item)
410
411 item = menu_master_data.Append(-1, _('&Provinces'), _('Manage provinces (counties, territories, ...).'))
412 self.Bind(wx.EVT_MENU, self.__on_manage_provinces, item)
413
414 menu_master_data.AppendSeparator()
415
416 item = menu_master_data.Append(-1, _('Substances'), _('Manage substances in use.'))
417 self.Bind(wx.EVT_MENU, self.__on_manage_substances, item)
418
419 item = menu_master_data.Append(-1, _('Drugs'), _('Manage branded drugs.'))
420 self.Bind(wx.EVT_MENU, self.__on_manage_branded_drugs, item)
421
422 item = menu_master_data.Append(-1, _('Drug components'), _('Manage components of branded drugs.'))
423 self.Bind(wx.EVT_MENU, self.__on_manage_substances_in_brands, item)
424
425 item = menu_master_data.Append(-1, _('Update ATC'), _('Install ATC reference data.'))
426 self.Bind(wx.EVT_MENU, self.__on_update_atc, item)
427
428 menu_master_data.AppendSeparator()
429
430 item = menu_master_data.Append(-1, _('Diagnostic orgs'), _('Manage diagnostic organisations (path labs etc).'))
431 self.Bind(wx.EVT_MENU, self.__on_manage_test_orgs, item)
432
433 item = menu_master_data.Append(-1, _('&Test types'), _('Manage test/measurement types.'))
434 self.Bind(wx.EVT_MENU, self.__on_manage_test_types, item)
435
436 item = menu_master_data.Append(-1, _('&Meta test types'), _('Show meta test/measurement types.'))
437 self.Bind(wx.EVT_MENU, self.__on_manage_meta_test_types, item)
438
439 item = menu_master_data.Append(-1, _('Update LOINC'), _('Download and install LOINC reference data.'))
440 self.Bind(wx.EVT_MENU, self.__on_update_loinc, item)
441
442 menu_master_data.AppendSeparator()
443
444 item = menu_master_data.Append(-1, _('Vaccines'), _('Show known vaccines.'))
445 self.Bind(wx.EVT_MENU, self.__on_manage_vaccines, item)
446
447
448 menu_users = wx.Menu()
449 menu_gnumed.AppendMenu(wx.NewId(), _('&Users ...'), menu_users)
450
451 item = menu_users.Append(-1, _('&Add user'), _('Add a new GNUmed user'))
452 self.Bind(wx.EVT_MENU, self.__on_add_new_staff, item)
453
454 item = menu_users.Append(-1, _('&Edit users'), _('Edit the list of GNUmed users'))
455 self.Bind(wx.EVT_MENU, self.__on_edit_staff_list, item)
456
457
458 menu_gnumed.AppendSeparator()
459
460 item = menu_gnumed.Append(wx.ID_EXIT, _('E&xit\tAlt-X'), _('Close this GNUmed client.'))
461 self.Bind(wx.EVT_MENU, self.__on_exit_gnumed, item)
462
463 self.mainmenu.Append(menu_gnumed, '&GNUmed')
464
465
466 menu_patient = wx.Menu()
467
468 ID_CREATE_PATIENT = wx.NewId()
469 menu_patient.Append(ID_CREATE_PATIENT, _('Register person'), _("Register a new person with GNUmed"))
470 wx.EVT_MENU(self, ID_CREATE_PATIENT, self.__on_create_new_patient)
471
472
473
474
475 ID_LOAD_EXT_PAT = wx.NewId()
476 menu_patient.Append(ID_LOAD_EXT_PAT, _('Load external'), _('Load and possibly create person from an external source.'))
477 wx.EVT_MENU(self, ID_LOAD_EXT_PAT, self.__on_load_external_patient)
478
479 ID_DEL_PAT = wx.NewId()
480 menu_patient.Append(ID_DEL_PAT, _('Deactivate record'), _('Deactivate (exclude from search) person record in database.'))
481 wx.EVT_MENU(self, ID_DEL_PAT, self.__on_delete_patient)
482
483 item = menu_patient.Append(-1, _('&Merge persons'), _('Merge two persons into one.'))
484 self.Bind(wx.EVT_MENU, self.__on_merge_patients, item)
485
486 menu_patient.AppendSeparator()
487
488 ID_ENLIST_PATIENT_AS_STAFF = wx.NewId()
489 menu_patient.Append(ID_ENLIST_PATIENT_AS_STAFF, _('Enlist as user'), _('Enlist current person as GNUmed user'))
490 wx.EVT_MENU(self, ID_ENLIST_PATIENT_AS_STAFF, self.__on_enlist_patient_as_staff)
491
492
493 ID = wx.NewId()
494 menu_patient.Append(ID, _('Export to GDT'), _('Export demographics of currently active person into GDT file.'))
495 wx.EVT_MENU(self, ID, self.__on_export_as_gdt)
496
497 menu_patient.AppendSeparator()
498
499 self.mainmenu.Append(menu_patient, '&Person')
500 self.__gb['main.patientmenu'] = menu_patient
501
502
503 menu_emr = wx.Menu()
504 self.mainmenu.Append(menu_emr, _("&EMR"))
505 self.__gb['main.emrmenu'] = menu_emr
506
507
508 menu_emr_show = wx.Menu()
509 menu_emr.AppendMenu(wx.NewId(), _('Show as ...'), menu_emr_show)
510 self.__gb['main.emr_showmenu'] = menu_emr_show
511
512
513 item = menu_emr_show.Append(-1, _('Summary'), _('Show a high-level summary of the EMR.'))
514 self.Bind(wx.EVT_MENU, self.__on_show_emr_summary, item)
515
516
517 item = menu_emr.Append(-1, _('Search this EMR'), _('Search for data in the EMR of the active patient'))
518 self.Bind(wx.EVT_MENU, self.__on_search_emr, item)
519
520 item = menu_emr.Append(-1, _('Search all EMRs'), _('Search for data across the EMRs of all patients'))
521 self.Bind(wx.EVT_MENU, self.__on_search_across_emrs, item)
522
523
524 menu_emr_edit = wx.Menu()
525 menu_emr.AppendMenu(wx.NewId(), _('&Add / Edit ...'), menu_emr_edit)
526
527 item = menu_emr_edit.Append(-1, _('&Past history (health issue / PMH)'), _('Add a past/previous medical history item (health issue) to the EMR of the active patient'))
528 self.Bind(wx.EVT_MENU, self.__on_add_health_issue, item)
529
530 item = menu_emr_edit.Append(-1, _('&Medication'), _('Add medication / substance use entry.'))
531 self.Bind(wx.EVT_MENU, self.__on_add_medication, item)
532
533 item = menu_emr_edit.Append(-1, _('&Allergies'), _('Manage documentation of allergies for the current patient.'))
534 self.Bind(wx.EVT_MENU, self.__on_manage_allergies, item)
535
536 item = menu_emr_edit.Append(-1, _('&Occupation'), _('Edit occupation details for the current patient.'))
537 self.Bind(wx.EVT_MENU, self.__on_edit_occupation, item)
538
539 item = menu_emr_edit.Append(-1, _('&Hospital stays'), _('Manage hospital stays.'))
540 self.Bind(wx.EVT_MENU, self.__on_manage_hospital_stays, item)
541
542 item = menu_emr_edit.Append(-1, _('&Procedures'), _('Manage procedures performed on the patient.'))
543 self.Bind(wx.EVT_MENU, self.__on_manage_performed_procedures, item)
544
545 item = menu_emr_edit.Append(-1, _('&Measurement(s)'), _('Add (a) measurement result(s) for the current patient.'))
546 self.Bind(wx.EVT_MENU, self.__on_add_measurement, item)
547
548
549
550
551
552
553
554 item = menu_emr.Append(-1, _('Start new encounter'), _('Start a new encounter for the active patient right now.'))
555 self.Bind(wx.EVT_MENU, self.__on_start_new_encounter, item)
556
557
558 item = menu_emr.Append(-1, _('&Encounters list'), _('List all encounters including empty ones.'))
559 self.Bind(wx.EVT_MENU, self.__on_list_encounters, item)
560
561
562 menu_emr.AppendSeparator()
563
564 menu_emr_export = wx.Menu()
565 menu_emr.AppendMenu(wx.NewId(), _('Export as ...'), menu_emr_export)
566
567 ID_EXPORT_EMR_ASCII = wx.NewId()
568 menu_emr_export.Append (
569 ID_EXPORT_EMR_ASCII,
570 _('Text document'),
571 _("Export the EMR of the active patient into a text file")
572 )
573 wx.EVT_MENU(self, ID_EXPORT_EMR_ASCII, self.OnExportEMR)
574
575 ID_EXPORT_EMR_JOURNAL = wx.NewId()
576 menu_emr_export.Append (
577 ID_EXPORT_EMR_JOURNAL,
578 _('Journal'),
579 _("Export the EMR of the active patient as a chronological journal into a text file")
580 )
581 wx.EVT_MENU(self, ID_EXPORT_EMR_JOURNAL, self.__on_export_emr_as_journal)
582
583 ID_EXPORT_MEDISTAR = wx.NewId()
584 menu_emr_export.Append (
585 ID_EXPORT_MEDISTAR,
586 _('MEDISTAR import format'),
587 _("GNUmed -> MEDISTAR. Export progress notes of active patient's active encounter into a text file.")
588 )
589 wx.EVT_MENU(self, ID_EXPORT_MEDISTAR, self.__on_export_for_medistar)
590
591
592 menu_emr.AppendSeparator()
593
594
595 menu_paperwork = wx.Menu()
596
597 item = menu_paperwork.Append(-1, _('&Write letter'), _('Write a letter for the current patient.'))
598 self.Bind(wx.EVT_MENU, self.__on_new_letter, item)
599
600 self.mainmenu.Append(menu_paperwork, _('&Correspondence'))
601
602
603 self.menu_tools = wx.Menu()
604 self.__gb['main.toolsmenu'] = self.menu_tools
605 self.mainmenu.Append(self.menu_tools, _("&Tools"))
606
607 ID_DICOM_VIEWER = wx.NewId()
608 viewer = _('no viewer installed')
609 if os.access('/Applications/OsiriX.app/Contents/MacOS/OsiriX', os.X_OK):
610 viewer = u'OsiriX'
611 elif gmShellAPI.detect_external_binary(binary = 'aeskulap')[0]:
612 viewer = u'Aeskulap'
613 elif gmShellAPI.detect_external_binary(binary = 'amide')[0]:
614 viewer = u'AMIDE'
615 elif gmShellAPI.detect_external_binary(binary = 'xmedcon')[0]:
616 viewer = u'(x)medcon'
617 self.menu_tools.Append(ID_DICOM_VIEWER, _('DICOM viewer'), _('Start DICOM viewer (%s) for CD-ROM (X-Ray, CT, MR, etc). On Windows just insert CD.') % viewer)
618 wx.EVT_MENU(self, ID_DICOM_VIEWER, self.__on_dicom_viewer)
619 if viewer == _('no viewer installed'):
620 _log.info('neither of OsiriX / Aeskulap / AMIDE / xmedcon found, disabling "DICOM viewer" menu item')
621 self.menu_tools.Enable(id=ID_DICOM_VIEWER, enable=False)
622
623
624
625
626
627 ID = wx.NewId()
628 self.menu_tools.Append(ID, _('Snellen chart'), _('Display fullscreen snellen chart.'))
629 wx.EVT_MENU(self, ID, self.__on_snellen)
630
631 item = self.menu_tools.Append(-1, _('MI/stroke risk'), _('Acute coronary syndrome/stroke risk assessment.'))
632 self.Bind(wx.EVT_MENU, self.__on_acs_risk_assessment, item)
633
634 self.menu_tools.AppendSeparator()
635
636
637 menu_knowledge = wx.Menu()
638 self.__gb['main.knowledgemenu'] = menu_knowledge
639 self.mainmenu.Append(menu_knowledge, _('&Knowledge'))
640
641 menu_drug_dbs = wx.Menu()
642 menu_knowledge.AppendMenu(wx.NewId(), _('&Drug Resources'), menu_drug_dbs)
643
644 item = menu_drug_dbs.Append(-1, _('&Database'), _('Jump to the drug database configured as the default.'))
645 self.Bind(wx.EVT_MENU, self.__on_jump_to_drug_db, item)
646
647
648
649
650
651
652 menu_id = wx.NewId()
653 menu_drug_dbs.Append(menu_id, u'kompendium.ch', _('Show "kompendium.ch" drug database (online, Switzerland)'))
654 wx.EVT_MENU(self, menu_id, self.__on_kompendium_ch)
655
656
657
658
659 ID_MEDICAL_LINKS = wx.NewId()
660 menu_knowledge.Append(ID_MEDICAL_LINKS, _('Medical links (www)'), _('Show a page of links to useful medical content.'))
661 wx.EVT_MENU(self, ID_MEDICAL_LINKS, self.__on_medical_links)
662
663
664 self.menu_office = wx.Menu()
665
666 self.__gb['main.officemenu'] = self.menu_office
667 self.mainmenu.Append(self.menu_office, _('&Office'))
668
669
670 help_menu = wx.Menu()
671
672 ID = wx.NewId()
673 help_menu.Append(ID, _('GNUmed wiki'), _('Go to the GNUmed wiki on the web.'))
674 wx.EVT_MENU(self, ID, self.__on_display_wiki)
675
676 ID = wx.NewId()
677 help_menu.Append(ID, _('User manual (www)'), _('Go to the User Manual on the web.'))
678 wx.EVT_MENU(self, ID, self.__on_display_user_manual_online)
679
680 item = help_menu.Append(-1, _('Menu reference (www)'), _('View the reference for menu items on the web.'))
681 self.Bind(wx.EVT_MENU, self.__on_menu_reference, item)
682
683 menu_debugging = wx.Menu()
684 help_menu.AppendMenu(wx.NewId(), _('Debugging ...'), menu_debugging)
685
686 ID_SCREENSHOT = wx.NewId()
687 menu_debugging.Append(ID_SCREENSHOT, _('Screenshot'), _('Save a screenshot of this GNUmed client.'))
688 wx.EVT_MENU(self, ID_SCREENSHOT, self.__on_save_screenshot)
689
690 item = menu_debugging.Append(-1, _('Show log file'), _('Show the log file in text viewer.'))
691 self.Bind(wx.EVT_MENU, self.__on_show_log_file, item)
692
693 ID = wx.NewId()
694 menu_debugging.Append(ID, _('Backup log file'), _('Backup the content of the log to another file.'))
695 wx.EVT_MENU(self, ID, self.__on_backup_log_file)
696
697 ID = wx.NewId()
698 menu_debugging.Append(ID, _('Bug tracker'), _('Go to the GNUmed bug tracker on the web.'))
699 wx.EVT_MENU(self, ID, self.__on_display_bugtracker)
700
701 ID_UNBLOCK = wx.NewId()
702 menu_debugging.Append(ID_UNBLOCK, _('Unlock mouse'), _('Unlock mouse pointer in case it got stuck in hourglass mode.'))
703 wx.EVT_MENU(self, ID_UNBLOCK, self.__on_unblock_cursor)
704
705 item = menu_debugging.Append(-1, _('pgAdmin III'), _('pgAdmin III: Browse GNUmed database(s) in PostgreSQL server.'))
706 self.Bind(wx.EVT_MENU, self.__on_pgadmin3, item)
707
708
709
710
711 if _cfg.get(option = 'debug'):
712 ID_TOGGLE_PAT_LOCK = wx.NewId()
713 menu_debugging.Append(ID_TOGGLE_PAT_LOCK, _('Lock/unlock patient'), _('Lock/unlock patient - USE ONLY IF YOU KNOW WHAT YOU ARE DOING !'))
714 wx.EVT_MENU(self, ID_TOGGLE_PAT_LOCK, self.__on_toggle_patient_lock)
715
716 ID_TEST_EXCEPTION = wx.NewId()
717 menu_debugging.Append(ID_TEST_EXCEPTION, _('Test error handling'), _('Throw an exception to test error handling.'))
718 wx.EVT_MENU(self, ID_TEST_EXCEPTION, self.__on_test_exception)
719
720 ID = wx.NewId()
721 menu_debugging.Append(ID, _('Invoke inspector'), _('Invoke the widget hierarchy inspector (needs wxPython 2.8).'))
722 wx.EVT_MENU(self, ID, self.__on_invoke_inspector)
723 try:
724 import wx.lib.inspection
725 except ImportError:
726 menu_debugging.Enable(id = ID, enable = False)
727
728 help_menu.AppendSeparator()
729
730 help_menu.Append(wx.ID_ABOUT, _('About GNUmed'), "")
731 wx.EVT_MENU (self, wx.ID_ABOUT, self.OnAbout)
732
733 ID_CONTRIBUTORS = wx.NewId()
734 help_menu.Append(ID_CONTRIBUTORS, _('GNUmed contributors'), _('show GNUmed contributors'))
735 wx.EVT_MENU(self, ID_CONTRIBUTORS, self.__on_show_contributors)
736
737 item = help_menu.Append(-1, _('About database'), _('Show information about the current database.'))
738 self.Bind(wx.EVT_MENU, self.__on_about_database, item)
739
740 help_menu.AppendSeparator()
741
742
743 self.__gb['main.helpmenu'] = help_menu
744 self.mainmenu.Append(help_menu, _("&Help"))
745
746
747
748 self.SetMenuBar(self.mainmenu)
749
752
753
754
756 """register events we want to react to"""
757
758 wx.EVT_CLOSE(self, self.OnClose)
759 wx.EVT_QUERY_END_SESSION(self, self._on_query_end_session)
760 wx.EVT_END_SESSION(self, self._on_end_session)
761
762 gmDispatcher.connect(signal = u'post_patient_selection', receiver = self._on_post_patient_selection)
763 gmDispatcher.connect(signal = u'name_mod_db', receiver = self._on_pat_name_changed)
764 gmDispatcher.connect(signal = u'identity_mod_db', receiver = self._on_pat_name_changed)
765 gmDispatcher.connect(signal = u'statustext', receiver = self._on_set_statustext)
766 gmDispatcher.connect(signal = u'request_user_attention', receiver = self._on_request_user_attention)
767 gmDispatcher.connect(signal = u'db_maintenance_warning', receiver = self._on_db_maintenance_warning)
768 gmDispatcher.connect(signal = u'register_pre_exit_callback', receiver = self._register_pre_exit_callback)
769 gmDispatcher.connect(signal = u'plugin_loaded', receiver = self._on_plugin_loaded)
770
771 wx.lib.pubsub.Publisher().subscribe(listener = self._on_set_statustext_pubsub, topic = 'statustext')
772
773 gmPerson.gmCurrentPatient().register_pre_selection_callback(callback = self._pre_selection_callback)
774
775 - def _on_plugin_loaded(self, plugin_name=None, class_name=None, menu_name=None, menu_item_name=None, menu_help_string=None):
776
777 _log.debug('registering plugin with menu system')
778 _log.debug(' generic name: %s', plugin_name)
779 _log.debug(' class name: %s', class_name)
780 _log.debug(' specific menu: %s', menu_name)
781 _log.debug(' menu item: %s', menu_item_name)
782
783
784 item = self.menu_plugins.Append(-1, plugin_name, _('Raise plugin [%s].') % plugin_name)
785 self.Bind(wx.EVT_MENU, self.__on_raise_a_plugin, item)
786 self.menu_id2plugin[item.Id] = class_name
787
788
789 if menu_name is not None:
790 menu = self.__gb['main.%smenu' % menu_name]
791 item = menu.Append(-1, menu_item_name, menu_help_string)
792 self.Bind(wx.EVT_MENU, self.__on_raise_a_plugin, item)
793 self.menu_id2plugin[item.Id] = class_name
794
795 return True
796
798 gmDispatcher.send (
799 signal = u'display_widget',
800 name = self.menu_id2plugin[evt.Id]
801 )
802
804 wx.Bell()
805 wx.Bell()
806 wx.Bell()
807 _log.warning('unhandled event detected: QUERY_END_SESSION')
808 _log.info('we should be saving ourselves from here')
809 gmLog2.flush()
810 print "unhandled event detected: QUERY_END_SESSION"
811
813 wx.Bell()
814 wx.Bell()
815 wx.Bell()
816 _log.warning('unhandled event detected: END_SESSION')
817 gmLog2.flush()
818 print "unhandled event detected: END_SESSION"
819
821 if not callable(callback):
822 raise TypeError(u'callback [%s] not callable' % callback)
823
824 self.__pre_exit_callbacks.append(callback)
825
826 - def _on_set_statustext_pubsub(self, context=None):
827 msg = u'%s %s' % (gmDateTime.pydt_now_here().strftime('%H:%M'), context.data['msg'])
828 wx.CallAfter(self.SetStatusText, msg)
829
830 try:
831 if context.data['beep']:
832 wx.Bell()
833 except KeyError:
834 pass
835
836 - def _on_set_statustext(self, msg=None, loglevel=None, beep=True):
837
838 if msg is None:
839 msg = _('programmer forgot to specify status message')
840
841 if loglevel is not None:
842 _log.log(loglevel, msg.replace('\015', ' ').replace('\012', ' '))
843
844 msg = u'%s %s' % (gmDateTime.pydt_now_here().strftime('%H:%M'), msg)
845 wx.CallAfter(self.SetStatusText, msg)
846
847 if beep:
848 wx.Bell()
849
851 wx.CallAfter(self.__on_db_maintenance_warning)
852
854
855 self.SetStatusText(_('The database will be shut down for maintenance in a few minutes.'))
856 wx.Bell()
857 if not wx.GetApp().IsActive():
858 self.RequestUserAttention(flags = wx.USER_ATTENTION_ERROR)
859
860 gmHooks.run_hook_script(hook = u'db_maintenance_warning')
861
862 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
863 None,
864 -1,
865 caption = _('Database shutdown warning'),
866 question = _(
867 'The database will be shut down for maintenance\n'
868 'in a few minutes.\n'
869 '\n'
870 'In order to not suffer any loss of data you\n'
871 'will need to save your current work and log\n'
872 'out of this GNUmed client.\n'
873 ),
874 button_defs = [
875 {
876 u'label': _('Close now'),
877 u'tooltip': _('Close this GNUmed client immediately.'),
878 u'default': False
879 },
880 {
881 u'label': _('Finish work'),
882 u'tooltip': _('Finish and save current work first, then manually close this GNUmed client.'),
883 u'default': True
884 }
885 ]
886 )
887 decision = dlg.ShowModal()
888 if decision == wx.ID_YES:
889 top_win = wx.GetApp().GetTopWindow()
890 wx.CallAfter(top_win.Close)
891
893 wx.CallAfter(self.__on_request_user_attention, msg, urgent)
894
896
897 if not wx.GetApp().IsActive():
898 if urgent:
899 self.RequestUserAttention(flags = wx.USER_ATTENTION_ERROR)
900 else:
901 self.RequestUserAttention(flags = wx.USER_ATTENTION_INFO)
902
903 if msg is not None:
904 self.SetStatusText(msg)
905
906 if urgent:
907 wx.Bell()
908
909 gmHooks.run_hook_script(hook = u'request_user_attention')
910
912 wx.CallAfter(self.__on_pat_name_changed)
913
915 self.__update_window_title()
916
918 wx.CallAfter(self.__on_post_patient_selection, **kwargs)
919
921 self.__update_window_title()
922 try:
923 gmHooks.run_hook_script(hook = u'post_patient_activation')
924 except:
925 gmDispatcher.send(signal = 'statustext', msg = _('Cannot run script after patient activation.'))
926 raise
927
929 return self.__sanity_check_encounter()
930
988
989
990
993
1001
1004
1005
1006
1021
1044
1046 from Gnumed.wxpython import gmAbout
1047 contribs = gmAbout.cContributorsDlg (
1048 parent = self,
1049 id = -1,
1050 title = _('GNUmed contributors'),
1051 size = wx.Size(400,600),
1052 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
1053 )
1054 contribs.ShowModal()
1055 del contribs
1056 del gmAbout
1057
1058
1059
1061 """Invoked from Menu GNUmed / Exit (which calls this ID_EXIT handler)."""
1062 _log.debug('gmTopLevelFrame._on_exit_gnumed() start')
1063 self.Close(True)
1064 _log.debug('gmTopLevelFrame._on_exit_gnumed() end')
1065
1068
1070 send = gmGuiHelpers.gm_show_question (
1071 _('This will send a notification about database downtime\n'
1072 'to all GNUmed clients connected to your database.\n'
1073 '\n'
1074 'Do you want to send the notification ?\n'
1075 ),
1076 _('Announcing database maintenance downtime')
1077 )
1078 if not send:
1079 return
1080 gmPG2.send_maintenance_notification()
1081
1082
1085
1086
1087
1119
1132
1133 gmCfgWidgets.configure_string_option (
1134 message = _(
1135 'Some network installations cannot cope with loading\n'
1136 'documents of arbitrary size in one piece from the\n'
1137 'database (mainly observed on older Windows versions)\n.'
1138 '\n'
1139 'Under such circumstances documents need to be retrieved\n'
1140 'in chunks and reassembled on the client.\n'
1141 '\n'
1142 'Here you can set the size (in Bytes) above which\n'
1143 'GNUmed will retrieve documents in chunks. Setting this\n'
1144 'value to 0 will disable the chunking protocol.'
1145 ),
1146 option = 'horstspace.blob_export_chunk_size',
1147 bias = 'workplace',
1148 default_value = 1024 * 1024,
1149 validator = is_valid
1150 )
1151
1152
1153
1221
1225
1226
1227
1236
1237 gmCfgWidgets.configure_string_option (
1238 message = _(
1239 'When GNUmed cannot find an OpenOffice server it\n'
1240 'will try to start one. OpenOffice, however, needs\n'
1241 'some time to fully start up.\n'
1242 '\n'
1243 'Here you can set the time for GNUmed to wait for OOo.\n'
1244 ),
1245 option = 'external.ooo.startup_settle_time',
1246 bias = 'workplace',
1247 default_value = 2.0,
1248 validator = is_valid
1249 )
1250
1253
1265
1266 gmCfgWidgets.configure_string_option (
1267 message = _(
1268 'GNUmed will use this URL to access an encyclopedia of\n'
1269 'measurement/lab methods from within the measurments grid.\n'
1270 '\n'
1271 'You can leave this empty but to set it to a specific\n'
1272 'address the URL must be accessible now.'
1273 ),
1274 option = 'external.urls.measurements_encyclopedia',
1275 bias = 'user',
1276 default_value = u'http://www.laborlexikon.de',
1277 validator = is_valid
1278 )
1279
1292
1293 gmCfgWidgets.configure_string_option (
1294 message = _(
1295 'Enter the shell command with which to start the\n'
1296 'the ACS risk assessment calculator.\n'
1297 '\n'
1298 'GNUmed will try to verify the path which may,\n'
1299 'however, fail if you are using an emulator such\n'
1300 'as Wine. Nevertheless, starting the calculator\n'
1301 'will work as long as the shell command is correct\n'
1302 'despite the failing test.'
1303 ),
1304 option = 'external.tools.acs_risk_calculator_cmd',
1305 bias = 'user',
1306 validator = is_valid
1307 )
1308
1311
1324
1325 gmCfgWidgets.configure_string_option (
1326 message = _(
1327 'Enter the shell command with which to start\n'
1328 'the FreeDiams drug database frontend.\n'
1329 '\n'
1330 'GNUmed will try to verify that path.'
1331 ),
1332 option = 'external.tools.freediams_cmd',
1333 bias = 'workplace',
1334 default_value = None,
1335 validator = is_valid
1336 )
1337
1350
1351 gmCfgWidgets.configure_string_option (
1352 message = _(
1353 'Enter the shell command with which to start the\n'
1354 'the IFAP drug database.\n'
1355 '\n'
1356 'GNUmed will try to verify the path which may,\n'
1357 'however, fail if you are using an emulator such\n'
1358 'as Wine. Nevertheless, starting IFAP will work\n'
1359 'as long as the shell command is correct despite\n'
1360 'the failing test.'
1361 ),
1362 option = 'external.ifap-win.shell_command',
1363 bias = 'workplace',
1364 default_value = 'C:\Ifapwin\WIAMDB.EXE',
1365 validator = is_valid
1366 )
1367
1368
1369
1418
1419
1420
1437
1440
1443
1448
1449 gmCfgWidgets.configure_string_option (
1450 message = _(
1451 'When a patient is activated GNUmed checks the\n'
1452 "proximity of the patient's birthday.\n"
1453 '\n'
1454 'If the birthday falls within the range of\n'
1455 ' "today %s <the interval you set here>"\n'
1456 'GNUmed will remind you of the recent or\n'
1457 'imminent anniversary.'
1458 ) % u'\u2213',
1459 option = u'patient_search.dob_warn_interval',
1460 bias = 'user',
1461 default_value = '1 week',
1462 validator = is_valid
1463 )
1464
1466
1467 gmCfgWidgets.configure_boolean_option (
1468 parent = self,
1469 question = _(
1470 'When adding progress notes do you want to\n'
1471 'allow opening several unassociated, new\n'
1472 'episodes for a patient at once ?\n'
1473 '\n'
1474 'This can be particularly helpful when entering\n'
1475 'progress notes on entirely new patients presenting\n'
1476 'with a multitude of problems on their first visit.'
1477 ),
1478 option = u'horstspace.soap_editor.allow_same_episode_multiple_times',
1479 button_tooltips = [
1480 _('Yes, allow for multiple new episodes concurrently.'),
1481 _('No, only allow editing one new episode at a time.')
1482 ]
1483 )
1484
1530
1531
1532
1535
1549
1551 gmCfgWidgets.configure_boolean_option (
1552 parent = self,
1553 question = _(
1554 'Do you want GNUmed to show the encounter\n'
1555 'details editor when changing the active patient ?'
1556 ),
1557 option = 'encounter.show_editor_before_patient_change',
1558 button_tooltips = [
1559 _('Yes, show the encounter editor if it seems appropriate.'),
1560 _('No, never show the encounter editor even if it would seem useful.')
1561 ]
1562 )
1563
1568
1569 gmCfgWidgets.configure_string_option (
1570 message = _(
1571 'When a patient is activated GNUmed checks the\n'
1572 'chart for encounters lacking any entries.\n'
1573 '\n'
1574 'Any such encounters older than what you set\n'
1575 'here will be removed from the medical record.\n'
1576 '\n'
1577 'To effectively disable removal of such encounters\n'
1578 'set this option to an improbable value.\n'
1579 ),
1580 option = 'encounter.ttl_if_empty',
1581 bias = 'user',
1582 default_value = '1 week',
1583 validator = is_valid
1584 )
1585
1590
1591 gmCfgWidgets.configure_string_option (
1592 message = _(
1593 'When a patient is activated GNUmed checks the\n'
1594 'age of the most recent encounter.\n'
1595 '\n'
1596 'If that encounter is younger than this age\n'
1597 'the existing encounter will be continued.\n'
1598 '\n'
1599 '(If it is really old a new encounter is\n'
1600 ' started, or else GNUmed will ask you.)\n'
1601 ),
1602 option = 'encounter.minimum_ttl',
1603 bias = 'user',
1604 default_value = '1 hour 30 minutes',
1605 validator = is_valid
1606 )
1607
1612
1613 gmCfgWidgets.configure_string_option (
1614 message = _(
1615 'When a patient is activated GNUmed checks the\n'
1616 'age of the most recent encounter.\n'
1617 '\n'
1618 'If that encounter is older than this age\n'
1619 'GNUmed will always start a new encounter.\n'
1620 '\n'
1621 '(If it is very recent the existing encounter\n'
1622 ' is continued, or else GNUmed will ask you.)\n'
1623 ),
1624 option = 'encounter.maximum_ttl',
1625 bias = 'user',
1626 default_value = '6 hours',
1627 validator = is_valid
1628 )
1629
1638
1639 gmCfgWidgets.configure_string_option (
1640 message = _(
1641 'At any time there can only be one open (ongoing)\n'
1642 'episode for each health issue.\n'
1643 '\n'
1644 'When you try to open (add data to) an episode on a health\n'
1645 'issue GNUmed will check for an existing open episode on\n'
1646 'that issue. If there is any it will check the age of that\n'
1647 'episode. The episode is closed if it has been dormant (no\n'
1648 'data added, that is) for the period of time (in days) you\n'
1649 'set here.\n'
1650 '\n'
1651 "If the existing episode hasn't been dormant long enough\n"
1652 'GNUmed will consult you what to do.\n'
1653 '\n'
1654 'Enter maximum episode dormancy in DAYS:'
1655 ),
1656 option = 'episode.ttl',
1657 bias = 'user',
1658 default_value = 60,
1659 validator = is_valid
1660 )
1661
1692
1695
1710
1735
1747
1748 gmCfgWidgets.configure_string_option (
1749 message = _(
1750 'GNUmed can check for new releases being available. To do\n'
1751 'so it needs to load version information from an URL.\n'
1752 '\n'
1753 'The default URL is:\n'
1754 '\n'
1755 ' http://www.gnumed.de/downloads/gnumed-versions.txt\n'
1756 '\n'
1757 'but you can configure any other URL locally. Note\n'
1758 'that you must enter the location as a valid URL.\n'
1759 'Depending on the URL the client will need online\n'
1760 'access when checking for updates.'
1761 ),
1762 option = u'horstspace.update.url',
1763 bias = u'workplace',
1764 default_value = u'http://www.gnumed.de/downloads/gnumed-versions.txt',
1765 validator = is_valid
1766 )
1767
1785
1802
1813
1814 gmCfgWidgets.configure_string_option (
1815 message = _(
1816 'GNUmed can show the document review dialog after\n'
1817 'calling the appropriate viewer for that document.\n'
1818 '\n'
1819 'Select the conditions under which you want\n'
1820 'GNUmed to do so:\n'
1821 '\n'
1822 ' 0: never display the review dialog\n'
1823 ' 1: always display the dialog\n'
1824 ' 2: only if there is no previous review by me\n'
1825 '\n'
1826 'Note that if a viewer is configured to not block\n'
1827 'GNUmed during document display the review dialog\n'
1828 'will actually appear in parallel to the viewer.'
1829 ),
1830 option = u'horstspace.document_viewer.review_after_display',
1831 bias = u'user',
1832 default_value = 2,
1833 validator = is_valid
1834 )
1835
1849
1851
1852 dbcfg = gmCfg.cCfgSQL()
1853 cmd = dbcfg.get2 (
1854 option = u'external.tools.acs_risk_calculator_cmd',
1855 workplace = gmSurgery.gmCurrentPractice().active_workplace,
1856 bias = 'user'
1857 )
1858
1859 if cmd is None:
1860 gmDispatcher.send(signal = u'statustext', msg = _('ACS risk assessment calculator not configured.'), beep = True)
1861 return
1862
1863 cwd = os.path.expanduser(os.path.join('~', '.gnumed', 'tmp'))
1864 try:
1865 subprocess.check_call (
1866 args = (cmd,),
1867 close_fds = True,
1868 cwd = cwd
1869 )
1870 except (OSError, ValueError, subprocess.CalledProcessError):
1871 _log.exception('there was a problem executing [%s]', cmd)
1872 gmDispatcher.send(signal = u'statustext', msg = _('Cannot run [%s] !') % cmd, beep = True)
1873 return
1874
1875 pdfs = glob.glob(os.path.join(cwd, 'arriba-%s-*.pdf' % gmDateTime.pydt_now_here().strftime('%Y-%m-%d')))
1876 for pdf in pdfs:
1877 try:
1878 open(pdf).close()
1879 except:
1880 _log.exception('error accessing [%s]', pdf)
1881 gmDispatcher.send(signal = u'statustext', msg = _('There was a problem accessing the ARRIBA result in [%s] !') % pdf, beep = True)
1882 continue
1883
1884 doc = gmDocumentWidgets.save_file_as_new_document (
1885 parent = self,
1886 filename = pdf,
1887 document_type = u'risk assessment'
1888 )
1889
1890 try:
1891 os.remove(pdf)
1892 except StandardError:
1893 _log.exception('cannot remove [%s]', pdf)
1894
1895 if doc is None:
1896 continue
1897 doc['comment'] = u'ARRIBA: %s' % _('cardiovascular risk assessment')
1898 doc.save()
1899
1900 return
1901
1903 dlg = gmSnellen.cSnellenCfgDlg()
1904 if dlg.ShowModal() != wx.ID_OK:
1905 return
1906
1907 frame = gmSnellen.cSnellenChart (
1908 width = dlg.vals[0],
1909 height = dlg.vals[1],
1910 alpha = dlg.vals[2],
1911 mirr = dlg.vals[3],
1912 parent = None
1913 )
1914 frame.CentreOnScreen(wx.BOTH)
1915
1916
1917 frame.Show(True)
1918
1919
1921 webbrowser.open (
1922 url = 'http://wiki.gnumed.de/bin/view/Gnumed/MedicalContentLinks#AnchorLocaleI%s' % gmI18N.system_locale_level['language'],
1923 new = False,
1924 autoraise = True
1925 )
1926
1929
1931 webbrowser.open (
1932 url = 'http://www.kompendium.ch',
1933 new = False,
1934 autoraise = True
1935 )
1936
1937
1938
1940 wx.CallAfter(self.__save_screenshot)
1941 evt.Skip()
1942
1944
1945 time.sleep(0.5)
1946
1947 rect = self.GetRect()
1948
1949
1950 if sys.platform == 'linux2':
1951 client_x, client_y = self.ClientToScreen((0, 0))
1952 border_width = client_x - rect.x
1953 title_bar_height = client_y - rect.y
1954
1955 if self.GetMenuBar():
1956 title_bar_height /= 2
1957 rect.width += (border_width * 2)
1958 rect.height += title_bar_height + border_width
1959
1960 wdc = wx.ScreenDC()
1961 mdc = wx.MemoryDC()
1962 img = wx.EmptyBitmap(rect.width, rect.height)
1963 mdc.SelectObject(img)
1964 mdc.Blit (
1965 0, 0,
1966 rect.width, rect.height,
1967 wdc,
1968 rect.x, rect.y
1969 )
1970
1971
1972 fname = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'gnumed-screenshot-%s.png')) % pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
1973 img.SaveFile(fname, wx.BITMAP_TYPE_PNG)
1974 gmDispatcher.send(signal = 'statustext', msg = _('Saved screenshot to file [%s].') % fname)
1975
1977
1978 raise ValueError('raised ValueError to test exception handling')
1979
1981 import wx.lib.inspection
1982 wx.lib.inspection.InspectionTool().Show()
1983
1985 webbrowser.open (
1986 url = 'https://bugs.launchpad.net/gnumed/',
1987 new = False,
1988 autoraise = True
1989 )
1990
1992 webbrowser.open (
1993 url = 'http://wiki.gnumed.de',
1994 new = False,
1995 autoraise = True
1996 )
1997
1999 webbrowser.open (
2000 url = 'http://wiki.gnumed.de/bin/view/Gnumed/GnumedManual#UserGuideInManual',
2001 new = False,
2002 autoraise = True
2003 )
2004
2006 webbrowser.open (
2007 url = 'http://wiki.gnumed.de/bin/view/Gnumed/MenuReference',
2008 new = False,
2009 autoraise = True
2010 )
2011
2018
2022
2025
2032
2037
2039 name = os.path.basename(gmLog2._logfile_name)
2040 name, ext = os.path.splitext(name)
2041 new_name = '%s_%s%s' % (name, pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), ext)
2042 new_path = os.path.expanduser(os.path.join('~', 'gnumed', 'logs'))
2043
2044 dlg = wx.FileDialog (
2045 parent = self,
2046 message = _("Save current log as..."),
2047 defaultDir = new_path,
2048 defaultFile = new_name,
2049 wildcard = "%s (*.log)|*.log" % _("log files"),
2050 style = wx.SAVE
2051 )
2052 choice = dlg.ShowModal()
2053 new_name = dlg.GetPath()
2054 dlg.Destroy()
2055 if choice != wx.ID_OK:
2056 return True
2057
2058 _log.warning('syncing log file for backup to [%s]', new_name)
2059 gmLog2.flush()
2060 shutil.copy2(gmLog2._logfile_name, new_name)
2061 gmDispatcher.send('statustext', msg = _('Log file backed up as [%s].') % new_name)
2062
2063
2064
2066 """This is the wx.EVT_CLOSE handler.
2067
2068 - framework still functional
2069 """
2070 _log.debug('gmTopLevelFrame.OnClose() start')
2071 self._clean_exit()
2072 self.Destroy()
2073 _log.debug('gmTopLevelFrame.OnClose() end')
2074 return True
2075
2081
2086
2094
2101
2108
2118
2126
2134
2142
2150
2158
2160 pat = gmPerson.gmCurrentPatient()
2161 if not pat.connected:
2162 gmDispatcher.send(signal = 'statustext', msg = _('Cannot show EMR summary. No active patient.'))
2163 return False
2164
2165 emr = pat.get_emr()
2166 dlg = wx.MessageDialog (
2167 parent = self,
2168 message = emr.format_statistics(),
2169 caption = _('EMR Summary'),
2170 style = wx.OK | wx.STAY_ON_TOP
2171 )
2172 dlg.ShowModal()
2173 dlg.Destroy()
2174 return True
2175
2178
2181
2183
2184 pat = gmPerson.gmCurrentPatient()
2185 if not pat.connected:
2186 gmDispatcher.send(signal = 'statustext', msg = _('Cannot export EMR journal. No active patient.'))
2187 return False
2188
2189 aWildcard = "%s (*.txt)|*.txt|%s (*)|*" % (_("text files"), _("all files"))
2190
2191 aDefDir = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'EMR', pat['dirname']))
2192 gmTools.mkdir(aDefDir)
2193
2194 fname = '%s-%s_%s.txt' % (_('emr-journal'), pat['lastnames'], pat['firstnames'])
2195 dlg = wx.FileDialog (
2196 parent = self,
2197 message = _("Save patient's EMR journal as..."),
2198 defaultDir = aDefDir,
2199 defaultFile = fname,
2200 wildcard = aWildcard,
2201 style = wx.SAVE
2202 )
2203 choice = dlg.ShowModal()
2204 fname = dlg.GetPath()
2205 dlg.Destroy()
2206 if choice != wx.ID_OK:
2207 return True
2208
2209 _log.debug('exporting EMR journal to [%s]' % fname)
2210
2211 exporter = gmPatientExporter.cEMRJournalExporter()
2212
2213 wx.BeginBusyCursor()
2214 try:
2215 fname = exporter.export_to_file(filename = fname)
2216 except:
2217 wx.EndBusyCursor()
2218 gmGuiHelpers.gm_show_error (
2219 _('Error exporting patient EMR as chronological journal.'),
2220 _('EMR journal export')
2221 )
2222 raise
2223 wx.EndBusyCursor()
2224
2225 gmDispatcher.send(signal = 'statustext', msg = _('Successfully exported EMR as chronological journal into file [%s].') % fname, beep=False)
2226
2227 return True
2228
2235
2245
2247 curr_pat = gmPerson.gmCurrentPatient()
2248 if not curr_pat.connected:
2249 gmDispatcher.send(signal = 'statustext', msg = _('Cannot export patient as GDT. No active patient.'))
2250 return False
2251
2252 enc = 'cp850'
2253 fname = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'xDT', 'current-patient.gdt'))
2254 curr_pat.export_as_gdt(filename = fname, encoding = enc)
2255 gmDispatcher.send(signal = 'statustext', msg = _('Exported demographics to GDT file [%s].') % fname)
2256
2259
2260
2261
2262
2263
2264
2265
2273
2281
2284
2293
2297
2301
2304
2307
2310
2313
2316
2319
2322
2325
2328
2331
2334
2337
2339 """Cleanup helper.
2340
2341 - should ALWAYS be called when this program is
2342 to be terminated
2343 - ANY code that should be executed before a
2344 regular shutdown should go in here
2345 - framework still functional
2346 """
2347 _log.debug('gmTopLevelFrame._clean_exit() start')
2348
2349
2350 listener = gmBackendListener.gmBackendListener()
2351 try:
2352 listener.shutdown()
2353 except:
2354 _log.exception('cannot stop backend notifications listener thread')
2355
2356
2357 if _scripting_listener is not None:
2358 try:
2359 _scripting_listener.shutdown()
2360 except:
2361 _log.exception('cannot stop scripting listener thread')
2362
2363
2364 self.clock_update_timer.Stop()
2365 gmTimer.shutdown()
2366 gmPhraseWheel.shutdown()
2367
2368
2369 for call_back in self.__pre_exit_callbacks:
2370 try:
2371 call_back()
2372 except:
2373 print "*** pre-exit callback failed ***"
2374 print call_back
2375 _log.exception('callback [%s] failed', call_back)
2376
2377
2378 gmDispatcher.send(u'application_closing')
2379
2380
2381 gmDispatcher.disconnect(self._on_set_statustext, 'statustext')
2382
2383
2384 curr_width, curr_height = self.GetClientSizeTuple()
2385 _log.info('GUI size at shutdown: [%s:%s]' % (curr_width, curr_height))
2386 dbcfg = gmCfg.cCfgSQL()
2387 dbcfg.set (
2388 option = 'main.window.width',
2389 value = curr_width,
2390 workplace = gmSurgery.gmCurrentPractice().active_workplace
2391 )
2392 dbcfg.set (
2393 option = 'main.window.height',
2394 value = curr_height,
2395 workplace = gmSurgery.gmCurrentPractice().active_workplace
2396 )
2397
2398 if _cfg.get(option = 'debug'):
2399 print '---=== GNUmed shutdown ===---'
2400 print _('You have to manually close this window to finalize shutting down GNUmed.')
2401 print _('This is so that you can inspect the console output at your leisure.')
2402 print '---=== GNUmed shutdown ===---'
2403
2404
2405 gmExceptionHandlingWidgets.uninstall_wx_exception_handler()
2406
2407
2408 import threading
2409 _log.debug("%s active threads", threading.activeCount())
2410 for t in threading.enumerate():
2411 _log.debug('thread %s', t)
2412
2413 _log.debug('gmTopLevelFrame._clean_exit() end')
2414
2415
2416
2418
2419 if _cfg.get(option = 'slave'):
2420 self.__title_template = u'GMdS: %%(pat)s [%%(prov)s@%%(wp)s] (%s:%s)' % (
2421 _cfg.get(option = 'slave personality'),
2422 _cfg.get(option = 'xml-rpc port')
2423 )
2424 else:
2425 self.__title_template = u'GMd: %(pat)s [%(prov)s@%(wp)s]'
2426
2428 """Update title of main window based on template.
2429
2430 This gives nice tooltips on iconified GNUmed instances.
2431
2432 User research indicates that in the title bar people want
2433 the date of birth, not the age, so please stick to this
2434 convention.
2435 """
2436 args = {}
2437
2438 pat = gmPerson.gmCurrentPatient()
2439 if pat.connected:
2440
2441
2442
2443
2444
2445
2446 args['pat'] = u'%s %s %s (%s) #%d' % (
2447 gmTools.coalesce(pat['title'], u'', u'%.4s'),
2448
2449 pat['firstnames'],
2450 pat['lastnames'],
2451 pat.get_formatted_dob(format = '%x', encoding = gmI18N.get_encoding()),
2452 pat['pk_identity']
2453 )
2454 else:
2455 args['pat'] = _('no patient')
2456
2457 args['prov'] = u'%s%s.%s' % (
2458 gmTools.coalesce(_provider['title'], u'', u'%s '),
2459 _provider['firstnames'][:1],
2460 _provider['lastnames']
2461 )
2462
2463 args['wp'] = gmSurgery.gmCurrentPractice().active_workplace
2464
2465 self.SetTitle(self.__title_template % args)
2466
2467
2469 sb = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
2470 sb.SetStatusWidths([-1, 225])
2471
2472 self.clock_update_timer = wx.PyTimer(self._cb_update_clock)
2473 self._cb_update_clock()
2474
2475 self.clock_update_timer.Start(milliseconds = 1000)
2476
2478 """Displays date and local time in the second slot of the status bar"""
2479 t = time.localtime(time.time())
2480 st = time.strftime('%c', t).decode(gmI18N.get_encoding())
2481 self.SetStatusText(st,1)
2482
2484 """Lock GNUmed client against unauthorized access"""
2485
2486
2487
2488 return
2489
2491 """Unlock the main notebook widgets
2492 As long as we are not logged into the database backend,
2493 all pages but the 'login' page of the main notebook widget
2494 are locked; i.e. not accessible by the user
2495 """
2496
2497
2498
2499
2500
2501 return
2502
2504 wx.LayoutAlgorithm().LayoutWindow (self.LayoutMgr, self.nb)
2505
2507
2509
2510 self.__starting_up = True
2511
2512 gmExceptionHandlingWidgets.install_wx_exception_handler()
2513 gmExceptionHandlingWidgets.set_client_version(_cfg.get(option = 'client_version'))
2514
2515
2516
2517
2518 self.SetAppName(u'gnumed')
2519 self.SetVendorName(u'The GNUmed Development Community.')
2520 paths = gmTools.gmPaths(app_name = u'gnumed', wx = wx)
2521 paths.init_paths(wx = wx, app_name = u'gnumed')
2522
2523 if not self.__setup_prefs_file():
2524 return False
2525
2526 gmExceptionHandlingWidgets.set_sender_email(gmSurgery.gmCurrentPractice().user_email)
2527
2528 self.__guibroker = gmGuiBroker.GuiBroker()
2529 self.__setup_platform()
2530
2531 if not self.__establish_backend_connection():
2532 return False
2533
2534 if not _cfg.get(option = 'skip-update-check'):
2535 self.__check_for_updates()
2536
2537 if _cfg.get(option = 'slave'):
2538 if not self.__setup_scripting_listener():
2539 return False
2540
2541
2542 frame = gmTopLevelFrame(None, -1, _('GNUmed client'), (640,440))
2543 frame.CentreOnScreen(wx.BOTH)
2544 self.SetTopWindow(frame)
2545 frame.Show(True)
2546
2547 if _cfg.get(option = 'debug'):
2548 self.RedirectStdio()
2549 self.SetOutputWindowAttributes(title = _('GNUmed stdout/stderr window'))
2550
2551
2552 print '---=== GNUmed startup ===---'
2553 print _('redirecting STDOUT/STDERR to this log window')
2554 print '---=== GNUmed startup ===---'
2555
2556 self.__setup_user_activity_timer()
2557 self.__register_events()
2558
2559 wx.CallAfter(self._do_after_init)
2560
2561 return True
2562
2564 """Called internally by wxPython after EVT_CLOSE has been handled on last frame.
2565
2566 - after destroying all application windows and controls
2567 - before wx.Windows internal cleanup
2568 """
2569 _log.debug('gmApp.OnExit() start')
2570
2571 self.__shutdown_user_activity_timer()
2572
2573 if _cfg.get(option = 'debug'):
2574 self.RestoreStdio()
2575 sys.stdin = sys.__stdin__
2576 sys.stdout = sys.__stdout__
2577 sys.stderr = sys.__stderr__
2578
2579 _log.debug('gmApp.OnExit() end')
2580
2582 wx.Bell()
2583 wx.Bell()
2584 wx.Bell()
2585 _log.warning('unhandled event detected: QUERY_END_SESSION')
2586 _log.info('we should be saving ourselves from here')
2587 gmLog2.flush()
2588 print "unhandled event detected: QUERY_END_SESSION"
2589
2591 wx.Bell()
2592 wx.Bell()
2593 wx.Bell()
2594 _log.warning('unhandled event detected: END_SESSION')
2595 gmLog2.flush()
2596 print "unhandled event detected: END_SESSION"
2597
2608
2610 self.user_activity_detected = True
2611 evt.Skip()
2612
2614
2615 if self.user_activity_detected:
2616 self.elapsed_inactivity_slices = 0
2617 self.user_activity_detected = False
2618 self.elapsed_inactivity_slices += 1
2619 else:
2620 if self.elapsed_inactivity_slices >= self.max_user_inactivity_slices:
2621
2622 pass
2623
2624 self.user_activity_timer.Start(oneShot = True)
2625
2626
2627
2629 try:
2630 kwargs['originated_in_database']
2631 print '==> got notification from database "%s":' % kwargs['signal']
2632 except KeyError:
2633 print '==> received signal from client: "%s"' % kwargs['signal']
2634
2635 del kwargs['signal']
2636 for key in kwargs.keys():
2637 print ' [%s]: %s' % (key, kwargs[key])
2638
2640 print "wx.lib.pubsub message:"
2641 print msg.topic
2642 print msg.data
2643
2649
2651 self.user_activity_detected = True
2652 self.elapsed_inactivity_slices = 0
2653
2654 self.max_user_inactivity_slices = 15
2655 self.user_activity_timer = gmTimer.cTimer (
2656 callback = self._on_user_activity_timer_expired,
2657 delay = 2000
2658 )
2659 self.user_activity_timer.Start(oneShot=True)
2660
2662 try:
2663 self.user_activity_timer.Stop()
2664 del self.user_activity_timer
2665 except:
2666 pass
2667
2669 wx.EVT_QUERY_END_SESSION(self, self._on_query_end_session)
2670 wx.EVT_END_SESSION(self, self._on_end_session)
2671
2672
2673
2674
2675
2676 self.Bind(wx.EVT_ACTIVATE_APP, self._on_app_activated)
2677
2678 self.Bind(wx.EVT_MOUSE_EVENTS, self._on_user_activity)
2679 self.Bind(wx.EVT_KEY_DOWN, self._on_user_activity)
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2705
2707 """Handle all the database related tasks necessary for startup."""
2708
2709
2710 override = _cfg.get(option = '--override-schema-check', source_order = [('cli', 'return')])
2711
2712 from Gnumed.wxpython import gmAuthWidgets
2713 connected = gmAuthWidgets.connect_to_database (
2714 expected_version = gmPG2.map_client_branch2required_db_version[_cfg.get(option = 'client_branch')],
2715 require_version = not override
2716 )
2717 if not connected:
2718 _log.warning("Login attempt unsuccessful. Can't run GNUmed without database connection")
2719 return False
2720
2721
2722 try:
2723 global _provider
2724 _provider = gmPerson.gmCurrentProvider(provider = gmPerson.cStaff())
2725 except ValueError:
2726 account = gmPG2.get_current_user()
2727 _log.exception('DB account [%s] cannot be used as a GNUmed staff login', account)
2728 msg = _(
2729 'The database account [%s] cannot be used as a\n'
2730 'staff member login for GNUmed. There was an\n'
2731 'error retrieving staff details for it.\n\n'
2732 'Please ask your administrator for help.\n'
2733 ) % account
2734 gmGuiHelpers.gm_show_error(msg, _('Checking access permissions'))
2735 return False
2736
2737
2738 tmp = '%s%s %s (%s = %s)' % (
2739 gmTools.coalesce(_provider['title'], ''),
2740 _provider['firstnames'],
2741 _provider['lastnames'],
2742 _provider['short_alias'],
2743 _provider['db_user']
2744 )
2745 gmExceptionHandlingWidgets.set_staff_name(staff_name = tmp)
2746
2747
2748 surgery = gmSurgery.gmCurrentPractice()
2749 msg = surgery.db_logon_banner
2750 if msg.strip() != u'':
2751
2752 login = gmPG2.get_default_login()
2753 auth = u'\n%s\n\n' % (_('Database <%s> on <%s>') % (
2754 login.database,
2755 gmTools.coalesce(login.host, u'localhost')
2756 ))
2757 msg = auth + msg + u'\n\n'
2758
2759 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
2760 None,
2761 -1,
2762 caption = _('Verifying database'),
2763 question = gmTools.wrap(msg, 60, initial_indent = u' ', subsequent_indent = u' '),
2764 button_defs = [
2765 {'label': _('Connect'), 'tooltip': _('Yes, connect to this database.'), 'default': True},
2766 {'label': _('Disconnect'), 'tooltip': _('No, do not connect to this database.'), 'default': False}
2767 ]
2768 )
2769 go_on = dlg.ShowModal()
2770 dlg.Destroy()
2771 if go_on != wx.ID_YES:
2772 _log.info('user decided to not connect to this database')
2773 return False
2774
2775
2776 self.__check_db_lang()
2777
2778 return True
2779
2781 """Setup access to a config file for storing preferences."""
2782
2783 paths = gmTools.gmPaths(app_name = u'gnumed', wx = wx)
2784
2785 candidates = []
2786 explicit_file = _cfg.get(option = '--conf-file', source_order = [('cli', 'return')])
2787 if explicit_file is not None:
2788 candidates.append(explicit_file)
2789
2790 candidates.append(os.path.join(paths.user_config_dir, 'gnumed.conf'))
2791 candidates.append(os.path.join(paths.local_base_dir, 'gnumed.conf'))
2792 candidates.append(os.path.join(paths.working_dir, 'gnumed.conf'))
2793
2794 prefs_file = None
2795 for candidate in candidates:
2796 try:
2797 open(candidate, 'a+').close()
2798 prefs_file = candidate
2799 break
2800 except IOError:
2801 continue
2802
2803 if prefs_file is None:
2804 msg = _(
2805 'Cannot find configuration file in any of:\n'
2806 '\n'
2807 ' %s\n'
2808 'You may need to use the comand line option\n'
2809 '\n'
2810 ' --conf-file=<FILE>'
2811 ) % '\n '.join(candidates)
2812 gmGuiHelpers.gm_show_error(msg, _('Checking configuration files'))
2813 return False
2814
2815 _cfg.set_option(option = u'user_preferences_file', value = prefs_file)
2816 _log.info('user preferences file: %s', prefs_file)
2817
2818 return True
2819
2821
2822 from socket import error as SocketError
2823 from Gnumed.pycommon import gmScriptingListener
2824 from Gnumed.wxpython import gmMacro
2825
2826 slave_personality = gmTools.coalesce (
2827 _cfg.get (
2828 group = u'workplace',
2829 option = u'slave personality',
2830 source_order = [
2831 ('explicit', 'return'),
2832 ('workbase', 'return'),
2833 ('user', 'return'),
2834 ('system', 'return')
2835 ]
2836 ),
2837 u'gnumed-client'
2838 )
2839 _cfg.set_option(option = 'slave personality', value = slave_personality)
2840
2841
2842 port = int (
2843 gmTools.coalesce (
2844 _cfg.get (
2845 group = u'workplace',
2846 option = u'xml-rpc port',
2847 source_order = [
2848 ('explicit', 'return'),
2849 ('workbase', 'return'),
2850 ('user', 'return'),
2851 ('system', 'return')
2852 ]
2853 ),
2854 9999
2855 )
2856 )
2857 _cfg.set_option(option = 'xml-rpc port', value = port)
2858
2859 macro_executor = gmMacro.cMacroPrimitives(personality = slave_personality)
2860 global _scripting_listener
2861 try:
2862 _scripting_listener = gmScriptingListener.cScriptingListener(port = port, macro_executor = macro_executor)
2863 except SocketError, e:
2864 _log.exception('cannot start GNUmed XML-RPC server')
2865 gmGuiHelpers.gm_show_error (
2866 aMessage = (
2867 'Cannot start the GNUmed server:\n'
2868 '\n'
2869 ' [%s]'
2870 ) % e,
2871 aTitle = _('GNUmed startup')
2872 )
2873 return False
2874
2875 return True
2876
2896
2898 if gmI18N.system_locale is None or gmI18N.system_locale == '':
2899 _log.warning("system locale is undefined (probably meaning 'C')")
2900 return True
2901
2902
2903 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': u"select i18n.get_curr_lang() as lang"}])
2904 db_lang = rows[0]['lang']
2905
2906 if db_lang is None:
2907 _log.debug("database locale currently not set")
2908 msg = _(
2909 "There is no language selected in the database for user [%s].\n"
2910 "Your system language is currently set to [%s].\n\n"
2911 "Do you want to set the database language to '%s' ?\n\n"
2912 ) % (_provider['db_user'], gmI18N.system_locale, gmI18N.system_locale)
2913 checkbox_msg = _('Remember to ignore missing language')
2914 else:
2915 _log.debug("current database locale: [%s]" % db_lang)
2916 msg = _(
2917 "The currently selected database language ('%s') does\n"
2918 "not match the current system language ('%s').\n"
2919 "\n"
2920 "Do you want to set the database language to '%s' ?\n"
2921 ) % (db_lang, gmI18N.system_locale, gmI18N.system_locale)
2922 checkbox_msg = _('Remember to ignore language mismatch')
2923
2924
2925 if db_lang == gmI18N.system_locale_level['full']:
2926 _log.debug('Database locale (%s) up to date.' % db_lang)
2927 return True
2928 if db_lang == gmI18N.system_locale_level['country']:
2929 _log.debug('Database locale (%s) matches system locale (%s) at country level.' % (db_lang, gmI18N.system_locale))
2930 return True
2931 if db_lang == gmI18N.system_locale_level['language']:
2932 _log.debug('Database locale (%s) matches system locale (%s) at language level.' % (db_lang, gmI18N.system_locale))
2933 return True
2934
2935 _log.warning('database locale [%s] does not match system locale [%s]' % (db_lang, gmI18N.system_locale))
2936
2937
2938 ignored_sys_lang = _cfg.get (
2939 group = u'backend',
2940 option = u'ignored mismatching system locale',
2941 source_order = [('explicit', 'return'), ('local', 'return'), ('user', 'return'), ('system', 'return')]
2942 )
2943
2944
2945 if gmI18N.system_locale == ignored_sys_lang:
2946 _log.info('configured to ignore system-to-database locale mismatch')
2947 return True
2948
2949
2950 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
2951 None,
2952 -1,
2953 caption = _('Checking database language settings'),
2954 question = msg,
2955 button_defs = [
2956 {'label': _('Set'), 'tooltip': _('Set your database language to [%s].') % gmI18N.system_locale, 'default': True},
2957 {'label': _("Don't set"), 'tooltip': _('Do not set your database language now.'), 'default': False}
2958 ],
2959 show_checkbox = True,
2960 checkbox_msg = checkbox_msg,
2961 checkbox_tooltip = _(
2962 'Checking this will make GNUmed remember your decision\n'
2963 'until the system language is changed.\n'
2964 '\n'
2965 'You can also reactivate this inquiry by removing the\n'
2966 'corresponding "ignore" option from the configuration file\n'
2967 '\n'
2968 ' [%s]'
2969 ) % _cfg.get(option = 'user_preferences_file')
2970 )
2971 decision = dlg.ShowModal()
2972 remember_ignoring_problem = dlg._CHBOX_dont_ask_again.GetValue()
2973 dlg.Destroy()
2974
2975 if decision == wx.ID_NO:
2976 if not remember_ignoring_problem:
2977 return True
2978 _log.info('User did not want to set database locale. Ignoring mismatch next time.')
2979 gmCfg2.set_option_in_INI_file (
2980 filename = _cfg.get(option = 'user_preferences_file'),
2981 group = 'backend',
2982 option = 'ignored mismatching system locale',
2983 value = gmI18N.system_locale
2984 )
2985 return True
2986
2987
2988 for lang in [gmI18N.system_locale_level['full'], gmI18N.system_locale_level['country'], gmI18N.system_locale_level['language']]:
2989 if len(lang) > 0:
2990
2991
2992 rows, idx = gmPG2.run_rw_queries (
2993 link_obj = None,
2994 queries = [{'cmd': u'select i18n.set_curr_lang(%s)', 'args': [lang]}],
2995 return_data = True
2996 )
2997 if rows[0][0]:
2998 _log.debug("Successfully set database language to [%s]." % lang)
2999 else:
3000 _log.error('Cannot set database language to [%s].' % lang)
3001 continue
3002 return True
3003
3004
3005 _log.info('forcing database language to [%s]', gmI18N.system_locale_level['country'])
3006 gmPG2.run_rw_queries(queries = [{
3007 'cmd': u'select i18n.force_curr_lang(%s)',
3008 'args': [gmI18N.system_locale_level['country']]
3009 }])
3010
3011 return True
3012
3014 try:
3015 kwargs['originated_in_database']
3016 print '==> got notification from database "%s":' % kwargs['signal']
3017 except KeyError:
3018 print '==> received signal from client: "%s"' % kwargs['signal']
3019
3020 del kwargs['signal']
3021 for key in kwargs.keys():
3022
3023 try: print ' [%s]: %s' % (key, kwargs[key])
3024 except: print 'cannot print signal information'
3025
3027
3028 try:
3029 print '==> received wx.lib.pubsub message: "%s"' % msg.topic
3030 print ' data: %s' % msg.data
3031 print msg
3032 except: print 'problem printing pubsub message information'
3033
3035
3036 if _cfg.get(option = 'debug'):
3037 gmDispatcher.connect(receiver = _signal_debugging_monitor)
3038 _log.debug('gmDispatcher signal monitor activated')
3039 wx.lib.pubsub.Publisher().subscribe (
3040 listener = _signal_debugging_monitor_pubsub,
3041 topic = wx.lib.pubsub.getStrAllTopics()
3042 )
3043 _log.debug('wx.lib.pubsub signal monitor activated')
3044
3045
3046
3047
3048 app = gmApp(redirect = False, clearSigInt = False)
3049 app.MainLoop()
3050
3051
3052
3053 if __name__ == '__main__':
3054
3055 from GNUmed.pycommon import gmI18N
3056 gmI18N.activate_locale()
3057 gmI18N.install_domain()
3058
3059 _log.info('Starting up as main module.')
3060 main()
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671