Search is not available for this dataset
text
stringlengths
75
104k
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 >...
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()
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 ...
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(...
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()
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("ite...
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)
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
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]
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) ...
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, ...
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, sp...
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 isins...
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 ...
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) ...
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)
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 pare...
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)
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) ...
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 ...
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 ...
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) ...
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 s...
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 positio...
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, ...
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[s...
def rebuild(self, **kwargs): "Update a property value with (used by the designer)" for name, value in kwargs.items(): setattr(self, name, value)
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()) ...
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(...
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)
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
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_R...
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)
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.rende...
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 =...
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 >...
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...
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...
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.Clea...
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(w...
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)
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.SetStringS...
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 ...
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)
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_N...
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) ...
def Enable(self, value): "enable or disable all menu items" for i in range(self.GetMenuItemCount()): it = self.FindItemByPosition(i) it.Enable(value)
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
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: ...
def Enable(self, value): "enable or disable all top menus" for i in range(self.GetMenuCount()): self.EnableTop(i, value)
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
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)
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
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)
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: ...
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] ==...
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): ...
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(sub...
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 AutoD...
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"'[^']*'", "...
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(fu...
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'...
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]) ...
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 = s...
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('o...
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 ...
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 = n...
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 | ic...
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, def...
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...
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 ...
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
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, ti...
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.fileDial...
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
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}
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()
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. ...
def bitmap_type(filename): """ Get the type of an image from the file's extension ( .jpg, etc. ) """ if filename == '': return None name, ext = os.path.splitext(filename) ext = ext[1:].upper() if ext == 'BMP': return wx.BITMAP_TYPE_BMP elif ext == 'GIF': ...
def _getbitmap_type( self, filename ) : """ Get the type of an image from the file's extension ( .jpg, etc. ) """ # KEA 2001-07-27 # was #name, ext = filename.split( '.' ) #ext = ext.upper() if filename is None or filename == '': retur...
def _set_icon(self, icon=None): """Set icon based on resource values""" if icon is not None: try: wx_icon = wx.Icon(icon, wx.BITMAP_TYPE_ICO) self.wx_obj.SetIcon(wx_icon) except: pass
def show(self, value=True, modal=None): "Display or hide the window, optionally disabling all other windows" self.wx_obj.Show(value) if modal: # disable all top level windows of this application (MakeModal) disabler = wx.WindowDisabler(self.wx_obj) # cre...
def draw_arc(self, x1y1, x2y2, xcyc): """ Draws an arc of a circle, centered on (xc, yc), with starting point (x1, y1) and ending at (x2, y2). The current pen is used for the outline and the current brush for filling the shape. The arc is drawn in an anticlockwise direction from...
def resize(self, evt=None): "automatically adjust relative pos and size of children controls" for child in self: if isinstance(child, Control): child.resize(evt) # call original handler (wx.HtmlWindow) if evt: evt.Skip()
def parse(filename=""): "Open, read and eval the resource from the source file" # use the provided resource file: s = open(filename).read() ##s.decode("latin1").encode("utf8") import datetime, decimal rsrc = eval(s) return rsrc
def save(filename, rsrc): "Save the resource to the source file" s = pprint.pformat(rsrc) ## s = s.encode("utf8") open(filename, "w").write(s)
def load(controller=None, filename="", name=None, rsrc=None): "Create the GUI objects defined in the resource (filename or python struct)" # if no filename is given, search for the rsrc.py with the same module name: if not filename and not rsrc: if isinstance(controller, types.ClassType): ...
def build_window(res): "Create a gui2py window based on the python resource" # windows specs (parameters) kwargs = dict(res.items()) wintype = kwargs.pop('type') menubar = kwargs.pop('menubar', None) components = kwargs.pop('components') panel = kwargs.pop('panel', {}) from gui...
def build_component(res, parent=None): "Create a gui2py control based on the python resource" # control specs (parameters) kwargs = dict(res.items()) comtype = kwargs.pop('type') if 'components' in res: components = kwargs.pop('components') elif comtype == 'Menu' and 'items' in res: ...
def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal, datetime from .font import Font from .graphic import Bitmap, Color from . import registry ret = {'type': obj.__class__.__name_...
def connect(component, controller=None): "Associate event handlers " # get the controller functions and names (module or class) if not controller or isinstance(controller, dict): if not controller: controller = util.get_caller_module_dict() controller_name = controller['__na...
def convert(self, name): "translate gui2py attribute name from pythoncard legacy code" new_name = PYTHONCARD_PROPERTY_MAP.get(name) if new_name: print "WARNING: property %s should be %s (%s)" % (name, new_name, self.obj.name) return new_name else: retu...
def get_data(): "Read from the clipboard content, return a suitable object (string or bitmap)" data = None try: if wx.TheClipboard.Open(): if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): do = wx.TextDataObject() wx.TheClipboard.GetData(do) ...
def set_data(data): "Write content to the clipboard, data can be either a string or a bitmap" try: if wx.TheClipboard.Open(): if isinstance(data, (str, unicode)): do = wx.TextDataObject() do.SetText(data) wx.TheClipboard.SetData(do) ...
def find_autosummary_in_files(filenames): """Find out what items are documented in source/*.rst. See `find_autosummary_in_lines`. """ documented = [] for filename in filenames: f = open(filename, 'r') lines = f.read().splitlines() documented.extend(find_autosummary_in_lines(...
def find_autosummary_in_docstring(name, module=None, filename=None): """Find out what items are documented in the given object's docstring. See `find_autosummary_in_lines`. """ try: real_name, obj, parent = import_by_name(name) lines = pydoc.getdoc(obj).splitlines() return find_...
def find_autosummary_in_lines(lines, module=None, filename=None): """Find out what items appear in autosummary:: directives in the given lines. Returns a list of (name, toctree, template) where *name* is a name of an object and *toctree* the :toctree: path of the corresponding autosummary directive...
def load_object(self, obj=None): "Add the object and all their childs" # if not obj is given, do a full reload using the current root if obj: self.root_obj = obj else: obj = self.root_obj self.tree.DeleteAllItems() self.root = self.tree.AddRoot("ap...
def inspect(self, obj, context_menu=False, edit_prop=False, mouse_pos=None): "Select the object and show its properties" child = self.tree.FindItem(self.root, obj.name) if DEBUG: print "inspect child", child if child: self.tree.ScrollTo(child) self.tree.SetCurrent...
def activate_item(self, child, edit_prop=False, select=False): "load the selected item in the property editor" d = self.tree.GetItemData(child) if d: o = d.GetData() self.selected_obj = o callback = lambda o=o, **kwargs: self.update(o, **kwargs) se...