INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns wx.Pen from pendata attribute list
def get_pen_from_data(pendata): """Returns wx.Pen from pendata attribute list""" pen_color = wx.Colour() pen_color.SetRGB(pendata[0]) pen = wx.Pen(pen_color, *pendata[1:]) pen.SetJoin(wx.JOIN_MITER) return pen
Returns wx.Colour from a string of a 3-tuple of floats in [0.0, 1.0]
def code2color(color_string): """Returns wx.Colour from a string of a 3-tuple of floats in [0.0, 1.0]""" color_tuple = ast.literal_eval(color_string) color_tuple_int = map(lambda x: int(x * 255.0), color_tuple) return wx.Colour(*color_tuple_int)
Returns r, g, b tuple from packed wx.ColourGetRGB value
def color_pack2rgb(packed): """Returns r, g, b tuple from packed wx.ColourGetRGB value""" r = packed & 255 g = (packed & (255 << 8)) >> 8 b = (packed & (255 << 16)) >> 16 return r, g, b
Returns a string from code that contains a repr of the string
def unquote_string(code): """Returns a string from code that contains a repr of the string""" scode = code.strip() assert scode[-1] in ["'", '"'] assert scode[0] in ["'", '"'] or scode[1] in ["'", '"'] return ast.literal_eval(scode)
Generator of elements of a dict that is given in the code string Parsing is shallow, i.e. all content is yielded as strings Parameters ---------- code: String \tString that contains a dict
def parse_dict_strings(code): """Generator of elements of a dict that is given in the code string Parsing is shallow, i.e. all content is yielded as strings Parameters ---------- code: String \tString that contains a dict """ i = 0 level = 0 chunk_start = 0 curr_paren = None for i, char in enumerate(code): if char in ["(", "[", "{"] and curr_paren is None: level += 1 elif char in [")", "]", "}"] and curr_paren is None: level -= 1 elif char in ['"', "'"]: if curr_paren == char: curr_paren = None elif curr_paren is None: curr_paren = char if level == 0 and char in [':', ','] and curr_paren is None: yield code[chunk_start: i].strip() chunk_start = i + 1 yield code[chunk_start:i + 1].strip()
Returns start sub-string that is common for all given strings Parameters ---------- strings: List of strings \tThese strings are evaluated for their largest common start string
def common_start(strings): """Returns start sub-string that is common for all given strings Parameters ---------- strings: List of strings \tThese strings are evaluated for their largest common start string """ def gen_start_strings(string): """Generator that yield start sub-strings of length 1, 2, ...""" for i in xrange(1, len(string) + 1): yield string[:i] # Empty strings list if not strings: return "" start_string = "" # Get sucessively start string of 1st string for start_string in gen_start_strings(max(strings)): if not all(string.startswith(start_string) for string in strings): return start_string[:-1] return start_string
Checks if code is an svg image Parameters ---------- code: String \tCode to be parsed in order to check svg complaince
def is_svg(code): """Checks if code is an svg image Parameters ---------- code: String \tCode to be parsed in order to check svg complaince """ if rsvg is None: return try: rsvg.Handle(data=code) except glib.GError: return False # The SVG file has to refer to its xmlns # Hopefully, it does so wiyhin the first 1000 characters if "http://www.w3.org/2000/svg" in code[:1000]: return True return False
Returns title string
def _get_dialog_title(self): """Returns title string""" title_filetype = self.filetype[0].upper() + self.filetype[1:] if self.filetype == "print": title_export = "" else: title_export = " export" return _("{filetype}{export} options").format(filetype=title_filetype, export=title_export)
Page layout choice event handler
def on_page_layout_choice(self, event): """Page layout choice event handler""" width, height = self.paper_sizes_points[event.GetString()] self.page_width_text_ctrl.SetValue(str(width / 72.0)) self.page_height_text_ctrl.SetValue(str(height / 72.0)) event.Skip()
Returns a dict with the dialog PDF info Dict keys are: top_row, bottom_row, left_col, right_col, first_tab, last_tab, paper_width, paper_height
def get_info(self): """Returns a dict with the dialog PDF info Dict keys are: top_row, bottom_row, left_col, right_col, first_tab, last_tab, paper_width, paper_height """ info = {} info["top_row"] = self.top_row_text_ctrl.GetValue() info["bottom_row"] = self.bottom_row_text_ctrl.GetValue() info["left_col"] = self.left_col_text_ctrl.GetValue() info["right_col"] = self.right_col_text_ctrl.GetValue() info["first_tab"] = self.first_tab_text_ctrl.GetValue() info["last_tab"] = self.last_tab_text_ctrl.GetValue() if self.filetype != "print": # If printing and not exporting then page info is # gathered from printer dialog info["paper_width"] = float( self.page_width_text_ctrl.GetValue()) * 72.0 info["paper_height"] = float( self.page_height_text_ctrl.GetValue()) * 72.0 if self.portrait_landscape_radio_box.GetSelection() == 0: orientation = "portrait" elif self.portrait_landscape_radio_box.GetSelection() == 1: orientation = "landscape" else: raise ValueError("Orientation not in portrait or landscape") info["orientation"] = orientation return info
Returns the path in which pyspread is installed
def get_program_path(): """Returns the path in which pyspread is installed""" src_folder = os.path.dirname(__file__) program_path = os.sep.join(src_folder.split(os.sep)[:-1]) + os.sep return program_path
Returns screen dpi resolution
def get_dpi(): """Returns screen dpi resolution""" def pxmm_2_dpi((pixels, length_mm)): return pixels * 25.6 / length_mm return map(pxmm_2_dpi, zip(wx.GetDisplaySize(), wx.GetDisplaySizeMM()))
Returns a sorted list of all system font names
def get_font_list(): """Returns a sorted list of all system font names""" font_map = pangocairo.cairo_font_map_get_default() font_list = [f.get_name() for f in font_map.list_families()] font_list.sort() return font_list
Returns list of dicts which indicate installed dependencies
def get_dependencies(): """Returns list of dicts which indicate installed dependencies""" dependencies = [] # Numpy dep_attrs = { "name": "numpy", "min_version": "1.1.0", "description": "required", } try: import numpy dep_attrs["version"] = numpy.version.version except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # wxPython dep_attrs = { "name": "wxPython", "min_version": "2.8.10.1", "description": "required", } try: import wx dep_attrs["version"] = wx.version() except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # Matplotlib dep_attrs = { "name": "matplotlib", "min_version": "1.1.1", "description": "required", } try: import matplotlib dep_attrs["version"] = matplotlib._version.get_versions()["version"] except ImportError: dep_attrs["version"] = None except AttributeError: # May happen in old matplotlib versions dep_attrs["version"] = matplotlib.__version__ dependencies.append(dep_attrs) # Pycairo dep_attrs = { "name": "pycairo", "min_version": "1.8.8", "description": "required", } try: import cairo dep_attrs["version"] = cairo.version except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # Python GnuPG dep_attrs = { "name": "python-gnupg", "min_version": "0.3.0", "description": "for opening own files without approval", } try: import gnupg dep_attrs["version"] = gnupg.__version__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # xlrd dep_attrs = { "name": "xlrd", "min_version": "0.9.2", "description": "for loading Excel files", } try: import xlrd dep_attrs["version"] = xlrd.__VERSION__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # xlwt dep_attrs = { "name": "xlwt", "min_version": "0.7.2", "description": "for saving Excel files", } try: import xlwt dep_attrs["version"] = xlwt.__VERSION__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # Jedi dep_attrs = { "name": "jedi", "min_version": "0.8.0", "description": "for tab completion and context help in the entry line", } try: import jedi dep_attrs["version"] = jedi.__version__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # pyrsvg dep_attrs = { "name": "pyrsvg", "min_version": "2.32", "description": "for displaying SVG files in cells", } try: import rsvg dep_attrs["version"] = True except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # pyenchant dep_attrs = { "name": "pyenchant", "min_version": "1.6.6", "description": "for spell checking", } try: import enchant dep_attrs["version"] = enchant.__version__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) return dependencies
Returns rectangle of cell on canvas
def get_cell_rect(self, row, col, tab): """Returns rectangle of cell on canvas""" top_row = self.row_tb[0] left_col = self.col_rl[0] pos_x = self.x_offset pos_y = self.y_offset merge_area = self._get_merge_area((row, col, tab)) for __row in xrange(top_row, row): __row_height = self.code_array.get_row_height(__row, tab) pos_y += __row_height for __col in xrange(left_col, col): __col_width = self.code_array.get_col_width(__col, tab) pos_x += __col_width if merge_area is None: height = self.code_array.get_row_height(row, tab) width = self.code_array.get_col_width(col, tab) else: # We have a merged cell top, left, bottom, right = merge_area # Are we drawing the top left cell? if top == row and left == col: # Set rect to merge area heights = (self.code_array.get_row_height(__row, tab) for __row in xrange(top, bottom+1)) widths = (self.code_array.get_col_width(__col, tab) for __col in xrange(left, right+1)) height = sum(heights) width = sum(widths) else: # Do not draw the cell because it is hidden return return pos_x, pos_y, width, height
Draws slice to context
def draw(self): """Draws slice to context""" row_start, row_stop = self.row_tb col_start, col_stop = self.col_rl tab_start, tab_stop = self.tab_fl for tab in xrange(tab_start, tab_stop): # Scale context to page extent # In order to keep the aspect ration intact use the maximum first_key = row_start, col_start, tab first_rect = self.get_cell_rect(*first_key) # If we have a merged cell then use the top left cell rect if first_rect is None: top, left, __, __ = self._get_merge_area(first_key) first_rect = self.get_cell_rect(top, left, tab) last_key = row_stop - 1, col_stop - 1, tab last_rect = self.get_cell_rect(*last_key) # If we have a merged cell then use the top left cell rect if last_rect is None: top, left, __, __ = self._get_merge_area(last_key) last_rect = self.get_cell_rect(top, left, tab) x_extent = last_rect[0] + last_rect[2] - first_rect[0] y_extent = last_rect[1] + last_rect[3] - first_rect[1] scale_x = (self.width - 2 * self.x_offset) / float(x_extent) scale_y = (self.height - 2 * self.y_offset) / float(y_extent) self.context.save() # Translate offset to o self.context.translate(first_rect[0], first_rect[1]) # Scale to fit page, do not change aspect ratio scale = min(scale_x, scale_y) self.context.scale(scale, scale) # Translate offset self.context.translate(-self.x_offset, -self.y_offset) # TODO: Center the grid on the page # Render cells for row in xrange(row_start, row_stop): for col in xrange(col_start, col_stop): key = row, col, tab rect = self.get_cell_rect(row, col, tab) # Rect if rect is not None: cell_renderer = GridCellCairoRenderer( self.context, self.code_array, key, # (row, col, tab) rect, self.view_frozen ) cell_renderer.draw() # Undo scaling, translation, ... self.context.restore() self.context.show_page()
Draws cell to context
def draw(self): """Draws cell to context""" cell_background_renderer = GridCellBackgroundCairoRenderer( self.context, self.code_array, self.key, self.rect, self.view_frozen) cell_content_renderer = GridCellContentCairoRenderer( self.context, self.code_array, self.key, self.rect, self.spell_check) cell_border_renderer = GridCellBorderCairoRenderer( self.context, self.code_array, self.key, self.rect) cell_background_renderer.draw() cell_content_renderer.draw() cell_border_renderer.draw()
Returns cell content
def get_cell_content(self): """Returns cell content""" try: if self.code_array.cell_attributes[self.key]["button_cell"]: return except IndexError: return try: return self.code_array[self.key] except IndexError: pass
Returns scale_x, scale_y for bitmap display
def _get_scalexy(self, ims_width, ims_height): """Returns scale_x, scale_y for bitmap display""" # Get cell attributes cell_attributes = self.code_array.cell_attributes[self.key] angle = cell_attributes["angle"] if abs(angle) == 90: scale_x = self.rect[3] / float(ims_width) scale_y = self.rect[2] / float(ims_height) else: # Normal case scale_x = self.rect[2] / float(ims_width) scale_y = self.rect[3] / float(ims_height) return scale_x, scale_y
Returns x and y for a bitmap translation
def _get_translation(self, ims_width, ims_height): """Returns x and y for a bitmap translation""" # Get cell attributes cell_attributes = self.code_array.cell_attributes[self.key] justification = cell_attributes["justification"] vertical_align = cell_attributes["vertical_align"] angle = cell_attributes["angle"] scale_x, scale_y = self._get_scalexy(ims_width, ims_height) scale = min(scale_x, scale_y) if angle not in (90, 180, -90): # Standard direction x = -2 # Otherwise there is a white border y = -2 # Otherwise there is a white border if scale_x > scale_y: if justification == "center": x += (self.rect[2] - ims_width * scale) / 2 elif justification == "right": x += self.rect[2] - ims_width * scale else: if vertical_align == "middle": y += (self.rect[3] - ims_height * scale) / 2 elif vertical_align == "bottom": y += self.rect[3] - ims_height * scale if angle == 90: x = -ims_width * scale + 2 y = -2 if scale_y > scale_x: if justification == "center": y += (self.rect[2] - ims_height * scale) / 2 elif justification == "right": y += self.rect[2] - ims_height * scale else: if vertical_align == "middle": x -= (self.rect[3] - ims_width * scale) / 2 elif vertical_align == "bottom": x -= self.rect[3] - ims_width * scale elif angle == 180: x = -ims_width * scale + 2 y = -ims_height * scale + 2 if scale_x > scale_y: if justification == "center": x -= (self.rect[2] - ims_width * scale) / 2 elif justification == "right": x -= self.rect[2] - ims_width * scale else: if vertical_align == "middle": y -= (self.rect[3] - ims_height * scale) / 2 elif vertical_align == "bottom": y -= self.rect[3] - ims_height * scale elif angle == -90: x = -2 y = -ims_height * scale + 2 if scale_y > scale_x: if justification == "center": y -= (self.rect[2] - ims_height * scale) / 2 elif justification == "right": y -= self.rect[2] - ims_height * scale else: if vertical_align == "middle": x += (self.rect[3] - ims_width * scale) / 2 elif vertical_align == "bottom": x += self.rect[3] - ims_width * scale return x, y
Draws bitmap cell content to context
def draw_bitmap(self, content): """Draws bitmap cell content to context""" if content.HasAlpha(): image = wx.ImageFromBitmap(content) image.ConvertAlphaToMask() image.SetMask(False) content = wx.BitmapFromImage(image) ims = wx.lib.wxcairo.ImageSurfaceFromBitmap(content) ims_width = ims.get_width() ims_height = ims.get_height() transx, transy = self._get_translation(ims_width, ims_height) scale_x, scale_y = self._get_scalexy(ims_width, ims_height) scale = min(scale_x, scale_y) angle = float(self.code_array.cell_attributes[self.key]["angle"]) self.context.save() self.context.rotate(-angle / 360 * 2 * math.pi) self.context.translate(transx, transy) self.context.scale(scale, scale) self.context.set_source_surface(ims, 0, 0) self.context.paint() self.context.restore()
Draws svg string to cell
def draw_svg(self, svg_str): """Draws svg string to cell""" try: import rsvg except ImportError: self.draw_text(svg_str) return svg = rsvg.Handle(data=svg_str) svg_width, svg_height = svg.get_dimension_data()[:2] transx, transy = self._get_translation(svg_width, svg_height) scale_x, scale_y = self._get_scalexy(svg_width, svg_height) scale = min(scale_x, scale_y) angle = float(self.code_array.cell_attributes[self.key]["angle"]) self.context.save() self.context.rotate(-angle / 360 * 2 * math.pi) self.context.translate(transx, transy) self.context.scale(scale, scale) svg.render_cairo(self.context) self.context.restore()
Draws matplotlib figure to context
def draw_matplotlib_figure(self, figure): """Draws matplotlib figure to context""" class CustomRendererCairo(RendererCairo): """Workaround for older versins with limited draw path length""" if sys.byteorder == 'little': BYTE_FORMAT = 0 # BGRA else: BYTE_FORMAT = 1 # ARGB def draw_path(self, gc, path, transform, rgbFace=None): ctx = gc.ctx transform = transform + Affine2D().scale(1.0, -1.0).\ translate(0, self.height) ctx.new_path() self.convert_path(ctx, path, transform) try: self._fill_and_stroke(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) except AttributeError: # Workaround for some Windiws version of Cairo self._fill_and_stroke(ctx, rgbFace, gc.get_alpha()) def draw_image(self, gc, x, y, im): # bbox - not currently used rows, cols, buf = im.color_conv(self.BYTE_FORMAT) surface = cairo.ImageSurface.create_for_data( buf, cairo.FORMAT_ARGB32, cols, rows, cols*4) ctx = gc.ctx y = self.height - y - rows ctx.save() ctx.set_source_surface(surface, x, y) if gc.get_alpha() != 1.0: ctx.paint_with_alpha(gc.get_alpha()) else: ctx.paint() ctx.restore() if pyplot is None: # Matplotlib is not installed return FigureCanvasCairo(figure) dpi = float(figure.dpi) # Set a border so that the figure is not cut off at the cell border border_x = 200 / (self.rect[2] / dpi) ** 2 border_y = 200 / (self.rect[3] / dpi) ** 2 width = (self.rect[2] - 2 * border_x) / dpi height = (self.rect[3] - 2 * border_y) / dpi figure.set_figwidth(width) figure.set_figheight(height) renderer = CustomRendererCairo(dpi) renderer.set_width_height(width, height) renderer.gc.ctx = self.context renderer.text_ctx = self.context self.context.save() self.context.translate(border_x, border_y + height * dpi) figure.draw(renderer) self.context.restore()
Returns text color rgb tuple of right line
def _get_text_color(self): """Returns text color rgb tuple of right line""" color = self.code_array.cell_attributes[self.key]["textcolor"] return tuple(c / 255.0 for c in color_pack2rgb(color))
Sets the font for draw_text
def set_font(self, pango_layout): """Sets the font for draw_text""" wx2pango_weights = { wx.FONTWEIGHT_BOLD: pango.WEIGHT_BOLD, wx.FONTWEIGHT_LIGHT: pango.WEIGHT_LIGHT, wx.FONTWEIGHT_NORMAL: None, # Do not set a weight by default } wx2pango_styles = { wx.FONTSTYLE_NORMAL: None, # Do not set a style by default wx.FONTSTYLE_SLANT: pango.STYLE_OBLIQUE, wx.FONTSTYLE_ITALIC: pango.STYLE_ITALIC, } cell_attributes = self.code_array.cell_attributes[self.key] # Text font attributes textfont = cell_attributes["textfont"] pointsize = cell_attributes["pointsize"] fontweight = cell_attributes["fontweight"] fontstyle = cell_attributes["fontstyle"] underline = cell_attributes["underline"] strikethrough = cell_attributes["strikethrough"] # Now construct the pango font font_description = pango.FontDescription( " ".join([textfont, str(pointsize)])) pango_layout.set_font_description(font_description) attrs = pango.AttrList() # Underline attrs.insert(pango.AttrUnderline(underline, 0, MAX_RESULT_LENGTH)) # Weight weight = wx2pango_weights[fontweight] if weight is not None: attrs.insert(pango.AttrWeight(weight, 0, MAX_RESULT_LENGTH)) # Style style = wx2pango_styles[fontstyle] if style is not None: attrs.insert(pango.AttrStyle(style, 0, MAX_RESULT_LENGTH)) # Strikethrough attrs.insert(pango.AttrStrikethrough(strikethrough, 0, MAX_RESULT_LENGTH)) pango_layout.set_attributes(attrs)
Rotates and translates cell if angle in [90, -90, 180]
def _rotate_cell(self, angle, rect, back=False): """Rotates and translates cell if angle in [90, -90, 180]""" if angle == 90 and not back: self.context.rotate(-math.pi / 2.0) self.context.translate(-rect[2] + 4, 0) elif angle == 90 and back: self.context.translate(rect[2] - 4, 0) self.context.rotate(math.pi / 2.0) elif angle == -90 and not back: self.context.rotate(math.pi / 2.0) self.context.translate(0, -rect[3] + 2) elif angle == -90 and back: self.context.translate(0, rect[3] - 2) self.context.rotate(-math.pi / 2.0) elif angle == 180 and not back: self.context.rotate(math.pi) self.context.translate(-rect[2] + 4, -rect[3] + 2) elif angle == 180 and back: self.context.translate(rect[2] - 4, rect[3] - 2) self.context.rotate(-math.pi)
Draws an error underline
def _draw_error_underline(self, ptx, pango_layout, start, stop): """Draws an error underline""" self.context.save() self.context.set_source_rgb(1.0, 0.0, 0.0) pit = pango_layout.get_iter() # Skip characters until start for i in xrange(start): pit.next_char() extents_list = [] for char_no in xrange(start, stop): char_extents = pit.get_char_extents() underline_pixel_extents = [ char_extents[0] / pango.SCALE, (char_extents[1] + char_extents[3]) / pango.SCALE - 2, char_extents[2] / pango.SCALE, 4, ] if extents_list: if extents_list[-1][1] == underline_pixel_extents[1]: # Same line extents_list[-1][2] = extents_list[-1][2] + \ underline_pixel_extents[2] else: # Line break extents_list.append(underline_pixel_extents) else: extents_list.append(underline_pixel_extents) pit.next_char() for extent in extents_list: pangocairo.show_error_underline(ptx, *extent) self.context.restore()
Returns a list of start stop tuples that have spelling errors Parameters ---------- text: Unicode or string \tThe text that is checked lang: String, defaults to "en_US" \tName of spell checking dictionary
def _check_spelling(self, text, lang="en_US"): """Returns a list of start stop tuples that have spelling errors Parameters ---------- text: Unicode or string \tThe text that is checked lang: String, defaults to "en_US" \tName of spell checking dictionary """ chkr = SpellChecker(lang) chkr.set_text(text) word_starts_ends = [] for err in chkr: start = err.wordpos stop = err.wordpos + len(err.word) + 1 word_starts_ends.append((start, stop)) return word_starts_ends
Draws text cell content to context
def draw_text(self, content): """Draws text cell content to context""" wx2pango_alignment = { "left": pango.ALIGN_LEFT, "center": pango.ALIGN_CENTER, "right": pango.ALIGN_RIGHT, } cell_attributes = self.code_array.cell_attributes[self.key] angle = cell_attributes["angle"] if angle in [-90, 90]: rect = self.rect[1], self.rect[0], self.rect[3], self.rect[2] else: rect = self.rect # Text color attributes self.context.set_source_rgb(*self._get_text_color()) ptx = pangocairo.CairoContext(self.context) pango_layout = ptx.create_layout() self.set_font(pango_layout) pango_layout.set_wrap(pango.WRAP_WORD_CHAR) pango_layout.set_width(int(round((rect[2] - 4.0) * pango.SCALE))) try: markup = cell_attributes["markup"] except KeyError: # Old file markup = False if markup: with warnings.catch_warnings(record=True) as warning_lines: warnings.resetwarnings() warnings.simplefilter("always") pango_layout.set_markup(unicode(content)) if warning_lines: w2unicode = lambda m: unicode(m.message) msg = u"\n".join(map(w2unicode, warning_lines)) pango_layout.set_text(msg) else: pango_layout.set_text(unicode(content)) alignment = cell_attributes["justification"] pango_layout.set_alignment(wx2pango_alignment[alignment]) # Shift text for vertical alignment extents = pango_layout.get_pixel_extents() downshift = 0 if cell_attributes["vertical_align"] == "bottom": downshift = rect[3] - extents[1][3] - 4 elif cell_attributes["vertical_align"] == "middle": downshift = int((rect[3] - extents[1][3]) / 2) - 2 self.context.save() self._rotate_cell(angle, rect) self.context.translate(0, downshift) # Spell check underline drawing if SpellChecker is not None and self.spell_check: text = unicode(pango_layout.get_text()) lang = config["spell_lang"] for start, stop in self._check_spelling(text, lang=lang): self._draw_error_underline(ptx, pango_layout, start, stop-1) ptx.update_layout(pango_layout) ptx.show_layout(pango_layout) self.context.restore()
Draws a rounded rectangle
def draw_roundedrect(self, x, y, w, h, r=10): """Draws a rounded rectangle""" # A****BQ # H C # * * # G D # F****E context = self.context context.save context.move_to(x+r, y) # Move to A context.line_to(x+w-r, y) # Straight line to B context.curve_to(x+w, y, x+w, y, x+w, y+r) # Curve to C # Control points are both at Q context.line_to(x+w, y+h-r) # Move to D context.curve_to(x+w, y+h, x+w, y+h, x+w-r, y+h) # Curve to E context.line_to(x+r, y+h) # Line to F context.curve_to(x, y+h, x, y+h, x, y+h-r) # Curve to G context.line_to(x, y+r) # Line to H context.curve_to(x, y, x, y, x+r, y) # Curve to A context.restore
Draws a button
def draw_button(self, x, y, w, h, label): """Draws a button""" context = self.context self.draw_roundedrect(x, y, w, h) context.clip() # Set up the gradients gradient = cairo.LinearGradient(0, 0, 0, 1) gradient.add_color_stop_rgba(0, 0.5, 0.5, 0.5, 0.1) gradient.add_color_stop_rgba(1, 0.8, 0.8, 0.8, 0.9) # # Transform the coordinates so the width and height are both 1 # # We save the current settings and restore them afterward context.save() context.scale(w, h) context.rectangle(0, 0, 1, 1) context.set_source_rgb(0, 0, 1) context.set_source(gradient) context.fill() context.restore() # Draw the button text # Center the text x_bearing, y_bearing, width, height, x_advance, y_advance = \ context.text_extents(label) text_x = (w / 2.0)-(width / 2.0 + x_bearing) text_y = (h / 2.0)-(height / 2.0 + y_bearing) + 1 # Draw the button text context.move_to(text_x, text_y) context.set_source_rgba(0, 0, 0, 1) context.show_text(label) # Draw the border of the button context.move_to(x, y) context.set_source_rgba(0, 0, 0, 1) self.draw_roundedrect(x, y, w, h) context.stroke()
Draws cell content to context
def draw(self): """Draws cell content to context""" # Content is only rendered within rect self.context.save() self.context.rectangle(*self.rect) self.context.clip() content = self.get_cell_content() pos_x, pos_y = self.rect[:2] self.context.translate(pos_x + 2, pos_y + 2) cell_attributes = self.code_array.cell_attributes # Do not draw cell content if cell is too small # This allows blending out small cells by reducing height to 0 if self.rect[2] < cell_attributes[self.key]["borderwidth_right"] or \ self.rect[3] < cell_attributes[self.key]["borderwidth_bottom"]: self.context.restore() return if self.code_array.cell_attributes[self.key]["button_cell"]: # Render a button instead of the cell label = self.code_array.cell_attributes[self.key]["button_cell"] self.draw_button(1, 1, self.rect[2]-5, self.rect[3]-5, label) elif isinstance(content, wx._gdi.Bitmap): # A bitmap is returned --> Draw it! self.draw_bitmap(content) elif pyplot is not None and isinstance(content, pyplot.Figure): # A matplotlib figure is returned --> Draw it! self.draw_matplotlib_figure(content) elif isinstance(content, basestring) and is_svg(content): # The content is a vaid SVG xml string self.draw_svg(content) elif content is not None: self.draw_text(content) self.context.translate(-pos_x - 2, -pos_y - 2) # Remove clipping to rect self.context.restore()
Returns background color rgb tuple of right line
def _get_background_color(self): """Returns background color rgb tuple of right line""" color = self.cell_attributes[self.key]["bgcolor"] return tuple(c / 255.0 for c in color_pack2rgb(color))
Draws frozen pattern, i.e. diagonal lines
def _draw_frozen_pattern(self): """Draws frozen pattern, i.e. diagonal lines""" self.context.save() x, y, w, h = self.rect self.context.set_source_rgb(0, 0, 1) self.context.set_line_width(0.25) self.context.rectangle(*self.rect) self.context.clip() for __x in numpy.arange(x-h, x+w, 5): self.context.move_to(__x, y + h) self.context.line_to(__x + h, y) self.context.stroke() self.context.restore()
Draws self to Cairo context
def draw(self, context): """Draws self to Cairo context""" context.set_line_width(self.width) context.set_source_rgb(*self.color) context.move_to(*self.start_point) context.line_to(*self.end_point) context.stroke()
Draws cell background to context
def draw(self): """Draws cell background to context""" self.context.set_source_rgb(*self._get_background_color()) self.context.rectangle(*self.rect) self.context.fill() # If show frozen is active, show frozen pattern if self.view_frozen and self.cell_attributes[self.key]["frozen"]: self._draw_frozen_pattern()
Returns tuple key rect of above cell
def get_above_key_rect(self): """Returns tuple key rect of above cell""" key_above = self.row - 1, self.col, self.tab border_width_bottom = \ float(self.cell_attributes[key_above]["borderwidth_bottom"]) / 2.0 rect_above = (self.x, self.y-border_width_bottom, self.width, border_width_bottom) return key_above, rect_above
Returns tuple key rect of below cell
def get_below_key_rect(self): """Returns tuple key rect of below cell""" key_below = self.row + 1, self.col, self.tab border_width_bottom = \ float(self.cell_attributes[self.key]["borderwidth_bottom"]) / 2.0 rect_below = (self.x, self.y+self.height, self.width, border_width_bottom) return key_below, rect_below
Returns tuple key rect of left cell
def get_left_key_rect(self): """Returns tuple key rect of left cell""" key_left = self.row, self.col - 1, self.tab border_width_right = \ float(self.cell_attributes[key_left]["borderwidth_right"]) / 2.0 rect_left = (self.x-border_width_right, self.y, border_width_right, self.height) return key_left, rect_left
Returns tuple key rect of right cell
def get_right_key_rect(self): """Returns tuple key rect of right cell""" key_right = self.row, self.col + 1, self.tab border_width_right = \ float(self.cell_attributes[self.key]["borderwidth_right"]) / 2.0 rect_right = (self.x+self.width, self.y, border_width_right, self.height) return key_right, rect_right
Returns tuple key rect of above left cell
def get_above_left_key_rect(self): """Returns tuple key rect of above left cell""" key_above_left = self.row - 1, self.col - 1, self.tab border_width_right = \ float(self.cell_attributes[key_above_left]["borderwidth_right"]) \ / 2.0 border_width_bottom = \ float(self.cell_attributes[key_above_left]["borderwidth_bottom"]) \ / 2.0 rect_above_left = (self.x-border_width_right, self.y-border_width_bottom, border_width_right, border_width_bottom) return key_above_left, rect_above_left
Returns tuple key rect of above right cell
def get_above_right_key_rect(self): """Returns tuple key rect of above right cell""" key_above = self.row - 1, self.col, self.tab key_above_right = self.row - 1, self.col + 1, self.tab border_width_right = \ float(self.cell_attributes[key_above]["borderwidth_right"]) / 2.0 border_width_bottom = \ float(self.cell_attributes[key_above_right]["borderwidth_bottom"])\ / 2.0 rect_above_right = (self.x+self.width, self.y-border_width_bottom, border_width_right, border_width_bottom) return key_above_right, rect_above_right
Returns tuple key rect of below left cell
def get_below_left_key_rect(self): """Returns tuple key rect of below left cell""" key_left = self.row, self.col - 1, self.tab key_below_left = self.row + 1, self.col - 1, self.tab border_width_right = \ float(self.cell_attributes[key_below_left]["borderwidth_right"]) \ / 2.0 border_width_bottom = \ float(self.cell_attributes[key_left]["borderwidth_bottom"]) / 2.0 rect_below_left = (self.x-border_width_right, self.y-self.height, border_width_right, border_width_bottom) return key_below_left, rect_below_left
Returns tuple key rect of below right cell
def get_below_right_key_rect(self): """Returns tuple key rect of below right cell""" key_below_right = self.row + 1, self.col + 1, self.tab border_width_right = \ float(self.cell_attributes[self.key]["borderwidth_right"]) / 2.0 border_width_bottom = \ float(self.cell_attributes[self.key]["borderwidth_bottom"]) / 2.0 rect_below_right = (self.x+self.width, self.y-self.height, border_width_right, border_width_bottom) return key_below_right, rect_below_right
Returns start and stop coordinates of bottom line
def _get_bottom_line_coordinates(self): """Returns start and stop coordinates of bottom line""" rect_x, rect_y, rect_width, rect_height = self.rect start_point = rect_x, rect_y + rect_height end_point = rect_x + rect_width, rect_y + rect_height return start_point, end_point
Returns color rgb tuple of bottom line
def _get_bottom_line_color(self): """Returns color rgb tuple of bottom line""" color = self.cell_attributes[self.key]["bordercolor_bottom"] return tuple(c / 255.0 for c in color_pack2rgb(color))
Returns color rgb tuple of right line
def _get_right_line_color(self): """Returns color rgb tuple of right line""" color = self.cell_attributes[self.key]["bordercolor_right"] return tuple(c / 255.0 for c in color_pack2rgb(color))
Returns the bottom border of the cell
def get_b(self): """Returns the bottom border of the cell""" start_point, end_point = self._get_bottom_line_coordinates() width = self._get_bottom_line_width() color = self._get_bottom_line_color() return CellBorder(start_point, end_point, width, color)
Returns the right border of the cell
def get_r(self): """Returns the right border of the cell""" start_point, end_point = self._get_right_line_coordinates() width = self._get_right_line_width() color = self._get_right_line_color() return CellBorder(start_point, end_point, width, color)
Returns the top border of the cell
def get_t(self): """Returns the top border of the cell""" cell_above = CellBorders(self.cell_attributes, *self.cell.get_above_key_rect()) return cell_above.get_b()
Returns the left border of the cell
def get_l(self): """Returns the left border of the cell""" cell_left = CellBorders(self.cell_attributes, *self.cell.get_left_key_rect()) return cell_left.get_r()
Returns the top left border of the cell
def get_tl(self): """Returns the top left border of the cell""" cell_above_left = CellBorders(self.cell_attributes, *self.cell.get_above_left_key_rect()) return cell_above_left.get_r()
Returns the top right border of the cell
def get_tr(self): """Returns the top right border of the cell""" cell_above = CellBorders(self.cell_attributes, *self.cell.get_above_key_rect()) return cell_above.get_r()
Returns the right top border of the cell
def get_rt(self): """Returns the right top border of the cell""" cell_above_right = CellBorders(self.cell_attributes, *self.cell.get_above_right_key_rect()) return cell_above_right.get_b()
Returns the right bottom border of the cell
def get_rb(self): """Returns the right bottom border of the cell""" cell_right = CellBorders(self.cell_attributes, *self.cell.get_right_key_rect()) return cell_right.get_b()
Returns the bottom right border of the cell
def get_br(self): """Returns the bottom right border of the cell""" cell_below = CellBorders(self.cell_attributes, *self.cell.get_below_key_rect()) return cell_below.get_r()
Returns the bottom left border of the cell
def get_bl(self): """Returns the bottom left border of the cell""" cell_below_left = CellBorders(self.cell_attributes, *self.cell.get_below_left_key_rect()) return cell_below_left.get_r()
Returns the left bottom border of the cell
def get_lb(self): """Returns the left bottom border of the cell""" cell_left = CellBorders(self.cell_attributes, *self.cell.get_left_key_rect()) return cell_left.get_b()
Returns the left top border of the cell
def get_lt(self): """Returns the left top border of the cell""" cell_above_left = CellBorders(self.cell_attributes, *self.cell.get_above_left_key_rect()) return cell_above_left.get_b()
Generator of all borders
def gen_all(self): """Generator of all borders""" borderfuncs = [ self.get_b, self.get_r, self.get_t, self.get_l, self.get_tl, self.get_tr, self.get_rt, self.get_rb, self.get_br, self.get_bl, self.get_lb, self.get_lt, ] for borderfunc in borderfuncs: yield borderfunc()
Draws cell border to context
def draw(self): """Draws cell border to context""" # Lines should have a square cap to avoid ugly edges self.context.set_line_cap(cairo.LINE_CAP_SQUARE) self.context.save() self.context.rectangle(*self.rect) self.context.clip() cell_borders = CellBorders(self.cell_attributes, self.key, self.rect) borders = list(cell_borders.gen_all()) borders.sort(key=attrgetter('width', 'color')) for border in borders: border.draw(self.context) self.context.restore()
Draws cursor as Rectangle in lower right corner
def _draw_cursor(self, dc, grid, row, col, pen=None, brush=None): """Draws cursor as Rectangle in lower right corner""" # If in full screen mode draw no cursor if grid.main_window.IsFullScreen(): return key = row, col, grid.current_table rect = grid.CellToRect(row, col) rect = self.get_merged_rect(grid, key, rect) # Check if cell is invisible if rect is None: return size = self.get_zoomed_size(1.0) caret_length = int(min([rect.width, rect.height]) / 5.0) color = get_color(config["text_color"]) if pen is None: pen = wx.Pen(color) if brush is None: brush = wx.Brush(color) pen.SetWidth(size) # Inner right and lower borders border_left = rect.x + size - 1 border_right = rect.x + rect.width - size - 1 border_upper = rect.y + size - 1 border_lower = rect.y + rect.height - size - 1 points_lr = [ (border_right, border_lower - caret_length), (border_right, border_lower), (border_right - caret_length, border_lower), (border_right, border_lower), ] points_ur = [ (border_right, border_upper + caret_length), (border_right, border_upper), (border_right - caret_length, border_upper), (border_right, border_upper), ] points_ul = [ (border_left, border_upper + caret_length), (border_left, border_upper), (border_left + caret_length, border_upper), (border_left, border_upper), ] points_ll = [ (border_left, border_lower - caret_length), (border_left, border_lower), (border_left + caret_length, border_lower), (border_left, border_lower), ] point_list = [points_lr, points_ur, points_ul, points_ll] dc.DrawPolygonList(point_list, pens=pen, brushes=brush) self.old_cursor_row_col = row, col
Whites out the old cursor and draws the new one
def update_cursor(self, dc, grid, row, col): """Whites out the old cursor and draws the new one""" old_row, old_col = self.old_cursor_row_col bgcolor = get_color(config["background_color"]) self._draw_cursor(dc, grid, old_row, old_col, pen=wx.Pen(bgcolor), brush=wx.Brush(bgcolor)) self._draw_cursor(dc, grid, row, col)
Returns cell rect for normal or merged cells and None for merged
def get_merged_rect(self, grid, key, rect): """Returns cell rect for normal or merged cells and None for merged""" row, col, tab = key # Check if cell is merged: cell_attributes = grid.code_array.cell_attributes merge_area = cell_attributes[(row, col, tab)]["merge_area"] if merge_area is None: return rect else: # We have a merged cell top, left, bottom, right = merge_area # Are we drawing the top left cell? if top == row and left == col: # Set rect to merge area ul_rect = grid.CellToRect(row, col) br_rect = grid.CellToRect(bottom, right) width = br_rect.x - ul_rect.x + br_rect.width height = br_rect.y - ul_rect.y + br_rect.height rect = wx.Rect(ul_rect.x, ul_rect.y, width, height) return rect
Replaces drawn rect if the one provided by wx is incorrect This handles merged rects including those that are partly off screen.
def _get_drawn_rect(self, grid, key, rect): """Replaces drawn rect if the one provided by wx is incorrect This handles merged rects including those that are partly off screen. """ rect = self.get_merged_rect(grid, key, rect) if rect is None: # Merged cell is drawn if grid.is_merged_cell_drawn(key): # Merging cell is outside view row, col, __ = key = self.get_merging_cell(grid, key) rect = grid.CellToRect(row, col) rect = self.get_merged_rect(grid, key, rect) else: return return rect
Returns key for the screen draw cache
def _get_draw_cache_key(self, grid, key, drawn_rect, is_selected): """Returns key for the screen draw cache""" row, col, tab = key cell_attributes = grid.code_array.cell_attributes zoomed_width = drawn_rect.width / self.zoom zoomed_height = drawn_rect.height / self.zoom # Button cells shall not be executed for preview if grid.code_array.cell_attributes[key]["button_cell"]: cell_preview = repr(grid.code_array(key))[:100] __id = id(grid.code_array(key)) else: cell_preview = repr(grid.code_array[key])[:100] __id = id(grid.code_array[key]) sorted_keys = sorted(grid.code_array.cell_attributes[key].iteritems()) key_above_left = row - 1, col - 1, tab key_above = row - 1, col, tab key_above_right = row - 1, col + 1, tab key_left = row, col - 1, tab key_right = row, col + 1, tab key_below_left = row + 1, col - 1, tab key_below = row + 1, col, tab borders = [] for k in [key, key_above_left, key_above, key_above_right, key_left, key_right, key_below_left, key_below]: borders.append(cell_attributes[k]["borderwidth_bottom"]) borders.append(cell_attributes[k]["borderwidth_right"]) borders.append(cell_attributes[k]["bordercolor_bottom"]) borders.append(cell_attributes[k]["bordercolor_right"]) return (zoomed_width, zoomed_height, is_selected, cell_preview, __id, tuple(sorted_keys), tuple(borders))
Returns a wx.Bitmap of cell key in size rect
def _get_cairo_bmp(self, mdc, key, rect, is_selected, view_frozen): """Returns a wx.Bitmap of cell key in size rect""" bmp = wx.EmptyBitmap(rect.width, rect.height) mdc.SelectObject(bmp) mdc.SetBackgroundMode(wx.SOLID) mdc.SetBackground(wx.WHITE_BRUSH) mdc.Clear() mdc.SetDeviceOrigin(0, 0) context = wx.lib.wxcairo.ContextFromDC(mdc) context.save() # Zoom context zoom = self.zoom context.scale(zoom, zoom) # Set off cell renderer by 1/2 a pixel to avoid blurry lines rect_tuple = \ -0.5, -0.5, rect.width / zoom + 0.5, rect.height / zoom + 0.5 spell_check = config["check_spelling"] cell_renderer = GridCellCairoRenderer(context, self.data_array, key, rect_tuple, view_frozen, spell_check=spell_check) # Draw cell cell_renderer.draw() # Draw selection if present if is_selected: context.set_source_rgba(*self.selection_color_tuple) context.rectangle(*rect_tuple) context.fill() context.restore() return bmp
Draws the cell border and content using pycairo
def Draw(self, grid, attr, dc, rect, row, col, isSelected): """Draws the cell border and content using pycairo""" key = row, col, grid.current_table # If cell is merge draw the merging cell if invisibile if grid.code_array.cell_attributes[key]["merge_area"]: key = self.get_merging_cell(grid, key) drawn_rect = self._get_drawn_rect(grid, key, rect) if drawn_rect is None: return cell_cache_key = self._get_draw_cache_key(grid, key, drawn_rect, isSelected) mdc = wx.MemoryDC() if vlc is not None and key in self.video_cells and \ grid.code_array.cell_attributes[key]["panel_cell"]: # Update video position of previously created video panel self.video_cells[key].SetClientRect(drawn_rect) elif cell_cache_key in self.cell_cache: mdc.SelectObject(self.cell_cache[cell_cache_key]) else: code = grid.code_array(key) if vlc is not None and code is not None and \ grid.code_array.cell_attributes[key]["panel_cell"]: try: # A panel is to be displayed panel_cls = grid.code_array[key] # Assert that we have a subclass of a wxPanel that we # can instantiate assert issubclass(panel_cls, wx.Panel) video_panel = panel_cls(grid) video_panel.SetClientRect(drawn_rect) # Register video cell self.video_cells[key] = video_panel return except Exception, err: # Someting is wrong with the panel to be displayed post_command_event(grid.main_window, self.StatusBarMsg, text=unicode(err)) bmp = self._get_cairo_bmp(mdc, key, drawn_rect, isSelected, grid._view_frozen) else: bmp = self._get_cairo_bmp(mdc, key, drawn_rect, isSelected, grid._view_frozen) # Put resulting bmp into cache self.cell_cache[cell_cache_key] = bmp dc.Blit(drawn_rect.x, drawn_rect.y, drawn_rect.width, drawn_rect.height, mdc, 0, 0, wx.COPY) # Draw cursor if grid.actions.cursor[:2] == (row, col): self.update_cursor(dc, grid, row, col)
Displays gpg key choice and returns key
def choose_key(gpg_private_keys): """Displays gpg key choice and returns key""" uid_strings_fp = [] uid_string_fp2key = {} current_key_index = None for i, key in enumerate(gpg_private_keys): fingerprint = key['fingerprint'] if fingerprint == config["gpg_key_fingerprint"]: current_key_index = i for uid_string in key['uids']: uid_string_fp = '"' + uid_string + ' (' + fingerprint + ')' uid_strings_fp.append(uid_string_fp) uid_string_fp2key[uid_string_fp] = key msg = _('Choose a GPG key for signing pyspread save files.\n' 'The GPG key must not have a passphrase set.') dlg = wx.SingleChoiceDialog(None, msg, _('Choose key'), uid_strings_fp, wx.CHOICEDLG_STYLE) childlist = list(dlg.GetChildren()) childlist[-3].SetLabel(_("Use chosen key")) childlist[-2].SetLabel(_("Create new key")) if current_key_index is not None: # Set choice to current key dlg.SetSelection(current_key_index) if dlg.ShowModal() == wx.ID_OK: uid_string_fp = dlg.GetStringSelection() key = uid_string_fp2key[uid_string_fp] else: key = None dlg.Destroy() return key
Registers key in config
def _register_key(fingerprint, gpg): """Registers key in config""" for private_key in gpg.list_keys(True): try: if str(fingerprint) == private_key['fingerprint']: config["gpg_key_fingerprint"] = \ repr(private_key['fingerprint']) except KeyError: pass
Returns True iif gpg_secret_key has a password
def has_no_password(gpg_secret_keyid): """Returns True iif gpg_secret_key has a password""" if gnupg is None: return False gpg = gnupg.GPG() s = gpg.sign("", keyid=gpg_secret_keyid, passphrase="") try: return s.status == "signature created" except AttributeError: # This may happen on Windows if hasattr(s, "stderr"): return "GOOD_PASSPHRASE" in s.stderr
Creates a new standard GPG key Parameters ---------- ui: Bool \tIf True, then a new key is created when required without user interaction
def genkey(key_name=None): """Creates a new standard GPG key Parameters ---------- ui: Bool \tIf True, then a new key is created when required without user interaction """ if gnupg is None: return gpg_key_param_list = [ ('key_type', 'DSA'), ('key_length', '2048'), ('subkey_type', 'ELG-E'), ('subkey_length', '2048'), ('expire_date', '0'), ] gpg = gnupg.GPG() gpg.encoding = 'utf-8' # Check if standard key is already present pyspread_key_fingerprint = config["gpg_key_fingerprint"] gpg_private_keys = [key for key in gpg.list_keys(secret=True) if has_no_password(key["keyid"])] gpg_private_fingerprints = \ [key['fingerprint'] for key in gpg.list_keys(secret=True) if has_no_password(key["keyid"])] pyspread_key = None for private_key, fingerprint in zip(gpg_private_keys, gpg_private_fingerprints): if str(pyspread_key_fingerprint) == fingerprint: pyspread_key = private_key if gpg_private_keys: # If GPG are available, choose one pyspread_key = choose_key(gpg_private_keys) if pyspread_key: # A key has been chosen config["gpg_key_fingerprint"] = repr(pyspread_key['fingerprint']) else: # No key has been chosen --> Create new one if key_name is None: gpg_key_parameters = get_key_params_from_user(gpg_key_param_list) if gpg_key_parameters is None: # No name entered return else: gpg_key_param_list.append( ('name_real', '{key_name}'.format(key_name=key_name))) gpg_key_parameters = dict(gpg_key_param_list) input_data = gpg.gen_key_input(**gpg_key_parameters) # Generate key # ------------ if key_name is None: # Show information dialog style = wx.ICON_INFORMATION | wx.DIALOG_NO_PARENT | wx.OK | \ wx.CANCEL pyspread_key_uid = gpg_key_parameters["name_real"] short_message = _("New GPG key").format(pyspread_key_uid) message = _("After confirming this dialog, a new GPG key ") + \ _("'{key}' will be generated.").format(key=pyspread_key_uid) +\ _(" \n \nThis may take some time.\nPlease wait.") dlg = wx.MessageDialog(None, message, short_message, style) dlg.Centre() if dlg.ShowModal() == wx.ID_OK: dlg.Destroy() gpg_key = gpg.gen_key(input_data) _register_key(gpg_key, gpg) fingerprint = gpg_key.fingerprint else: dlg.Destroy() return else: gpg_key = gpg.gen_key(input_data) _register_key(gpg_key, gpg) fingerprint = gpg_key.fingerprint return fingerprint
Returns keyid from fingerprint for private keys
def fingerprint2keyid(fingerprint): """Returns keyid from fingerprint for private keys""" if gnupg is None: return gpg = gnupg.GPG() private_keys = gpg.list_keys(True) keyid = None for private_key in private_keys: if private_key['fingerprint'] == config["gpg_key_fingerprint"]: keyid = private_key['keyid'] break return keyid
Returns detached signature for file
def sign(filename): """Returns detached signature for file""" if gnupg is None: return gpg = gnupg.GPG() with open(filename, "rb") as signfile: keyid = fingerprint2keyid(config["gpg_key_fingerprint"]) if keyid is None: msg = "No private key for GPG fingerprint '{}'." raise ValueError(msg.format(config["gpg_key_fingerprint"])) signed_data = gpg.sign_file(signfile, keyid=keyid, detach=True) return signed_data
Verifies a signature, returns True if successful else False.
def verify(sigfilename, filefilename=None): """Verifies a signature, returns True if successful else False.""" if gnupg is None: return False gpg = gnupg.GPG() with open(sigfilename, "rb") as sigfile: verified = gpg.verify_file(sigfile, filefilename) pyspread_keyid = fingerprint2keyid(config["gpg_key_fingerprint"]) if verified.valid and verified.key_id == pyspread_keyid: return True return False
Returns the length of the table cache
def _len_table_cache(self): """Returns the length of the table cache""" length = 0 for table in self._table_cache: length += len(self._table_cache[table]) return length
Clears and updates the table cache to be in sync with self
def _update_table_cache(self): """Clears and updates the table cache to be in sync with self""" self._table_cache.clear() for sel, tab, val in self: try: self._table_cache[tab].append((sel, val)) except KeyError: self._table_cache[tab] = [(sel, val)] assert len(self) == self._len_table_cache()
Returns key of cell that merges the cell key or None if cell key not merged Parameters ---------- key: 3-tuple of Integer \tThe key of the cell that is merged
def get_merging_cell(self, key): """Returns key of cell that merges the cell key or None if cell key not merged Parameters ---------- key: 3-tuple of Integer \tThe key of the cell that is merged """ row, col, tab = key # Is cell merged merge_area = self[key]["merge_area"] if merge_area: return merge_area[0], merge_area[1], tab
Returns dict of data content. Keys ---- shape: 3-tuple of Integer \tGrid shape grid: Dict of 3-tuples to strings \tCell content attributes: List of 3-tuples \tCell attributes row_heights: Dict of 2-tuples to float \t(row, tab): row_height col_widths: Dict of 2-tuples to float \t(col, tab): col_width macros: String \tMacros from macro list
def _get_data(self): """Returns dict of data content. Keys ---- shape: 3-tuple of Integer \tGrid shape grid: Dict of 3-tuples to strings \tCell content attributes: List of 3-tuples \tCell attributes row_heights: Dict of 2-tuples to float \t(row, tab): row_height col_widths: Dict of 2-tuples to float \t(col, tab): col_width macros: String \tMacros from macro list """ data = {} data["shape"] = self.shape data["grid"] = {}.update(self.dict_grid) data["attributes"] = [ca for ca in self.cell_attributes] data["row_heights"] = self.row_heights data["col_widths"] = self.col_widths data["macros"] = self.macros return data
Sets data from given parameters Old values are deleted. If a paremeter is not given, nothing is changed. Parameters ---------- shape: 3-tuple of Integer \tGrid shape grid: Dict of 3-tuples to strings \tCell content attributes: List of 3-tuples \tCell attributes row_heights: Dict of 2-tuples to float \t(row, tab): row_height col_widths: Dict of 2-tuples to float \t(col, tab): col_width macros: String \tMacros from macro list
def _set_data(self, **kwargs): """Sets data from given parameters Old values are deleted. If a paremeter is not given, nothing is changed. Parameters ---------- shape: 3-tuple of Integer \tGrid shape grid: Dict of 3-tuples to strings \tCell content attributes: List of 3-tuples \tCell attributes row_heights: Dict of 2-tuples to float \t(row, tab): row_height col_widths: Dict of 2-tuples to float \t(col, tab): col_width macros: String \tMacros from macro list """ if "shape" in kwargs: self.shape = kwargs["shape"] if "grid" in kwargs: self.dict_grid.clear() self.dict_grid.update(kwargs["grid"]) if "attributes" in kwargs: self.attributes[:] = kwargs["attributes"] if "row_heights" in kwargs: self.row_heights = kwargs["row_heights"] if "col_widths" in kwargs: self.col_widths = kwargs["col_widths"] if "macros" in kwargs: self.macros = kwargs["macros"]
Returns row height
def get_row_height(self, row, tab): """Returns row height""" try: return self.row_heights[(row, tab)] except KeyError: return config["default_row_height"]
Returns column width
def get_col_width(self, col, tab): """Returns column width""" try: return self.col_widths[(col, tab)] except KeyError: return config["default_col_width"]
Deletes all cells beyond new shape and sets dict_grid shape Parameters ---------- shape: 3-tuple of Integer \tTarget shape for grid
def _set_shape(self, shape): """Deletes all cells beyond new shape and sets dict_grid shape Parameters ---------- shape: 3-tuple of Integer \tTarget shape for grid """ # Delete each cell that is beyond new borders old_shape = self.shape deleted_cells = {} if any(new_axis < old_axis for new_axis, old_axis in zip(shape, old_shape)): for key in self.dict_grid.keys(): if any(key_ele >= new_axis for key_ele, new_axis in zip(key, shape)): deleted_cells[key] = self.pop(key) # Set dict_grid shape attribute self.dict_grid.shape = shape self._adjust_rowcol(0, 0, 0) self._adjust_cell_attributes(0, 0, 0) # Undo actions yield "_set_shape" self.shape = old_shape for key in deleted_cells: self[key] = deleted_cells[key]
Returns key for the bottommost rightmost cell with content Parameters ---------- table: Integer, defaults to None \tLimit search to this table
def get_last_filled_cell(self, table=None): """Returns key for the bottommost rightmost cell with content Parameters ---------- table: Integer, defaults to None \tLimit search to this table """ maxrow = 0 maxcol = 0 for row, col, tab in self.dict_grid: if table is None or tab == table: maxrow = max(row, maxrow) maxcol = max(col, maxcol) return maxrow, maxcol, table
Generator traversing cells specified in key Parameters ---------- key: Iterable of Integer or slice \tThe key specifies the cell keys of the generator
def cell_array_generator(self, key): """Generator traversing cells specified in key Parameters ---------- key: Iterable of Integer or slice \tThe key specifies the cell keys of the generator """ for i, key_ele in enumerate(key): # Get first element of key that is a slice if type(key_ele) is SliceType: slc_keys = xrange(*key_ele.indices(self.dict_grid.shape[i])) key_list = list(key) key_list[i] = None has_subslice = any(type(ele) is SliceType for ele in key_list) for slc_key in slc_keys: key_list[i] = slc_key if has_subslice: # If there is a slice left yield generator yield self.cell_array_generator(key_list) else: # No slices? Yield value yield self[tuple(key_list)] break
Shifts row and column sizes when a table is inserted or deleted
def _shift_rowcol(self, insertion_point, no_to_insert): """Shifts row and column sizes when a table is inserted or deleted""" # Shift row heights new_row_heights = {} del_row_heights = [] for row, tab in self.row_heights: if tab > insertion_point: new_row_heights[(row, tab + no_to_insert)] = \ self.row_heights[(row, tab)] del_row_heights.append((row, tab)) for row, tab in new_row_heights: self.set_row_height(row, tab, new_row_heights[(row, tab)]) for row, tab in del_row_heights: if (row, tab) not in new_row_heights: self.set_row_height(row, tab, None) # Shift column widths new_col_widths = {} del_col_widths = [] for col, tab in self.col_widths: if tab > insertion_point: new_col_widths[(col, tab + no_to_insert)] = \ self.col_widths[(col, tab)] del_col_widths.append((col, tab)) for col, tab in new_col_widths: self.set_col_width(col, tab, new_col_widths[(col, tab)]) for col, tab in del_col_widths: if (col, tab) not in new_col_widths: self.set_col_width(col, tab, None)
Adjusts row and column sizes on insertion/deletion
def _adjust_rowcol(self, insertion_point, no_to_insert, axis, tab=None): """Adjusts row and column sizes on insertion/deletion""" if axis == 2: self._shift_rowcol(insertion_point, no_to_insert) return assert axis in (0, 1) cell_sizes = self.col_widths if axis else self.row_heights set_cell_size = self.set_col_width if axis else self.set_row_height new_sizes = {} del_sizes = [] for pos, table in cell_sizes: if pos > insertion_point and (tab is None or tab == table): if 0 <= pos + no_to_insert < self.shape[axis]: new_sizes[(pos + no_to_insert, table)] = \ cell_sizes[(pos, table)] del_sizes.append((pos, table)) for pos, table in new_sizes: set_cell_size(pos, table, new_sizes[(pos, table)]) for pos, table in del_sizes: if (pos, table) not in new_sizes: set_cell_size(pos, table, None)
Returns updated merge area Parameters ---------- attrs: Dict \tCell attribute dictionary that shall be adjusted insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be inserted axis: Integer in range(2) \tSpecifies number of dimension, i.e. 0 == row, 1 == col
def _get_adjusted_merge_area(self, attrs, insertion_point, no_to_insert, axis): """Returns updated merge area Parameters ---------- attrs: Dict \tCell attribute dictionary that shall be adjusted insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be inserted axis: Integer in range(2) \tSpecifies number of dimension, i.e. 0 == row, 1 == col """ assert axis in range(2) if "merge_area" not in attrs or attrs["merge_area"] is None: return top, left, bottom, right = attrs["merge_area"] selection = Selection([(top, left)], [(bottom, right)], [], [], []) selection.insert(insertion_point, no_to_insert, axis) __top, __left = selection.block_tl[0] __bottom, __right = selection.block_br[0] # Adjust merge area if it is beyond the grid shape rows, cols, tabs = self.shape if __top < 0 and __bottom < 0 or __top >= rows and __bottom >= rows or\ __left < 0 and __right < 0 or __left >= cols and __right >= cols: return if __top < 0: __top = 0 if __top >= rows: __top = rows - 1 if __bottom < 0: __bottom = 0 if __bottom >= rows: __bottom = rows - 1 if __left < 0: __left = 0 if __left >= cols: __left = cols - 1 if __right < 0: __right = 0 if __right >= cols: __right = cols - 1 return __top, __left, __bottom, __right
Adjusts cell attributes on insertion/deletion Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be inserted axis: Integer in range(3) \tSpecifies number of dimension, i.e. 0 == row, 1 == col, ... tab: Integer, defaults to None \tIf given then insertion is limited to this tab for axis < 2 cell_attrs: List, defaults to [] \tIf not empty then the given cell attributes replace the existing ones
def _adjust_cell_attributes(self, insertion_point, no_to_insert, axis, tab=None, cell_attrs=None): """Adjusts cell attributes on insertion/deletion Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be inserted axis: Integer in range(3) \tSpecifies number of dimension, i.e. 0 == row, 1 == col, ... tab: Integer, defaults to None \tIf given then insertion is limited to this tab for axis < 2 cell_attrs: List, defaults to [] \tIf not empty then the given cell attributes replace the existing ones """ def replace_cell_attributes_table(index, new_table): """Replaces table in cell_attributes item""" ca = list(list.__getitem__(self.cell_attributes, index)) ca[1] = new_table self.cell_attributes.__setitem__(index, tuple(ca)) def get_ca_with_updated_ma(attrs, merge_area): """Returns cell attributes with updated merge area""" new_attrs = copy(attrs) if merge_area is None: try: new_attrs.pop("merge_area") except KeyError: pass else: new_attrs["merge_area"] = merge_area return new_attrs if axis not in range(3): raise ValueError("Axis must be in [0, 1, 2]") assert tab is None or tab >= 0 if cell_attrs is None: cell_attrs = [] if cell_attrs: self.cell_attributes[:] = cell_attrs elif axis < 2: # Adjust selections on given table ca_updates = {} for i, (selection, table, attrs) in enumerate( self.cell_attributes): selection = copy(selection) if tab is None or tab == table: selection.insert(insertion_point, no_to_insert, axis) # Update merge area if present merge_area = self._get_adjusted_merge_area(attrs, insertion_point, no_to_insert, axis) new_attrs = get_ca_with_updated_ma(attrs, merge_area) ca_updates[i] = selection, table, new_attrs for idx in ca_updates: self.cell_attributes[idx] = ca_updates[idx] elif axis == 2: # Adjust tabs pop_indices = [] for i, cell_attribute in enumerate(self.cell_attributes): selection, table, value = cell_attribute if no_to_insert < 0 and insertion_point <= table: if insertion_point > table + no_to_insert: # Delete later pop_indices.append(i) else: replace_cell_attributes_table(i, table + no_to_insert) elif insertion_point < table: # Insert replace_cell_attributes_table(i, table + no_to_insert) for i in pop_indices[::-1]: self.cell_attributes.pop(i) self.cell_attributes._attr_cache.clear() self.cell_attributes._update_table_cache()
Inserts no_to_insert rows/cols/tabs/... before insertion_point Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be inserted axis: Integer \tSpecifies number of dimension, i.e. 0 == row, 1 == col, ... tab: Integer, defaults to None \tIf given then insertion is limited to this tab for axis < 2
def insert(self, insertion_point, no_to_insert, axis, tab=None): """Inserts no_to_insert rows/cols/tabs/... before insertion_point Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be inserted axis: Integer \tSpecifies number of dimension, i.e. 0 == row, 1 == col, ... tab: Integer, defaults to None \tIf given then insertion is limited to this tab for axis < 2 """ if not 0 <= axis <= len(self.shape): raise ValueError("Axis not in grid dimensions") if insertion_point > self.shape[axis] or \ insertion_point < -self.shape[axis]: raise IndexError("Insertion point not in grid") new_keys = {} del_keys = [] for key in self.dict_grid.keys(): if key[axis] > insertion_point and (tab is None or tab == key[2]): new_key = list(key) new_key[axis] += no_to_insert if 0 <= new_key[axis] < self.shape[axis]: new_keys[tuple(new_key)] = self(key) del_keys.append(key) # Now re-insert moved keys for key in del_keys: if key not in new_keys and self(key) is not None: self.pop(key) self._adjust_rowcol(insertion_point, no_to_insert, axis, tab=tab) self._adjust_cell_attributes(insertion_point, no_to_insert, axis, tab) for key in new_keys: self.__setitem__(key, new_keys[key])
Deletes no_to_delete rows/cols/... starting with deletion_point Axis specifies number of dimension, i.e. 0 == row, 1 == col, 2 == tab
def delete(self, deletion_point, no_to_delete, axis, tab=None): """Deletes no_to_delete rows/cols/... starting with deletion_point Axis specifies number of dimension, i.e. 0 == row, 1 == col, 2 == tab """ if not 0 <= axis < len(self.shape): raise ValueError("Axis not in grid dimensions") if no_to_delete < 0: raise ValueError("Cannot delete negative number of rows/cols/...") elif no_to_delete >= self.shape[axis]: raise ValueError("Last row/column/table must not be deleted") if deletion_point > self.shape[axis] or \ deletion_point <= -self.shape[axis]: raise IndexError("Deletion point not in grid") new_keys = {} del_keys = [] # Note that the loop goes over a list that copies all dict keys for key in self.dict_grid.keys(): if tab is None or tab == key[2]: if deletion_point <= key[axis] < deletion_point + no_to_delete: del_keys.append(key) elif key[axis] >= deletion_point + no_to_delete: new_key = list(key) new_key[axis] -= no_to_delete new_keys[tuple(new_key)] = self(key) del_keys.append(key) # Now re-insert moved keys for key in new_keys: self.__setitem__(key, new_keys[key]) for key in del_keys: if key not in new_keys and self(key) is not None: self.pop(key) self._adjust_rowcol(deletion_point, -no_to_delete, axis, tab=tab) self._adjust_cell_attributes(deletion_point, -no_to_delete, axis)
Sets row height
def set_row_height(self, row, tab, height): """Sets row height""" try: old_height = self.row_heights.pop((row, tab)) except KeyError: old_height = None if height is not None: self.row_heights[(row, tab)] = float(height)
Sets column width
def set_col_width(self, col, tab, width): """Sets column width""" try: old_width = self.col_widths.pop((col, tab)) except KeyError: old_width = None if width is not None: self.col_widths[(col, tab)] = float(width)
Returns position of 1st char after assignment traget. If there is no assignment, -1 is returned If there are more than one of any ( expressions or assigments) then a ValueError is raised.
def _get_assignment_target_end(self, ast_module): """Returns position of 1st char after assignment traget. If there is no assignment, -1 is returned If there are more than one of any ( expressions or assigments) then a ValueError is raised. """ if len(ast_module.body) > 1: raise ValueError("More than one expression or assignment.") elif len(ast_module.body) > 0 and \ type(ast_module.body[0]) is ast.Assign: if len(ast_module.body[0].targets) != 1: raise ValueError("More than one assignment target.") else: return len(ast_module.body[0].targets[0].id) return -1
Makes nested list from generator for creating numpy.array
def _make_nested_list(self, gen): """Makes nested list from generator for creating numpy.array""" res = [] for ele in gen: if ele is None: res.append(None) elif not is_string_like(ele) and is_generator_like(ele): # Nested generator res.append(self._make_nested_list(ele)) else: res.append(ele) return res
Returns globals environment with 'magic' variable Parameters ---------- env_dict: Dict, defaults to {'S': self} \tDict that maps global variable name to value
def _get_updated_environment(self, env_dict=None): """Returns globals environment with 'magic' variable Parameters ---------- env_dict: Dict, defaults to {'S': self} \tDict that maps global variable name to value """ if env_dict is None: env_dict = {'S': self} env = globals().copy() env.update(env_dict) return env
Evaluates one cell and returns its result
def _eval_cell(self, key, code): """Evaluates one cell and returns its result""" # Flatten helper function def nn(val): """Returns flat numpy arraz without None values""" try: return numpy.array(filter(None, val.flat)) except AttributeError: # Probably no numpy array return numpy.array(filter(None, val)) # Set up environment for evaluation env_dict = {'X': key[0], 'Y': key[1], 'Z': key[2], 'bz2': bz2, 'base64': base64, 'charts': charts, 'nn': nn, 'R': key[0], 'C': key[1], 'T': key[2], 'S': self, 'vlcpanel_factory': vlcpanel_factory} env = self._get_updated_environment(env_dict=env_dict) #_old_code = self(key) # Return cell value if in safe mode if self.safe_mode: return code # If cell is not present return None if code is None: return elif is_generator_like(code): # We have a generator object return numpy.array(self._make_nested_list(code), dtype="O") # If only 1 term in front of the "=" --> global try: assignment_target_error = None module = ast.parse(code) assignment_target_end = self._get_assignment_target_end(module) except ValueError, err: assignment_target_error = ValueError(err) except AttributeError, err: # Attribute Error includes RunTimeError assignment_target_error = AttributeError(err) except Exception, err: assignment_target_error = Exception(err) if assignment_target_error is None and assignment_target_end != -1: glob_var = code[:assignment_target_end] expression = code.split("=", 1)[1] expression = expression.strip() # Delete result cache because assignment changes results self.result_cache.clear() else: glob_var = None expression = code if assignment_target_error is not None: result = assignment_target_error else: try: import signal signal.signal(signal.SIGALRM, self.handler) signal.alarm(config["timeout"]) except: # No POSIX system pass try: result = eval(expression, env, {}) except AttributeError, err: # Attribute Error includes RunTimeError result = AttributeError(err) except RuntimeError, err: result = RuntimeError(err) except Exception, err: result = Exception(err) finally: try: signal.alarm(0) except: # No POSIX system pass # Change back cell value for evaluation from other cells #self.dict_grid[key] = _old_code if glob_var is not None: globals().update({glob_var: result}) return result
Pops dict_grid with undo and redo support Parameters ---------- key: 3-tuple of Integer \tCell key that shall be popped
def pop(self, key): """Pops dict_grid with undo and redo support Parameters ---------- key: 3-tuple of Integer \tCell key that shall be popped """ try: self.result_cache.pop(repr(key)) except KeyError: pass return DataArray.pop(self, key)
Reloads modules that are available in cells
def reload_modules(self): """Reloads modules that are available in cells""" import src.lib.charts as charts from src.gui.grid_panels import vlcpanel_factory modules = [charts, bz2, base64, re, ast, sys, wx, numpy, datetime] for module in modules: reload(module)
Clears all newly assigned globals
def clear_globals(self): """Clears all newly assigned globals""" base_keys = ['cStringIO', 'IntType', 'KeyValueStore', 'undoable', 'is_generator_like', 'is_string_like', 'bz2', 'base64', '__package__', 're', 'config', '__doc__', 'SliceType', 'CellAttributes', 'product', 'ast', '__builtins__', '__file__', 'charts', 'sys', 'is_slice_like', '__name__', 'copy', 'imap', 'wx', 'ifilter', 'Selection', 'DictGrid', 'numpy', 'CodeArray', 'DataArray', 'datetime', 'vlcpanel_factory'] for key in globals().keys(): if key not in base_keys: globals().pop(key)