Package gui :: Package input_elements :: Module sequence
[hide private]
[frames] | no frames]

Source Code for Module gui.input_elements.sequence

  1  ############################################################################### 
  2  #                                                                             # 
  3  # Copyright (C) 2012 Edward d'Auvergne                                        # 
  4  #                                                                             # 
  5  # This file is part of the program relax (http://www.nmr-relax.com).          # 
  6  #                                                                             # 
  7  # This program is free software: you can redistribute it and/or modify        # 
  8  # it under the terms of the GNU General Public License as published by        # 
  9  # the Free Software Foundation, either version 3 of the License, or           # 
 10  # (at your option) any later version.                                         # 
 11  #                                                                             # 
 12  # This program is distributed in the hope that it will be useful,             # 
 13  # but WITHOUT ANY WARRANTY; without even the implied warranty of              # 
 14  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               # 
 15  # GNU General Public License for more details.                                # 
 16  #                                                                             # 
 17  # You should have received a copy of the GNU General Public License           # 
 18  # along with this program.  If not, see <http://www.gnu.org/licenses/>.       # 
 19  #                                                                             # 
 20  ############################################################################### 
 21   
 22  # Module docstring. 
 23  """Module containing a set of special GUI elements to be used in the relax wizards.""" 
 24   
 25  # Python module imports. 
 26  import wx 
 27  import wx.lib.mixins.listctrl 
 28   
 29  # relax module imports. 
 30  from relax_errors import RelaxError 
 31  from status import Status; status = Status() 
 32   
 33  # relax GUI module imports. 
 34  from gui.input_elements.combo_list import Combo_list 
 35  from gui.fonts import font 
 36  from gui.misc import add_border 
 37  from gui import paths 
 38  from gui.string_conv import float_to_gui, gui_to_float, gui_to_int, gui_to_list, gui_to_py, gui_to_str, gui_to_tuple, int_to_gui, list_to_gui, py_to_gui, str_to_gui, tuple_to_gui 
 39   
 40   
