Package Gnumed :: Package wxpython :: Module gmCodingWidgets |
[frames] | no frames]

# Source Code for Module Gnumed.wxpython.gmCodingWidgets

      1  """GNUmed coding related widgets."""
      2  #================================================================
      3  __author__ = 'karsten.hilbert@gmx.net'
      4  __license__ = 'GPL v2 or later (details at http://www.gnu.org)'
      5
      6  # stdlib
      7  import logging, sys
      8
      9
     10  # 3rd party
     11  import wx
     12
     13
     14  # GNUmed
     15  if __name__ == '__main__':
     16          sys.path.insert(0, '../../')
     17
     18  from Gnumed.business import gmCoding
     19
     20  from Gnumed.pycommon import gmTools
     21  from Gnumed.pycommon import gmMatchProvider
     22
     23  from Gnumed.wxpython import gmListWidgets
     24  from Gnumed.wxpython import gmPhraseWheel
     25
     26
     27  _log = logging.getLogger('gm.ui')
     28
     29  #================================================================
     30 -def browse_data_sources(parent=None):
     31
     32          if parent is None:
     33                  parent = wx.GetApp().GetTopWindow()
     34          #------------------------------------------------------------
     35          def refresh(lctrl):
     36                  srcs = gmCoding.get_data_sources()
     37                  items = [ [
     38                          u'%s (%s): %s' % (
     39                                  s['name_short'],
     40                                  gmTools.coalesce(s['lang'], u'?'),
     41                                  s['version']
     42                          ),
     43                          s['name_long'].split(u'\n')[0].split(u'\r')[0],
     44                          s['source'].split(u'\n')[0].split(u'\r')[0],
     45                          gmTools.coalesce(s['description'], u'').split(u'\n')[0].split(u'\r')[0],
     46                          s['pk']
     47                  ] for s in srcs ]
     48                  lctrl.set_string_items(items)
     49                  lctrl.set_data(srcs)
     50          #------------------------------------------------------------
     51          gmListWidgets.get_choices_from_list (
     52                  parent = parent,
     53                  msg = _('Sources of reference data registered in GNUmed.'),
     54                  caption = _('Showing data sources'),
     55                  columns = [ _('System'), _('Name'), _('Source'), _('Description'), '#' ],
     56                  single_selection = True,
     57                  can_return_empty = False,
     58                  ignore_OK_button = True,
     59                  refresh_callback = refresh
     60  #               edit_callback=None,
     61  #               new_callback=None,
     62  #               delete_callback=None,
     63  #               left_extra_button=None,
     64  #               middle_extra_button=None,
     65  #               right_extra_button=None
     66          )
     67
     68  #----------------------------------------------------------------
     69 -class cDataSourcePhraseWheel(gmPhraseWheel.cPhraseWheel):
     70
     71 -        def __init__(self, *args, **kwargs):
     72
     73                  gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
     74
     75                  query = u"""
     76                          SELECT DISTINCT ON (list_label)
     77                                  pk
     78                                          AS data,
     79                                  name_short || ' (' || version || ')'
     80                                          AS field_label,
     81                                  name_short || ' ' || version || ' (' || name_long || ')'
     82                                          AS list_label
     83                          FROM
     84                                  ref.data_source
     85                          WHERE
     86                                  name_short %(fragment_condition)s
     87                                          OR
     88                                  name_long %(fragment_condition)s
     89                          ORDER BY list_label
     90                          LIMIT 50
     91                  """
     92                  mp = gmMatchProvider.cMatchProvider_SQL2(queries = query)
     93                  mp.setThresholds(1, 2, 4)
     94  #               mp.word_separators = '[ \t=+&:@]+'
     95                  self.SetToolTipString(_('Select a data source / coding system.'))
     96                  self.matcher = mp
     97                  self.selection_only = True
     98
     99  #================================================================
    100 -def browse_coded_terms(parent=None, coding_systems=None, languages=None):
    101
    102          if parent is None:
    103                  parent = wx.GetApp().GetTopWindow()
    104          #------------------------------------------------------------
    105          def refresh(lctrl):
    106                  coded_terms = gmCoding.get_coded_terms (
    107                          coding_systems = coding_systems,
    108                          languages = languages,
    109                          order_by = u'term, coding_system, code'
    110                  )
    111                  items = [ [
    112                          ct['term'],
    113                          ct['code'],
    114                          ct['coding_system'],
    115                          gmTools.coalesce(ct['lang'], u''),
    116                          ct['version'],
    117                          ct['coding_system_long']
    118                  ] for ct in coded_terms ]
    119                  lctrl.set_string_items(items)
    120                  lctrl.set_data(coded_terms)
    121          #------------------------------------------------------------
    122          gmListWidgets.get_choices_from_list (
    123                  parent = parent,
    124                  msg = _('Coded terms known to GNUmed (may take a while to load).'),
    125                  caption = _('Showing coded terms.'),
    126                  columns = [ _('Term'), _('Code'), _('System'), _('Language'), _('Version'), _(u'Coding system details') ],
    127                  single_selection = True,
    128                  can_return_empty = True,
    129                  ignore_OK_button = True,
    130                  refresh_callback = refresh
    131  #               edit_callback=None,
    132  #               new_callback=None,
    133  #               delete_callback=None,
    134  #               left_extra_button=None,
    135  #               middle_extra_button=None,
    136  #               right_extra_button=None
    137          )
    138
    139  #================================================================
    140
    141 -class cGenericCodesPhraseWheel(gmPhraseWheel.cMultiPhraseWheel):
    142
    143 -        def __init__(self, *args, **kwargs):
    144
    145                  super(cGenericCodesPhraseWheel, self).__init__(*args, **kwargs)
    146
    147                  query = u"""
    148                          SELECT
    149                                  -- DISTINCT ON (list_label)
    150                                  data,
    151                                  list_label,
    152                                  field_label
    153                          FROM (
    154
    155                                  SELECT
    156                                          pk_generic_code
    157                                                  AS data,
    158                                          (code || ' (' || coding_system || '): ' || term || ' (' || version || coalesce(' - ' || lang, '') || ')')
    159                                                  AS list_label,
    160                                          code AS
    161                                                  field_label
    162                                  FROM
    163                                          ref.v_coded_terms
    164                                  WHERE
    165                                          term %(fragment_condition)s
    166                                                  OR
    167                                          code %(fragment_condition)s
    168                                          %(ctxt_system)s
    169                                          %(ctxt_lang)s
    170
    171                          ) AS applicable_codes
    172                          ORDER BY list_label
    173                          LIMIT 30
    174                  """
    175                  ctxt = {
    176                          'ctxt_system': {                                # must be a TUPLE !
    177                                  'where_part': u'AND coding_system IN %(system)s',
    178                                  'placeholder': u'system'
    179                          },
    180                          'ctxt_lang': {
    181                                  'where_part': u'AND lang = %(lang)s',
    182                                  'placeholder': u'lang'
    183                          }
    184                  }
    185
    186                  mp = gmMatchProvider.cMatchProvider_SQL2(queries = query, context = ctxt)
    187                  mp.setThresholds(2, 4, 5)
    188                  mp.word_separators = '[ \t=+&/:-]+'
    189                  #mp.print_queries = True
    190
    191                  self.phrase_separators = ';'
    192                  self.selection_only = False                     # not sure yet how this fares with multi-phrase input
    193                  self.SetToolTipString(_('Select one or more codes that apply.'))
    194                  self.matcher = mp
    195
    196                  self.add_callback_on_lose_focus(callback = self.__on_losing_focus)
    197          #------------------------------------------------------------
    198 -        def __on_losing_focus(self):
    199                  self._adjust_data_after_text_update()
    200                  if self.GetValue().strip() == u'':
    201                          return
    202
    203                  if len(self.data) != len(self.displayed_strings):
    204                          self.display_as_valid(valid = False, partially_invalid = True)
    205                          return
    206
    207                  self.display_as_valid(valid = True)
    208          #------------------------------------------------------------
    209 -        def _get_data_tooltip(self):
    210                  if len(self.data) == 0:
    211                          return u''
    212
    213                  return u';\n'.join([ i['list_label'] for i in self.data.values() ]) + u';'
    214          #------------------------------------------------------------
    215 -        def generic_linked_codes2item_dict(self, codes):
    216                  if len(codes) == 0:
    217                          return u'', {}
    218
    219                  code_dict = {}
    220                  val = u''
    221                  for code in codes:
    222                          list_label = u'%s (%s): %s (%s - %s)' % (
    223                                  code['code'],
    224                                  code['name_short'],
    225                                  code['term'],
    226                                  code['version'],
    227                                  code['lang']
    228                          )
    229                          field_label = code['code']
    230                          code_dict[field_label] = {'data': code['pk_generic_code'], 'field_label': field_label, 'list_label': list_label}
    231                          val += u'%s; ' % field_label
    232
    233                  return val.strip(), code_dict
    234  #================================================================
    235  # main
    236  #----------------------------------------------------------------
    237  if __name__ == '__main__':
    238
    239          if len(sys.argv) < 2:
    240                  sys.exit()
    241
    242          if sys.argv[1] != 'test':
    243                  sys.exit()
    244
    245          from Gnumed.pycommon import gmI18N
    246          gmI18N.activate_locale()
    247          gmI18N.install_domain()
    248          from Gnumed.pycommon import gmPG2
    249
    250          #--------------------------------------------------------
    251 -        def test_generic_codes_prw():
    252                  gmPG2.get_connection()
    253                  app = wx.PyWidgetTester(size = (500, 40))
    254                  pw = cGenericCodesPhraseWheel(app.frame, -1)
    255                  #pw.set_context(context = u'zip', val = u'04318')
    256                  app.frame.Show(True)
    257                  app.MainLoop()
    258          #--------------------------------------------------------
    259          test_generic_codes_prw()
    260
    261  #================================================================
    262