INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Convenience function for accessing tag parameters
def GetParam(tag, param, default=__SENTINEL): """ Convenience function for accessing tag parameters""" if tag.HasParam(param): return tag.GetParam(param) else: if default == __SENTINEL: raise KeyError else: return default
Process an outgoing communication
def send(evt): "Process an outgoing communication" # get the text written by the user (input textbox control) msg = ctrl_input.value # send the message (replace with socket/queue/etc.) gui.alert(msg, "Message") # record the message (update the UI) log(msg) ctrl_input.value = "" ctrl_input.set_focus()
Basic save functionality: just replaces the gui code
def save(evt, designer): "Basic save functionality: just replaces the gui code" # ask the user if we should save the changes: ok = gui.confirm("Save the changes?", "GUI2PY Designer", cancel=True, default=True) if ok: wx_obj = evt.GetEventObject() w = wx_obj.obj try: if DEBUG: print "saving..." # make a backup: fin = open(designer.filename, "r") fout = open(designer.filename + ".bak", "w") fout.write(fin.read()) fout.close() fin.close() if designer.filename.endswith(".rsrc.py"): # serialize and save the resource gui.save(designer.filename, [gui.dump(w)]) else: # reopen the files to proccess them fin = open(designer.filename + ".bak", "r") fout = open(designer.filename, "w") copy = True newlines = fin.newlines or "\n" def dump(obj, indent=1): "recursive convert object to string" for ctl in obj[:]: write(ctl, indent) def write(ctl, indent): if ctl[:]: fout.write(" " * indent * 4) fout.write("with %s:" % ctl.__repr__(parent=None, indent=indent, context=True)) fout.write(newlines) dump(ctl, indent + 1) else: fout.write(" " * indent * 4) fout.write(ctl.__repr__(parent=None, indent=indent)) fout.write(newlines) dumped = False for line in fin: if line.startswith("# --- gui2py designer generated code starts ---"): fout.write(line) fout.write(newlines) write(w, indent=0) fout.write(newlines) dumped = True copy = False if line.startswith("# --- gui2py designer generated code ends ---"): copy = True if copy: fout.write(line) #fout.write("\n\r") if not dumped: gui.alert("No valid # --- gui2py... delimiters! \n" "Unable to write down design code!", "Design not updated:") fout.close() fin.close() except Exception, e: import traceback print(traceback.print_exc()) ok = gui.confirm("Close anyway?\n%s" % str(e), 'Unable to save:', ok=True, cancel=True) if ok is not None: wx.CallAfter(exit) # terminate the designer program return ok
Show a tip message
def wellcome_tip(wx_obj): "Show a tip message" msg = ("Close the main window to exit & save.\n" "Drag & Drop / Click the controls from the ToolBox to create new ones.\n" "Left click on the created controls to select them.\n" "Double click to edit the default property.\n" "Right click to pop-up the context menu.\n") # create a super tool tip manager and set some styles stt = STT.SuperToolTip(msg) stt.SetHeader("Welcome to gui2py designer!") stt.SetDrawHeaderLine(True) stt.ApplyStyle("Office 2007 Blue") stt.SetDropShadow(True) stt.SetHeaderBitmap(images.designer.GetBitmap()) stt.SetEndDelay(15000) # hide in 15 s # create a independent tip window, show/hide manually (avoid binding wx_obj) tip = CustomToolTipWindow(wx_obj, stt) tip.CalculateBestSize() tip.CalculateBestPosition(wx_obj) tip.DropShadow(stt.GetDropShadow()) if stt.GetUseFade(): show = lambda: tip.StartAlpha(True) else: show = lambda: tip.Show() wx.CallLater(1000, show) # show the tip in 1 s wx.CallLater(30000, tip.Destroy)
Get the selected object and store start position
def mouse_down(self, evt): "Get the selected object and store start position" if DEBUG: print "down!" if (not evt.ControlDown() and not evt.ShiftDown()) or evt.AltDown(): for obj in self.selection: # clear marker if obj.sel_marker: obj.sel_marker.show(False) obj.sel_marker.destroy() obj.sel_marker = None self.selection = [] # clear previous selection wx_obj = evt.GetEventObject() if wx_obj.Parent is None or evt.AltDown(): if not evt.AltDown(): evt.Skip() # start the rubberband effect (multiple selection using the mouse) self.current = wx_obj self.overlay = wx.Overlay() self.pos = evt.GetPosition() self.parent.wx_obj.CaptureMouse() #if self.inspector and hasattr(wx_obj, "obj"): # self.inspector.inspect(wx_obj.obj) # inspect top level window #self.dclick = False else: # create the selection marker and assign it to the control obj = wx_obj.obj self.overlay = None if DEBUG: print wx_obj sx, sy = wx_obj.ScreenToClient(wx_obj.GetPositionTuple()) dx, dy = wx_obj.ScreenToClient(wx.GetMousePosition()) self.pos = wx_obj.ScreenToClient(wx.GetMousePosition()) self.start = (sx - dx, sy - dy) self.current = wx_obj if DEBUG: print "capture..." # do not capture on TextCtrl, it will fail (blocking) at least in gtk # do not capture on wx.Notebook to allow selecting the tabs if not isinstance(wx_obj, wx.Notebook): self.parent.wx_obj.CaptureMouse() self.select(obj, keep_selection=True)
Move the selected object
def mouse_move(self, evt): "Move the selected object" if DEBUG: print "move!" if self.current and not self.overlay: wx_obj = self.current sx, sy = self.start x, y = wx.GetMousePosition() # calculate the new position (this will overwrite relative dimensions): x, y = (x + sx, y + sy) if evt.ShiftDown(): # snap to grid: x = x / GRID_SIZE[0] * GRID_SIZE[0] y = y / GRID_SIZE[1] * GRID_SIZE[1] # calculate the diff to use in the rest of the selected objects: ox, oy = wx_obj.obj.pos dx, dy = (x - ox), (y - oy) # move all selected objects: for obj in self.selection: x, y = obj.pos x = x + dx y = y + dy obj.pos = (wx.Point(x, y)) elif self.overlay: wx_obj = self.current pos = evt.GetPosition() # convert to relative client coordinates of the containter: if evt.GetEventObject() != wx_obj: pos = evt.GetEventObject().ClientToScreen(pos) # frame pos = wx_obj.ScreenToClient(pos) # panel rect = wx.RectPP(self.pos, pos) # Draw the rubber-band rectangle using an overlay so it # will manage keeping the rectangle and the former window # contents separate. dc = wx.ClientDC(wx_obj) odc = wx.DCOverlay(self.overlay, dc) odc.Clear() dc.SetPen(wx.Pen("blue", 2)) if 'wxMac' in wx.PlatformInfo: dc.SetBrush(wx.Brush(wx.Colour(0xC0, 0xC0, 0xC0, 0x80))) else: dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawRectangleRect(rect) del odc
Called by SelectionTag
def do_resize(self, evt, wx_obj, (n, w, s, e)): "Called by SelectionTag" # calculate the pos (minus the offset, not in a panel like rw!) pos = wx_obj.ScreenToClient(wx.GetMousePosition()) x, y = pos if evt.ShiftDown(): # snap to grid: x = x / GRID_SIZE[0] * GRID_SIZE[0] y = y / GRID_SIZE[1] * GRID_SIZE[1] pos = wx.Point(x, y) if not self.resizing or self.resizing != (wx_obj, (n, w, s, e)): self.pos = list(pos) # store starting point self.resizing = (wx_obj, (n, w, s, e)) # track obj and handle else: delta = pos - self.pos if DEBUG: print "RESIZING: n, w, s, e", n, w, s, e if n or w or s or e: # resize according the direction (n, w, s, e) x = wx_obj.Position[0] + e * delta[0] y = wx_obj.Position[1] + n * delta[1] if w or e: if not isinstance(wx_obj, wx.TopLevelWindow): width = wx_obj.Size[0] + (w - e) * delta[0] else: width = wx_obj.ClientSize[0] + (w - e) * delta[0] else: width = None if n or s: height = wx_obj.Size[1] + (s - n) * delta[1] else: height = None else: # just move x = wx_obj.Position[0] + delta[0] y = wx_obj.Position[1] + delta[1] width = height = None new_pos = (x, y) new_size = (width, height) if new_size != wx_obj.GetSize() or new_pos != wx_obj.GetPosition(): # reset margins (TODO: avoid resizing recursion) wx_obj.obj.margin_left = 0 wx_obj.obj.margin_right = 0 wx_obj.obj.margin_top = 0 wx_obj.obj.margin_bottom = 0 wx_obj.obj.pos = new_pos # update gui specs (position) # update gui specs (size), but do not alter default value if width is not None and height is not None: wx_obj.obj.width = width wx_obj.obj.height = height elif width is not None: wx_obj.obj.width = width elif height is not None: wx_obj.obj.height = height # only update on sw for a smooth resize if w: self.pos[0] = pos[0] # store new starting point if s: self.pos[1] = pos[1]
Release the selected object ( pass a wx_obj if the event was captured )
def mouse_up(self, evt, wx_obj=None): "Release the selected object (pass a wx_obj if the event was captured)" self.resizing = False if self.current: wx_obj = self.current if self.parent.wx_obj.HasCapture(): self.parent.wx_obj.ReleaseMouse() self.current = None if self.overlay: # When the mouse is released we reset the overlay and it # restores the former content to the window. dc = wx.ClientDC(wx_obj) odc = wx.DCOverlay(self.overlay, dc) odc.Clear() del odc self.overlay.Reset() self.overlay = None pos = evt.GetPosition() # convert to relative client coordinates of the container: if evt.GetEventObject() != wx_obj: pos = evt.GetEventObject().ClientToScreen(pos) # frame pos = wx_obj.ScreenToClient(pos) # panel # finish the multiple selection using the mouse: rect = wx.RectPP(self.pos, pos) for obj in wx_obj.obj: # only check child controls (not menubar/statusbar) if isinstance(obj, Control): obj_rect = obj.wx_obj.GetRect() if rect.ContainsRect(obj_rect): self.select(obj, keep_selection=True) self.pos = None if self.inspector and wx_obj: self.inspector.inspect(wx_obj.obj) if DEBUG: print "SELECTION", self.selection
support cursor keys to move components one pixel at a time
def key_press(self, event): "support cursor keys to move components one pixel at a time" key = event.GetKeyCode() if key in (wx.WXK_LEFT, wx.WXK_UP, wx.WXK_RIGHT, wx.WXK_DOWN): for obj in self.selection: x, y = obj.pos if event.ShiftDown(): # snap to grid:t # for now I'm only going to align to grid # in the direction of the cursor movement if key == wx.WXK_LEFT: x = (x - GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0] elif key == wx.WXK_RIGHT: x = (x + GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0] elif key == wx.WXK_UP: y = (y - GRID_SIZE[1]) / GRID_SIZE[1] * GRID_SIZE[1] elif key == wx.WXK_DOWN: y = (y + GRID_SIZE[1]) / GRID_SIZE[1] * GRID_SIZE[1] else: if key == wx.WXK_LEFT: x = x - 1 elif key == wx.WXK_RIGHT: x = x + 1 elif key == wx.WXK_UP: y = y - 1 elif key == wx.WXK_DOWN: y = y + 1 obj.pos = (x, y) elif key == wx.WXK_DELETE: self.delete(event) elif key == wx.WXK_INSERT: self.duplicate(event) else: if DEBUG: print "KEY:", key
delete all of the selected objects
def delete(self, event): "delete all of the selected objects" # get the selected objects (if any) for obj in self.selection: if obj: if DEBUG: print "deleting", obj.name obj.destroy() self.selection = [] # clean selection self.inspector.load_object()
create a copy of each selected object
def duplicate(self, event): "create a copy of each selected object" # duplicate the selected objects (if any) new_selection = [] for obj in self.selection: if obj: if DEBUG: print "duplicating", obj.name obj.sel_marker.destroy() obj.sel_marker = None obj2 = obj.duplicate() obj2.sel_marker = SelectionMarker(obj2) obj2.sel_marker.show(True) new_selection.append(obj2) self.selection = new_selection # update with new obj's self.inspector.load_object()
Adjust facade with the dimensions of the original object ( and repaint )
def update(self): "Adjust facade with the dimensions of the original object (and repaint)" x, y = self.obj.wx_obj.GetPosition() w, h = self.obj.wx_obj.GetSize() self.Hide() self.Move((x, y)) self.SetSize((w, h)) # allow original control to repaint before taking the new snapshot image: wx.CallLater(200, self.refresh)
Capture the new control superficial image after an update
def refresh(self): "Capture the new control superficial image after an update" self.bmp = self.obj.snapshot() # change z-order to overlap controls (windows) and show the image: self.Raise() self.Show() self.Refresh()
When dealing with a Top - Level window position it absolute lower - right
def CalculateBestPosition(self,widget): "When dealing with a Top-Level window position it absolute lower-right" if isinstance(widget, wx.Frame): screen = wx.ClientDisplayRect()[2:] left,top = widget.ClientToScreenXY(0,0) right,bottom = widget.ClientToScreenXY(*widget.GetClientRect()[2:]) size = self.GetSize() xpos = right ypos = bottom - size[1] self.SetPosition((xpos,ypos)) else: STT.ToolTipWindow.CalculateBestPosition(self, widget)
Returns the pyth item data associated with the item
def GetPyData(self, item): "Returns the pyth item data associated with the item" wx_data = self.GetItemData(item) py_data = self._py_data_map.get(wx_data) return py_data
Set the python item data associated wit the wx item
def SetPyData(self, item, py_data): "Set the python item data associated wit the wx item" wx_data = wx.NewId() # create a suitable key self.SetItemData(item, wx_data) # store it in wx self._py_data_map[wx_data] = py_data # map it internally self._wx_data_map[py_data] = wx_data # reverse map return wx_data
Do a reverse look up for an item containing the requested data
def FindPyData(self, start, py_data): "Do a reverse look up for an item containing the requested data" # first, look at our internal dict: wx_data = self._wx_data_map[py_data] # do the real search at the wx control: if wx.VERSION < (3, 0, 0) or 'classic' in wx.version(): data = self.FindItemData(start, wx_data) else: data = self.FindItem(start, wx_data) return data
Remove the item from the list and unset the related data
def DeleteItem(self, item): "Remove the item from the list and unset the related data" wx_data = self.GetItemData(item) py_data = self._py_data_map[wx_data] del self._py_data_map[wx_data] del self._wx_data_map[py_data] wx.ListCtrl.DeleteItem(self, item)
Remove all the item from the list and unset the related data
def DeleteAllItems(self): "Remove all the item from the list and unset the related data" self._py_data_map.clear() self._wx_data_map.clear() wx.ListCtrl.DeleteAllItems(self)
Set item ( row ) count - useful only in virtual mode -
def set_count(self, value): "Set item (row) count -useful only in virtual mode-" if self.view == "report" and self.virtual and value is not None: self.wx_obj.SetItemCount(value)
Deletes the item at the zero - based index n from the control.
def delete(self, a_position): "Deletes the item at the zero-based index 'n' from the control." key = self.wx_obj.GetPyData(a_position) del self._items[key]
Remove all items and column headings
def clear_all(self): "Remove all items and column headings" self.clear() for ch in reversed(self.columns): del self[ch.name]
Associate the header to the control ( it could be recreated )
def set_parent(self, new_parent, init=False): "Associate the header to the control (it could be recreated)" self._created = False SubComponent.set_parent(self, new_parent, init) # if index not given, append the column at the last position: if self.index == -1 or self.index > self._parent.wx_obj.GetColumnCount(): self.index = self._parent.wx_obj.GetColumnCount() # insert the column in the listview: self._parent.wx_obj.InsertColumn(self.index, self.text, self._align, self.width) self._created = True
Remove all items and reset internal structures
def clear(self): "Remove all items and reset internal structures" dict.clear(self) self._key = 0 if hasattr(self._list_view, "wx_obj"): self._list_view.wx_obj.DeleteAllItems()
Returns the index of the selected item ( list for multiselect ) or None
def _get_selection(self): "Returns the index of the selected item (list for multiselect) or None" if self.multiselect: return self.wx_obj.GetSelections() else: sel = self.wx_obj.GetSelection() if sel == wx.NOT_FOUND: return None else: return sel
Sets the item at index n to be the selected item.
def _set_selection(self, index, dummy=False): "Sets the item at index 'n' to be the selected item." # only change selection if index is None and not dummy: if index is None: self.wx_obj.SetSelection(-1) # clean up text if control supports it: if hasattr(self.wx_obj, "SetValue"): self.wx_obj.SetValue("") else: self.wx_obj.SetSelection(index) # send a programmatically event (not issued by wx) wx_event = ItemContainerControlSelectEvent(self._commandtype, index, self.wx_obj) if hasattr(self, "onchange") and self.onchange: # TODO: fix (should work but it doesn't): ## wx.PostEvent(self.wx_obj, wx_evt) # WORKAROUND: event = FormEvent(name="change", wx_event=wx_event) self.onchange(event)
Returns the label of the selected item or an empty string if none
def _get_string_selection(self): "Returns the label of the selected item or an empty string if none" if self.multiselect: return [self.wx_obj.GetString(i) for i in self.wx_obj.GetSelections()] else: return self.wx_obj.GetStringSelection()
Clear and set the strings ( and data if any ) in the control from a list
def _set_items(self, a_iter): "Clear and set the strings (and data if any) in the control from a list" self._items_dict = {} if not a_iter: string_list = [] data_list = [] elif not isinstance(a_iter, (tuple, list, dict)): raise ValueError("items must be an iterable") elif isinstance(a_iter, dict): # use keys as data, values as label strings self._items_dict = a_iter string_list = a_iter.values() data_list = a_iter.keys() elif isinstance(a_iter[0], (tuple, list)) and len(a_iter[0]) == 2: # like the dict, but ordered self._items_dict = dict(a_iter) data_list, string_list = zip(*a_iter) else: # use the same strings as data string_list = a_iter data_list = a_iter # set the strings self.wx_obj.SetItems(string_list) # set the associated data for i, data in enumerate(data_list): self.set_data(i, data)
Associate the given client data with the item at position n.
def set_data(self, n, data): "Associate the given client data with the item at position n." self.wx_obj.SetClientData(n, data) # reverse association: self._items_dict[data] = self.get_string(n)
Adds the item to the control associating the given data if not None.
def append(self, a_string, data=None): "Adds the item to the control, associating the given data if not None." self.wx_obj.Append(a_string, data) # reverse association: self._items_dict[data] = a_string
Deletes the item at the zero - based index n from the control.
def delete(self, a_position): "Deletes the item at the zero-based index 'n' from the control." self.wx_obj.Delete(a_position) data = self.get_data() if data in self._items_dict: del self._items_dict[data]
Construct a string representing the object
def represent(obj, prefix, parent="", indent=0, context=False, max_cols=80): "Construct a string representing the object" try: name = getattr(obj, "name", "") class_name = "%s.%s" % (prefix, obj.__class__.__name__) padding = len(class_name) + 1 + indent * 4 + (5 if context else 0) params = [] for (k, spec) in sorted(obj._meta.specs.items(), key=get_sort_key): if k == "index": # index is really defined by creation order continue # also, avoid infinite recursion if k == "parent" and parent != "": v = parent else: v = getattr(obj, k, "") if (not isinstance(spec, InternalSpec) and v != spec.default and (k != 'id' or v > 0) and isinstance(v, (basestring, int, long, float, bool, dict, list, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, Font, Color)) and repr(v) != 'None' ): v = repr(v) else: v = None if v is not None: params.append("%s=%s" % (k, v)) param_lines = [] line = "" for param in params: if len(line + param) + 3 > max_cols - padding: param_lines.append(line) line = "" line += param + ", " param_lines.append(line) param_str = ("\n%s" % (" " * padding)).join(param_lines) return "%s(%s)" % (class_name, param_str) except: raise # uninitialized, use standard representation to not break debuggers return object.__repr__(obj)
Find an object already created
def get(obj_name, init=False): "Find an object already created" wx_parent = None # check if new_parent is given as string (useful for designer!) if isinstance(obj_name, basestring): # find the object reference in the already created gui2py objects # TODO: only useful for designer, get a better way obj_parent = COMPONENTS.get(obj_name) if not obj_parent: # try to find window (it can be a plain wx frame/control) wx_parent = wx.FindWindowByName(obj_name) if wx_parent: # store gui object (if any) obj_parent = getattr(wx_parent, "obj") else: # fallback using just object name (backward compatibility) for obj in COMPONENTS.values(): if obj.name==obj_name: obj_parent = obj else: obj_parent = obj_name # use the provided parent (as is) return obj_parent or wx_parent
Recreate ( if needed ) the wx_obj and apply new properties
def rebuild(self, recreate=True, force=False, **kwargs): "Recreate (if needed) the wx_obj and apply new properties" # detect if this involves a spec that needs to recreate the wx_obj: needs_rebuild = any([isinstance(spec, (StyleSpec, InitSpec)) for spec_name, spec in self._meta.specs.items() if spec_name in kwargs]) # validate if this gui object needs and support recreation if needs_rebuild and recreate or force: if DEBUG: print "rebuilding window!" # recreate the wx_obj! warning: it will call Destroy() self.__init__(**kwargs) else: if DEBUG: print "just setting attr!" for name, value in kwargs.items(): setattr(self, name, value)
Remove event references and destroy wx object ( and children )
def destroy(self): "Remove event references and destroy wx object (and children)" # unreference the obj from the components map and parent if self._name: del COMPONENTS[self._get_fully_qualified_name()] if DEBUG: print "deleted from components!" if isinstance(self._parent, Component): del self._parent[self._name] if DEBUG: print "deleted from parent!" # destroy the wx_obj (only if sure that reference is not needed!) if self.wx_obj: self.wx_obj.Destroy() for child in self: print "destroying child", child.destroy() # destroy the designer selection marker (if any) if hasattr(self, 'sel_marker') and self.sel_marker: self.sel_marker.destroy() if hasattr(self, 'facade') and self.facade: self.facade.destroy()
Create a new object exactly similar to self
def duplicate(self, new_parent=None): "Create a new object exactly similar to self" kwargs = {} for spec_name, spec in self._meta.specs.items(): value = getattr(self, spec_name) if isinstance(value, Color): print "COLOR", value, value.default if value.default: value = None if value is not None: kwargs[spec_name] = value del kwargs['parent'] new_id = wx.NewId() kwargs['id'] = new_id kwargs['name'] = "%s_%s" % (kwargs['name'], new_id) new_obj = self.__class__(new_parent or self.get_parent(), **kwargs) # recursively create a copy of each child (in the new parent!) for child in self: child.duplicate(new_obj) return new_obj
Raises/ lower the component in the window hierarchy ( Z - order/ tab order )
def reindex(self, z=None): "Raises/lower the component in the window hierarchy (Z-order/tab order)" # z=0: lowers(first index), z=-1: raises (last) # actually, only useful in design mode if isinstance(self._parent, Component): # get the current index (z-order) if not self in self._parent._children_list: return len(self._parent._children_list) i = self._parent._children_list.index(self) if z is None: return i if not hasattr(self, "designer") and not self.designer: raise RuntimeError("reindexing can only be done on design mode") # delete the element reference from the list del self._parent._children_list[i] # insert as last element if z < 0: self._parent._children_list.append(self) else: self._parent._children_list.insert(z, self)
Store the gui/ wx object parent for this component
def set_parent(self, new_parent, init=False): "Store the gui/wx object parent for this component" # set init=True if this is called from the constructor self._parent = get(new_parent, init)
Return parent window name ( used in __repr__ parent spec )
def _get_parent_name(self): "Return parent window name (used in __repr__ parent spec)" parent = self.get_parent() parent_names = [] while parent: if isinstance(parent, Component): parent_name = parent.name # Top Level Windows has no parent! if parent_name: parent_names.insert(0, parent_name) parent = parent.get_parent() else: break if not parent_names: return None else: return '.'.join(parent_names)
return full parents name + self name ( useful as key )
def _get_fully_qualified_name(self): "return full parents name + self name (useful as key)" parent_name = self._get_parent_name() if not parent_name: return self._name else: return "%s.%s" % (parent_name, self._name)
Capture the screen appearance of the control ( to be used as facade )
def snapshot(self): "Capture the screen appearance of the control (to be used as facade)" width, height = self.wx_obj.GetSize() bmp = wx.EmptyBitmap(width, height) wdc = wx.ClientDC(self.wx_obj) mdc = wx.MemoryDC(bmp) mdc.Blit(0, 0, width, height, wdc, 0, 0) #bmp.SaveFile("test.bmp", wx.BITMAP_TYPE_BMP) wdc.Destroy() mdc.Destroy() return bmp
called when adding a control to the window
def _sizer_add(self, child): "called when adding a control to the window" if self.sizer: if DEBUG: print "adding to sizer:", child.name border = None if not border: border = child.sizer_border flags = child._sizer_flags if child.sizer_align: flags |= child._sizer_align if child.sizer_expand: flags |= wx.EXPAND if 'grid' in self.sizer: self._sizer.Add(child.wx_obj, flag=flags, border=border, pos=(child.sizer_row, child.sizer_col), span=(child.sizer_rowspan, child.sizer_colspan)) else: self._sizer.Add(child.wx_obj, 0, flags, border)
Re - parent a child control with the new wx_obj parent
def set_parent(self, new_parent, init=False): "Re-parent a child control with the new wx_obj parent" Component.set_parent(self, new_parent, init) # if not called from constructor, we must also reparent in wx: if not init: if DEBUG: print "reparenting", ctrl.name if hasattr(self.wx_obj, "Reparent"): self.wx_obj.Reparent(self._parent.wx_obj)
Calculate final pos and size ( auto absolute in pixels & relativa )
def _calc_dimension(self, dim_val, dim_max, font_dim): "Calculate final pos and size (auto, absolute in pixels & relativa)" if dim_val is None: return -1 # let wx automatic pos/size elif isinstance(dim_val, int): return dim_val # use fixed pixel value (absolute) elif isinstance(dim_val, basestring): if dim_val.endswith("%"): # percentaje, relative to parent max size: dim_val = int(dim_val[:-1]) dim_val = dim_val / 100.0 * dim_max elif dim_val.endswith("em"): # use current font size (suport fractions): dim_val = float(dim_val[:-2]) dim_val = dim_val * font_dim elif dim_val.endswith("px"): # fixed pixels dim_val = dim_val[:-2] elif dim_val == "" or dim_val == "auto": dim_val = -1 return int(dim_val)
automatically adjust relative pos and size of children controls
def resize(self, evt=None): "automatically adjust relative pos and size of children controls" if DEBUG: print "RESIZE!", self.name, self.width, self.height if not isinstance(self.wx_obj, wx.TopLevelWindow): # check that size and pos is relative, then resize/move if self._left and self._left[-1] == "%" or \ self._top and self._top[-1] == "%": if DEBUG: print "MOVING", self.name, self._width self._set_pos((self._left, self._top)) if self._width and self._width[-1] == "%" or \ self._height and self._height[-1] == "%": if DEBUG: print "RESIZING", self.name, self._width, self._height self._set_size((self._width, self._height)) for child in self: if isinstance(child, Control): child.resize(evt) # call original handler (wx.HtmlWindow) if evt: evt.Skip()
make several copies of the background bitmap
def __tile_background(self, dc): "make several copies of the background bitmap" sz = self.wx_obj.GetClientSize() bmp = self._bitmap.get_bits() w = bmp.GetWidth() h = bmp.GetHeight() if isinstance(self, wx.ScrolledWindow): # adjust for scrolled position spx, spy = self.wx_obj.GetScrollPixelsPerUnit() vsx, vsy = self.wx_obj.GetViewStart() dx, dy = (spx * vsx) % w, (spy * vsy) % h else: dx, dy = (w, h) x = -dx while x < sz.width: y = -dy while y < sz.height: dc.DrawBitmap(bmp, x, y) y = y + h x = x + w
Draw the image as background
def __on_erase_background(self, evt): "Draw the image as background" if self._bitmap: dc = evt.GetDC() if not dc: dc = wx.ClientDC(self) r = self.wx_obj.GetUpdateRegion().GetBox() dc.SetClippingRegion(r.x, r.y, r.width, r.height) if self._background_tiling: self.__tile_background(dc) else: dc.DrawBitmapPoint(self._bitmap.get_bits(), (0, 0))
Associate the component to the control ( it could be recreated )
def set_parent(self, new_parent, init=False): "Associate the component to the control (it could be recreated)" # store gui reference inside of wx object (this will enable rebuild...) self._parent = get(new_parent, init=False) # store new parent if init: self._parent[self._name] = self
Update a property value with ( used by the designer )
def rebuild(self, **kwargs): "Update a property value with (used by the designer)" for name, value in kwargs.items(): setattr(self, name, value)
Custom draws the label when transparent background is needed
def __on_paint(self, event): "Custom draws the label when transparent background is needed" # use a Device Context that supports anti-aliased drawing # and semi-transparent colours on all platforms dc = wx.GCDC(wx.PaintDC(self.wx_obj)) dc.SetFont(self.wx_obj.GetFont()) dc.SetTextForeground(self.wx_obj.GetForegroundColour()) dc.DrawText(self.wx_obj.GetLabel(), 0, 0)
Look for every file in the directory tree and return a dict Hacked from sphinx. autodoc
def find_modules(rootpath, skip): """ Look for every file in the directory tree and return a dict Hacked from sphinx.autodoc """ INITPY = '__init__.py' rootpath = os.path.normpath(os.path.abspath(rootpath)) if INITPY in os.listdir(rootpath): root_package = rootpath.split(os.path.sep)[-1] print "Searching modules in", rootpath else: print "No modules in", rootpath return def makename(package, module): """Join package and module with a dot.""" if package: name = package if module: name += '.' + module else: name = module return name skipall = [] for m in skip.keys(): if skip[m] is None: skipall.append(m) tree = {} saved = 0 found = 0 def save(module, submodule): name = module+ "."+ submodule for s in skipall: if name.startswith(s): print "Skipping "+name return False if skip.has_key(module): if submodule in skip[module]: print "Skipping "+name return False if not tree.has_key(module): tree[module] = [] tree[module].append(submodule) return True for root, subs, files in os.walk(rootpath): py_files = sorted([f for f in files if os.path.splitext(f)[1] == '.py']) if INITPY in py_files: subpackage = root[len(rootpath):].lstrip(os.path.sep).\ replace(os.path.sep, '.') full = makename(root_package, subpackage) part = full.rpartition('.') base_package, submodule = part[0], part[2] found += 1 if save(base_package, submodule): saved += 1 py_files.remove(INITPY) for py_file in py_files: found += 1 module = os.path.splitext(py_file)[0] if save(full, module): saved += 1 for item in tree.keys(): tree[item].sort() print "%s contains %i submodules, %i skipped" % \ (root_package, found, found-saved) return tree
Return a list of children sub - components that are column headings
def _get_column_headings(self): "Return a list of children sub-components that are column headings" # return it in the same order as inserted in the Grid headers = [ctrl for ctrl in self if isinstance(ctrl, GridColumn)] return sorted(headers, key=lambda ch: ch.index)
Set the row label format string ( empty to hide )
def _set_row_label(self, value): "Set the row label format string (empty to hide)" if not value: self.wx_obj.SetRowLabelSize(0) else: self.wx_obj._table._row_label = value
Update the grid if rows and columns have been added or deleted
def ResetView(self, grid): "Update the grid if rows and columns have been added or deleted" grid.BeginBatch() for current, new, delmsg, addmsg in [ (self._rows, self.GetNumberRows(), gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED, gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED), (self._cols, self.GetNumberCols(), gridlib.GRIDTABLE_NOTIFY_COLS_DELETED, gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED), ]: if new < current: msg = gridlib.GridTableMessage(self,delmsg,new,current-new) grid.ProcessTableMessage(msg) elif new > current: msg = gridlib.GridTableMessage(self,addmsg,new-current) grid.ProcessTableMessage(msg) self.UpdateValues(grid) grid.EndBatch() self._rows = self.GetNumberRows() self._cols = self.GetNumberCols() # update the column rendering plugins self._updateColAttrs(grid) # update the scrollbars and the displayed part of the grid grid.AdjustScrollbars() grid.ForceRefresh()
Update all displayed values
def UpdateValues(self, grid): "Update all displayed values" # This sends an event to the grid table to update all of the values msg = gridlib.GridTableMessage(self, gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES) grid.ProcessTableMessage(msg)
update the column attributes to add the appropriate renderer
def _updateColAttrs(self, grid): "update the column attributes to add the appropriate renderer" col = 0 for column in self.columns: attr = gridlib.GridCellAttr() if False: # column.readonly attr.SetReadOnly() if False: # column.renderer attr.SetRenderer(renderer) grid.SetColSize(col, column.width) grid.SetColAttr(col, attr) col += 1
col - > sort the data based on the column indexed by col
def SortColumn(self, col): "col -> sort the data based on the column indexed by col" name = self.columns[col].name _data = [] for row in self.data: rowname, entry = row _data.append((entry.get(name, None), row)) _data.sort() self.data = [] for sortvalue, row in _data: self.data.append(row)
Associate the header to the control ( it could be recreated )
def set_parent(self, new_parent, init=False): "Associate the header to the control (it could be recreated)" self._created = False SubComponent.set_parent(self, new_parent, init) # if index not given, append the column at the last position: if self.index == -1 or self.index >= len(self._parent.columns): self.index = len(self._parent.columns) - 1 # insert the column in the listview: self._parent.wx_obj.AppendCols(1) #self._parent.wx_obj.SetColLabelValue(self.index, self.text) #self.SetColLabel(self.index, self.align) #self._parent.wx_obj.SetColSize(self.index, self.width) self._created = True
Insert a number of rows into the grid ( and associated table )
def insert(self, pos, values): "Insert a number of rows into the grid (and associated table)" if isinstance(values, dict): row = GridRow(self, **values) else: row = GridRow(self, *values) list.insert(self, pos, row) self._grid_view.wx_obj.InsertRows(pos, numRows=1)
Insert a number of rows into the grid ( and associated table )
def append(self, values): "Insert a number of rows into the grid (and associated table)" if isinstance(values, dict): row = GridRow(self, **values) else: row = GridRow(self, *values) list.append(self, row) self._grid_view.wx_obj.AppendRows(numRows=1)
Remove all rows and reset internal structures
def clear(self): "Remove all rows and reset internal structures" ## list has no clear ... remove items in reverse order for i in range(len(self)-1, -1, -1): del self[i] self._key = 0 if hasattr(self._grid_view, "wx_obj"): self._grid_view.wx_obj.ClearGrid()
Called to create the control which must derive from wxControl.
def Create(self, parent, id, evtHandler): "Called to create the control, which must derive from wxControl." self._tc = wx.ComboBox(parent, id, "", (100, 50)) self.SetControl(self._tc) # pushing a different event handler instead evtHandler: self._tc.PushEventHandler(wx.EvtHandler()) self._tc.Bind(wx.EVT_COMBOBOX, self.OnChange)
Called to position/ size the edit control within the cell rectangle.
def SetSize(self, rect): "Called to position/size the edit control within the cell rectangle." self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2, wx.SIZE_ALLOW_MINUS_ONE)
Fetch the value from the table and prepare the edit control
def BeginEdit(self, row, col, grid): "Fetch the value from the table and prepare the edit control" self.startValue = grid.GetTable().GetValue(row, col) choices = grid.GetTable().columns[col]._choices self._tc.Clear() self._tc.AppendItems(choices) self._tc.SetStringSelection(self.startValue) self._tc.SetFocus()
Complete the editing of the current cell. Returns True if changed
def EndEdit(self, row, col, grid, val=None): "Complete the editing of the current cell. Returns True if changed" changed = False val = self._tc.GetStringSelection() print "val", val, row, col, self.startValue if val != self.startValue: changed = True grid.GetTable().SetValue(row, col, val) # update the table self.startValue = '' self._tc.SetStringSelection('') return changed
Return True to allow the given key to start editing
def IsAcceptedKey(self, evt): "Return True to allow the given key to start editing" ## Oops, there's a bug here, we'll have to do it ourself.. ##return self.base_IsAcceptedKey(evt) return (not (evt.ControlDown() or evt.AltDown()) and evt.GetKeyCode() != wx.WXK_SHIFT)
This will be called to let the editor do something with the first key
def StartingKey(self, evt): "This will be called to let the editor do something with the first key" key = evt.GetKeyCode() ch = None if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]: ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0) elif key < 256 and key >= 0 and chr(key) in string.printable: ch = chr(key) if not evt.ShiftDown(): ch = ch.lower() if ch is not None: self._tc.SetStringSelection(ch) else: evt.Skip()
A metaclass generator. Returns a metaclass which will register it s class as the class that handles input type = typeName
def TypeHandler(type_name): """ A metaclass generator. Returns a metaclass which will register it's class as the class that handles input type=typeName """ def metaclass(name, bases, dict): klass = type(name, bases, dict) form.FormTagHandler.register_type(type_name.upper(), klass) return klass return metaclass
enable or disable all menu items
def Enable(self, value): "enable or disable all menu items" for i in range(self.GetMenuItemCount()): it = self.FindItemByPosition(i) it.Enable(value)
check if all menu items are enabled
def IsEnabled(self, *args, **kwargs): "check if all menu items are enabled" for i in range(self.GetMenuItemCount()): it = self.FindItemByPosition(i) if not it.IsEnabled(): return False return True
Recursively find a menu item by its id ( useful for event handlers )
def find(self, item_id=None): "Recursively find a menu item by its id (useful for event handlers)" for it in self: if it.id == item_id: return it elif isinstance(it, Menu): found = it.find(item_id) if found: return found
enable or disable all top menus
def Enable(self, value): "enable or disable all top menus" for i in range(self.GetMenuCount()): self.EnableTop(i, value)
check if all top menus are enabled
def IsEnabled(self, *args, **kwargs): "check if all top menus are enabled" for i in range(self.GetMenuCount()): if not self.IsEnabledTop(i): return False return True
Helper method to remove a menu avoiding using its position
def RemoveItem(self, menu): "Helper method to remove a menu avoiding using its position" menus = self.GetMenus() # get the list of (menu, title) menus = [submenu for submenu in menus if submenu[0] != menu] self.SetMenus(menus)
Recursively find a menu item by its id ( useful for event handlers )
def find(self, item_id=None): "Recursively find a menu item by its id (useful for event handlers)" for it in self: found = it.find(item_id) if found: return found
Process form submission
def submit(self, btn=None): "Process form submission" data = self.build_data_set() if btn and btn.name: data[btn.name] = btn.name evt = FormSubmitEvent(self, data) self.container.ProcessEvent(evt)
Construct a sequence of name/ value pairs from controls
def build_data_set(self): "Construct a sequence of name/value pairs from controls" data = {} for field in self.fields: if field.name:# and field.enabled: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! val = field.get_value() if val is None: continue elif isinstance(val, unicode): # web2py string processing # requires utf-8 encoded text val = val.encode("utf-8") data[field.name] = val return data
Add a tag attribute to the wx window
def setObjectTag(self, object, tag): """ Add a tag attribute to the wx window """ object._attributes = {} object._name = tag.GetName().lower() for name in self.attributes: object._attributes["_%s" % name] = tag.GetParam(name) if object._attributes["_%s" % name] == "": object._attributes["_%s" % name] = None
Insert items described in autosummary:: to the TOC tree but do not generate the toctree:: list.
def process_autosummary_toc(app, doctree): """Insert items described in autosummary:: to the TOC tree, but do not generate the toctree:: list. """ env = app.builder.env crawled = {} def crawl_toc(node, depth=1): crawled[node] = True for j, subnode in enumerate(node): try: if (isinstance(subnode, autosummary_toc) and isinstance(subnode[0], addnodes.toctree)): env.note_toctree(env.docname, subnode[0]) continue except IndexError: continue if not isinstance(subnode, nodes.section): continue if subnode not in crawled: crawl_toc(subnode, depth+1) crawl_toc(doctree)
Make the first column of the table non - breaking.
def autosummary_table_visit_html(self, node): """Make the first column of the table non-breaking.""" try: tbody = node[0][0][-1] for row in tbody: col1_entry = row[0] par = col1_entry[0] for j, subnode in enumerate(list(par)): if isinstance(subnode, nodes.Text): new_text = unicode(subnode.astext()) new_text = new_text.replace(u" ", u"\u00a0") par[j] = nodes.Text(new_text) except IndexError: pass
Get an autodoc. Documenter class suitable for documenting the given object.
def get_documenter(obj, parent): """Get an autodoc.Documenter class suitable for documenting the given object. *obj* is the Python object to be documented, and *parent* is an another Python object (e.g. a module or a class) to which *obj* belongs to. """ from sphinx.ext.autodoc import AutoDirective, DataDocumenter, \ ModuleDocumenter if inspect.ismodule(obj): # ModuleDocumenter.can_document_member always returns False return ModuleDocumenter # Construct a fake documenter for *parent* if parent is not None: parent_doc_cls = get_documenter(parent, None) else: parent_doc_cls = ModuleDocumenter if hasattr(parent, '__name__'): parent_doc = parent_doc_cls(FakeDirective(), parent.__name__) else: parent_doc = parent_doc_cls(FakeDirective(), "") # Get the corrent documenter class for *obj* classes = [cls for cls in AutoDirective._registry.values() if cls.can_document_member(obj, '', False, parent_doc)] if classes: classes.sort(key=lambda cls: cls.priority) return classes[-1] else: return DataDocumenter
Reformat a function signature to a more compact form.
def mangle_signature(sig, max_chars=30): """Reformat a function signature to a more compact form.""" s = re.sub(r"^\((.*)\)$", r"\1", sig).strip() # Strip strings (which can contain things that confuse the code below) s = re.sub(r"\\\\", "", s) s = re.sub(r"\\'", "", s) s = re.sub(r"'[^']*'", "", s) # Parse the signature to arguments + options args = [] opts = [] opt_re = re.compile(r"^(.*, |)([a-zA-Z0-9_*]+)=") while s: m = opt_re.search(s) if not m: # The rest are arguments args = s.split(', ') break opts.insert(0, m.group(2)) s = m.group(1)[:-2] # Produce a more compact signature sig = limited_join(", ", args, max_chars=max_chars-2) if opts: if not sig: sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars-4) elif len(sig) < max_chars - 4 - 2 - 3: sig += "[, %s]" % limited_join(", ", opts, max_chars=max_chars-len(sig)-4-2) return u"(%s)" % sig
Join a number of strings to one limiting the length to * max_chars *.
def limited_join(sep, items, max_chars=30, overflow_marker="..."): """Join a number of strings to one, limiting the length to *max_chars*. If the string overflows this limit, replace the last fitting item by *overflow_marker*. Returns: joined_string """ full_str = sep.join(items) if len(full_str) < max_chars: return full_str n_chars = 0 n_items = 0 for j, item in enumerate(items): n_chars += len(item) + len(sep) if n_chars < max_chars - len(overflow_marker): n_items += 1 else: break return sep.join(list(items[:n_items]) + [overflow_marker])
Obtain current Python import prefixes ( for import_by_name ) from document. env
def get_import_prefixes_from_env(env): """ Obtain current Python import prefixes (for `import_by_name`) from ``document.env`` """ prefixes = [None] currmodule = env.temp_data.get('py:module') if currmodule: prefixes.insert(0, currmodule) currclass = env.temp_data.get('py:class') if currclass: if currmodule: prefixes.insert(0, currmodule + "." + currclass) else: prefixes.insert(0, currclass) return prefixes
Import a Python object that has the given * name * under one of the * prefixes *. The first name that succeeds is used.
def import_by_name(name, prefixes=[None]): """Import a Python object that has the given *name*, under one of the *prefixes*. The first name that succeeds is used. """ tried = [] for prefix in prefixes: try: if prefix: prefixed_name = '.'.join([prefix, name]) else: prefixed_name = name obj, parent = _import_by_name(prefixed_name) return prefixed_name, obj, parent except ImportError: tried.append(prefixed_name) raise ImportError('no module named %s' % ' or '.join(tried))
Import a Python object given its full name.
def _import_by_name(name): """Import a Python object given its full name.""" try: name_parts = name.split('.') # try first interpret `name` as MODNAME.OBJ modname = '.'.join(name_parts[:-1]) if modname: try: __import__(modname) mod = sys.modules[modname] return getattr(mod, name_parts[-1]), mod except (ImportError, IndexError, AttributeError): pass # ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ... last_j = 0 modname = None for j in reversed(range(1, len(name_parts)+1)): last_j = j modname = '.'.join(name_parts[:j]) try: __import__(modname) except:# ImportError: continue if modname in sys.modules: break if last_j < len(name_parts): parent = None obj = sys.modules[modname] for obj_name in name_parts[last_j:]: parent = obj obj = getattr(obj, obj_name) return obj, parent else: return sys.modules[modname], None except (ValueError, ImportError, AttributeError, KeyError), e: raise ImportError(*e.args)
Smart linking role.
def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]): """Smart linking role. Expands to ':obj:`text`' if `text` is an object that can be imported; otherwise expands to '*text*'. """ env = inliner.document.settings.env r = env.get_domain('py').role('obj')( 'obj', rawtext, etext, lineno, inliner, options, content) pnode = r[0][0] prefixes = get_import_prefixes_from_env(env) try: name, obj, parent = import_by_name(pnode['reftarget'], prefixes) except ImportError: content = pnode[0] r[0][0] = nodes.emphasis(rawtext, content[0].astext(), classes=content['classes']) return r
Try to import the given names and return a list of [ ( name signature summary_string real_name )... ].
def get_items(self, names): """Try to import the given names, and return a list of ``[(name, signature, summary_string, real_name), ...]``. """ env = self.state.document.settings.env prefixes = get_import_prefixes_from_env(env) items = [] max_item_chars = 50 for name in names: display_name = name if name.startswith('~'): name = name[1:] display_name = name.split('.')[-1] try: real_name, obj, parent = import_by_name(name, prefixes=prefixes) except ImportError: self.warn('failed to import %s' % name) items.append((name, '', '', name)) continue # NB. using real_name here is important, since Documenters # handle module prefixes slightly differently documenter = get_documenter(obj, parent)(self, real_name) if not documenter.parse_name(): self.warn('failed to parse name %s' % real_name) items.append((display_name, '', '', real_name)) continue if not documenter.import_object(): self.warn('failed to import object %s' % real_name) items.append((display_name, '', '', real_name)) continue # -- Grab the signature sig = documenter.format_signature() if not sig: sig = '' else: max_chars = max(10, max_item_chars - len(display_name)) sig = mangle_signature(sig, max_chars=max_chars) sig = sig.replace('*', r'\*') # -- Grab the summary doc = list(documenter.process_doc(documenter.get_doc())) while doc and not doc[0].strip(): doc.pop(0) m = re.search(r"^([A-Z][^A-Z]*?\.\s)", " ".join(doc).strip()) if m: summary = m.group(1).strip() elif doc: summary = doc[0].strip() else: summary = '' items.append((display_name, sig, summary, real_name)) return items
Generate a proper list of table nodes for autosummary:: directive.
def get_table(self, items): """Generate a proper list of table nodes for autosummary:: directive. *items* is a list produced by :meth:`get_items`. """ table_spec = addnodes.tabular_col_spec() table_spec['spec'] = 'll' table = autosummary_table('') real_table = nodes.table('', classes=['longtable']) table.append(real_table) group = nodes.tgroup('', cols=2) real_table.append(group) group.append(nodes.colspec('', colwidth=10)) group.append(nodes.colspec('', colwidth=90)) body = nodes.tbody('') group.append(body) def append_row(*column_texts): row = nodes.row('') for text in column_texts: node = nodes.paragraph('') vl = ViewList() vl.append(text, '<autosummary>') self.state.nested_parse(vl, 0, node) try: if isinstance(node[0], nodes.paragraph): node = node[0] except IndexError: pass row.append(nodes.entry('', node)) body.append(row) for name, sig, summary, real_name in items: qualifier = 'obj' if 'nosignatures' not in self.options: col1 = ':%s:`%s <%s>`\ %s' % (qualifier, name, real_name, sig) else: col1 = ':%s:`%s <%s>`' % (qualifier, name, real_name) col2 = summary append_row(col1, col2) return [table_spec, table]
Show a simple pop - up modal dialog
def alert(message, title="", parent=None, scrolled=False, icon="exclamation"): "Show a simple pop-up modal dialog" if not scrolled: icons = {'exclamation': wx.ICON_EXCLAMATION, 'error': wx.ICON_ERROR, 'question': wx.ICON_QUESTION, 'info': wx.ICON_INFORMATION} style = wx.OK | icons[icon] result = dialogs.messageDialog(parent, message, title, style) else: result = dialogs.scrolledMessageDialog(parent, message, title)
Modal dialog asking for an input returns string or None if cancelled
def prompt(message="", title="", default="", multiline=False, password=None, parent=None): "Modal dialog asking for an input, returns string or None if cancelled" if password: style = wx.TE_PASSWORD | wx.OK | wx.CANCEL result = dialogs.textEntryDialog(parent, message, title, default, style) elif multiline: style = wx.TE_MULTILINE | wx.OK | wx.CANCEL result = dialogs.textEntryDialog(parent, message, title, default, style) # workaround for Mac OS X result.text = '\n'.join(result.text.splitlines()) else: result = dialogs.textEntryDialog(parent, message, title, default) if result.accepted: return result.text
Ask for confirmation ( yes/ no or ok and cancel ) returns True or False
def confirm(message="", title="", default=False, ok=False, cancel=False, parent=None): "Ask for confirmation (yes/no or ok and cancel), returns True or False" style = wx.CENTRE if ok: style |= wx.OK else: style |= wx.YES | wx.NO if default: style |= wx.YES_DEFAULT else: style |= wx.NO_DEFAULT if cancel: style |= wx.CANCEL result = dialogs.messageDialog(parent, message, title, style) if cancel and result.returned == wx.ID_CANCEL: return None return result.accepted
Show a dialog to select a font
def select_font(message="", title="", font=None, parent=None): "Show a dialog to select a font" if font is not None: wx_font = font._get_wx_font() # use as default else: wx_font = None font = Font() # create an empty font result = dialogs.fontDialog(parent, font=wx_font) if result.accepted: font_data = result.fontData result.color = result.fontData.GetColour().Get() wx_font = result.fontData.GetChosenFont() font.set_wx_font(wx_font) wx_font = None return font
Show a dialog to pick a color
def select_color(message="", title="", color=None, parent=None): "Show a dialog to pick a color" result = dialogs.colorDialog(parent, color=color) return result.accepted and result.color
Show a dialog to select files to open return path ( s ) if accepted
def open_file(title="Open", directory='', filename='', wildcard='All Files (*.*)|*.*', multiple=False, parent=None): "Show a dialog to select files to open, return path(s) if accepted" style = wx.OPEN if multiple: style |= wx.MULTIPLE result = dialogs.fileDialog(parent, title, directory, filename, wildcard, style) if result.paths and not multiple: return result.paths[0] else: return result.paths
Show a dialog to select file to save return path ( s ) if accepted
def save_file(title="Save", directory='', filename='', wildcard='All Files (*.*)|*.*', overwrite=False, parent=None): "Show a dialog to select file to save, return path(s) if accepted" style = wx.SAVE if not overwrite: style |= wx.OVERWRITE_PROMPT result = dialogs.fileDialog(parent, title, directory, filename, wildcard, style) return result.paths
Show a dialog to choose a directory
def choose_directory(message='Choose a directory', path="", parent=None): "Show a dialog to choose a directory" result = dialogs.directoryDialog(parent, message, path) return result.path
Shows a find text dialog
def find(default='', whole_words=0, case_sensitive=0, parent=None): "Shows a find text dialog" result = dialogs.findDialog(parent, default, whole_words, case_sensitive) return {'text': result.searchText, 'whole_words': result.wholeWordsOnly, 'case_sensitive': result.caseSensitive}
Remove all items and reset internal structures
def clear(self): "Remove all items and reset internal structures" dict.clear(self) self._key = 0 if hasattr(self._tree_view, "wx_obj"): self._tree_view.wx_obj.DeleteAllItems()
Force appearance of the button next to the item
def set_has_children(self, has_children=True): "Force appearance of the button next to the item" # This is useful to allow the user to expand the items which don't have # any children now, but instead adding them only when needed, thus # minimizing memory usage and loading time. self._tree_model._tree_view.wx_obj.SetItemHasChildren(self.wx_item, has_children)