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
18
19 __version__ = "$Revision: 1.491 $"
20 __author__ = "H. Herb <hherb@gnumed.net>,\
21 K. Hilbert <Karsten.Hilbert@gmx.net>,\
22 I. Haywood <i.haywood@ugrad.unimelb.edu.au>"
23 __license__ = 'GPL (details at http://www.gnu.org)'
24
25
26 import sys, time, os, cPickle, zlib, locale, os.path, datetime as pyDT, webbrowser, shutil, logging, urllib2
27
28
29
30
31 if not hasattr(sys, 'frozen'):
32 import wxversion
33 wxversion.ensureMinimal('2.8-unicode', optionsRequired=True)
34
35 try:
36 import wx
37 import wx.lib.pubsub
38 except ImportError:
39 print "GNUmed startup: Cannot import wxPython library."
40 print "GNUmed startup: Make sure wxPython is installed."
41 print 'CRITICAL ERROR: Error importing wxPython. Halted.'
42 raise
43
44
45
46 version = int(u'%s%s' % (wx.MAJOR_VERSION, wx.MINOR_VERSION))
47 if (version < 28) or ('unicode' not in wx.PlatformInfo):
48 print "GNUmed startup: Unsupported wxPython version (%s: %s)." % (wx.VERSION_STRING, wx.PlatformInfo)
49 print "GNUmed startup: wxPython 2.8+ with unicode support is required."
50 print 'CRITICAL ERROR: Proper wxPython version not found. Halted.'
51 raise ValueError('wxPython 2.8+ with unicode support not found')
52
53
54
55 from Gnumed.pycommon import gmCfg, gmPG2, gmDispatcher, gmGuiBroker, gmI18N
56 from Gnumed.pycommon import gmExceptions, gmShellAPI, gmTools, gmDateTime
57 from Gnumed.pycommon import gmHooks, gmBackendListener, gmCfg2, gmLog2
58
59 from Gnumed.business import gmPerson, gmClinicalRecord, gmSurgery, gmEMRStructItems
60
61 from Gnumed.exporters import gmPatientExporter
62
63 from Gnumed.wxpython import gmGuiHelpers, gmHorstSpace, gmEMRBrowser, gmDemographicsWidgets, gmEMRStructWidgets
64 from Gnumed.wxpython import gmStaffWidgets, gmMedDocWidgets, gmPatSearchWidgets, gmAllergyWidgets, gmListWidgets
65 from Gnumed.wxpython import gmFormWidgets, gmSnellen, gmProviderInboxWidgets, gmCfgWidgets, gmExceptionHandlingWidgets
66 from Gnumed.wxpython import gmTimer, gmMeasurementWidgets, gmNarrativeWidgets, gmPhraseWheel, gmMedicationWidgets
67
68 try:
69 _('dummy-no-need-to-translate-but-make-epydoc-happy')
70 except NameError:
71 _ = lambda x:x
72
73 _cfg = gmCfg2.gmCfgData()
74 _provider = None
75 _scripting_listener = None
76
77 _log = logging.getLogger('gm.main')
78 _log.info(__version__)
79 _log.info('wxPython GUI framework: %s %s' % (wx.VERSION_STRING, wx.PlatformInfo))
80
81
82 icon_serpent = \
83 """x\xdae\x8f\xb1\x0e\x83 \x10\x86w\x9f\xe2\x92\x1blb\xf2\x07\x96\xeaH:0\xd6\
84 \xc1\x85\xd5\x98N5\xa5\xef?\xf5N\xd0\x8a\xdcA\xc2\xf7qw\x84\xdb\xfa\xb5\xcd\
85 \xd4\xda;\xc9\x1a\xc8\xb6\xcd<\xb5\xa0\x85\x1e\xeb\xbc\xbc7b!\xf6\xdeHl\x1c\
86 \x94\x073\xec<*\xf7\xbe\xf7\x99\x9d\xb21~\xe7.\xf5\x1f\x1c\xd3\xbdVlL\xc2\
87 \xcf\xf8ye\xd0\x00\x90\x0etH \x84\x80B\xaa\x8a\x88\x85\xc4(U\x9d$\xfeR;\xc5J\
88 \xa6\x01\xbbt9\xceR\xc8\x81e_$\x98\xb9\x9c\xa9\x8d,y\xa9t\xc8\xcf\x152\xe0x\
89 \xe9$\xf5\x07\x95\x0cD\x95t:\xb1\x92\xae\x9cI\xa8~\x84\x1f\xe0\xa3ec"""
90
92 """GNUmed client's main windows frame.
93
94 This is where it all happens. Avoid popping up any other windows.
95 Most user interaction should happen to and from widgets within this frame
96 """
97
98 - def __init__(self, parent, id, title, size=wx.DefaultSize):
99 """You'll have to browse the source to understand what the constructor does
100 """
101 wx.Frame.__init__(self, parent, id, title, size, style = wx.DEFAULT_FRAME_STYLE)
102
103 self.__gb = gmGuiBroker.GuiBroker()
104 self.__pre_exit_callbacks = []
105 self.bar_width = -1
106 self.menu_id2plugin = {}
107
108 _log.info('workplace is >>>%s<<<', gmSurgery.gmCurrentPractice().active_workplace)
109
110 self.__setup_main_menu()
111 self.setup_statusbar()
112 self.SetStatusText(_('You are logged in as %s%s.%s (%s). DB account <%s>.') % (
113 gmTools.coalesce(_provider['title'], ''),
114 _provider['firstnames'][:1],
115 _provider['lastnames'],
116 _provider['short_alias'],
117 _provider['db_user']
118 ))
119
120 self.__set_window_title_template()
121 self.__update_window_title()
122 self.__set_window_icon()
123
124 self.__register_events()
125
126 self.LayoutMgr = gmHorstSpace.cHorstSpaceLayoutMgr(self, -1)
127 self.vbox = wx.BoxSizer(wx.VERTICAL)
128 self.vbox.Add(self.LayoutMgr, 10, wx.EXPAND | wx.ALL, 1)
129
130 self.SetAutoLayout(True)
131 self.SetSizerAndFit(self.vbox)
132
133
134
135
136
137 self.__set_GUI_size()
138
140
141 icon_bmp_data = wx.BitmapFromXPMData(cPickle.loads(zlib.decompress(icon_serpent)))
142 icon = wx.EmptyIcon()
143 icon.CopyFromBitmap(icon_bmp_data)
144 self.SetIcon(icon)
145
147 """Try to get previous window size from backend."""
148
149 cfg = gmCfg.cCfgSQL()
150
151
152 width = int(cfg.get2 (
153 option = 'main.window.width',
154 workplace = gmSurgery.gmCurrentPractice().active_workplace,
155 bias = 'workplace',
156 default = 800
157 ))
158
159
160 height = int(cfg.get2 (
161 option = 'main.window.height',
162 workplace = gmSurgery.gmCurrentPractice().active_workplace,
163 bias = 'workplace',
164 default = 600
165 ))
166
167 _log.debug('setting GUI size to [%s:%s]' % (width, height))
168 self.SetClientSize(wx.Size(width, height))
169
171 """Create the main menu entries.
172
173 Individual entries are farmed out to the modules.
174 """
175 global wx
176 self.mainmenu = wx.MenuBar()
177 self.__gb['main.mainmenu'] = self.mainmenu
178
179
180 menu_gnumed = wx.Menu()
181
182 self.menu_plugins = wx.Menu()
183 menu_gnumed.AppendMenu(wx.NewId(), _('&Go to plugin ...'), self.menu_plugins)
184
185 ID = wx.NewId()
186 menu_gnumed.Append(ID, _('Check for updates'), _('Check for new releases of the GNUmed client.'))
187 wx.EVT_MENU(self, ID, self.__on_check_for_updates)
188
189 item = menu_gnumed.Append(-1, _('Announce downtime'), _('Announce database maintenance downtime to all connected clients.'))
190 self.Bind(wx.EVT_MENU, self.__on_announce_maintenance, item)
191
192
193 menu_gnumed.AppendSeparator()
194
195
196 menu_config = wx.Menu()
197 menu_gnumed.AppendMenu(wx.NewId(), _('Preferences ...'), menu_config)
198
199
200 menu_cfg_db = wx.Menu()
201 menu_config.AppendMenu(wx.NewId(), _('Database ...'), menu_cfg_db)
202
203 ID = wx.NewId()
204 menu_cfg_db.Append(ID, _('Language'), _('Configure the database language'))
205 wx.EVT_MENU(self, ID, self.__on_configure_db_lang)
206
207 ID = wx.NewId()
208 menu_cfg_db.Append(ID, _('Welcome message'), _('Configure the database welcome message (all users).'))
209 wx.EVT_MENU(self, ID, self.__on_configure_db_welcome)
210
211
212 menu_cfg_client = wx.Menu()
213 menu_config.AppendMenu(wx.NewId(), _('Client parameters ...'), menu_cfg_client)
214
215 ID = wx.NewId()
216 menu_cfg_client.Append(ID, _('Export chunk size'), _('Configure the chunk size used when exporting BLOBs from the database.'))
217 wx.EVT_MENU(self, ID, self.__on_configure_export_chunk_size)
218
219 ID = wx.NewId()
220 menu_cfg_client.Append(ID, _('Temporary directory'), _('Configure the directory to use as scratch space for temporary files.'))
221 wx.EVT_MENU(self, ID, self.__on_configure_temp_dir)
222
223 item = menu_cfg_client.Append(-1, _('Email address'), _('The email address of the user for sending bug reports, etc.'))
224 self.Bind(wx.EVT_MENU, self.__on_configure_user_email, item)
225
226
227 menu_cfg_ui = wx.Menu()
228 menu_config.AppendMenu(wx.NewId(), _('User interface ...'), menu_cfg_ui)
229
230
231 menu_cfg_doc = wx.Menu()
232 menu_cfg_ui.AppendMenu(wx.NewId(), _('Document handling ...'), menu_cfg_doc)
233
234 ID = wx.NewId()
235 menu_cfg_doc.Append(ID, _('Review dialog'), _('Configure review dialog after document display.'))
236 wx.EVT_MENU(self, ID, self.__on_configure_doc_review_dialog)
237
238 ID = wx.NewId()
239 menu_cfg_doc.Append(ID, _('UUID display'), _('Configure unique ID dialog on document import.'))
240 wx.EVT_MENU(self, ID, self.__on_configure_doc_uuid_dialog)
241
242 ID = wx.NewId()
243 menu_cfg_doc.Append(ID, _('Empty documents'), _('Whether to allow saving documents without parts.'))
244 wx.EVT_MENU(self, ID, self.__on_configure_partless_docs)
245
246
247 menu_cfg_update = wx.Menu()
248 menu_cfg_ui.AppendMenu(wx.NewId(), _('Update handling ...'), menu_cfg_update)
249
250 ID = wx.NewId()
251 menu_cfg_update.Append(ID, _('Auto-check'), _('Whether to auto-check for updates at startup.'))
252 wx.EVT_MENU(self, ID, self.__on_configure_update_check)
253
254 ID = wx.NewId()
255 menu_cfg_update.Append(ID, _('Check scope'), _('When checking for updates, consider latest branch, too ?'))
256 wx.EVT_MENU(self, ID, self.__on_configure_update_check_scope)
257
258 ID = wx.NewId()
259 menu_cfg_update.Append(ID, _('URL'), _('The URL to retrieve version information from.'))
260 wx.EVT_MENU(self, ID, self.__on_configure_update_url)
261
262
263 menu_cfg_pat_search = wx.Menu()
264 menu_cfg_ui.AppendMenu(wx.NewId(), _('Person ...'), menu_cfg_pat_search)
265
266 ID = wx.NewId()
267 menu_cfg_pat_search.Append(ID, _('Birthday reminder'), _('Configure birthday reminder proximity interval.'))
268 wx.EVT_MENU(self, ID, self.__on_configure_dob_reminder_proximity)
269
270 ID = wx.NewId()
271 menu_cfg_pat_search.Append(ID, _('Immediate source activation'), _('Configure immediate activation of single external person.'))
272 wx.EVT_MENU(self, ID, self.__on_configure_quick_pat_search)
273
274 ID = wx.NewId()
275 menu_cfg_pat_search.Append(ID, _('Initial plugin'), _('Configure which plugin to show right after person activation.'))
276 wx.EVT_MENU(self, ID, self.__on_configure_initial_pat_plugin)
277
278 item = menu_cfg_pat_search.Append(-1, _('Default region'), _('Configure the default province/region/state for person creation.'))
279 self.Bind(wx.EVT_MENU, self.__on_cfg_default_region, item)
280
281 item = menu_cfg_pat_search.Append(-1, _('Default country'), _('Configure the default country for person creation.'))
282 self.Bind(wx.EVT_MENU, self.__on_cfg_default_country, item)
283
284
285 menu_cfg_soap_editing = wx.Menu()
286 menu_cfg_ui.AppendMenu(wx.NewId(), _('Progress notes handling ...'), menu_cfg_soap_editing)
287
288 ID = wx.NewId()
289 menu_cfg_soap_editing.Append(ID, _('Multiple new episodes'), _('Configure opening multiple new episodes on a patient at once.'))
290 wx.EVT_MENU(self, ID, self.__on_allow_multiple_new_episodes)
291
292
293 menu_cfg_ext_tools = wx.Menu()
294 menu_config.AppendMenu(wx.NewId(), _('External tools ...'), menu_cfg_ext_tools)
295
296 ID = wx.NewId()
297 menu_cfg_ext_tools.Append(ID, _('IFAP command'), _('Set the command to start IFAP.'))
298 wx.EVT_MENU(self, ID, self.__on_configure_ifap_cmd)
299
300 item = menu_cfg_ext_tools.Append(-1, _('MI/stroke risk calc cmd'), _('Set the command to start the CV risk calculator.'))
301 self.Bind(wx.EVT_MENU, self.__on_configure_acs_risk_calculator_cmd, item)
302
303 ID = wx.NewId()
304 menu_cfg_ext_tools.Append(ID, _('OOo startup time'), _('Set the time to wait for OpenOffice to settle after startup.'))
305 wx.EVT_MENU(self, ID, self.__on_configure_ooo_settle_time)
306
307 item = menu_cfg_ext_tools.Append(-1, _('Measurements URL'), _('URL for measurements encyclopedia.'))
308 self.Bind(wx.EVT_MENU, self.__on_configure_measurements_url, item)
309
310 item = menu_cfg_ext_tools.Append(-1, _('Drug data source'), _('Select the drug data source.'))
311 self.Bind(wx.EVT_MENU, self.__on_configure_drug_data_source, item)
312
313
314 menu_cfg_emr = wx.Menu()
315 menu_config.AppendMenu(wx.NewId(), _('EMR ...'), menu_cfg_emr)
316
317 item = menu_cfg_emr.Append(-1, _('Medication list template'), _('Select the template for printing a medication list.'))
318 self.Bind(wx.EVT_MENU, self.__on_cfg_medication_list_template, item)
319
320
321 menu_cfg_encounter = wx.Menu()
322 menu_cfg_emr.AppendMenu(wx.NewId(), _('Encounter ...'), menu_cfg_encounter)
323
324 ID = wx.NewId()
325 menu_cfg_encounter.Append(ID, _('Edit on patient change'), _('Edit encounter details on changing of patients.'))
326 wx.EVT_MENU(self, ID, self.__on_cfg_enc_pat_change)
327
328 ID = wx.NewId()
329 menu_cfg_encounter.Append(ID, _('Minimum duration'), _('Minimum duration of an encounter.'))
330 wx.EVT_MENU(self, ID, self.__on_cfg_enc_min_ttl)
331
332 ID = wx.NewId()
333 menu_cfg_encounter.Append(ID, _('Maximum duration'), _('Maximum duration of an encounter.'))
334 wx.EVT_MENU(self, ID, self.__on_cfg_enc_max_ttl)
335
336 ID = wx.NewId()
337 menu_cfg_encounter.Append(ID, _('Minimum empty age'), _('Minimum age of an empty encounter before considering for deletion.'))
338 wx.EVT_MENU(self, ID, self.__on_cfg_enc_empty_ttl)
339
340 ID = wx.NewId()
341 menu_cfg_encounter.Append(ID, _('Default type'), _('Default type for new encounters.'))
342 wx.EVT_MENU(self, ID, self.__on_cfg_enc_default_type)
343
344
345 menu_cfg_episode = wx.Menu()
346 menu_cfg_emr.AppendMenu(wx.NewId(), _('Episode ...'), menu_cfg_episode)
347
348 ID = wx.NewId()
349 menu_cfg_episode.Append(ID, _('Dormancy'), _('Maximum length of dormancy after which an episode will be considered closed.'))
350 wx.EVT_MENU(self, ID, self.__on_cfg_epi_ttl)
351
352
353 menu_master_data = wx.Menu()
354 menu_gnumed.AppendMenu(wx.NewId(), _('&Master data ...'), menu_master_data)
355
356 item = menu_master_data.Append(-1, _('Workplace profiles'), _('Manage the plugins to load per workplace.'))
357 self.Bind(wx.EVT_MENU, self.__on_configure_workplace, item)
358
359 menu_master_data.AppendSeparator()
360
361 item = menu_master_data.Append(-1, _('&Document types'), _('Manage the document types available in the system.'))
362 self.Bind(wx.EVT_MENU, self.__on_edit_doc_types, item)
363
364 item = menu_master_data.Append(-1, _('&Form templates'), _('Manage templates for forms and letters.'))
365 self.Bind(wx.EVT_MENU, self.__on_manage_form_templates, item)
366
367 item = menu_master_data.Append(-1, _('&Text expansions'), _('Manage keyword based text expansion macros.'))
368 self.Bind(wx.EVT_MENU, self.__on_manage_text_expansion, item)
369
370 menu_master_data.AppendSeparator()
371
372 item = menu_master_data.Append(-1, _('&Encounter types'), _('Manage encounter types.'))
373 self.Bind(wx.EVT_MENU, self.__on_manage_encounter_types, item)
374
375 item = menu_master_data.Append(-1, _('&Provinces'), _('Manage provinces (counties, territories, ...).'))
376 self.Bind(wx.EVT_MENU, self.__on_manage_provinces, item)
377
378 menu_master_data.AppendSeparator()
379
380 item = menu_master_data.Append(-1, _('Substances'), _('Manage substances in use.'))
381 self.Bind(wx.EVT_MENU, self.__on_manage_substances, item)
382
383 item = menu_master_data.Append(-1, _('Drugs'), _('Manage branded drugs.'))
384 self.Bind(wx.EVT_MENU, self.__on_manage_branded_drugs, item)
385
386 item = menu_master_data.Append(-1, _('Drug components'), _('Manage components of branded drugs.'))
387 self.Bind(wx.EVT_MENU, self.__on_manage_substances_in_brands, item)
388
389 item = menu_master_data.Append(-1, _('Update ATC'), _('Install ATC reference data.'))
390 self.Bind(wx.EVT_MENU, self.__on_update_atc, item)
391
392 menu_master_data.AppendSeparator()
393
394 item = menu_master_data.Append(-1, _('Diagnostic orgs'), _('Manage diagnostic organisations (path labs etc).'))
395 self.Bind(wx.EVT_MENU, self.__on_manage_test_orgs, item)
396
397 item = menu_master_data.Append(-1, _('&Test types'), _('Manage test/measurement types.'))
398 self.Bind(wx.EVT_MENU, self.__on_manage_test_types, item)
399
400 item = menu_master_data.Append(-1, _('&Meta test types'), _('Show meta test/measurement types.'))
401 self.Bind(wx.EVT_MENU, self.__on_manage_meta_test_types, item)
402
403 item = menu_master_data.Append(-1, _('Update LOINC'), _('Download and install LOINC reference data.'))
404 self.Bind(wx.EVT_MENU, self.__on_update_loinc, item)
405
406
407
408
409 menu_users = wx.Menu()
410 menu_gnumed.AppendMenu(wx.NewId(), _('&Users ...'), menu_users)
411
412 item = menu_users.Append(-1, _('&Add user'), _('Add a new GNUmed user'))
413 self.Bind(wx.EVT_MENU, self.__on_add_new_staff, item)
414
415 item = menu_users.Append(-1, _('&Edit users'), _('Edit the list of GNUmed users'))
416 self.Bind(wx.EVT_MENU, self.__on_edit_staff_list, item)
417
418
419 menu_gnumed.AppendSeparator()
420
421 item = menu_gnumed.Append(wx.ID_EXIT, _('E&xit\tAlt-X'), _('Close this GNUmed client.'))
422 self.Bind(wx.EVT_MENU, self.__on_exit_gnumed, item)
423
424 self.mainmenu.Append(menu_gnumed, '&GNUmed')
425
426
427 menu_patient = wx.Menu()
428
429 ID_CREATE_PATIENT = wx.NewId()
430 menu_patient.Append(ID_CREATE_PATIENT, _('Register person'), _("Register a new person with GNUmed"))
431 wx.EVT_MENU(self, ID_CREATE_PATIENT, self.__on_create_new_patient)
432
433
434
435
436 ID_LOAD_EXT_PAT = wx.NewId()
437 menu_patient.Append(ID_LOAD_EXT_PAT, _('Load external'), _('Load and possibly create person from an external source.'))
438 wx.EVT_MENU(self, ID_LOAD_EXT_PAT, self.__on_load_external_patient)
439
440 ID_DEL_PAT = wx.NewId()
441 menu_patient.Append(ID_DEL_PAT, _('Deactivate record'), _('Deactivate (exclude from search) person record in database.'))
442 wx.EVT_MENU(self, ID_DEL_PAT, self.__on_delete_patient)
443
444 item = menu_patient.Append(-1, _('&Merge persons'), _('Merge two persons into one.'))
445 self.Bind(wx.EVT_MENU, self.__on_merge_patients, item)
446
447 menu_patient.AppendSeparator()
448
449 ID_ENLIST_PATIENT_AS_STAFF = wx.NewId()
450 menu_patient.Append(ID_ENLIST_PATIENT_AS_STAFF, _('Enlist as user'), _('Enlist current person as GNUmed user'))
451 wx.EVT_MENU(self, ID_ENLIST_PATIENT_AS_STAFF, self.__on_enlist_patient_as_staff)
452
453
454 ID = wx.NewId()
455 menu_patient.Append(ID, _('Export to GDT'), _('Export demographics of currently active person into GDT file.'))
456 wx.EVT_MENU(self, ID, self.__on_export_as_gdt)
457
458 menu_patient.AppendSeparator()
459
460 self.mainmenu.Append(menu_patient, '&Person')
461 self.__gb['main.patientmenu'] = menu_patient
462
463
464 menu_emr = wx.Menu()
465 self.mainmenu.Append(menu_emr, _("&EMR"))
466 self.__gb['main.emrmenu'] = menu_emr
467
468
469 menu_emr_show = wx.Menu()
470 menu_emr.AppendMenu(wx.NewId(), _('Show as ...'), menu_emr_show)
471 self.__gb['main.emr_showmenu'] = menu_emr_show
472
473
474 item = menu_emr_show.Append(-1, _('Summary'), _('Show a high-level summary of the EMR.'))
475 self.Bind(wx.EVT_MENU, self.__on_show_emr_summary, item)
476
477
478 item = menu_emr.Append(-1, _('Search this EMR'), _('Search for data in the EMR of the active patient'))
479 self.Bind(wx.EVT_MENU, self.__on_search_emr, item)
480
481 item = menu_emr.Append(-1, _('Search all EMRs'), _('Search for data across the EMRs of all patients'))
482 self.Bind(wx.EVT_MENU, self.__on_search_across_emrs, item)
483
484
485 menu_emr_edit = wx.Menu()
486 menu_emr.AppendMenu(wx.NewId(), _('&Add / Edit ...'), menu_emr_edit)
487
488 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'))
489 self.Bind(wx.EVT_MENU, self.__on_add_health_issue, item)
490
491
492
493
494 item = menu_emr_edit.Append(-1, _('&Allergies'), _('Manage documentation of allergies for the current patient.'))
495 self.Bind(wx.EVT_MENU, self.__on_manage_allergies, item)
496
497 item = menu_emr_edit.Append(-1, _('&Occupation'), _('Edit occupation details for the current patient.'))
498 self.Bind(wx.EVT_MENU, self.__on_edit_occupation, item)
499
500 item = menu_emr_edit.Append(-1, _('&Hospital stays'), _('Manage hospital stays.'))
501 self.Bind(wx.EVT_MENU, self.__on_manage_hospital_stays, item)
502
503 item = menu_emr_edit.Append(-1, _('&Procedures'), _('Manage procedures performed on the patient.'))
504 self.Bind(wx.EVT_MENU, self.__on_manage_performed_procedures, item)
505
506 item = menu_emr_edit.Append(-1, _('&Measurement(s)'), _('Add (a) measurement result(s) for the current patient.'))
507 self.Bind(wx.EVT_MENU, self.__on_add_measurement, item)
508
509
510
511
512
513
514
515 item = menu_emr.Append(-1, _('Start new encounter'), _('Start a new encounter for the active patient right now.'))
516 self.Bind(wx.EVT_MENU, self.__on_start_new_encounter, item)
517
518
519 item = menu_emr.Append(-1, _('&Encounters list'), _('List all encounters including empty ones.'))
520 self.Bind(wx.EVT_MENU, self.__on_list_encounters, item)
521
522
523 menu_emr.AppendSeparator()
524
525 menu_emr_export = wx.Menu()
526 menu_emr.AppendMenu(wx.NewId(), _('Export as ...'), menu_emr_export)
527
528 ID_EXPORT_EMR_ASCII = wx.NewId()
529 menu_emr_export.Append (
530 ID_EXPORT_EMR_ASCII,
531 _('Text document'),
532 _("Export the EMR of the active patient into a text file")
533 )
534 wx.EVT_MENU(self, ID_EXPORT_EMR_ASCII, self.OnExportEMR)
535
536 ID_EXPORT_EMR_JOURNAL = wx.NewId()
537 menu_emr_export.Append (
538 ID_EXPORT_EMR_JOURNAL,
539 _('Journal'),
540 _("Export the EMR of the active patient as a chronological journal into a text file")
541 )
542 wx.EVT_MENU(self, ID_EXPORT_EMR_JOURNAL, self.__on_export_emr_as_journal)
543
544 ID_EXPORT_MEDISTAR = wx.NewId()
545 menu_emr_export.Append (
546 ID_EXPORT_MEDISTAR,
547 _('MEDISTAR import format'),
548 _("GNUmed -> MEDISTAR. Export progress notes of active patient's active encounter into a text file.")
549 )
550 wx.EVT_MENU(self, ID_EXPORT_MEDISTAR, self.__on_export_for_medistar)
551
552
553 menu_emr.AppendSeparator()
554
555
556 menu_paperwork = wx.Menu()
557
558 item = menu_paperwork.Append(-1, _('&Write letter'), _('Write a letter for the current patient.'))
559 self.Bind(wx.EVT_MENU, self.__on_new_letter, item)
560
561 self.mainmenu.Append(menu_paperwork, _('&Correspondence'))
562
563
564 self.menu_tools = wx.Menu()
565 self.__gb['main.toolsmenu'] = self.menu_tools
566 self.mainmenu.Append(self.menu_tools, _("&Tools"))
567
568 ID_DICOM_VIEWER = wx.NewId()
569 viewer = _('no viewer installed')
570 if os.access('/Applications/OsiriX.app/Contents/MacOS/OsiriX', os.X_OK):
571 viewer = u'OsiriX'
572 elif gmShellAPI.detect_external_binary(binary = 'aeskulap')[0]:
573 viewer = u'Aeskulap'
574 elif gmShellAPI.detect_external_binary(binary = 'amide')[0]:
575 viewer = u'AMIDE'
576 elif gmShellAPI.detect_external_binary(binary = 'xmedcon')[0]:
577 viewer = u'(x)medcon'
578 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)
579 wx.EVT_MENU(self, ID_DICOM_VIEWER, self.__on_dicom_viewer)
580 if viewer == _('no viewer installed'):
581 _log.info('neither of OsiriX / Aeskulap / AMIDE / xmedcon found, disabling "DICOM viewer" menu item')
582 self.menu_tools.Enable(id=ID_DICOM_VIEWER, enable=False)
583
584
585
586
587
588 ID = wx.NewId()
589 self.menu_tools.Append(ID, _('Snellen chart'), _('Display fullscreen snellen chart.'))
590 wx.EVT_MENU(self, ID, self.__on_snellen)
591
592 item = self.menu_tools.Append(-1, _('MI/stroke risk'), _('Acute coronary syndrome/stroke risk assessment.'))
593 self.Bind(wx.EVT_MENU, self.__on_acs_risk_assessment, item)
594
595 self.menu_tools.AppendSeparator()
596
597
598 menu_knowledge = wx.Menu()
599 self.__gb['main.knowledgemenu'] = menu_knowledge
600 self.mainmenu.Append(menu_knowledge, _('&Knowledge'))
601
602 menu_drug_dbs = wx.Menu()
603 menu_knowledge.AppendMenu(wx.NewId(), _('&Drug Resources'), menu_drug_dbs)
604
605 item = menu_drug_dbs.Append(-1, _('&Database'), _('Jump to the drug database configured as the default.'))
606 self.Bind(wx.EVT_MENU, self.__on_jump_to_drug_db, item)
607
608
609 ID_IFAP = wx.NewId()
610 menu_drug_dbs.Append(ID_IFAP, u'ifap', _('Start "ifap index PRAXIS" %s drug browser (Windows/Wine, Germany)') % gmTools.u_registered_trademark)
611 wx.EVT_MENU(self, ID_IFAP, self.__on_ifap)
612
613 menu_id = wx.NewId()
614 menu_drug_dbs.Append(menu_id, u'kompendium.ch', _('Show "kompendium.ch" drug database (online, Switzerland)'))
615 wx.EVT_MENU(self, menu_id, self.__on_kompendium_ch)
616
617
618
619
620 ID_MEDICAL_LINKS = wx.NewId()
621 menu_knowledge.Append(ID_MEDICAL_LINKS, _('Medical links (www)'), _('Show a page of links to useful medical content.'))
622 wx.EVT_MENU(self, ID_MEDICAL_LINKS, self.__on_medical_links)
623
624
625 self.menu_office = wx.Menu()
626
627 self.__gb['main.officemenu'] = self.menu_office
628 self.mainmenu.Append(self.menu_office, _('&Office'))
629
630
631 help_menu = wx.Menu()
632
633 ID = wx.NewId()
634 help_menu.Append(ID, _('GNUmed wiki'), _('Go to the GNUmed wiki on the web.'))
635 wx.EVT_MENU(self, ID, self.__on_display_wiki)
636
637 ID = wx.NewId()
638 help_menu.Append(ID, _('User manual (www)'), _('Go to the User Manual on the web.'))
639 wx.EVT_MENU(self, ID, self.__on_display_user_manual_online)
640
641 item = help_menu.Append(-1, _('Menu reference (www)'), _('View the reference for menu items on the web.'))
642 self.Bind(wx.EVT_MENU, self.__on_menu_reference, item)
643
644 menu_debugging = wx.Menu()
645 help_menu.AppendMenu(wx.NewId(), _('Debugging ...'), menu_debugging)
646
647 ID_SCREENSHOT = wx.NewId()
648 menu_debugging.Append(ID_SCREENSHOT, _('Screenshot'), _('Save a screenshot of this GNUmed client.'))
649 wx.EVT_MENU(self, ID_SCREENSHOT, self.__on_save_screenshot)
650
651 item = menu_debugging.Append(-1, _('Show log file'), _('Show the log file in text viewer.'))
652 self.Bind(wx.EVT_MENU, self.__on_show_log_file, item)
653
654 ID = wx.NewId()
655 menu_debugging.Append(ID, _('Backup log file'), _('Backup the content of the log to another file.'))
656 wx.EVT_MENU(self, ID, self.__on_backup_log_file)
657
658 ID = wx.NewId()
659 menu_debugging.Append(ID, _('Bug tracker'), _('Go to the GNUmed bug tracker on the web.'))
660 wx.EVT_MENU(self, ID, self.__on_display_bugtracker)
661
662 ID_UNBLOCK = wx.NewId()
663 menu_debugging.Append(ID_UNBLOCK, _('Unlock mouse'), _('Unlock mouse pointer in case it got stuck in hourglass mode.'))
664 wx.EVT_MENU(self, ID_UNBLOCK, self.__on_unblock_cursor)
665
666 item = menu_debugging.Append(-1, _('pgAdmin III'), _('pgAdmin III: Browse GNUmed database(s) in PostgreSQL server.'))
667 self.Bind(wx.EVT_MENU, self.__on_pgadmin3, item)
668
669
670
671
672 if _cfg.get(option = 'debug'):
673 ID_TOGGLE_PAT_LOCK = wx.NewId()
674 menu_debugging.Append(ID_TOGGLE_PAT_LOCK, _('Lock/unlock patient'), _('Lock/unlock patient - USE ONLY IF YOU KNOW WHAT YOU ARE DOING !'))
675 wx.EVT_MENU(self, ID_TOGGLE_PAT_LOCK, self.__on_toggle_patient_lock)
676
677 ID_TEST_EXCEPTION = wx.NewId()
678 menu_debugging.Append(ID_TEST_EXCEPTION, _('Test error handling'), _('Throw an exception to test error handling.'))
679 wx.EVT_MENU(self, ID_TEST_EXCEPTION, self.__on_test_exception)
680
681 ID = wx.NewId()
682 menu_debugging.Append(ID, _('Invoke inspector'), _('Invoke the widget hierarchy inspector (needs wxPython 2.8).'))
683 wx.EVT_MENU(self, ID, self.__on_invoke_inspector)
684 try:
685 import wx.lib.inspection
686 except ImportError:
687 menu_debugging.Enable(id = ID, enable = False)
688
689 help_menu.AppendSeparator()
690
691 help_menu.Append(wx.ID_ABOUT, _('About GNUmed'), "")
692 wx.EVT_MENU (self, wx.ID_ABOUT, self.OnAbout)
693
694 ID_CONTRIBUTORS = wx.NewId()
695 help_menu.Append(ID_CONTRIBUTORS, _('GNUmed contributors'), _('show GNUmed contributors'))
696 wx.EVT_MENU(self, ID_CONTRIBUTORS, self.__on_show_contributors)
697
698 item = help_menu.Append(-1, _('About database'), _('Show information about the current database.'))
699 self.Bind(wx.EVT_MENU, self.__on_about_database, item)
700
701 help_menu.AppendSeparator()
702
703
704 self.__gb['main.helpmenu'] = help_menu
705 self.mainmenu.Append(help_menu, _("&Help"))
706
707
708
709 self.SetMenuBar(self.mainmenu)
710
713
714
715
717 """register events we want to react to"""
718
719 wx.EVT_CLOSE(self, self.OnClose)
720 wx.EVT_QUERY_END_SESSION(self, self._on_query_end_session)
721 wx.EVT_END_SESSION(self, self._on_end_session)
722
723 gmDispatcher.connect(signal = u'post_patient_selection', receiver = self._on_post_patient_selection)
724 gmDispatcher.connect(signal = u'name_mod_db', receiver = self._on_pat_name_changed)
725 gmDispatcher.connect(signal = u'identity_mod_db', receiver = self._on_pat_name_changed)
726 gmDispatcher.connect(signal = u'statustext', receiver = self._on_set_statustext)
727 gmDispatcher.connect(signal = u'request_user_attention', receiver = self._on_request_user_attention)
728 gmDispatcher.connect(signal = u'db_maintenance_warning', receiver = self._on_db_maintenance_warning)
729 gmDispatcher.connect(signal = u'register_pre_exit_callback', receiver = self._register_pre_exit_callback)
730 gmDispatcher.connect(signal = u'plugin_loaded', receiver = self._on_plugin_loaded)
731
732 wx.lib.pubsub.Publisher().subscribe(listener = self._on_set_statustext_pubsub, topic = 'statustext')
733
734 gmPerson.gmCurrentPatient().register_pre_selection_callback(callback = self._pre_selection_callback)
735
736 - def _on_plugin_loaded(self, plugin_name=None, class_name=None, menu_name=None, menu_item_name=None, menu_help_string=None):
737
738 _log.debug('registering plugin with menu system')
739 _log.debug(' generic name: %s', plugin_name)
740 _log.debug(' class name: %s', class_name)
741 _log.debug(' specific menu: %s', menu_name)
742 _log.debug(' menu item: %s', menu_item_name)
743
744
745 item = self.menu_plugins.Append(-1, plugin_name, _('Raise plugin [%s].') % plugin_name)
746 self.Bind(wx.EVT_MENU, self.__on_raise_a_plugin, item)
747 self.menu_id2plugin[item.Id] = class_name
748
749
750 if menu_name is not None:
751 menu = self.__gb['main.%smenu' % menu_name]
752 item = menu.Append(-1, menu_item_name, menu_help_string)
753 self.Bind(wx.EVT_MENU, self.__on_raise_a_plugin, item)
754 self.menu_id2plugin[item.Id] = class_name
755
756 return True
757
759 gmDispatcher.send (
760 signal = u'display_widget',
761 name = self.menu_id2plugin[evt.Id]
762 )
763
765 wx.Bell()
766 wx.Bell()
767 wx.Bell()
768 _log.warning('unhandled event detected: QUERY_END_SESSION')
769 _log.info('we should be saving ourselves from here')
770 gmLog2.flush()
771 print "unhandled event detected: QUERY_END_SESSION"
772
774 wx.Bell()
775 wx.Bell()
776 wx.Bell()
777 _log.warning('unhandled event detected: END_SESSION')
778 gmLog2.flush()
779 print "unhandled event detected: END_SESSION"
780
782 if not callable(callback):
783 raise TypeError(u'callback [%s] not callable' % callback)
784
785 self.__pre_exit_callbacks.append(callback)
786
787 - def _on_set_statustext_pubsub(self, context=None):
788 msg = u'%s %s' % (gmDateTime.pydt_now_here().strftime('%H:%M'), context.data['msg'])
789 wx.CallAfter(self.SetStatusText, msg)
790
791 try:
792 if context.data['beep']:
793 wx.Bell()
794 except KeyError:
795 pass
796
797 - def _on_set_statustext(self, msg=None, loglevel=None, beep=True):
798
799 if msg is None:
800 msg = _('programmer forgot to specify status message')
801
802 if loglevel is not None:
803 _log.log(loglevel, msg.replace('\015', ' ').replace('\012', ' '))
804
805 msg = u'%s %s' % (gmDateTime.pydt_now_here().strftime('%H:%M'), msg)
806 wx.CallAfter(self.SetStatusText, msg)
807
808 if beep:
809 wx.Bell()
810
812 wx.CallAfter(self.__on_db_maintenance_warning)
813
815
816 self.SetStatusText(_('The database will be shut down for maintenance in a few minutes.'))
817 wx.Bell()
818 if not wx.GetApp().IsActive():
819 self.RequestUserAttention(flags = wx.USER_ATTENTION_ERROR)
820
821 gmHooks.run_hook_script(hook = u'db_maintenance_warning')
822
823 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
824 None,
825 -1,
826 caption = _('Database shutdown warning'),
827 question = _(
828 'The database will be shut down for maintenance\n'
829 'in a few minutes.\n'
830 '\n'
831 'In order to not suffer any loss of data you\n'
832 'will need to save your current work and log\n'
833 'out of this GNUmed client.\n'
834 ),
835 button_defs = [
836 {
837 u'label': _('Close now'),
838 u'tooltip': _('Close this GNUmed client immediately.'),
839 u'default': False
840 },
841 {
842 u'label': _('Finish work'),
843 u'tooltip': _('Finish and save current work first, then manually close this GNUmed client.'),
844 u'default': True
845 }
846 ]
847 )
848 decision = dlg.ShowModal()
849 if decision == wx.ID_YES:
850 top_win = wx.GetApp().GetTopWindow()
851 wx.CallAfter(top_win.Close)
852
854 wx.CallAfter(self.__on_request_user_attention, msg, urgent)
855
857
858 if not wx.GetApp().IsActive():
859 if urgent:
860 self.RequestUserAttention(flags = wx.USER_ATTENTION_ERROR)
861 else:
862 self.RequestUserAttention(flags = wx.USER_ATTENTION_INFO)
863
864 if msg is not None:
865 self.SetStatusText(msg)
866
867 if urgent:
868 wx.Bell()
869
870 gmHooks.run_hook_script(hook = u'request_user_attention')
871
873 wx.CallAfter(self.__on_pat_name_changed)
874
876 self.__update_window_title()
877
879 wx.CallAfter(self.__on_post_patient_selection, **kwargs)
880
882 self.__update_window_title()
883 try:
884 gmHooks.run_hook_script(hook = u'post_patient_activation')
885 except:
886 gmDispatcher.send(signal = 'statustext', msg = _('Cannot run script after patient activation.'))
887 raise
888
890 return self.__sanity_check_encounter()
891
949
950
951
954
962
965
966
967
982
1005
1007 from Gnumed.wxpython import gmAbout
1008 contribs = gmAbout.cContributorsDlg (
1009 parent = self,
1010 id = -1,
1011 title = _('GNUmed contributors'),
1012 size = wx.Size(400,600),
1013 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
1014 )
1015 contribs.ShowModal()
1016 del contribs
1017 del gmAbout
1018
1019
1020
1022 """Invoked from Menu GNUmed / Exit (which calls this ID_EXIT handler)."""
1023 _log.debug('gmTopLevelFrame._on_exit_gnumed() start')
1024 self.Close(True)
1025 _log.debug('gmTopLevelFrame._on_exit_gnumed() end')
1026
1029
1031 send = gmGuiHelpers.gm_show_question (
1032 _('This will send a notification about database downtime\n'
1033 'to all GNUmed clients connected to your database.\n'
1034 '\n'
1035 'Do you want to send the notification ?\n'
1036 ),
1037 _('Announcing database maintenance downtime')
1038 )
1039 if not send:
1040 return
1041 gmPG2.send_maintenance_notification()
1042
1043
1044
1076
1089
1090 gmCfgWidgets.configure_string_option (
1091 message = _(
1092 'Some network installations cannot cope with loading\n'
1093 'documents of arbitrary size in one piece from the\n'
1094 'database (mainly observed on older Windows versions)\n.'
1095 '\n'
1096 'Under such circumstances documents need to be retrieved\n'
1097 'in chunks and reassembled on the client.\n'
1098 '\n'
1099 'Here you can set the size (in Bytes) above which\n'
1100 'GNUmed will retrieve documents in chunks. Setting this\n'
1101 'value to 0 will disable the chunking protocol.'
1102 ),
1103 option = 'horstspace.blob_export_chunk_size',
1104 bias = 'workplace',
1105 default_value = 1024 * 1024,
1106 validator = is_valid
1107 )
1108
1109
1110
1178
1182
1183
1184
1192
1193 gmCfgWidgets.configure_string_option (
1194 message = _(
1195 'When GNUmed cannot find an OpenOffice server it\n'
1196 'will try to start one. OpenOffice, however, needs\n'
1197 'some time to fully start up.\n'
1198 '\n'
1199 'Here you can set the time for GNUmed to wait for OOo.\n'
1200 ),
1201 option = 'external.ooo.startup_settle_time',
1202 bias = 'workplace',
1203 default_value = 2.0,
1204 validator = is_valid
1205 )
1206
1209
1221
1222 gmCfgWidgets.configure_string_option (
1223 message = _(
1224 'GNUmed will use this URL to access an encyclopedia of\n'
1225 'measurement/lab methods from within the measurments grid.\n'
1226 '\n'
1227 'You can leave this empty but to set it to a specific\n'
1228 'address the URL must be accessible now.'
1229 ),
1230 option = 'external.urls.measurements_encyclopedia',
1231 bias = 'user',
1232 default_value = u'http://www.laborlexikon.de',
1233 validator = is_valid
1234 )
1235
1248
1249 gmCfgWidgets.configure_string_option (
1250 message = _(
1251 'Enter the shell command with which to start the\n'
1252 'the ACS risk assessment calculator.\n'
1253 '\n'
1254 'GNUmed will try to verify the path which may,\n'
1255 'however, fail if you are using an emulator such\n'
1256 'as Wine. Nevertheless, starting the calculator\n'
1257 'will work as long as the shell command is correct\n'
1258 'despite the failing test.'
1259 ),
1260 option = 'external.tools.acs_risk_calculator_cmd',
1261 bias = 'user',
1262 validator = is_valid
1263 )
1264
1277
1278 gmCfgWidgets.configure_string_option (
1279 message = _(
1280 'Enter the shell command with which to start the\n'
1281 'the IFAP drug database.\n'
1282 '\n'
1283 'GNUmed will try to verify the path which may,\n'
1284 'however, fail if you are using an emulator such\n'
1285 'as Wine. Nevertheless, starting IFAP will work\n'
1286 'as long as the shell command is correct despite\n'
1287 'the failing test.'
1288 ),
1289 option = 'external.ifap-win.shell_command',
1290 bias = 'workplace',
1291 default_value = 'C:\Ifapwin\WIAMDB.EXE',
1292 validator = is_valid
1293 )
1294
1295
1296
1345
1346
1347
1364
1367
1370
1375
1376 gmCfgWidgets.configure_string_option (
1377 message = _(
1378 'When a patient is activated GNUmed checks the\n'
1379 "proximity of the patient's birthday.\n"
1380 '\n'
1381 'If the birthday falls within the range of\n'
1382 ' "today %s <the interval you set here>"\n'
1383 'GNUmed will remind you of the recent or\n'
1384 'imminent anniversary.'
1385 ) % u'\u2213',
1386 option = u'patient_search.dob_warn_interval',
1387 bias = 'user',
1388 default_value = '1 week',
1389 validator = is_valid
1390 )
1391
1393
1394 gmCfgWidgets.configure_boolean_option (
1395 parent = self,
1396 question = _(
1397 'When adding progress notes do you want to\n'
1398 'allow opening several unassociated, new\n'
1399 'episodes for a patient at once ?\n'
1400 '\n'
1401 'This can be particularly helpful when entering\n'
1402 'progress notes on entirely new patients presenting\n'
1403 'with a multitude of problems on their first visit.'
1404 ),
1405 option = u'horstspace.soap_editor.allow_same_episode_multiple_times',
1406 button_tooltips = [
1407 _('Yes, allow for multiple new episodes concurrently.'),
1408 _('No, only allow editing one new episode at a time.')
1409 ]
1410 )
1411
1457
1458
1459
1462
1476
1478 gmCfgWidgets.configure_boolean_option (
1479 parent = self,
1480 question = _(
1481 'Do you want GNUmed to show the encounter\n'
1482 'details editor when changing the active patient ?'
1483 ),
1484 option = 'encounter.show_editor_before_patient_change',
1485 button_tooltips = [
1486 _('Yes, show the encounter editor if it seems appropriate.'),
1487 _('No, never show the encounter editor even if it would seem useful.')
1488 ]
1489 )
1490
1495
1496 gmCfgWidgets.configure_string_option (
1497 message = _(
1498 'When a patient is activated GNUmed checks the\n'
1499 'chart for encounters lacking any entries.\n'
1500 '\n'
1501 'Any such encounters older than what you set\n'
1502 'here will be removed from the medical record.\n'
1503 '\n'
1504 'To effectively disable removal of such encounters\n'
1505 'set this option to an improbable value.\n'
1506 ),
1507 option = 'encounter.ttl_if_empty',
1508 bias = 'user',
1509 default_value = '1 week',
1510 validator = is_valid
1511 )
1512
1517
1518 gmCfgWidgets.configure_string_option (
1519 message = _(
1520 'When a patient is activated GNUmed checks the\n'
1521 'age of the most recent encounter.\n'
1522 '\n'
1523 'If that encounter is younger than this age\n'
1524 'the existing encounter will be continued.\n'
1525 '\n'
1526 '(If it is really old a new encounter is\n'
1527 ' started, or else GNUmed will ask you.)\n'
1528 ),
1529 option = 'encounter.minimum_ttl',
1530 bias = 'user',
1531 default_value = '1 hour 30 minutes',
1532 validator = is_valid
1533 )
1534
1539
1540 gmCfgWidgets.configure_string_option (
1541 message = _(
1542 'When a patient is activated GNUmed checks the\n'
1543 'age of the most recent encounter.\n'
1544 '\n'
1545 'If that encounter is older than this age\n'
1546 'GNUmed will always start a new encounter.\n'
1547 '\n'
1548 '(If it is very recent the existing encounter\n'
1549 ' is continued, or else GNUmed will ask you.)\n'
1550 ),
1551 option = 'encounter.maximum_ttl',
1552 bias = 'user',
1553 default_value = '6 hours',
1554 validator = is_valid
1555 )
1556
1565
1566 gmCfgWidgets.configure_string_option (
1567 message = _(
1568 'At any time there can only be one open (ongoing)\n'
1569 'episode for each health issue.\n'
1570 '\n'
1571 'When you try to open (add data to) an episode on a health\n'
1572 'issue GNUmed will check for an existing open episode on\n'
1573 'that issue. If there is any it will check the age of that\n'
1574 'episode. The episode is closed if it has been dormant (no\n'
1575 'data added, that is) for the period of time (in days) you\n'
1576 'set here.\n'
1577 '\n'
1578 "If the existing episode hasn't been dormant long enough\n"
1579 'GNUmed will consult you what to do.\n'
1580 '\n'
1581 'Enter maximum episode dormancy in DAYS:'
1582 ),
1583 option = 'episode.ttl',
1584 bias = 'user',
1585 default_value = 60,
1586 validator = is_valid
1587 )
1588
1619
1622
1637
1662
1674
1675 gmCfgWidgets.configure_string_option (
1676 message = _(
1677 'GNUmed can check for new releases being available. To do\n'
1678 'so it needs to load version information from an URL.\n'
1679 '\n'
1680 'The default URL is:\n'
1681 '\n'
1682 ' http://www.gnumed.de/downloads/gnumed-versions.txt\n'
1683 '\n'
1684 'but you can configure any other URL locally. Note\n'
1685 'that you must enter the location as a valid URL.\n'
1686 'Depending on the URL the client will need online\n'
1687 'access when checking for updates.'
1688 ),
1689 option = u'horstspace.update.url',
1690 bias = u'workplace',
1691 default_value = u'http://www.gnumed.de/downloads/gnumed-versions.txt',
1692 validator = is_valid
1693 )
1694
1712
1729
1740
1741 gmCfgWidgets.configure_string_option (
1742 message = _(
1743 'GNUmed can show the document review dialog after\n'
1744 'calling the appropriate viewer for that document.\n'
1745 '\n'
1746 'Select the conditions under which you want\n'
1747 'GNUmed to do so:\n'
1748 '\n'
1749 ' 0: never display the review dialog\n'
1750 ' 1: always display the dialog\n'
1751 ' 2: only if there is no previous review by me\n'
1752 '\n'
1753 'Note that if a viewer is configured to not block\n'
1754 'GNUmed during document display the review dialog\n'
1755 'will actually appear in parallel to the viewer.'
1756 ),
1757 option = u'horstspace.document_viewer.review_after_display',
1758 bias = u'user',
1759 default_value = 2,
1760 validator = is_valid
1761 )
1762
1776
1793
1795 dlg = gmSnellen.cSnellenCfgDlg()
1796 if dlg.ShowModal() != wx.ID_OK:
1797 return
1798
1799 frame = gmSnellen.cSnellenChart (
1800 width = dlg.vals[0],
1801 height = dlg.vals[1],
1802 alpha = dlg.vals[2],
1803 mirr = dlg.vals[3],
1804 parent = None
1805 )
1806 frame.CentreOnScreen(wx.BOTH)
1807
1808
1809 frame.Show(True)
1810
1811
1813 webbrowser.open (
1814 url = 'http://wiki.gnumed.de/bin/view/Gnumed/MedicalContentLinks#AnchorLocaleI%s' % gmI18N.system_locale_level['language'],
1815 new = False,
1816 autoraise = True
1817 )
1818
1821
1824
1826 webbrowser.open (
1827 url = 'http://www.kompendium.ch',
1828 new = False,
1829 autoraise = True
1830 )
1831
1832
1833
1835 wx.CallAfter(self.__save_screenshot)
1836 evt.Skip()
1837
1839
1840 time.sleep(0.5)
1841
1842 rect = self.GetRect()
1843
1844
1845 if sys.platform == 'linux2':
1846 client_x, client_y = self.ClientToScreen((0, 0))
1847 border_width = client_x - rect.x
1848 title_bar_height = client_y - rect.y
1849
1850 if self.GetMenuBar():
1851 title_bar_height /= 2
1852 rect.width += (border_width * 2)
1853 rect.height += title_bar_height + border_width
1854
1855 wdc = wx.ScreenDC()
1856 mdc = wx.MemoryDC()
1857 img = wx.EmptyBitmap(rect.width, rect.height)
1858 mdc.SelectObject(img)
1859 mdc.Blit (
1860 0, 0,
1861 rect.width, rect.height,
1862 wdc,
1863 rect.x, rect.y
1864 )
1865
1866
1867 fname = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'gnumed-screenshot-%s.png')) % pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
1868 img.SaveFile(fname, wx.BITMAP_TYPE_PNG)
1869 gmDispatcher.send(signal = 'statustext', msg = _('Saved screenshot to file [%s].') % fname)
1870
1872
1873 raise ValueError('raised ValueError to test exception handling')
1874
1876 import wx.lib.inspection
1877 wx.lib.inspection.InspectionTool().Show()
1878
1880 webbrowser.open (
1881 url = 'https://bugs.launchpad.net/gnumed/',
1882
1883 new = False,
1884 autoraise = True
1885 )
1886
1888 webbrowser.open (
1889 url = 'http://wiki.gnumed.de',
1890 new = False,
1891 autoraise = True
1892 )
1893
1895 webbrowser.open (
1896 url = 'http://wiki.gnumed.de/bin/view/Gnumed/GnumedManual#UserGuideInManual',
1897 new = False,
1898 autoraise = True
1899 )
1900
1902 webbrowser.open (
1903 url = 'http://wiki.gnumed.de/bin/view/Gnumed/MenuReference',
1904 new = False,
1905 autoraise = True
1906 )
1907
1914
1918
1921
1928
1933
1935 name = os.path.basename(gmLog2._logfile_name)
1936 name, ext = os.path.splitext(name)
1937 new_name = '%s_%s%s' % (name, pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), ext)
1938 new_path = os.path.expanduser(os.path.join('~', 'gnumed', 'logs'))
1939
1940 dlg = wx.FileDialog (
1941 parent = self,
1942 message = _("Save current log as..."),
1943 defaultDir = new_path,
1944 defaultFile = new_name,
1945 wildcard = "%s (*.log)|*.log" % _("log files"),
1946 style = wx.SAVE
1947 )
1948 choice = dlg.ShowModal()
1949 new_name = dlg.GetPath()
1950 dlg.Destroy()
1951 if choice != wx.ID_OK:
1952 return True
1953
1954 _log.warning('syncing log file for backup to [%s]', new_name)
1955 gmLog2.flush()
1956 shutil.copy2(gmLog2._logfile_name, new_name)
1957 gmDispatcher.send('statustext', msg = _('Log file backed up as [%s].') % new_name)
1958
1959
1960
1962 """This is the wx.EVT_CLOSE handler.
1963
1964 - framework still functional
1965 """
1966 _log.debug('gmTopLevelFrame.OnClose() start')
1967 self._clean_exit()
1968 self.Destroy()
1969 _log.debug('gmTopLevelFrame.OnClose() end')
1970 return True
1971
1977
1982
1990
1997
2004
2014
2022
2030
2038
2046
2054
2056 pat = gmPerson.gmCurrentPatient()
2057 if not pat.connected:
2058 gmDispatcher.send(signal = 'statustext', msg = _('Cannot show EMR summary. No active patient.'))
2059 return False
2060
2061 emr = pat.get_emr()
2062 dlg = wx.MessageDialog (
2063 parent = self,
2064 message = emr.format_statistics(),
2065 caption = _('EMR Summary'),
2066 style = wx.OK | wx.STAY_ON_TOP
2067 )
2068 dlg.ShowModal()
2069 dlg.Destroy()
2070 return True
2071
2074
2077
2079
2080 pat = gmPerson.gmCurrentPatient()
2081 if not pat.connected:
2082 gmDispatcher.send(signal = 'statustext', msg = _('Cannot export EMR journal. No active patient.'))
2083 return False
2084
2085 aWildcard = "%s (*.txt)|*.txt|%s (*)|*" % (_("text files"), _("all files"))
2086
2087 aDefDir = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'EMR', pat['dirname']))
2088 gmTools.mkdir(aDefDir)
2089
2090 fname = '%s-%s_%s.txt' % (_('emr-journal'), pat['lastnames'], pat['firstnames'])
2091 dlg = wx.FileDialog (
2092 parent = self,
2093 message = _("Save patient's EMR journal as..."),
2094 defaultDir = aDefDir,
2095 defaultFile = fname,
2096 wildcard = aWildcard,
2097 style = wx.SAVE
2098 )
2099 choice = dlg.ShowModal()
2100 fname = dlg.GetPath()
2101 dlg.Destroy()
2102 if choice != wx.ID_OK:
2103 return True
2104
2105 _log.debug('exporting EMR journal to [%s]' % fname)
2106
2107 exporter = gmPatientExporter.cEMRJournalExporter()
2108
2109 wx.BeginBusyCursor()
2110 try:
2111 fname = exporter.export_to_file(filename = fname)
2112 except:
2113 wx.EndBusyCursor()
2114 gmGuiHelpers.gm_show_error (
2115 _('Error exporting patient EMR as chronological journal.'),
2116 _('EMR journal export')
2117 )
2118 raise
2119 wx.EndBusyCursor()
2120
2121 gmDispatcher.send(signal = 'statustext', msg = _('Successfully exported EMR as chronological journal into file [%s].') % fname, beep=False)
2122
2123 return True
2124
2131
2141
2143 curr_pat = gmPerson.gmCurrentPatient()
2144 if not curr_pat.connected:
2145 gmDispatcher.send(signal = 'statustext', msg = _('Cannot export patient as GDT. No active patient.'))
2146 return False
2147
2148 enc = 'cp850'
2149 fname = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'xDT', 'current-patient.gdt'))
2150 curr_pat.export_as_gdt(filename = fname, encoding = enc)
2151 gmDispatcher.send(signal = 'statustext', msg = _('Exported demographics to GDT file [%s].') % fname)
2152
2155
2156
2157
2158
2159
2160
2161
2169
2177
2180
2189
2193
2197
2200
2203
2206
2209
2212
2215
2218
2221
2224
2227
2230
2232 """Cleanup helper.
2233
2234 - should ALWAYS be called when this program is
2235 to be terminated
2236 - ANY code that should be executed before a
2237 regular shutdown should go in here
2238 - framework still functional
2239 """
2240 _log.debug('gmTopLevelFrame._clean_exit() start')
2241
2242
2243 listener = gmBackendListener.gmBackendListener()
2244 try:
2245 listener.shutdown()
2246 except:
2247 _log.exception('cannot stop backend notifications listener thread')
2248
2249
2250 if _scripting_listener is not None:
2251 try:
2252 _scripting_listener.shutdown()
2253 except:
2254 _log.exception('cannot stop scripting listener thread')
2255
2256
2257 self.clock_update_timer.Stop()
2258 gmTimer.shutdown()
2259 gmPhraseWheel.shutdown()
2260
2261
2262 for call_back in self.__pre_exit_callbacks:
2263 try:
2264 call_back()
2265 except:
2266 print "*** pre-exit callback failed ***"
2267 print call_back
2268 _log.exception('callback [%s] failed', call_back)
2269
2270
2271 gmDispatcher.send(u'application_closing')
2272
2273
2274 gmDispatcher.disconnect(self._on_set_statustext, 'statustext')
2275
2276
2277 curr_width, curr_height = self.GetClientSizeTuple()
2278 _log.info('GUI size at shutdown: [%s:%s]' % (curr_width, curr_height))
2279 dbcfg = gmCfg.cCfgSQL()
2280 dbcfg.set (
2281 option = 'main.window.width',
2282 value = curr_width,
2283 workplace = gmSurgery.gmCurrentPractice().active_workplace
2284 )
2285 dbcfg.set (
2286 option = 'main.window.height',
2287 value = curr_height,
2288 workplace = gmSurgery.gmCurrentPractice().active_workplace
2289 )
2290
2291 if _cfg.get(option = 'debug'):
2292 print '---=== GNUmed shutdown ===---'
2293 print _('You have to manually close this window to finalize shutting down GNUmed.')
2294 print _('This is so that you can inspect the console output at your leisure.')
2295 print '---=== GNUmed shutdown ===---'
2296
2297
2298 gmExceptionHandlingWidgets.uninstall_wx_exception_handler()
2299
2300
2301 import threading
2302 _log.debug("%s active threads", threading.activeCount())
2303 for t in threading.enumerate():
2304 _log.debug('thread %s', t)
2305
2306 _log.debug('gmTopLevelFrame._clean_exit() end')
2307
2308
2309
2311
2312 if _cfg.get(option = 'slave'):
2313 self.__title_template = u'GMdS: %%(pat)s [%%(prov)s@%%(wp)s] (%s:%s)' % (
2314 _cfg.get(option = 'slave personality'),
2315 _cfg.get(option = 'xml-rpc port')
2316 )
2317 else:
2318 self.__title_template = u'GMd: %(pat)s [%(prov)s@%(wp)s]'
2319
2321 """Update title of main window based on template.
2322
2323 This gives nice tooltips on iconified GNUmed instances.
2324
2325 User research indicates that in the title bar people want
2326 the date of birth, not the age, so please stick to this
2327 convention.
2328 """
2329 args = {}
2330
2331 pat = gmPerson.gmCurrentPatient()
2332 if pat.connected:
2333
2334
2335
2336
2337
2338
2339 args['pat'] = u'%s %s %s (%s) #%d' % (
2340 gmTools.coalesce(pat['title'], u'', u'%.4s'),
2341
2342 pat['firstnames'],
2343 pat['lastnames'],
2344 pat.get_formatted_dob(format = '%x', encoding = gmI18N.get_encoding()),
2345 pat['pk_identity']
2346 )
2347 else:
2348 args['pat'] = _('no patient')
2349
2350 args['prov'] = u'%s%s.%s' % (
2351 gmTools.coalesce(_provider['title'], u'', u'%s '),
2352 _provider['firstnames'][:1],
2353 _provider['lastnames']
2354 )
2355
2356 args['wp'] = gmSurgery.gmCurrentPractice().active_workplace
2357
2358 self.SetTitle(self.__title_template % args)
2359
2360
2362 sb = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
2363 sb.SetStatusWidths([-1, 225])
2364
2365 self.clock_update_timer = wx.PyTimer(self._cb_update_clock)
2366 self._cb_update_clock()
2367
2368 self.clock_update_timer.Start(milliseconds = 1000)
2369
2371 """Displays date and local time in the second slot of the status bar"""
2372 t = time.localtime(time.time())
2373 st = time.strftime('%c', t).decode(gmI18N.get_encoding())
2374 self.SetStatusText(st,1)
2375
2377 """Lock GNUmed client against unauthorized access"""
2378
2379
2380
2381 return
2382
2384 """Unlock the main notebook widgets
2385 As long as we are not logged into the database backend,
2386 all pages but the 'login' page of the main notebook widget
2387 are locked; i.e. not accessible by the user
2388 """
2389
2390
2391
2392
2393
2394 return
2395
2397 wx.LayoutAlgorithm().LayoutWindow (self.LayoutMgr, self.nb)
2398
2400
2402
2403 self.__starting_up = True
2404
2405 gmExceptionHandlingWidgets.install_wx_exception_handler()
2406 gmExceptionHandlingWidgets.set_client_version(_cfg.get(option = 'client_version'))
2407
2408 _log.info('display: %s:%s' % (wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X), wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)))
2409
2410
2411 self.SetAppName(u'gnumed')
2412 self.SetVendorName(u'The GNUmed Development Community.')
2413 paths = gmTools.gmPaths(app_name = u'gnumed', wx = wx)
2414 paths.init_paths(wx = wx, app_name = u'gnumed')
2415
2416 if not self.__setup_prefs_file():
2417 return False
2418
2419 gmExceptionHandlingWidgets.set_sender_email(gmSurgery.gmCurrentPractice().user_email)
2420
2421 self.__guibroker = gmGuiBroker.GuiBroker()
2422 self.__setup_platform()
2423
2424 if not self.__establish_backend_connection():
2425 return False
2426
2427 if not _cfg.get(option = 'skip-update-check'):
2428 self.__check_for_updates()
2429
2430 if _cfg.get(option = 'slave'):
2431 if not self.__setup_scripting_listener():
2432 return False
2433
2434
2435 frame = gmTopLevelFrame(None, -1, _('GNUmed client'), (640,440))
2436 frame.CentreOnScreen(wx.BOTH)
2437 self.SetTopWindow(frame)
2438 frame.Show(True)
2439
2440 if _cfg.get(option = 'debug'):
2441 self.RedirectStdio()
2442 self.SetOutputWindowAttributes(title = _('GNUmed stdout/stderr window'))
2443
2444
2445 print '---=== GNUmed startup ===---'
2446 print _('redirecting STDOUT/STDERR to this log window')
2447 print '---=== GNUmed startup ===---'
2448
2449 self.__setup_user_activity_timer()
2450 self.__register_events()
2451
2452 wx.CallAfter(self._do_after_init)
2453
2454 return True
2455
2457 """Called internally by wxPython after EVT_CLOSE has been handled on last frame.
2458
2459 - after destroying all application windows and controls
2460 - before wx.Windows internal cleanup
2461 """
2462 _log.debug('gmApp.OnExit() start')
2463
2464 self.__shutdown_user_activity_timer()
2465
2466 if _cfg.get(option = 'debug'):
2467 self.RestoreStdio()
2468 sys.stdin = sys.__stdin__
2469 sys.stdout = sys.__stdout__
2470 sys.stderr = sys.__stderr__
2471
2472 _log.debug('gmApp.OnExit() end')
2473
2475 wx.Bell()
2476 wx.Bell()
2477 wx.Bell()
2478 _log.warning('unhandled event detected: QUERY_END_SESSION')
2479 _log.info('we should be saving ourselves from here')
2480 gmLog2.flush()
2481 print "unhandled event detected: QUERY_END_SESSION"
2482
2484 wx.Bell()
2485 wx.Bell()
2486 wx.Bell()
2487 _log.warning('unhandled event detected: END_SESSION')
2488 gmLog2.flush()
2489 print "unhandled event detected: END_SESSION"
2490
2501
2503 self.user_activity_detected = True
2504 evt.Skip()
2505
2507
2508 if self.user_activity_detected:
2509 self.elapsed_inactivity_slices = 0
2510 self.user_activity_detected = False
2511 self.elapsed_inactivity_slices += 1
2512 else:
2513 if self.elapsed_inactivity_slices >= self.max_user_inactivity_slices:
2514
2515 pass
2516
2517 self.user_activity_timer.Start(oneShot = True)
2518
2519
2520
2522 try:
2523 kwargs['originated_in_database']
2524 print '==> got notification from database "%s":' % kwargs['signal']
2525 except KeyError:
2526 print '==> received signal from client: "%s"' % kwargs['signal']
2527
2528 del kwargs['signal']
2529 for key in kwargs.keys():
2530 print ' [%s]: %s' % (key, kwargs[key])
2531
2533 print "wx.lib.pubsub message:"
2534 print msg.topic
2535 print msg.data
2536
2542
2544 self.user_activity_detected = True
2545 self.elapsed_inactivity_slices = 0
2546
2547 self.max_user_inactivity_slices = 15
2548 self.user_activity_timer = gmTimer.cTimer (
2549 callback = self._on_user_activity_timer_expired,
2550 delay = 2000
2551 )
2552 self.user_activity_timer.Start(oneShot=True)
2553
2555 try:
2556 self.user_activity_timer.Stop()
2557 del self.user_activity_timer
2558 except:
2559 pass
2560
2562 wx.EVT_QUERY_END_SESSION(self, self._on_query_end_session)
2563 wx.EVT_END_SESSION(self, self._on_end_session)
2564
2565
2566
2567
2568
2569 self.Bind(wx.EVT_ACTIVATE_APP, self._on_app_activated)
2570
2571 self.Bind(wx.EVT_MOUSE_EVENTS, self._on_user_activity)
2572 self.Bind(wx.EVT_KEY_DOWN, self._on_user_activity)
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2598
2600 """Handle all the database related tasks necessary for startup."""
2601
2602
2603 override = _cfg.get(option = '--override-schema-check', source_order = [('cli', 'return')])
2604
2605 from Gnumed.wxpython import gmAuthWidgets
2606 connected = gmAuthWidgets.connect_to_database (
2607 expected_version = gmPG2.map_client_branch2required_db_version[_cfg.get(option = 'client_branch')],
2608 require_version = not override
2609 )
2610 if not connected:
2611 _log.warning("Login attempt unsuccessful. Can't run GNUmed without database connection")
2612 return False
2613
2614
2615 try:
2616 global _provider
2617 _provider = gmPerson.gmCurrentProvider(provider = gmPerson.cStaff())
2618 except ValueError:
2619 account = gmPG2.get_current_user()
2620 _log.exception('DB account [%s] cannot be used as a GNUmed staff login', account)
2621 msg = _(
2622 'The database account [%s] cannot be used as a\n'
2623 'staff member login for GNUmed. There was an\n'
2624 'error retrieving staff details for it.\n\n'
2625 'Please ask your administrator for help.\n'
2626 ) % account
2627 gmGuiHelpers.gm_show_error(msg, _('Checking access permissions'))
2628 return False
2629
2630
2631 tmp = '%s%s %s (%s = %s)' % (
2632 gmTools.coalesce(_provider['title'], ''),
2633 _provider['firstnames'],
2634 _provider['lastnames'],
2635 _provider['short_alias'],
2636 _provider['db_user']
2637 )
2638 gmExceptionHandlingWidgets.set_staff_name(staff_name = tmp)
2639
2640
2641 surgery = gmSurgery.gmCurrentPractice()
2642 msg = surgery.db_logon_banner
2643 if msg.strip() != u'':
2644
2645 login = gmPG2.get_default_login()
2646 auth = u'\n%s\n\n' % (_('Database <%s> on <%s>') % (
2647 login.database,
2648 gmTools.coalesce(login.host, u'localhost')
2649 ))
2650 msg = auth + msg + u'\n\n'
2651
2652 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
2653 None,
2654 -1,
2655 caption = _('Verifying database'),
2656 question = gmTools.wrap(msg, 60, initial_indent = u' ', subsequent_indent = u' '),
2657 button_defs = [
2658 {'label': _('Connect'), 'tooltip': _('Yes, connect to this database.'), 'default': True},
2659 {'label': _('Disconnect'), 'tooltip': _('No, do not connect to this database.'), 'default': False}
2660 ]
2661 )
2662 go_on = dlg.ShowModal()
2663 dlg.Destroy()
2664 if go_on != wx.ID_YES:
2665 _log.info('user decided to not connect to this database')
2666 return False
2667
2668
2669 self.__check_db_lang()
2670
2671 return True
2672
2674 """Setup access to a config file for storing preferences."""
2675
2676 paths = gmTools.gmPaths(app_name = u'gnumed', wx = wx)
2677
2678 candidates = []
2679 explicit_file = _cfg.get(option = '--conf-file', source_order = [('cli', 'return')])
2680 if explicit_file is not None:
2681 candidates.append(explicit_file)
2682
2683 candidates.append(os.path.join(paths.user_config_dir, 'gnumed.conf'))
2684 candidates.append(os.path.join(paths.local_base_dir, 'gnumed.conf'))
2685 candidates.append(os.path.join(paths.working_dir, 'gnumed.conf'))
2686
2687 prefs_file = None
2688 for candidate in candidates:
2689 try:
2690 open(candidate, 'a+').close()
2691 prefs_file = candidate
2692 break
2693 except IOError:
2694 continue
2695
2696 if prefs_file is None:
2697 msg = _(
2698 'Cannot find configuration file in any of:\n'
2699 '\n'
2700 ' %s\n'
2701 'You may need to use the comand line option\n'
2702 '\n'
2703 ' --conf-file=<FILE>'
2704 ) % '\n '.join(candidates)
2705 gmGuiHelpers.gm_show_error(msg, _('Checking configuration files'))
2706 return False
2707
2708 _cfg.set_option(option = u'user_preferences_file', value = prefs_file)
2709 _log.info('user preferences file: %s', prefs_file)
2710
2711 return True
2712
2714
2715 from socket import error as SocketError
2716 from Gnumed.pycommon import gmScriptingListener
2717 from Gnumed.wxpython import gmMacro
2718
2719 slave_personality = gmTools.coalesce (
2720 _cfg.get (
2721 group = u'workplace',
2722 option = u'slave personality',
2723 source_order = [
2724 ('explicit', 'return'),
2725 ('workbase', 'return'),
2726 ('user', 'return'),
2727 ('system', 'return')
2728 ]
2729 ),
2730 u'gnumed-client'
2731 )
2732 _cfg.set_option(option = 'slave personality', value = slave_personality)
2733
2734
2735 port = int (
2736 gmTools.coalesce (
2737 _cfg.get (
2738 group = u'workplace',
2739 option = u'xml-rpc port',
2740 source_order = [
2741 ('explicit', 'return'),
2742 ('workbase', 'return'),
2743 ('user', 'return'),
2744 ('system', 'return')
2745 ]
2746 ),
2747 9999
2748 )
2749 )
2750 _cfg.set_option(option = 'xml-rpc port', value = port)
2751
2752 macro_executor = gmMacro.cMacroPrimitives(personality = slave_personality)
2753 global _scripting_listener
2754 try:
2755 _scripting_listener = gmScriptingListener.cScriptingListener(port = port, macro_executor = macro_executor)
2756 except SocketError, e:
2757 _log.exception('cannot start GNUmed XML-RPC server')
2758 gmGuiHelpers.gm_show_error (
2759 aMessage = (
2760 'Cannot start the GNUmed server:\n'
2761 '\n'
2762 ' [%s]'
2763 ) % e,
2764 aTitle = _('GNUmed startup')
2765 )
2766 return False
2767
2768 return True
2769
2789
2791 if gmI18N.system_locale is None or gmI18N.system_locale == '':
2792 _log.warning("system locale is undefined (probably meaning 'C')")
2793 return True
2794
2795
2796 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': u"select i18n.get_curr_lang() as lang"}])
2797 db_lang = rows[0]['lang']
2798
2799 if db_lang is None:
2800 _log.debug("database locale currently not set")
2801 msg = _(
2802 "There is no language selected in the database for user [%s].\n"
2803 "Your system language is currently set to [%s].\n\n"
2804 "Do you want to set the database language to '%s' ?\n\n"
2805 ) % (_provider['db_user'], gmI18N.system_locale, gmI18N.system_locale)
2806 checkbox_msg = _('Remember to ignore missing language')
2807 else:
2808 _log.debug("current database locale: [%s]" % db_lang)
2809 msg = _(
2810 "The currently selected database language ('%s') does\n"
2811 "not match the current system language ('%s').\n"
2812 "\n"
2813 "Do you want to set the database language to '%s' ?\n"
2814 ) % (db_lang, gmI18N.system_locale, gmI18N.system_locale)
2815 checkbox_msg = _('Remember to ignore language mismatch')
2816
2817
2818 if db_lang == gmI18N.system_locale_level['full']:
2819 _log.debug('Database locale (%s) up to date.' % db_lang)
2820 return True
2821 if db_lang == gmI18N.system_locale_level['country']:
2822 _log.debug('Database locale (%s) matches system locale (%s) at country level.' % (db_lang, gmI18N.system_locale))
2823 return True
2824 if db_lang == gmI18N.system_locale_level['language']:
2825 _log.debug('Database locale (%s) matches system locale (%s) at language level.' % (db_lang, gmI18N.system_locale))
2826 return True
2827
2828 _log.warning('database locale [%s] does not match system locale [%s]' % (db_lang, gmI18N.system_locale))
2829
2830
2831 ignored_sys_lang = _cfg.get (
2832 group = u'backend',
2833 option = u'ignored mismatching system locale',
2834 source_order = [('explicit', 'return'), ('local', 'return'), ('user', 'return'), ('system', 'return')]
2835 )
2836
2837
2838 if gmI18N.system_locale == ignored_sys_lang:
2839 _log.info('configured to ignore system-to-database locale mismatch')
2840 return True
2841
2842
2843 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
2844 None,
2845 -1,
2846 caption = _('Checking database language settings'),
2847 question = msg,
2848 button_defs = [
2849 {'label': _('Set'), 'tooltip': _('Set your database language to [%s].') % gmI18N.system_locale, 'default': True},
2850 {'label': _("Don't set"), 'tooltip': _('Do not set your database language now.'), 'default': False}
2851 ],
2852 show_checkbox = True,
2853 checkbox_msg = checkbox_msg,
2854 checkbox_tooltip = _(
2855 'Checking this will make GNUmed remember your decision\n'
2856 'until the system language is changed.\n'
2857 '\n'
2858 'You can also reactivate this inquiry by removing the\n'
2859 'corresponding "ignore" option from the configuration file\n'
2860 '\n'
2861 ' [%s]'
2862 ) % _cfg.get(option = 'user_preferences_file')
2863 )
2864 decision = dlg.ShowModal()
2865 remember_ignoring_problem = dlg._CHBOX_dont_ask_again.GetValue()
2866 dlg.Destroy()
2867
2868 if decision == wx.ID_NO:
2869 if not remember_ignoring_problem:
2870 return True
2871 _log.info('User did not want to set database locale. Ignoring mismatch next time.')
2872 gmCfg2.set_option_in_INI_file (
2873 filename = _cfg.get(option = 'user_preferences_file'),
2874 group = 'backend',
2875 option = 'ignored mismatching system locale',
2876 value = gmI18N.system_locale
2877 )
2878 return True
2879
2880
2881 for lang in [gmI18N.system_locale_level['full'], gmI18N.system_locale_level['country'], gmI18N.system_locale_level['language']]:
2882 if len(lang) > 0:
2883
2884
2885 rows, idx = gmPG2.run_rw_queries (
2886 link_obj = None,
2887 queries = [{'cmd': u'select i18n.set_curr_lang(%s)', 'args': [lang]}],
2888 return_data = True
2889 )
2890 if rows[0][0]:
2891 _log.debug("Successfully set database language to [%s]." % lang)
2892 else:
2893 _log.error('Cannot set database language to [%s].' % lang)
2894 continue
2895 return True
2896
2897
2898 _log.info('forcing database language to [%s]', gmI18N.system_locale_level['country'])
2899 gmPG2.run_rw_queries(queries = [{
2900 'cmd': u'select i18n.force_curr_lang(%s)',
2901 'args': [gmI18N.system_locale_level['country']]
2902 }])
2903
2904 return True
2905
2907 try:
2908 kwargs['originated_in_database']
2909 print '==> got notification from database "%s":' % kwargs['signal']
2910 except KeyError:
2911 print '==> received signal from client: "%s"' % kwargs['signal']
2912
2913 del kwargs['signal']
2914 for key in kwargs.keys():
2915
2916 try: print ' [%s]: %s' % (key, kwargs[key])
2917 except: print 'cannot print signal information'
2918
2920
2921 try:
2922 print '==> received wx.lib.pubsub message: "%s"' % msg.topic
2923 print ' data: %s' % msg.data
2924 print msg
2925 except: print 'problem printing pubsub message information'
2926
2928
2929 if _cfg.get(option = 'debug'):
2930 gmDispatcher.connect(receiver = _signal_debugging_monitor)
2931 _log.debug('gmDispatcher signal monitor activated')
2932 wx.lib.pubsub.Publisher().subscribe (
2933 listener = _signal_debugging_monitor_pubsub,
2934 topic = wx.lib.pubsub.getStrAllTopics()
2935 )
2936 _log.debug('wx.lib.pubsub signal monitor activated')
2937
2938
2939
2940
2941 app = gmApp(redirect = False, clearSigInt = False)
2942 app.MainLoop()
2943
2944
2945
2946 if __name__ == '__main__':
2947
2948 from GNUmed.pycommon import gmI18N
2949 gmI18N.activate_locale()
2950 gmI18N.install_domain()
2951
2952 _log.info('Starting up as main module.')
2953 main()
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
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