41 -class Sequence:
42 """Wizard GUI element for the input of all types of Python sequence objects. 43 44 The supported Python types include: 45 - list of floats 46 - list of integers 47 - list of strings 48 - tuple of floats 49 - tuple of integers 50 - tuple of strings 51 """ 52
53 - def __init__(self, name=None, default=None, parent=None, element_type='default', seq_type=None, value_type=None, dim=None, min=0, max=1000, sizer=None, desc=None, combo_choices=None, combo_data=None, combo_list_min=None, tooltip=None, divider=None, padding=0, spacer=None, height_element=27, single_value=False, read_only=False, can_be_none=False):
54 """Set up the element. 55 56 @keyword name: The name of the element to use in titles, etc. 57 @type name: str 58 @keyword default: The default value of the element. 59 @type default: sequence object 60 @keyword parent: The wizard GUI element. 61 @type parent: wx.Panel instance 62 @keyword element_type: The type of GUI element to create. If set to 'default', the wx.TextCtrl element with a button to bring up a dialog with ListCtrl will be used. If set to 'combo_list', the special gui.components.combo_list.Combo_list element will be used. 63 @type element_type: str 64 @keyword seq_type: The type of Python sequence. This should be one of 'list' or 'tuple'. 65 @type seq_type: str 66 @keyword value_type: The type of Python object that the value should be. This can be one of 'float', 'int', or 'str'. 67 @type value_type: str 68 @keyword dim: The dimensions that a list or tuple must conform to. For a 1D sequence, this can be a single value or a tuple of possible sizes. For a 2D sequence (a numpy matrix or list of lists), this must be a tuple of the fixed dimension sizes, e.g. a 3x5 matrix should be specified as (3, 5). 69 @type dim: int, tuple of int or None 70 @keyword min: For a SpinCtrl, the minimum value allowed. 71 @type min: int 72 @keyword max: For a SpinCtrl, the maximum value allowed. 73 @type max: int 74 @keyword sizer: The sizer to put the input field widget into. 75 @type sizer: wx.Sizer instance 76 @keyword desc: The text description. 77 @type desc: str 78 @keyword combo_choices: The list of choices to present to the user. This is only used if the element_type is set to 'combo'. 79 @type combo_choices: list of str 80 @keyword combo_data: The data returned by a call to GetValue(). This is only used if the element_type is set to 'combo'. If supplied, it should be the same length at the combo_choices list. If not supplied, the combo_choices list will be used for the returned data. 81 @type combo_data: list 82 @keyword combo_list_min: The minimum length for the Combo_list object. 83 @type combo_list_min: int or None 84 @keyword tooltip: The tooltip which appears on hovering over the text or input field. 85 @type tooltip: str 86 @keyword divider: The position of the divider. 87 @type divider: int 88 @keyword padding: Spacing to the left and right of the widgets. 89 @type padding: int 90 @keyword spacer: The amount of spacing to add below the field in pixels. If None, a stretchable spacer will be used. 91 @type spacer: None or int 92 @keyword height_element: The height in pixels of the GUI element. 93 @type height_element: int 94 @keyword single_value: A flag which if True will cause single input values to be treated as single values rather than a list or tuple. 95 @type single_value: bool 96 @keyword read_only: A flag which if True means that the text of the element cannot be edited. 97 @type read_only: bool 98 @keyword can_be_none: A flag which specifies if the element is allowed to have the None value. 99 @type can_be_none: bool 100 """ 101 102 # Store the args. 103 self.parent = parent 104 self.name = name 105 self.default = default 106 self.element_type = element_type 107 self.seq_type = seq_type 108 self.value_type = value_type 109 self.dim = dim 110 self.min = min 111 self.max = max 112 self.single_value = single_value 113 self.can_be_none = can_be_none 114 115 # The base types. 116 if value_type in ['float', 'num']: 117 self.convert_from_gui = gui_to_float 118 self.convert_to_gui = float_to_gui 119 elif value_type == 'int': 120 self.convert_from_gui = gui_to_int 121 self.convert_to_gui = int_to_gui 122 elif value_type == 'str': 123 self.convert_from_gui = gui_to_str 124 self.convert_to_gui = str_to_gui 125 else: 126 self.convert_from_gui = gui_to_py 127 self.convert_to_gui = py_to_gui 128 129 # The sequence types. 130 if seq_type == 'list': 131 self.convert_from_gui_seq = gui_to_list 132 self.convert_to_gui_seq = list_to_gui 133 elif seq_type == 'tuple': 134 self.convert_from_gui_seq = gui_to_tuple 135 self.convert_to_gui_seq = tuple_to_gui 136 else: 137 raise RelaxError("Unknown sequence type '%s'." % seq_type) 138 139 # Initialise the default element. 140 if self.element_type == 'default': 141 # Translate the read_only flag if None. 142 if read_only == None: 143 read_only = False 144 145 # Init. 146 sub_sizer = wx.BoxSizer(wx.HORIZONTAL) 147 148 # Left padding. 149 sub_sizer.AddSpacer(padding) 150 151 # The description. 152 text = wx.StaticText(parent, -1, desc, style=wx.ALIGN_LEFT) 153 text.SetFont(font.normal) 154 sub_sizer.Add(text, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 0) 155 156 # The divider. 157 if not divider: 158 raise RelaxError("The divider position has not been supplied.") 159 160 # Spacing. 161 x, y = text.GetSize() 162 sub_sizer.AddSpacer((divider - x, 0)) 163 164 # The input field. 165 self._field = wx.TextCtrl(parent, -1, '') 166 self._field.SetMinSize((50, height_element)) 167 self._field.SetFont(font.normal) 168 sub_sizer.Add(self._field, 1, wx.ADJUST_MINSIZE|wx.ALIGN_CENTER_VERTICAL, 0) 169 170 # Read-only. 171 if read_only: 172 self._field.SetEditable(False) 173 colour = parent.GetBackgroundColour() 174 self._field.SetOwnBackgroundColour(colour) 175 176 # A little spacing. 177 sub_sizer.AddSpacer(5) 178 179 # The edit button. 180 button = wx.BitmapButton(parent, -1, wx.Bitmap(paths.icon_16x16.edit_rename, wx.BITMAP_TYPE_ANY)) 181 button.SetMinSize((height_element, height_element)) 182 button.SetToolTipString("Edit the values.") 183 sub_sizer.Add(button, 0, wx.ADJUST_MINSIZE|wx.ALIGN_CENTER_VERTICAL, 0) 184 parent.Bind(wx.EVT_BUTTON, self.open_dialog, button) 185 186 # Right padding. 187 sub_sizer.AddSpacer(padding) 188 189 # Add to the main sizer. 190 sizer.Add(sub_sizer, 1, wx.EXPAND|wx.ALL, 0) 191 192 # Spacing below the widget. 193 if spacer == None: 194 sizer.AddStretchSpacer() 195 else: 196 sizer.AddSpacer(spacer) 197 198 # Tooltip. 199 if tooltip: 200 text.SetToolTipString(tooltip) 201 self._field.SetToolTipString(tooltip) 202 203 # Set the default value. 204 if self.default != None: 205 self._field.SetValue(self.convert_to_gui_seq(self.default)) 206 207 # Initialise the combo list input field. 208 elif self.element_type == 'combo_list': 209 # Translate the read_only flag if None. 210 if read_only == None: 211 read_only = False 212 213 # Set up the Combo_list object. 214 self._field = Combo_list(parent, sizer, desc, value_type=value_type, min_length=combo_list_min, choices=combo_choices, data=combo_data, default=default, tooltip=tooltip, read_only=read_only, can_be_none=can_be_none) 215 216 # Unknown field. 217 else: 218 raise RelaxError("Unknown element type '%s'." % self.element_type)
219 220
221 - def Clear(self):
222 """Special method for clearing or resetting the GUI element.""" 223 224 # Clear the value from a TextCtrl or ComboBox. 225 if self.element_type in ['default', 'combo_list']: 226 self._field.Clear()
227 228
229 - def GetValue(self):
230 """Special method for returning the sequence values of the GUI element. 231 232 @return: The sequence of values. 233 @rtype: sequence type 234 """ 235 236 # The value. 237 value = self._field.GetValue() 238 239 # Handle Combo_list elements. 240 if self.element_type == 'combo_list': 241 # Empty lists. 242 if value == [] or value == None: 243 return None 244 245 # Non Combo_list elements. 246 else: 247 # Handle single values. 248 value_set = False 249 if self.single_value: 250 try: 251 # Convert. 252 value = self.convert_from_gui(value) 253 254 # Check that the conversion was successful. 255 if value == None and self.can_be_none: 256 value_set = True 257 elif self.value_type == None: 258 value_set = True 259 elif self.value_type in ['float', 'num']: 260 if isinstance(value, int) or isinstance(value, float): 261 value_set = True 262 elif self.value_type == 'int': 263 if isinstance(value, int): 264 value_set = True 265 elif self.value_type == 'str': 266 if isinstance(value, str): 267 value_set = True 268 except: 269 pass 270 271 # Convert to a sequence, handling bad user behaviour. 272 if not value_set: 273 try: 274 value = self.convert_from_gui_seq(value) 275 276 # Set the value to None or an empty sequence. 277 except RelaxError: 278 if self.can_be_none: 279 value = None 280 elif self.seq_type == 'list': 281 value = [] 282 else: 283 value = () 284 285 # Convert sequences to single values as needed. 286 if self.single_value: 287 if (isinstance(value, list) or isinstance(value, tuple)) and len(value) == 1: 288 value = value[0] 289 290 # Convert single values to sequences as needed. 291 elif value != None: 292 if self.seq_type == 'list' and not isinstance(value, list): 293 value = [value] 294 elif self.seq_type == 'tuple' and not isinstance(value, tuple): 295 value = (value,) 296 297 # Handle empty list and tuple values. 298 if not self.single_value and len(value) == 0: 299 return None 300 301 # Return the value. 302 return value
303 304
305 - def SetValue(self, value=None, index=None):
306 """Special method for setting the value of the GUI element. 307 308 @keyword value: The value to set. 309 @type value: value or list of values 310 @keyword index: The index of the value to set, if the full list is not given. 311 @type index: int or None 312 """ 313 314 # The ComboBox list. 315 if self.element_type == 'combo_list': 316 self._field.SetValue(value=value, index=index) 317 318 # The other elements. 319 else: 320 # Handle single values. 321 if self.single_value and isinstance(value, list) and len(value) == 1: 322 value = value[0] 323 324 # Convert and set the value. 325 self._field.SetValue(self.convert_to_gui_seq(value))
326 327
328 - def UpdateChoices(self, combo_choices=None, combo_data=None, combo_default=None):
329 """Special wizard method for updating the list of choices in a ComboBox type element. 330 331 @keyword combo_choices: The list of choices to present to the user. This is only used if the element_type is set to 'combo_list'. 332 @type combo_choices: list of str 333 @keyword combo_data: The data returned by a call to GetValue(). This is only used if the element_type is set to 'combo_list'. If supplied, it should be the same length at the combo_choices list. If not supplied, the combo_choices list will be used for the returned data. 334 @type combo_data: list 335 @keyword combo_default: The default value of the ComboBox. This is only used if the element_type is set to 'combo_list'. 336 @type combo_default: str or None 337 """ 338 339 # The ComboBox list. 340 if self.element_type == 'combo_list': 341 self._field.UpdateChoices(combo_choices=combo_choices, combo_data=combo_data, combo_default=combo_default)
342 343
344 - def open_dialog(self, event):
345 """Open a special dialog for inputting a list of text values. 346 347 @param event: The wx event. 348 @type event: wx event 349 """ 350 351 # Show the window. 352 self.selection_win_show() 353 354 # Extract the data from the selection window once closed. 355 self.selection_win_data() 356 357 # Destroy the window. 358 del self.sel_win
359 360
361 - def selection_win_data(self):
362 """Extract the data from the selection window.""" 363 364 # Get the value. 365 value = self.sel_win.GetValue() 366 367 # No sequence data. 368 if not len(value): 369 self.Clear() 370 371 # Set the values. 372 else: 373 self.SetValue(value)
374 375
376 - def selection_win_show(self):
377 """Show the selection window.""" 378 379 # Initialise the model selection window. 380 self.sel_win = Sequence_window(parent=self.parent, name=self.name, seq_type=self.seq_type, value_type=self.value_type, dim=self.dim) 381 382 # Set the model selector window selections. 383 self.sel_win.SetValue(self.GetValue()) 384 385 # Show the model selector window. 386 if status.show_gui: 387 self.sel_win.ShowModal() 388 self.sel_win.Close()
389 390 391
392 -class Sequence_list_ctrl(wx.ListCtrl, wx.lib.mixins.listctrl.TextEditMixin, wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin):
393 """The string list ListCtrl object.""" 394
395 - def __init__(self, parent):
396 """Initialise the control. 397 398 @param parent: The parent window. 399 @type parent: wx.Frame instance 400 """ 401 402 # Execute the parent __init__() methods. 403 wx.ListCtrl.__init__(self, parent, -1, style=wx.BORDER_SUNKEN|wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES) 404 wx.lib.mixins.listctrl.TextEditMixin.__init__(self) 405 wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin.__init__(self)
406 407 408
409 -class Sequence_window(wx.Dialog):
410 """The Python sequence object editor window.""" 411 412 # The window size. 413 SIZE = (600, 600) 414 415 # A border. 416 BORDER = 10 417 418 # Sizes. 419 SIZE_BUTTON = (150, 33) 420
421 - def __init__(self, parent=None, name='', seq_type='list', value_type='str', dim=None):
422 """Set up the string list editor window. 423 424 @keyword parent: The parent GUI element. 425 @type parent: wx.Window instance or None 426 @keyword name: The name of the window. 427 @type name: str 428 @keyword seq_type: The type of Python sequence. This should be one of 'list' or 'tuple'. 429 @type seq_type: str 430 @keyword value_type: The type of Python data expected in the sequence. This should be one of 'float', 'int', or 'str'. 431 @type value_type: str 432 @keyword dim: The fixed dimension that the sequence must conform to. 433 @type dim: int or None 434 """ 435 436 # Store the args. 437 self.name = name 438 self.seq_type = seq_type 439 self.value_type = value_type 440 self.dim = dim 441 442 # The base types. 443 if value_type in ['float', 'num']: 444 self.convert_from_gui = gui_to_float 445 self.convert_to_gui = float_to_gui 446 elif value_type == 'int': 447 self.convert_from_gui = gui_to_int 448 self.convert_to_gui = int_to_gui 449 elif value_type == 'str': 450 self.convert_from_gui = gui_to_str 451 self.convert_to_gui = str_to_gui 452 else: 453 raise RelaxError("Unknown base data type '%s'." % value_type) 454 455 # The title of the dialog. 456 title = "Edit the %s values." % name 457 458 # Set up the dialog. 459 wx.Dialog.__init__(self, parent, id=-1, title=title) 460 461 # Initialise some values 462 self.width = self.SIZE[0] - 2*self.BORDER 463 464 # Set the frame properties. 465 self.SetSize(self.SIZE) 466 self.Centre() 467 self.SetFont(font.normal) 468 469 # The main box sizer. 470 main_sizer = wx.BoxSizer(wx.VERTICAL) 471 472 # Pack the sizer into the frame. 473 self.SetSizer(main_sizer) 474 475 # Build the central sizer, with borders. 476 sizer = add_border(main_sizer, border=self.BORDER, packing=wx.VERTICAL) 477 478 # Add the list control. 479 self.add_list(sizer) 480 481 # Some spacing. 482 sizer.AddSpacer(self.BORDER) 483 484 # Add the bottom buttons. 485 self.add_buttons(sizer)
486 487
488 - def GetValue(self):
489 """Return the values as a sequence of values. 490 491 @return: The sequence of values. 492 @rtype: sequence type 493 """ 494 495 # Init. 496 values = [] 497 498 # Loop over the entries. 499 for i in range(self.sequence.GetItemCount()): 500 values.append(self.convert_from_gui(self.sequence.GetItemText(i))) 501 502 # Sequence conversion. 503 if self.seq_type == 'tuple': 504 values = tuple(values) 505 506 # Return the sequence. 507 return values
508 509
510 - def SetValue(self, values):
511 """Set up the list values. 512 513 @param values: The list of values to add to the list. 514 @type values: list of str or None 515 """ 516 517 # No value. 518 if values == None: 519 return 520 521 # Single values. 522 try: 523 len(values) 524 except TypeError: 525 if self.seq_type == 'list': 526 values = [values] 527 elif self.seq_type == 'tuple': 528 values = (values,) 529 530 # Loop over the entries. 531 for i in range(len(values)): 532 # Fixed dimension sequences - set the values of the pre-created list. 533 if self.dim: 534 self.sequence.SetStringItem(index=i, col=0, label=self.convert_to_gui(values[i])) 535 536 # Variable dimension sequences - append the item to the end of the blank list. 537 else: 538 self.sequence.InsertStringItem(i, self.convert_to_gui(values[i]))
539 540
541 - def add_buttons(self, sizer):
542 """Add the buttons to the sizer. 543 544 @param sizer: A sizer object. 545 @type sizer: wx.Sizer instance 546 """ 547 548 # Create a horizontal layout for the buttons. 549 button_sizer = wx.BoxSizer(wx.HORIZONTAL) 550 sizer.Add(button_sizer, 0, wx.ALIGN_CENTER|wx.ALL, 0) 551 552 # The non-fixed sequence buttons. 553 if self.dim == None or (isinstance(self.dim, tuple) and self.dim[0] == None): 554 # The add button. 555 button = wx.lib.buttons.ThemedGenBitmapTextButton(self, -1, None, " Add") 556 button.SetBitmapLabel(wx.Bitmap(paths.icon_22x22.add, wx.BITMAP_TYPE_ANY)) 557 button.SetFont(font.normal) 558 button.SetToolTipString("Add a row to the list.") 559 button.SetMinSize(self.SIZE_BUTTON) 560 button_sizer.Add(button, 0, wx.ADJUST_MINSIZE, 0) 561 self.Bind(wx.EVT_BUTTON, self.append_row, button) 562 563 # Spacer. 564 button_sizer.AddSpacer(20) 565 566 # The delete all button. 567 button = wx.lib.buttons.ThemedGenBitmapTextButton(self, -1, None, " Delete all") 568 button.SetBitmapLabel(wx.Bitmap(paths.icon_22x22.edit_delete, wx.BITMAP_TYPE_ANY)) 569 button.SetFont(font.normal) 570 button.SetToolTipString("Delete all items.") 571 button.SetMinSize(self.SIZE_BUTTON) 572 button_sizer.Add(button, 0, wx.ADJUST_MINSIZE, 0) 573 self.Bind(wx.EVT_BUTTON, self.delete_all, button) 574 575 # Spacer. 576 button_sizer.AddSpacer(20) 577 578 # The Ok button. 579 button = wx.lib.buttons.ThemedGenBitmapTextButton(self, -1, None, " Ok") 580 button.SetBitmapLabel(wx.Bitmap(paths.icon_22x22.dialog_ok, wx.BITMAP_TYPE_ANY)) 581 button.SetFont(font.normal) 582 button.SetMinSize(self.SIZE_BUTTON) 583 button_sizer.Add(button, 0, wx.ADJUST_MINSIZE, 0) 584 self.Bind(wx.EVT_BUTTON, self.close, button)
585 586
587 - def add_list(self, sizer):
588 """Set up the list control. 589 590 @param sizer: A sizer object. 591 @type sizer: wx.Sizer instance 592 """ 593 594 # The control. 595 self.sequence = Sequence_list_ctrl(self) 596 597 # Set the column title. 598 title = "%s%s" % (self.name[0].upper(), self.name[1:]) 599 600 # Add a single column, full width. 601 self.sequence.InsertColumn(0, title) 602 self.sequence.SetColumnWidth(0, wx.LIST_AUTOSIZE) 603 604 # Add the table to the sizer. 605 sizer.Add(self.sequence, 1, wx.ALL|wx.EXPAND, 0) 606 607 # The fixed dimension sequence - add all the rows needed. 608 if self.dim: 609 for i in range(self.dim): 610 self.append_row(None)
611 612
613 - def append_row(self, event):
614 """Append a new row to the list. 615 616 @param event: The wx event. 617 @type event: wx event 618 """ 619 620 # The next index. 621 next = self.sequence.GetItemCount() 622 623 # Add a new empty row. 624 self.sequence.InsertStringItem(next, '')
625 626
627 - def close(self, event):
628 """Close the window. 629 630 @param event: The wx event. 631 @type event: wx event 632 """ 633 634 # Destroy the window. 635 self.Destroy()
636 637
638 - def delete_all(self, event):
639 """Remove all items from the list. 640 641 @param event: The wx event. 642 @type event: wx event 643 """ 644 645 # Delete. 646 self.sequence.DeleteAllItems()
647