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.489 $"
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 menu_master_data.AppendSeparator()
368
369 item = menu_master_data.Append(-1, _('&Text expansions'), _('Manage keyword based text expansion macros.'))
370 self.Bind(wx.EVT_MENU, self.__on_manage_text_expansion, item)
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, _('View encounter 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 wx.CallAfter(self.SetStatusText, context.data['msg'])
789 try:
790 if context.data['beep']:
791 wx.Bell()
792 except KeyError:
793 pass
794
795 - def _on_set_statustext(self, msg=None, loglevel=None, beep=True):
796
797 if msg is None:
798 msg = _('programmer forgot to specify status message')
799
800 if loglevel is not None:
801 _log.log(loglevel, msg.replace('\015', ' ').replace('\012', ' '))
802
803 wx.CallAfter(self.SetStatusText, msg)
804
805 if beep:
806 wx.Bell()
807
809 wx.CallAfter(self.__on_db_maintenance_warning)
810
812
813 self.SetStatusText(_('The database will be shut down for maintenance in a few minutes.'))
814 wx.Bell()
815 if not wx.GetApp().IsActive():
816 self.RequestUserAttention(flags = wx.USER_ATTENTION_ERROR)
817
818 gmHooks.run_hook_script(hook = u'db_maintenance_warning')
819
820 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
821 None,
822 -1,
823 caption = _('Database shutdown warning'),
824 question = _(
825 'The database will be shut down for maintenance\n'
826 'in a few minutes.\n'
827 '\n'
828 'In order to not suffer any loss of data you\n'
829 'will need to save your current work and log\n'
830 'out of this GNUmed client.\n'
831 ),
832 button_defs = [
833 {
834 u'label': _('Close now'),
835 u'tooltip': _('Close this GNUmed client immediately.'),
836 u'default': False
837 },
838 {
839 u'label': _('Finish work'),
840 u'tooltip': _('Finish and save current work first, then manually close this GNUmed client.'),
841 u'default': True
842 }
843 ]
844 )
845 decision = dlg.ShowModal()
846 if decision == wx.ID_YES:
847 top_win = wx.GetApp().GetTopWindow()
848 wx.CallAfter(top_win.Close)
849
851 wx.CallAfter(self.__on_request_user_attention, msg, urgent)
852
854
855 if not wx.GetApp().IsActive():
856 if urgent:
857 self.RequestUserAttention(flags = wx.USER_ATTENTION_ERROR)
858 else:
859 self.RequestUserAttention(flags = wx.USER_ATTENTION_INFO)
860
861 if msg is not None:
862 self.SetStatusText(msg)
863
864 if urgent:
865 wx.Bell()
866
867 gmHooks.run_hook_script(hook = u'request_user_attention')
868
870 wx.CallAfter(self.__on_pat_name_changed)
871
873 self.__update_window_title()
874
876 wx.CallAfter(self.__on_post_patient_selection, **kwargs)
877
879 self.__update_window_title()
880 try:
881 gmHooks.run_hook_script(hook = u'post_patient_activation')
882 except:
883 gmDispatcher.send(signal = 'statustext', msg = _('Cannot run script after patient activation.'))
884 raise
885
887 return self.__sanity_check_encounter()
888
946
947
948
951
959
962
963
964
979
1002
1004 from Gnumed.wxpython import gmAbout
1005 contribs = gmAbout.cContributorsDlg (
1006 parent = self,
1007 id = -1,
1008 title = _('GNUmed contributors'),
1009 size = wx.Size(400,600),
1010 style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
1011 )
1012 contribs.ShowModal()
1013 del contribs
1014 del gmAbout
1015
1016
1017
1019 """Invoked from Menu GNUmed / Exit (which calls this ID_EXIT handler)."""
1020 _log.debug('gmTopLevelFrame._on_exit_gnumed() start')
1021 self.Close(True)
1022 _log.debug('gmTopLevelFrame._on_exit_gnumed() end')
1023
1026
1028 send = gmGuiHelpers.gm_show_question (
1029 _('This will send a notification about database downtime\n'
1030 'to all GNUmed clients connected to your database.\n'
1031 '\n'
1032 'Do you want to send the notification ?\n'
1033 ),
1034 _('Announcing database maintenance downtime')
1035 )
1036 if not send:
1037 return
1038 gmPG2.send_maintenance_notification()
1039
1040
1041
1073
1086
1087 gmCfgWidgets.configure_string_option (
1088 message = _(
1089 'Some network installations cannot cope with loading\n'
1090 'documents of arbitrary size in one piece from the\n'
1091 'database (mainly observed on older Windows versions)\n.'
1092 '\n'
1093 'Under such circumstances documents need to be retrieved\n'
1094 'in chunks and reassembled on the client.\n'
1095 '\n'
1096 'Here you can set the size (in Bytes) above which\n'
1097 'GNUmed will retrieve documents in chunks. Setting this\n'
1098 'value to 0 will disable the chunking protocol.'
1099 ),
1100 option = 'horstspace.blob_export_chunk_size',
1101 bias = 'workplace',
1102 default_value = 1024 * 1024,
1103 validator = is_valid
1104 )
1105
1106
1107
1175
1179
1180
1181
1189
1190 gmCfgWidgets.configure_string_option (
1191 message = _(
1192 'When GNUmed cannot find an OpenOffice server it\n'
1193 'will try to start one. OpenOffice, however, needs\n'
1194 'some time to fully start up.\n'
1195 '\n'
1196 'Here you can set the time for GNUmed to wait for OOo.\n'
1197 ),
1198 option = 'external.ooo.startup_settle_time',
1199 bias = 'workplace',
1200 default_value = 2.0,
1201 validator = is_valid
1202 )
1203
1206
1218
1219 gmCfgWidgets.configure_string_option (
1220 message = _(
1221 'GNUmed will use this URL to access an encyclopedia of\n'
1222 'measurement/lab methods from within the measurments grid.\n'
1223 '\n'
1224 'You can leave this empty but to set it to a specific\n'
1225 'address the URL must be accessible now.'
1226 ),
1227 option = 'external.urls.measurements_encyclopedia',
1228 bias = 'user',
1229 default_value = u'http://www.laborlexikon.de',
1230 validator = is_valid
1231 )
1232
1245
1246 gmCfgWidgets.configure_string_option (
1247 message = _(
1248 'Enter the shell command with which to start the\n'
1249 'the ACS risk assessment calculator.\n'
1250 '\n'
1251 'GNUmed will try to verify the path which may,\n'
1252 'however, fail if you are using an emulator such\n'
1253 'as Wine. Nevertheless, starting the calculator\n'
1254 'will work as long as the shell command is correct\n'
1255 'despite the failing test.'
1256 ),
1257 option = 'external.tools.acs_risk_calculator_cmd',
1258 bias = 'user',
1259 validator = is_valid
1260 )
1261
1274
1275 gmCfgWidgets.configure_string_option (
1276 message = _(
1277 'Enter the shell command with which to start the\n'
1278 'the IFAP drug database.\n'
1279 '\n'
1280 'GNUmed will try to verify the path which may,\n'
1281 'however, fail if you are using an emulator such\n'
1282 'as Wine. Nevertheless, starting IFAP will work\n'
1283 'as long as the shell command is correct despite\n'
1284 'the failing test.'
1285 ),
1286 option = 'external.ifap-win.shell_command',
1287 bias = 'workplace',
1288 default_value = 'C:\Ifapwin\WIAMDB.EXE',
1289 validator = is_valid
1290 )
1291
1292
1293
1342
1343
1344
1361
1364
1367
1372
1373 gmCfgWidgets.configure_string_option (
1374 message = _(
1375 'When a patient is activated GNUmed checks the\n'
1376 "proximity of the patient's birthday.\n"
1377 '\n'
1378 'If the birthday falls within the range of\n'
1379 ' "today %s <the interval you set here>"\n'
1380 'GNUmed will remind you of the recent or\n'
1381 'imminent anniversary.'
1382 ) % u'\u2213',
1383 option = u'patient_search.dob_warn_interval',
1384 bias = 'user',
1385 default_value = '1 week',
1386 validator = is_valid
1387 )
1388
1390
1391 gmCfgWidgets.configure_boolean_option (
1392 parent = self,
1393 question = _(
1394 'When adding progress notes do you want to\n'
1395 'allow opening several unassociated, new\n'
1396 'episodes for a patient at once ?\n'
1397 '\n'
1398 'This can be particularly helpful when entering\n'
1399 'progress notes on entirely new patients presenting\n'
1400 'with a multitude of problems on their first visit.'
1401 ),
1402 option = u'horstspace.soap_editor.allow_same_episode_multiple_times',
1403 button_tooltips = [
1404 _('Yes, allow for multiple new episodes concurrently.'),
1405 _('No, only allow editing one new episode at a time.')
1406 ]
1407 )
1408
1454
1455
1456
1459
1473
1475 gmCfgWidgets.configure_boolean_option (
1476 parent = self,
1477 question = _(
1478 'Do you want GNUmed to show the encounter\n'
1479 'details editor when changing the active patient ?'
1480 ),
1481 option = 'encounter.show_editor_before_patient_change',
1482 button_tooltips = [
1483 _('Yes, show the encounter editor if it seems appropriate.'),
1484 _('No, never show the encounter editor even if it would seem useful.')
1485 ]
1486 )
1487
1492
1493 gmCfgWidgets.configure_string_option (
1494 message = _(
1495 'When a patient is activated GNUmed checks the\n'
1496 'chart for encounters lacking any entries.\n'
1497 '\n'
1498 'Any such encounters older than what you set\n'
1499 'here will be removed from the medical record.\n'
1500 '\n'
1501 'To effectively disable removal of such encounters\n'
1502 'set this option to an improbable value.\n'
1503 ),
1504 option = 'encounter.ttl_if_empty',
1505 bias = 'user',
1506 default_value = '1 week',
1507 validator = is_valid
1508 )
1509
1514
1515 gmCfgWidgets.configure_string_option (
1516 message = _(
1517 'When a patient is activated GNUmed checks the\n'
1518 'age of the most recent encounter.\n'
1519 '\n'
1520 'If that encounter is younger than this age\n'
1521 'the existing encounter will be continued.\n'
1522 '\n'
1523 '(If it is really old a new encounter is\n'
1524 ' started, or else GNUmed will ask you.)\n'
1525 ),
1526 option = 'encounter.minimum_ttl',
1527 bias = 'user',
1528 default_value = '1 hour 30 minutes',
1529 validator = is_valid
1530 )
1531
1536
1537 gmCfgWidgets.configure_string_option (
1538 message = _(
1539 'When a patient is activated GNUmed checks the\n'
1540 'age of the most recent encounter.\n'
1541 '\n'
1542 'If that encounter is older than this age\n'
1543 'GNUmed will always start a new encounter.\n'
1544 '\n'
1545 '(If it is very recent the existing encounter\n'
1546 ' is continued, or else GNUmed will ask you.)\n'
1547 ),
1548 option = 'encounter.maximum_ttl',
1549 bias = 'user',
1550 default_value = '6 hours',
1551 validator = is_valid
1552 )
1553
1562
1563 gmCfgWidgets.configure_string_option (
1564 message = _(
1565 'At any time there can only be one open (ongoing)\n'
1566 'episode for each health issue.\n'
1567 '\n'
1568 'When you try to open (add data to) an episode on a health\n'
1569 'issue GNUmed will check for an existing open episode on\n'
1570 'that issue. If there is any it will check the age of that\n'
1571 'episode. The episode is closed if it has been dormant (no\n'
1572 'data added, that is) for the period of time (in days) you\n'
1573 'set here.\n'
1574 '\n'
1575 "If the existing episode hasn't been dormant long enough\n"
1576 'GNUmed will consult you what to do.\n'
1577 '\n'
1578 'Enter maximum episode dormancy in DAYS:'
1579 ),
1580 option = 'episode.ttl',
1581 bias = 'user',
1582 default_value = 60,
1583 validator = is_valid
1584 )
1585
1616
1619
1634
1659
1671
1672 gmCfgWidgets.configure_string_option (
1673 message = _(
1674 'GNUmed can check for new releases being available. To do\n'
1675 'so it needs to load version information from an URL.\n'
1676 '\n'
1677 'The default URL is:\n'
1678 '\n'
1679 ' http://www.gnumed.de/downloads/gnumed-versions.txt\n'
1680 '\n'
1681 'but you can configure any other URL locally. Note\n'
1682 'that you must enter the location as a valid URL.\n'
1683 'Depending on the URL the client will need online\n'
1684 'access when checking for updates.'
1685 ),
1686 option = u'horstspace.update.url',
1687 bias = u'workplace',
1688 default_value = u'http://www.gnumed.de/downloads/gnumed-versions.txt',
1689 validator = is_valid
1690 )
1691
1709
1726
1737
1738 gmCfgWidgets.configure_string_option (
1739 message = _(
1740 'GNUmed can show the document review dialog after\n'
1741 'calling the appropriate viewer for that document.\n'
1742 '\n'
1743 'Select the conditions under which you want\n'
1744 'GNUmed to do so:\n'
1745 '\n'
1746 ' 0: never display the review dialog\n'
1747 ' 1: always display the dialog\n'
1748 ' 2: only if there is no previous review by me\n'
1749 '\n'
1750 'Note that if a viewer is configured to not block\n'
1751 'GNUmed during document display the review dialog\n'
1752 'will actually appear in parallel to the viewer.'
1753 ),
1754 option = u'horstspace.document_viewer.review_after_display',
1755 bias = u'user',
1756 default_value = 2,
1757 validator = is_valid
1758 )
1759
1773
1790
1792 dlg = gmSnellen.cSnellenCfgDlg()
1793 if dlg.ShowModal() != wx.ID_OK:
1794 return
1795
1796 frame = gmSnellen.cSnellenChart (
1797 width = dlg.vals[0],
1798 height = dlg.vals[1],
1799 alpha = dlg.vals[2],
1800 mirr = dlg.vals[3],
1801 parent = None
1802 )
1803 frame.CentreOnScreen(wx.BOTH)
1804
1805
1806 frame.Show(True)
1807
1808
1810 webbrowser.open (
1811 url = 'http://wiki.gnumed.de/bin/view/Gnumed/MedicalContentLinks#AnchorLocaleI%s' % gmI18N.system_locale_level['language'],
1812 new = False,
1813 autoraise = True
1814 )
1815
1818
1821
1823 webbrowser.open (
1824 url = 'http://www.kompendium.ch',
1825 new = False,
1826 autoraise = True
1827 )
1828
1829
1830
1832 wx.CallAfter(self.__save_screenshot)
1833 evt.Skip()
1834
1836
1837 time.sleep(0.5)
1838
1839 rect = self.GetRect()
1840
1841
1842 if sys.platform == 'linux2':
1843 client_x, client_y = self.ClientToScreen((0, 0))
1844 border_width = client_x - rect.x
1845 title_bar_height = client_y - rect.y
1846
1847 if self.GetMenuBar():
1848 title_bar_height /= 2
1849 rect.width += (border_width * 2)
1850 rect.height += title_bar_height + border_width
1851
1852 wdc = wx.ScreenDC()
1853 mdc = wx.MemoryDC()
1854 img = wx.EmptyBitmap(rect.width, rect.height)
1855 mdc.SelectObject(img)
1856 mdc.Blit (
1857 0, 0,
1858 rect.width, rect.height,
1859 wdc,
1860 rect.x, rect.y
1861 )
1862
1863
1864 fname = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'gnumed-screenshot-%s.png')) % pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
1865 img.SaveFile(fname, wx.BITMAP_TYPE_PNG)
1866 gmDispatcher.send(signal = 'statustext', msg = _('Saved screenshot to file [%s].') % fname)
1867
1869
1870 raise ValueError('raised ValueError to test exception handling')
1871
1873 import wx.lib.inspection
1874 wx.lib.inspection.InspectionTool().Show()
1875
1877 webbrowser.open (
1878 url = 'https://bugs.launchpad.net/gnumed/',
1879
1880 new = False,
1881 autoraise = True
1882 )
1883
1885 webbrowser.open (
1886 url = 'http://wiki.gnumed.de',
1887 new = False,
1888 autoraise = True
1889 )
1890
1892 webbrowser.open (
1893 url = 'http://wiki.gnumed.de/bin/view/Gnumed/GnumedManual#UserGuideInManual',
1894 new = False,
1895 autoraise = True
1896 )
1897
1899 webbrowser.open (
1900 url = 'http://wiki.gnumed.de/bin/view/Gnumed/MenuReference',
1901 new = False,
1902 autoraise = True
1903 )
1904
1911
1915
1918
1925
1930
1932 name = os.path.basename(gmLog2._logfile_name)
1933 name, ext = os.path.splitext(name)
1934 new_name = '%s_%s%s' % (name, pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), ext)
1935 new_path = os.path.expanduser(os.path.join('~', 'gnumed', 'logs'))
1936
1937 dlg = wx.FileDialog (
1938 parent = self,
1939 message = _("Save current log as..."),
1940 defaultDir = new_path,
1941 defaultFile = new_name,
1942 wildcard = "%s (*.log)|*.log" % _("log files"),
1943 style = wx.SAVE
1944 )
1945 choice = dlg.ShowModal()
1946 new_name = dlg.GetPath()
1947 dlg.Destroy()
1948 if choice != wx.ID_OK:
1949 return True
1950
1951 _log.warning('syncing log file for backup to [%s]', new_name)
1952 gmLog2.flush()
1953 shutil.copy2(gmLog2._logfile_name, new_name)
1954 gmDispatcher.send('statustext', msg = _('Log file backed up as [%s].') % new_name)
1955
1956
1957
1959 """This is the wx.EVT_CLOSE handler.
1960
1961 - framework still functional
1962 """
1963 _log.debug('gmTopLevelFrame.OnClose() start')
1964 self._clean_exit()
1965 self.Destroy()
1966 _log.debug('gmTopLevelFrame.OnClose() end')
1967 return True
1968
1974
1979
1987
1994
2001
2011
2019
2027
2035
2043
2051
2053 pat = gmPerson.gmCurrentPatient()
2054 if not pat.connected:
2055 gmDispatcher.send(signal = 'statustext', msg = _('Cannot show EMR summary. No active patient.'))
2056 return False
2057
2058 emr = pat.get_emr()
2059 dlg = wx.MessageDialog (
2060 parent = self,
2061 message = emr.format_statistics(),
2062 caption = _('EMR Summary'),
2063 style = wx.OK | wx.STAY_ON_TOP
2064 )
2065 dlg.ShowModal()
2066 dlg.Destroy()
2067 return True
2068
2071
2074
2076
2077 pat = gmPerson.gmCurrentPatient()
2078 if not pat.connected:
2079 gmDispatcher.send(signal = 'statustext', msg = _('Cannot export EMR journal. No active patient.'))
2080 return False
2081
2082 aWildcard = "%s (*.txt)|*.txt|%s (*)|*" % (_("text files"), _("all files"))
2083
2084 aDefDir = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'EMR', pat['dirname']))
2085 gmTools.mkdir(aDefDir)
2086
2087 fname = '%s-%s_%s.txt' % (_('emr-journal'), pat['lastnames'], pat['firstnames'])
2088 dlg = wx.FileDialog (
2089 parent = self,
2090 message = _("Save patient's EMR journal as..."),
2091 defaultDir = aDefDir,
2092 defaultFile = fname,
2093 wildcard = aWildcard,
2094 style = wx.SAVE
2095 )
2096 choice = dlg.ShowModal()
2097 fname = dlg.GetPath()
2098 dlg.Destroy()
2099 if choice != wx.ID_OK:
2100 return True
2101
2102 _log.debug('exporting EMR journal to [%s]' % fname)
2103
2104 exporter = gmPatientExporter.cEMRJournalExporter()
2105
2106 wx.BeginBusyCursor()
2107 try:
2108 fname = exporter.export_to_file(filename = fname)
2109 except:
2110 wx.EndBusyCursor()
2111 gmGuiHelpers.gm_show_error (
2112 _('Error exporting patient EMR as chronological journal.'),
2113 _('EMR journal export')
2114 )
2115 raise
2116 wx.EndBusyCursor()
2117
2118 gmDispatcher.send(signal = 'statustext', msg = _('Successfully exported EMR as chronological journal into file [%s].') % fname, beep=False)
2119
2120 return True
2121
2128
2138
2140 curr_pat = gmPerson.gmCurrentPatient()
2141 if not curr_pat.connected:
2142 gmDispatcher.send(signal = 'statustext', msg = _('Cannot export patient as GDT. No active patient.'))
2143 return False
2144
2145 enc = 'cp850'
2146 fname = os.path.expanduser(os.path.join('~', 'gnumed', 'export', 'xDT', 'current-patient.gdt'))
2147 curr_pat.export_as_gdt(filename = fname, encoding = enc)
2148 gmDispatcher.send(signal = 'statustext', msg = _('Exported demographics to GDT file [%s].') % fname)
2149
2152
2158
2166
2174
2177
2185
2189
2193
2196
2199
2202
2205
2208
2211
2214
2217
2220
2223
2226
2228 """Cleanup helper.
2229
2230 - should ALWAYS be called when this program is
2231 to be terminated
2232 - ANY code that should be executed before a
2233 regular shutdown should go in here
2234 - framework still functional
2235 """
2236 _log.debug('gmTopLevelFrame._clean_exit() start')
2237
2238
2239 listener = gmBackendListener.gmBackendListener()
2240 try:
2241 listener.shutdown()
2242 except:
2243 _log.exception('cannot stop backend notifications listener thread')
2244
2245
2246 if _scripting_listener is not None:
2247 try:
2248 _scripting_listener.shutdown()
2249 except:
2250 _log.exception('cannot stop scripting listener thread')
2251
2252
2253 self.clock_update_timer.Stop()
2254 gmTimer.shutdown()
2255 gmPhraseWheel.shutdown()
2256
2257
2258 for call_back in self.__pre_exit_callbacks:
2259 try:
2260 call_back()
2261 except:
2262 print "*** pre-exit callback failed ***"
2263 print call_back
2264 _log.exception('callback [%s] failed', call_back)
2265
2266
2267 gmDispatcher.send(u'application_closing')
2268
2269
2270 gmDispatcher.disconnect(self._on_set_statustext, 'statustext')
2271
2272
2273 curr_width, curr_height = self.GetClientSizeTuple()
2274 _log.info('GUI size at shutdown: [%s:%s]' % (curr_width, curr_height))
2275 dbcfg = gmCfg.cCfgSQL()
2276 dbcfg.set (
2277 option = 'main.window.width',
2278 value = curr_width,
2279 workplace = gmSurgery.gmCurrentPractice().active_workplace
2280 )
2281 dbcfg.set (
2282 option = 'main.window.height',
2283 value = curr_height,
2284 workplace = gmSurgery.gmCurrentPractice().active_workplace
2285 )
2286
2287 if _cfg.get(option = 'debug'):
2288 print '---=== GNUmed shutdown ===---'
2289 print _('You have to manually close this window to finalize shutting down GNUmed.')
2290 print _('This is so that you can inspect the console output at your leisure.')
2291 print '---=== GNUmed shutdown ===---'
2292
2293
2294 gmExceptionHandlingWidgets.uninstall_wx_exception_handler()
2295
2296
2297 import threading
2298 _log.debug("%s active threads", threading.activeCount())
2299 for t in threading.enumerate():
2300 _log.debug('thread %s', t)
2301
2302 _log.debug('gmTopLevelFrame._clean_exit() end')
2303
2304
2305
2307
2308 if _cfg.get(option = 'slave'):
2309 self.__title_template = u'GMdS: %%(pat)s [%%(prov)s@%%(wp)s] (%s:%s)' % (
2310 _cfg.get(option = 'slave personality'),
2311 _cfg.get(option = 'xml-rpc port')
2312 )
2313 else:
2314 self.__title_template = u'GMd: %(pat)s [%(prov)s@%(wp)s]'
2315
2317 """Update title of main window based on template.
2318
2319 This gives nice tooltips on iconified GNUmed instances.
2320
2321 User research indicates that in the title bar people want
2322 the date of birth, not the age, so please stick to this
2323 convention.
2324 """
2325 args = {}
2326
2327 pat = gmPerson.gmCurrentPatient()
2328 if pat.connected:
2329
2330
2331
2332
2333
2334
2335 args['pat'] = u'%s %s %s (%s) #%d' % (
2336 gmTools.coalesce(pat['title'], u'', u'%.4s'),
2337
2338 pat['firstnames'],
2339 pat['lastnames'],
2340 pat.get_formatted_dob(format = '%x', encoding = gmI18N.get_encoding()),
2341 pat['pk_identity']
2342 )
2343 else:
2344 args['pat'] = _('no patient')
2345
2346 args['prov'] = u'%s%s.%s' % (
2347 gmTools.coalesce(_provider['title'], u'', u'%s '),
2348 _provider['firstnames'][:1],
2349 _provider['lastnames']
2350 )
2351
2352 args['wp'] = gmSurgery.gmCurrentPractice().active_workplace
2353
2354 self.SetTitle(self.__title_template % args)
2355
2356
2358 sb = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
2359 sb.SetStatusWidths([-1, 225])
2360
2361 self.clock_update_timer = wx.PyTimer(self._cb_update_clock)
2362 self._cb_update_clock()
2363
2364 self.clock_update_timer.Start(milliseconds = 1000)
2365
2367 """Displays date and local time in the second slot of the status bar"""
2368 t = time.localtime(time.time())
2369 st = time.strftime('%c', t).decode(gmI18N.get_encoding())
2370 self.SetStatusText(st,1)
2371
2373 """Lock GNUmed client against unauthorized access"""
2374
2375
2376
2377 return
2378
2380 """Unlock the main notebook widgets
2381 As long as we are not logged into the database backend,
2382 all pages but the 'login' page of the main notebook widget
2383 are locked; i.e. not accessible by the user
2384 """
2385
2386
2387
2388
2389
2390 return
2391
2393 wx.LayoutAlgorithm().LayoutWindow (self.LayoutMgr, self.nb)
2394
2396
2398
2399 self.__starting_up = True
2400
2401 gmExceptionHandlingWidgets.install_wx_exception_handler()
2402 gmExceptionHandlingWidgets.set_client_version(_cfg.get(option = 'client_version'))
2403
2404 _log.info('display: %s:%s' % (wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X), wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)))
2405
2406
2407 self.SetAppName(u'gnumed')
2408 self.SetVendorName(u'The GNUmed Development Community.')
2409 paths = gmTools.gmPaths(app_name = u'gnumed', wx = wx)
2410 paths.init_paths(wx = wx, app_name = u'gnumed')
2411
2412 if not self.__setup_prefs_file():
2413 return False
2414
2415 gmExceptionHandlingWidgets.set_sender_email(gmSurgery.gmCurrentPractice().user_email)
2416
2417 self.__guibroker = gmGuiBroker.GuiBroker()
2418 self.__setup_platform()
2419
2420 if not self.__establish_backend_connection():
2421 return False
2422
2423 if not _cfg.get(option = 'skip-update-check'):
2424 self.__check_for_updates()
2425
2426 if _cfg.get(option = 'slave'):
2427 if not self.__setup_scripting_listener():
2428 return False
2429
2430
2431 frame = gmTopLevelFrame(None, -1, _('GNUmed client'), (640,440))
2432 frame.CentreOnScreen(wx.BOTH)
2433 self.SetTopWindow(frame)
2434 frame.Show(True)
2435
2436 if _cfg.get(option = 'debug'):
2437 self.RedirectStdio()
2438 self.SetOutputWindowAttributes(title = _('GNUmed stdout/stderr window'))
2439
2440
2441 print '---=== GNUmed startup ===---'
2442 print _('redirecting STDOUT/STDERR to this log window')
2443 print '---=== GNUmed startup ===---'
2444
2445 self.__setup_user_activity_timer()
2446 self.__register_events()
2447
2448 wx.CallAfter(self._do_after_init)
2449
2450 return True
2451
2453 """Called internally by wxPython after EVT_CLOSE has been handled on last frame.
2454
2455 - after destroying all application windows and controls
2456 - before wx.Windows internal cleanup
2457 """
2458 _log.debug('gmApp.OnExit() start')
2459
2460 self.__shutdown_user_activity_timer()
2461
2462 if _cfg.get(option = 'debug'):
2463 self.RestoreStdio()
2464 sys.stdin = sys.__stdin__
2465 sys.stdout = sys.__stdout__
2466 sys.stderr = sys.__stderr__
2467
2468 _log.debug('gmApp.OnExit() end')
2469
2471 wx.Bell()
2472 wx.Bell()
2473 wx.Bell()
2474 _log.warning('unhandled event detected: QUERY_END_SESSION')
2475 _log.info('we should be saving ourselves from here')
2476 gmLog2.flush()
2477 print "unhandled event detected: QUERY_END_SESSION"
2478
2480 wx.Bell()
2481 wx.Bell()
2482 wx.Bell()
2483 _log.warning('unhandled event detected: END_SESSION')
2484 gmLog2.flush()
2485 print "unhandled event detected: END_SESSION"
2486
2497
2499 self.user_activity_detected = True
2500 evt.Skip()
2501
2503
2504 if self.user_activity_detected:
2505 self.elapsed_inactivity_slices = 0
2506 self.user_activity_detected = False
2507 self.elapsed_inactivity_slices += 1
2508 else:
2509 if self.elapsed_inactivity_slices >= self.max_user_inactivity_slices:
2510
2511 pass
2512
2513 self.user_activity_timer.Start(oneShot = True)
2514
2515
2516
2518 try:
2519 kwargs['originated_in_database']
2520 print '==> got notification from database "%s":' % kwargs['signal']
2521 except KeyError:
2522 print '==> received signal from client: "%s"' % kwargs['signal']
2523
2524 del kwargs['signal']
2525 for key in kwargs.keys():
2526 print ' [%s]: %s' % (key, kwargs[key])
2527
2529 print "wx.lib.pubsub message:"
2530 print msg.topic
2531 print msg.data
2532
2538
2540 self.user_activity_detected = True
2541 self.elapsed_inactivity_slices = 0
2542
2543 self.max_user_inactivity_slices = 15
2544 self.user_activity_timer = gmTimer.cTimer (
2545 callback = self._on_user_activity_timer_expired,
2546 delay = 2000
2547 )
2548 self.user_activity_timer.Start(oneShot=True)
2549
2551 try:
2552 self.user_activity_timer.Stop()
2553 del self.user_activity_timer
2554 except:
2555 pass
2556
2558 wx.EVT_QUERY_END_SESSION(self, self._on_query_end_session)
2559 wx.EVT_END_SESSION(self, self._on_end_session)
2560
2561
2562
2563
2564
2565 self.Bind(wx.EVT_ACTIVATE_APP, self._on_app_activated)
2566
2567 self.Bind(wx.EVT_MOUSE_EVENTS, self._on_user_activity)
2568 self.Bind(wx.EVT_KEY_DOWN, self._on_user_activity)
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2594
2596 """Handle all the database related tasks necessary for startup."""
2597
2598
2599 override = _cfg.get(option = '--override-schema-check', source_order = [('cli', 'return')])
2600
2601 from Gnumed.wxpython import gmAuthWidgets
2602 connected = gmAuthWidgets.connect_to_database (
2603 expected_version = gmPG2.map_client_branch2required_db_version[_cfg.get(option = 'client_branch')],
2604 require_version = not override
2605 )
2606 if not connected:
2607 _log.warning("Login attempt unsuccessful. Can't run GNUmed without database connection")
2608 return False
2609
2610
2611 try:
2612 global _provider
2613 _provider = gmPerson.gmCurrentProvider(provider = gmPerson.cStaff())
2614 except ValueError:
2615 account = gmPG2.get_current_user()
2616 _log.exception('DB account [%s] cannot be used as a GNUmed staff login', account)
2617 msg = _(
2618 'The database account [%s] cannot be used as a\n'
2619 'staff member login for GNUmed. There was an\n'
2620 'error retrieving staff details for it.\n\n'
2621 'Please ask your administrator for help.\n'
2622 ) % account
2623 gmGuiHelpers.gm_show_error(msg, _('Checking access permissions'))
2624 return False
2625
2626
2627 tmp = '%s%s %s (%s = %s)' % (
2628 gmTools.coalesce(_provider['title'], ''),
2629 _provider['firstnames'],
2630 _provider['lastnames'],
2631 _provider['short_alias'],
2632 _provider['db_user']
2633 )
2634 gmExceptionHandlingWidgets.set_staff_name(staff_name = tmp)
2635
2636
2637 surgery = gmSurgery.gmCurrentPractice()
2638 msg = surgery.db_logon_banner
2639 if msg.strip() != u'':
2640
2641 login = gmPG2.get_default_login()
2642 auth = u'\n%s\n\n' % (_('Database <%s> on <%s>') % (
2643 login.database,
2644 gmTools.coalesce(login.host, u'localhost')
2645 ))
2646 msg = auth + msg + u'\n\n'
2647
2648 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
2649 None,
2650 -1,
2651 caption = _('Verifying database'),
2652 question = gmTools.wrap(msg, 60, initial_indent = u' ', subsequent_indent = u' '),
2653 button_defs = [
2654 {'label': _('Connect'), 'tooltip': _('Yes, connect to this database.'), 'default': True},
2655 {'label': _('Disconnect'), 'tooltip': _('No, do not connect to this database.'), 'default': False}
2656 ]
2657 )
2658 go_on = dlg.ShowModal()
2659 dlg.Destroy()
2660 if go_on != wx.ID_YES:
2661 _log.info('user decided to not connect to this database')
2662 return False
2663
2664
2665 self.__check_db_lang()
2666
2667 return True
2668
2670 """Setup access to a config file for storing preferences."""
2671
2672 paths = gmTools.gmPaths(app_name = u'gnumed', wx = wx)
2673
2674 candidates = []
2675 explicit_file = _cfg.get(option = '--conf-file', source_order = [('cli', 'return')])
2676 if explicit_file is not None:
2677 candidates.append(explicit_file)
2678
2679 candidates.append(os.path.join(paths.user_config_dir, 'gnumed.conf'))
2680 candidates.append(os.path.join(paths.local_base_dir, 'gnumed.conf'))
2681 candidates.append(os.path.join(paths.working_dir, 'gnumed.conf'))
2682
2683 prefs_file = None
2684 for candidate in candidates:
2685 try:
2686 open(candidate, 'a+').close()
2687 prefs_file = candidate
2688 break
2689 except IOError:
2690 continue
2691
2692 if prefs_file is None:
2693 msg = _(
2694 'Cannot find configuration file in any of:\n'
2695 '\n'
2696 ' %s\n'
2697 'You may need to use the comand line option\n'
2698 '\n'
2699 ' --conf-file=<FILE>'
2700 ) % '\n '.join(candidates)
2701 gmGuiHelpers.gm_show_error(msg, _('Checking configuration files'))
2702 return False
2703
2704 _cfg.set_option(option = u'user_preferences_file', value = prefs_file)
2705 _log.info('user preferences file: %s', prefs_file)
2706
2707 return True
2708
2710
2711 from socket import error as SocketError
2712 from Gnumed.pycommon import gmScriptingListener
2713 from Gnumed.wxpython import gmMacro
2714
2715 slave_personality = gmTools.coalesce (
2716 _cfg.get (
2717 group = u'workplace',
2718 option = u'slave personality',
2719 source_order = [
2720 ('explicit', 'return'),
2721 ('workbase', 'return'),
2722 ('user', 'return'),
2723 ('system', 'return')
2724 ]
2725 ),
2726 u'gnumed-client'
2727 )
2728 _cfg.set_option(option = 'slave personality', value = slave_personality)
2729
2730
2731 port = int (
2732 gmTools.coalesce (
2733 _cfg.get (
2734 group = u'workplace',
2735 option = u'xml-rpc port',
2736 source_order = [
2737 ('explicit', 'return'),
2738 ('workbase', 'return'),
2739 ('user', 'return'),
2740 ('system', 'return')
2741 ]
2742 ),
2743 9999
2744 )
2745 )
2746 _cfg.set_option(option = 'xml-rpc port', value = port)
2747
2748 macro_executor = gmMacro.cMacroPrimitives(personality = slave_personality)
2749 global _scripting_listener
2750 try:
2751 _scripting_listener = gmScriptingListener.cScriptingListener(port = port, macro_executor = macro_executor)
2752 except SocketError, e:
2753 _log.exception('cannot start GNUmed XML-RPC server')
2754 gmGuiHelpers.gm_show_error (
2755 aMessage = (
2756 'Cannot start the GNUmed server:\n'
2757 '\n'
2758 ' [%s]'
2759 ) % e,
2760 aTitle = _('GNUmed startup')
2761 )
2762 return False
2763
2764 return True
2765
2785
2787 if gmI18N.system_locale is None or gmI18N.system_locale == '':
2788 _log.warning("system locale is undefined (probably meaning 'C')")
2789 return True
2790
2791
2792 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': u"select i18n.get_curr_lang() as lang"}])
2793 db_lang = rows[0]['lang']
2794
2795 if db_lang is None:
2796 _log.debug("database locale currently not set")
2797 msg = _(
2798 "There is no language selected in the database for user [%s].\n"
2799 "Your system language is currently set to [%s].\n\n"
2800 "Do you want to set the database language to '%s' ?\n\n"
2801 ) % (_provider['db_user'], gmI18N.system_locale, gmI18N.system_locale)
2802 checkbox_msg = _('Remember to ignore missing language')
2803 else:
2804 _log.debug("current database locale: [%s]" % db_lang)
2805 msg = _(
2806 "The currently selected database language ('%s') does\n"
2807 "not match the current system language ('%s').\n"
2808 "\n"
2809 "Do you want to set the database language to '%s' ?\n"
2810 ) % (db_lang, gmI18N.system_locale, gmI18N.system_locale)
2811 checkbox_msg = _('Remember to ignore language mismatch')
2812
2813
2814 if db_lang == gmI18N.system_locale_level['full']:
2815 _log.debug('Database locale (%s) up to date.' % db_lang)
2816 return True
2817 if db_lang == gmI18N.system_locale_level['country']:
2818 _log.debug('Database locale (%s) matches system locale (%s) at country level.' % (db_lang, gmI18N.system_locale))
2819 return True
2820 if db_lang == gmI18N.system_locale_level['language']:
2821 _log.debug('Database locale (%s) matches system locale (%s) at language level.' % (db_lang, gmI18N.system_locale))
2822 return True
2823
2824 _log.warning('database locale [%s] does not match system locale [%s]' % (db_lang, gmI18N.system_locale))
2825
2826
2827 ignored_sys_lang = _cfg.get (
2828 group = u'backend',
2829 option = u'ignored mismatching system locale',
2830 source_order = [('explicit', 'return'), ('local', 'return'), ('user', 'return'), ('system', 'return')]
2831 )
2832
2833
2834 if gmI18N.system_locale == ignored_sys_lang:
2835 _log.info('configured to ignore system-to-database locale mismatch')
2836 return True
2837
2838
2839 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
2840 None,
2841 -1,
2842 caption = _('Checking database language settings'),
2843 question = msg,
2844 button_defs = [
2845 {'label': _('Set'), 'tooltip': _('Set your database language to [%s].') % gmI18N.system_locale, 'default': True},
2846 {'label': _("Don't set"), 'tooltip': _('Do not set your database language now.'), 'default': False}
2847 ],
2848 show_checkbox = True,
2849 checkbox_msg = checkbox_msg,
2850 checkbox_tooltip = _(
2851 'Checking this will make GNUmed remember your decision\n'
2852 'until the system language is changed.\n'
2853 '\n'
2854 'You can also reactivate this inquiry by removing the\n'
2855 'corresponding "ignore" option from the configuration file\n'
2856 '\n'
2857 ' [%s]'
2858 ) % _cfg.get(option = 'user_preferences_file')
2859 )
2860 decision = dlg.ShowModal()
2861 remember_ignoring_problem = dlg._CHBOX_dont_ask_again.GetValue()
2862 dlg.Destroy()
2863
2864 if decision == wx.ID_NO:
2865 if not remember_ignoring_problem:
2866 return True
2867 _log.info('User did not want to set database locale. Ignoring mismatch next time.')
2868 gmCfg2.set_option_in_INI_file (
2869 filename = _cfg.get(option = 'user_preferences_file'),
2870 group = 'backend',
2871 option = 'ignored mismatching system locale',
2872 value = gmI18N.system_locale
2873 )
2874 return True
2875
2876
2877 for lang in [gmI18N.system_locale_level['full'], gmI18N.system_locale_level['country'], gmI18N.system_locale_level['language']]:
2878 if len(lang) > 0:
2879
2880
2881 rows, idx = gmPG2.run_rw_queries (
2882 link_obj = None,
2883 queries = [{'cmd': u'select i18n.set_curr_lang(%s)', 'args': [lang]}],
2884 return_data = True
2885 )
2886 if rows[0][0]:
2887 _log.debug("Successfully set database language to [%s]." % lang)
2888 else:
2889 _log.error('Cannot set database language to [%s].' % lang)
2890 continue
2891 return True
2892
2893
2894 _log.info('forcing database language to [%s]', gmI18N.system_locale_level['country'])
2895 gmPG2.run_rw_queries(queries = [{
2896 'cmd': u'select i18n.force_curr_lang(%s)',
2897 'args': [gmI18N.system_locale_level['country']]
2898 }])
2899
2900 return True
2901
2903 try:
2904 kwargs['originated_in_database']
2905 print '==> got notification from database "%s":' % kwargs['signal']
2906 except KeyError:
2907 print '==> received signal from client: "%s"' % kwargs['signal']
2908
2909 del kwargs['signal']
2910 for key in kwargs.keys():
2911
2912 try: print ' [%s]: %s' % (key, kwargs[key])
2913 except: print 'cannot print signal information'
2914
2916
2917 try:
2918 print '==> received wx.lib.pubsub message: "%s"' % msg.topic
2919 print ' data: %s' % msg.data
2920 print msg
2921 except: print 'problem printing pubsub message information'
2922
2924
2925 if _cfg.get(option = 'debug'):
2926 gmDispatcher.connect(receiver = _signal_debugging_monitor)
2927 _log.debug('gmDispatcher signal monitor activated')
2928 wx.lib.pubsub.Publisher().subscribe (
2929 listener = _signal_debugging_monitor_pubsub,
2930 topic = wx.lib.pubsub.getStrAllTopics()
2931 )
2932 _log.debug('wx.lib.pubsub signal monitor activated')
2933
2934
2935
2936
2937 app = gmApp(redirect = False, clearSigInt = False)
2938 app.MainLoop()
2939
2940
2941
2942 if __name__ == '__main__':
2943
2944 from GNUmed.pycommon import gmI18N
2945 gmI18N.activate_locale()
2946 gmI18N.install_domain()
2947
2948 _log.info('Starting up as main module.')
2949 main()
2950
2951
2952
2953
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