1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
|
"""GNUmed date input widget
All GNUmed date input should happen via classes in
this module.
@copyright: author(s)
"""
#==============================================================================
__version__ = "$Revision: 1.66 $"
__author__ = "K. Hilbert <Karsten.Hilbert@gmx.net>"
__licence__ = "GPL v2 or later (details at http://www.gnu.org)"
# standard libary
import re, string, sys, time, datetime as pyDT, logging
# 3rd party
import mx.DateTime as mxDT
import wx
import wx.calendar
# GNUmed specific
if __name__ == '__main__':
sys.path.insert(0, '../../')
from Gnumed.pycommon import gmMatchProvider
from Gnumed.pycommon import gmDateTime
from Gnumed.pycommon import gmI18N
from Gnumed.wxpython import gmPhraseWheel
from Gnumed.wxpython import gmGuiHelpers
_log = logging.getLogger('gm.ui')
#============================================================
#class cIntervalMatchProvider(gmMatchProvider.cMatchProvider):
# """Turns strings into candidate intervals."""
# def __init__(self):
#
# gmMatchProvider.cMatchProvider.__init__(self)
#
# self.setThresholds(aPhrase = 1, aWord = 998, aSubstring = 999)
# self.word_separators = None
## self.ignored_chars("""[?!."'\\(){}\[\]<>~#*$%^_]+""")
# #--------------------------------------------------------
# # external API
# #--------------------------------------------------------
# #--------------------------------------------------------
# # base class API
# #--------------------------------------------------------
# def getMatchesByPhrase(self, aFragment):
# intv = gmDateTime.str2interval(str_interval = aFragment)
#
# if intv is None:
# return (False, [])
#
# items = [{
# 'data': intv,
# 'field_label': gmDateTime.format_interval(intv, gmDateTime.acc_minutes),
# 'list_label': gmDateTime.format_interval(intv, gmDateTime.acc_minutes)
# }]
#
# return (True, items)
# #--------------------------------------------------------
# def getMatchesByWord(self, aFragment):
# return self.getMatchesByPhrase(aFragment)
# #--------------------------------------------------------
# def getMatchesBySubstr(self, aFragment):
# return self.getMatchesByPhrase(aFragment)
# #--------------------------------------------------------
# def getAllMatches(self):
# matches = (False, [])
# return matches
#============================================================
class cIntervalPhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.phrase_separators = None
self.display_accuracy = None
#--------------------------------------------------------
# phrasewheel internal API
#--------------------------------------------------------
def _update_candidates_in_picklist(self, val):
intv = gmDateTime.str2interval(str_interval = val)
if intv is None:
self._current_match_candidates = []
else:
self._current_match_candidates = [{
'data': intv,
'field_label': gmDateTime.format_interval(intv, gmDateTime.acc_minutes),
'list_label': gmDateTime.format_interval(intv, gmDateTime.acc_minutes)
}]
self._picklist.SetItems(self._current_match_candidates)
#---------------------------------------------------------
# def _on_lose_focus(self, event):
# # are we valid ?
# if len(self._data) == 0:
# self._set_data_to_first_match()
#
# # let the base class do its thing
# super(cIntervalPhraseWheel, self)._on_lose_focus(event)
#--------------------------------------------------------
def _picklist_item2display_string(self, item=None):
intv = item['data']
if intv is not None:
return gmDateTime.format_interval (
interval = intv,
accuracy_wanted = self.display_accuracy
)
return item['field_label']
#--------------------------------------------------------
def _get_data_tooltip(self):
intv = self.GetData()
if intv is None:
return u''
return gmDateTime.format_interval (
interval = intv,
accuracy_wanted = self.display_accuracy
)
#--------------------------------------------------------
# external API
#--------------------------------------------------------
def SetValue(self, value):
if isinstance(value, pyDT.timedelta):
self.SetText(data = value, suppress_smarts = True)
return
if value is None:
value = u''
super(cIntervalPhraseWheel, self).SetValue(value)
#--------------------------------------------------------
def SetText(self, value=u'', data=None, suppress_smarts=False):
if data is not None:
if value.strip() == u'':
value = gmDateTime.format_interval (
interval = data,
accuracy_wanted = self.display_accuracy
)
super(cIntervalPhraseWheel, self).SetText(value = value, data = data, suppress_smarts = suppress_smarts)
#--------------------------------------------------------
def SetData(self, data=None):
if data is None:
super(cIntervalPhraseWheel, self).SetText(u'', None)
return
value = gmDateTime.format_interval (
interval = data,
accuracy_wanted = self.display_accuracy
)
super(cIntervalPhraseWheel, self).SetText(value = value, data = data)
#--------------------------------------------------------
def GetData(self):
if len(self._data) == 0:
self._set_data_to_first_match()
return super(cIntervalPhraseWheel, self).GetData()
#============================================================
class cCalendarDatePickerDlg(wx.Dialog):
"""Shows a calendar control from which the user can pick a date."""
def __init__(self, parent):
wx.Dialog.__init__(self, parent, title = _('Pick a date ...'))
panel = wx.Panel(self, -1)
sizer = wx.BoxSizer(wx.VERTICAL)
panel.SetSizer(sizer)
cal = wx.calendar.CalendarCtrl(panel)
if sys.platform != 'win32':
# gtk truncates the year - this fixes it
w, h = cal.Size
cal.Size = (w+25, h)
cal.MinSize = cal.Size
sizer.Add(cal, 0)
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer.Add((0, 0), 1)
btn_ok = wx.Button(panel, wx.ID_OK)
btn_ok.SetDefault()
button_sizer.Add(btn_ok, 0, wx.ALL, 2)
button_sizer.Add((0, 0), 1)
btn_can = wx.Button(panel, wx.ID_CANCEL)
button_sizer.Add(btn_can, 0, wx.ALL, 2)
button_sizer.Add((0, 0), 1)
sizer.Add(button_sizer, 1, wx.EXPAND | wx.ALL, 10)
sizer.Fit(panel)
self.ClientSize = panel.Size
cal.Bind(wx.EVT_KEY_DOWN, self.__on_key_down)
cal.SetFocus()
self.cal = cal
#-----------------------------------------------------------
def __on_key_down(self, evt):
code = evt.KeyCode
if code == wx.WXK_TAB:
self.cal.Navigate()
elif code in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
self.EndModal(wx.ID_OK)
elif code == wx.WXK_ESCAPE:
self.EndModal(wx.ID_CANCEL)
else:
evt.Skip()
#============================================================
class cDateMatchProvider(gmMatchProvider.cMatchProvider):
"""Turns strings into candidate dates.
Matching on "all" (*, '') will pop up a calendar :-)
"""
def __init__(self):
gmMatchProvider.cMatchProvider.__init__(self)
self.setThresholds(aPhrase = 1, aWord = 998, aSubstring = 999)
self.word_separators = None
# self.ignored_chars("""[?!."'\\(){}\[\]<>~#*$%^_]+""")
#--------------------------------------------------------
# external API
#--------------------------------------------------------
#--------------------------------------------------------
# base class API
#--------------------------------------------------------
# internal matching algorithms
#
# if we end up here:
# - aFragment will not be "None"
# - aFragment will be lower case
# - we _do_ deliver matches (whether we find any is a different story)
#--------------------------------------------------------
def getMatchesByPhrase(self, aFragment):
"""Return matches for aFragment at start of phrases."""
matches = gmDateTime.str2pydt_matches(str2parse = aFragment.strip())
if len(matches) == 0:
return (False, [])
items = []
for match in matches:
if match['data'] is None:
items.append ({
'data': None,
'field_label': match['label'],
'list_label': match['label']
})
continue
data = match['data'].replace (
hour = 11,
minute = 11,
second = 11,
microsecond = 111111
)
list_label = gmDateTime.pydt_strftime (
data,
format = '%A, %d. %B %Y (%x)',
accuracy = gmDateTime.acc_days
)
items.append ({
'data': data,
'field_label': match['label'],
'list_label': list_label
})
return (True, items)
#--------------------------------------------------------
def getMatchesByWord(self, aFragment):
"""Return matches for aFragment at start of words inside phrases."""
return self.getMatchesByPhrase(aFragment)
#--------------------------------------------------------
def getMatchesBySubstr(self, aFragment):
"""Return matches for aFragment as a true substring."""
return self.getMatchesByPhrase(aFragment)
#--------------------------------------------------------
def getAllMatches(self):
"""Return all items."""
matches = (False, [])
return matches
# # consider this:
# dlg = cCalendarDatePickerDlg(None)
# # FIXME: show below parent
# dlg.CentreOnScreen()
#
# if dlg.ShowModal() == wx.ID_OK:
# date = dlg.cal.Date
# if date is not None:
# if date.IsValid():
# date = gmDateTime.wxDate2py_dt(wxDate = date).replace (
# hour = 11,
# minute = 11,
# second = 11,
# microsecond = 111111
# )
# lbl = gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days)
# matches = (True, [{'data': date, 'label': lbl}])
# dlg.Destroy()
#
# return matches
#============================================================
class cDateInputPhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.matcher = cDateMatchProvider()
self.phrase_separators = None
self.static_tooltip_extra = _('<ALT-C/K>: pick from (c/k)alendar')
#--------------------------------------------------------
# internal helpers
#--------------------------------------------------------
# def __text2timestamp(self):
#
# self._update_candidates_in_picklist(val = self.GetValue().strip())
#
# if len(self._current_match_candidates) == 1:
# return self._current_match_candidates[0]['data']
#
# return None
#--------------------------------------------------------
def __pick_from_calendar(self):
dlg = cCalendarDatePickerDlg(self)
# FIXME: show below parent
dlg.CentreOnScreen()
decision = dlg.ShowModal()
date = dlg.cal.Date
dlg.Destroy()
if decision != wx.ID_OK:
return
if date is None:
return
if not date.IsValid():
return
date = gmDateTime.wxDate2py_dt(wxDate = date).replace (
hour = 11,
minute = 11,
second = 11,
microsecond = 111111
)
val = gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days)
self.SetText(value = val, data = date, suppress_smarts = True)
#--------------------------------------------------------
# phrasewheel internal API
#--------------------------------------------------------
def _on_lose_focus(self, event):
# no valid date yet ?
if len(self._data) == 0:
self._set_data_to_first_match()
date = self.GetData()
if date is not None:
self.SetValue(gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days))
# let the base class do its thing
super(cDateInputPhraseWheel, self)._on_lose_focus(event)
#--------------------------------------------------------
def _picklist_item2display_string(self, item=None):
data = item['data']
if data is not None:
return gmDateTime.pydt_strftime(data, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days)
return item['field_label']
#--------------------------------------------------------
def _on_key_down(self, event):
# <ALT-C> / <ALT-K> -> calendar
if event.AltDown() is True:
char = unichr(event.GetUnicodeKey())
if char in u'ckCK':
self.__pick_from_calendar()
return
super(cDateInputPhraseWheel, self)._on_key_down(event)
#--------------------------------------------------------
def _get_data_tooltip(self):
if len(self._data) == 0:
return u''
date = self.GetData()
# if match provider only provided completions
# but not a full date with it
if date is None:
return u''
return gmDateTime.pydt_strftime (
date,
format = '%A, %d. %B %Y (%x)',
accuracy = gmDateTime.acc_days
)
#--------------------------------------------------------
# external API
#--------------------------------------------------------
def SetValue(self, value):
if isinstance(value, pyDT.datetime):
date = value.replace (
hour = 11,
minute = 11,
second = 11,
microsecond = 111111
)
self.SetText(data = date, suppress_smarts = True)
return
if value is None:
value = u''
super(self.__class__, self).SetValue(value)
#--------------------------------------------------------
def SetText(self, value=u'', data=None, suppress_smarts=False):
if data is not None:
if isinstance(data, gmDateTime.cFuzzyTimestamp):
data = data.timestamp.replace (
hour = 11,
minute = 11,
second = 11,
microsecond = 111111
)
if value.strip() == u'':
value = gmDateTime.pydt_strftime(data, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days)
super(self.__class__, self).SetText(value = value, data = data, suppress_smarts = suppress_smarts)
#--------------------------------------------------------
def SetData(self, data=None):
if data is None:
gmPhraseWheel.cPhraseWheel.SetText(self, u'', None)
return
self.SetText(data = data)
#--------------------------------------------------------
def GetData(self):
if len(self._data) == 0:
self._set_data_to_first_match()
return super(self.__class__, self).GetData()
#--------------------------------------------------------
def is_valid_timestamp(self, allow_empty=True):
if len(self._data) > 0:
self.display_as_valid(True)
return True
if self.GetValue().strip() == u'':
if allow_empty:
self.display_as_valid(True)
return True
else:
self.display_as_valid(False)
return False
# skip showing calendar on '*' from here
if self.GetValue().strip() == u'*':
self.display_as_valid(False)
return False
# try to auto-snap to first match
self._set_data_to_first_match()
if len(self._data) == 0:
self.display_as_valid(False)
return False
date = self.GetData()
self.SetValue(gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days))
self.display_as_valid(True)
return True
#--------------------------------------------------------
# properties
#--------------------------------------------------------
def _get_date(self):
return self.GetData()
def _set_date(self, date):
raise AttributeError('._set_date not implemented')
# val = gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days)
# self.data = date.replace (
# hour = 11,
# minute = 11,
# second = 11,
# microsecond = 111111
# )
date = property(_get_date, _set_date)
#============================================================
class cMatchProvider_FuzzyTimestamp(gmMatchProvider.cMatchProvider):
def __init__(self):
self.__allow_past = 1
self.__shifting_base = None
gmMatchProvider.cMatchProvider.__init__(self)
self.setThresholds(aPhrase = 1, aWord = 998, aSubstring = 999)
self.word_separators = None
# self.ignored_chars("""[?!."'\\(){}\[\]<>~#*$%^_]+""")
#--------------------------------------------------------
# external API
#--------------------------------------------------------
#--------------------------------------------------------
# base class API
#--------------------------------------------------------
# internal matching algorithms
#
# if we end up here:
# - aFragment will not be "None"
# - aFragment will be lower case
# - we _do_ deliver matches (whether we find any is a different story)
#--------------------------------------------------------
def getMatchesByPhrase(self, aFragment):
"""Return matches for aFragment at start of phrases."""
matches = gmDateTime.str2fuzzy_timestamp_matches(aFragment.strip())
if len(matches) == 0:
return (False, [])
items = []
for match in matches:
items.append ({
'data': match['data'],
'field_label': match['label'],
'list_label': match['label']
})
return (True, items)
#--------------------------------------------------------
def getMatchesByWord(self, aFragment):
"""Return matches for aFragment at start of words inside phrases."""
return self.getMatchesByPhrase(aFragment)
#--------------------------------------------------------
def getMatchesBySubstr(self, aFragment):
"""Return matches for aFragment as a true substring."""
return self.getMatchesByPhrase(aFragment)
#--------------------------------------------------------
def getAllMatches(self):
"""Return all items."""
return (False, [])
#==================================================
class cFuzzyTimestampInput(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.matcher = cMatchProvider_FuzzyTimestamp()
self.phrase_separators = None
self.selection_only = True
self.selection_only_error_msg = _('Cannot interpret input as timestamp.')
self.display_accuracy = None
#--------------------------------------------------------
# internal helpers
#--------------------------------------------------------
def __text2timestamp(self, val=None):
if val is None:
val = self.GetValue()
val = val.strip()
if val == u'':
return None
success, matches = self.matcher.getMatchesByPhrase(val)
if len(matches) == 1:
return matches[0]['data']
return None
#--------------------------------------------------------
# phrasewheel internal API
#--------------------------------------------------------
def _on_lose_focus(self, event):
# are we valid ?
if self.data is None:
# no, so try
date = self.__text2timestamp()
if date is not None:
self.SetValue(value = date.format_accurately(accuracy = self.display_accuracy))
self.data = date
# let the base class do its thing
gmPhraseWheel.cPhraseWheel._on_lose_focus(self, event)
#--------------------------------------------------------
def _picklist_item2display_string(self, item=None):
data = item['data']
if data is not None:
return data.format_accurately(accuracy = self.display_accuracy)
return item['field_label']
#--------------------------------------------------------
# external API
#--------------------------------------------------------
def SetText(self, value=u'', data=None, suppress_smarts=False):
if data is not None:
if isinstance(data, pyDT.datetime):
data = gmDateTime.cFuzzyTimestamp(timestamp=data)
if value.strip() == u'':
value = data.format_accurately(accuracy = self.display_accuracy)
gmPhraseWheel.cPhraseWheel.SetText(self, value = value, data = data, suppress_smarts = suppress_smarts)
#--------------------------------------------------------
def SetData(self, data=None):
if data is None:
gmPhraseWheel.cPhraseWheel.SetText(self, u'', None)
else:
if isinstance(data, pyDT.datetime):
data = gmDateTime.cFuzzyTimestamp(timestamp=data)
gmPhraseWheel.cPhraseWheel.SetText(self, value = data.format_accurately(accuracy = self.display_accuracy), data = data)
#--------------------------------------------------------
def is_valid_timestamp(self, empty_is_valid=True):
if self.GetData() is not None:
return True
# skip empty value
if self.GetValue().strip() == u'':
if empty_is_valid:
return True
return False
date = self.__text2timestamp()
if date is None:
return False
self.SetText (
value = date.format_accurately(accuracy = self.display_accuracy),
data = date,
suppress_smarts = True
)
return True
#==================================================
# main
#--------------------------------------------------
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.exit()
if sys.argv[1] != 'test':
sys.exit()
gmI18N.activate_locale()
gmI18N.install_domain(domain='gnumed')
gmDateTime.init()
#----------------------------------------------------
def test_cli():
mp = cMatchProvider_FuzzyTimestamp()
mp.word_separators = None
mp.setThresholds(aWord = 998, aSubstring = 999)
val = None
while val != 'exit':
print "************************************"
val = raw_input('Enter date fragment ("exit" to quit): ')
found, matches = mp.getMatches(aFragment=val)
for match in matches:
#print match
print match['label']
print match['data']
print "---------------"
#--------------------------------------------------------
def test_fuzzy_picker():
app = wx.PyWidgetTester(size = (300, 40))
app.SetWidget(cFuzzyTimestampInput, id=-1, size=(180,20), pos=(10,20))
app.MainLoop()
#--------------------------------------------------------
def test_picker():
app = wx.PyWidgetTester(size = (300, 40))
app.SetWidget(cDateInputPhraseWheel, id=-1, size=(180,20), pos=(10,20))
app.MainLoop()
#--------------------------------------------------------
#test_cli()
#test_fuzzy_picker()
test_picker()
#==================================================
|