desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Called when wxPaintEvt is generated'
def _onPaint(self, evt):
DEBUG_MSG('_onPaint()', 1, self) drawDC = wx.PaintDC(self) if (not self._isDrawn): self.draw(drawDC=drawDC) else: self.gui_repaint(drawDC=drawDC) evt.Skip()
'Called when window is redrawn; since we are blitting the entire image, we can leave this blank to suppress flicker.'
def _onEraseBackground(self, evt):
pass
'Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window.'
def _onSize(self, evt):
DEBUG_MSG('_onSize()', 2, self) (self._width, self._height) = self.GetClientSize() self.bitmap = wx.EmptyBitmap(self._width, self._height) self._isDrawn = False if ((self._width <= 1) or (self._height <= 1)): return dpival = self.figure.dpi winch = (self._width / dpival) hinch = (self._height / dpival) self.figure.set_size_inches(winch, hinch) self.Refresh(eraseBackground=False)
'a GUI idle event'
def _onIdle(self, evt):
evt.Skip() FigureCanvasBase.idle_event(self, guiEvent=evt)
'Capture key press.'
def _onKeyDown(self, evt):
key = self._get_key(evt) evt.Skip() FigureCanvasBase.key_press_event(self, key, guiEvent=evt)
'Release key.'
def _onKeyUp(self, evt):
key = self._get_key(evt) evt.Skip() FigureCanvasBase.key_release_event(self, key, guiEvent=evt)
'Start measuring on an axis.'
def _onRightButtonDown(self, evt):
x = evt.GetX() y = (self.figure.bbox.height - evt.GetY()) evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 3, guiEvent=evt)
'End measuring on an axis.'
def _onRightButtonUp(self, evt):
x = evt.GetX() y = (self.figure.bbox.height - evt.GetY()) evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 3, guiEvent=evt)
'Start measuring on an axis.'
def _onLeftButtonDown(self, evt):
x = evt.GetX() y = (self.figure.bbox.height - evt.GetY()) evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 1, guiEvent=evt)
'End measuring on an axis.'
def _onLeftButtonUp(self, evt):
x = evt.GetX() y = (self.figure.bbox.height - evt.GetY()) evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt)
'Translate mouse wheel events into matplotlib events'
def _onMouseWheel(self, evt):
x = evt.GetX() y = (self.figure.bbox.height - evt.GetY()) delta = evt.GetWheelDelta() rotation = evt.GetWheelRotation() rate = evt.GetLinesPerAction() step = ((rate * float(rotation)) / delta) evt.Skip() if (wx.Platform == '__WXMAC__'): if (not hasattr(self, '_skipwheelevent')): self._skipwheelevent = True elif self._skipwheelevent: self._skipwheelevent = False return else: self._skipwheelevent = True FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=evt)
'Start measuring on an axis.'
def _onMotion(self, evt):
x = evt.GetX() y = (self.figure.bbox.height - evt.GetY()) evt.Skip() FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt)
'Mouse has left the window.'
def _onLeave(self, evt):
evt.Skip() FigureCanvasBase.leave_notify_event(self, guiEvent=evt)
'Mouse has entered the window.'
def _onEnter(self, evt):
FigureCanvasBase.enter_notify_event(self, guiEvent=evt)
'Override wxFrame::GetToolBar as we don\'t have managed toolbar'
def GetToolBar(self):
return self.toolbar
'Set the canvas size in pixels'
def resize(self, width, height):
self.canvas.SetInitialSize(wx.Size(width, height)) self.window.GetSizer().Fit(self.window)
'Handle menu button pressed.'
def _onMenuButton(self, evt):
(x, y) = self.GetPositionTuple() (w, h) = self.GetSizeTuple() self.PopupMenuXY(self._menu, x, ((y + h) - 4)) evt.Skip()
'Called when the \'select all axes\' menu item is selected.'
def _handleSelectAllAxes(self, evt):
if (len(self._axisId) == 0): return for i in range(len(self._axisId)): self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip()
'Called when the invert all menu item is selected'
def _handleInvertAxesSelected(self, evt):
if (len(self._axisId) == 0): return for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): self._menu.Check(self._axisId[i], False) else: self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip()
'Called whenever one of the specific axis menu items is selected'
def _onMenuItemSelected(self, evt):
current = self._menu.IsChecked(evt.GetId()) if current: new = False else: new = True self._menu.Check(evt.GetId(), new) self._toolbar.set_active(self.getActiveAxes()) evt.Skip()
'Ensures that there are entries for max_axis axes in the menu (selected by default).'
def updateAxes(self, maxAxis):
if (maxAxis > len(self._axisId)): for i in range((len(self._axisId) + 1), (maxAxis + 1), 1): menuId = wx.NewId() self._axisId.append(menuId) self._menu.Append(menuId, ('Axis %d' % i), ('Select axis %d' % i), True) self._menu.Check(menuId, True) bind(self, wx.EVT_MENU, self._onMenuItemSelected, id=menuId) self._toolbar.set_active(range(len(self._axisId)))
'Return a list of the selected axes.'
def getActiveAxes(self):
active = [] for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): active.append(i) return active
'Update the list of selected axes in the menu button'
def updateButtonText(self, lst):
axis_txt = '' for e in lst: axis_txt += ('%d,' % (e + 1)) self.SetLabel(('Axes: %s' % axis_txt[:(-1)]))
'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744'
def draw_rubberband(self, event, x0, y0, x1, y1):
canvas = self.canvas dc = wx.ClientDC(canvas) dc.SetLogicalFunction(wx.XOR) wbrush = wx.Brush(wx.Colour(255, 255, 255), wx.TRANSPARENT) wpen = wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID) dc.SetBrush(wbrush) dc.SetPen(wpen) dc.ResetBoundingBox() dc.BeginDrawing() height = self.canvas.figure.bbox.height y1 = (height - y1) y0 = (height - y0) if (y1 < y0): (y0, y1) = (y1, y0) if (x1 < y0): (x0, x1) = (x1, x0) w = (x1 - x0) h = (y1 - y0) rect = (int(x0), int(y0), int(w), int(h)) try: lastrect = self.lastrect except AttributeError: pass else: dc.DrawRectangle(*lastrect) self.lastrect = rect dc.DrawRectangle(*rect) dc.EndDrawing()
'figure is the Figure instance that the toolboar controls win, if not None, is the wxWindow the Figure is embedded in'
def __init__(self, canvas, can_kill=False):
wx.ToolBar.__init__(self, canvas.GetParent(), (-1)) DEBUG_MSG('__init__()', 1, self) self.canvas = canvas self._lastControl = None self._mouseOnButton = None self._parent = canvas.GetParent() self._NTB_BUTTON_HANDLER = {_NTB_X_PAN_LEFT: self.panx, _NTB_X_PAN_RIGHT: self.panx, _NTB_X_ZOOMIN: self.zoomx, _NTB_X_ZOOMOUT: self.zoomy, _NTB_Y_PAN_UP: self.pany, _NTB_Y_PAN_DOWN: self.pany, _NTB_Y_ZOOMIN: self.zoomy, _NTB_Y_ZOOMOUT: self.zoomy} self._create_menu() self._create_controls(can_kill) self.Realize()
'Creates the \'menu\' - implemented as a button which opens a pop-up menu since wxPython does not allow a menu as a control'
def _create_menu(self):
DEBUG_MSG('_create_menu()', 1, self) self._menu = MenuButtonWx(self) self.AddControl(self._menu) self.AddSeparator()
'Creates the button controls, and links them to event handlers'
def _create_controls(self, can_kill):
DEBUG_MSG('_create_controls()', 1, self) self.SetToolBitmapSize(wx.Size(16, 16)) self.AddSimpleTool(_NTB_X_PAN_LEFT, _load_bitmap('stock_left.xpm'), 'Left', 'Scroll left') self.AddSimpleTool(_NTB_X_PAN_RIGHT, _load_bitmap('stock_right.xpm'), 'Right', 'Scroll right') self.AddSimpleTool(_NTB_X_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase X axis magnification') self.AddSimpleTool(_NTB_X_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease X axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_Y_PAN_UP, _load_bitmap('stock_up.xpm'), 'Up', 'Scroll up') self.AddSimpleTool(_NTB_Y_PAN_DOWN, _load_bitmap('stock_down.xpm'), 'Down', 'Scroll down') self.AddSimpleTool(_NTB_Y_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase Y axis magnification') self.AddSimpleTool(_NTB_Y_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease Y axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_SAVE, _load_bitmap('stock_save_as.xpm'), 'Save', 'Save plot contents as images') self.AddSeparator() bind(self, wx.EVT_TOOL, self._onLeftScroll, id=_NTB_X_PAN_LEFT) bind(self, wx.EVT_TOOL, self._onRightScroll, id=_NTB_X_PAN_RIGHT) bind(self, wx.EVT_TOOL, self._onXZoomIn, id=_NTB_X_ZOOMIN) bind(self, wx.EVT_TOOL, self._onXZoomOut, id=_NTB_X_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onUpScroll, id=_NTB_Y_PAN_UP) bind(self, wx.EVT_TOOL, self._onDownScroll, id=_NTB_Y_PAN_DOWN) bind(self, wx.EVT_TOOL, self._onYZoomIn, id=_NTB_Y_ZOOMIN) bind(self, wx.EVT_TOOL, self._onYZoomOut, id=_NTB_Y_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onSave, id=_NTB_SAVE) bind(self, wx.EVT_TOOL_ENTER, self._onEnterTool, id=self.GetId()) if can_kill: bind(self, wx.EVT_TOOL, self._onClose, id=_NTB_CLOSE) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel)
'ind is a list of index numbers for the axes which are to be made active'
def set_active(self, ind):
DEBUG_MSG('set_active()', 1, self) self._ind = ind if (ind != None): self._active = [self._axes[i] for i in self._ind] else: self._active = [] self._menu.updateButtonText(ind)
'Returns the identity of the last toolbar button pressed.'
def get_last_control(self):
return self._lastControl
'Update the toolbar menu - called when (e.g.) a new subplot or axes are added'
def update(self):
DEBUG_MSG('update()', 1, self) self._axes = self.canvas.figure.get_axes() self._menu.updateAxes(len(self._axes))
'A NULL event handler - does nothing whatsoever'
def _do_nothing(self, d):
pass
'id: object id of stream; len: an unused Reference object for the length of the stream, or None (to use a memory buffer); file: a PdfFile; extra: a dictionary of extra key-value pairs to include in the stream header'
def __init__(self, id, len, file, extra=None):
self.id = id self.len = len self.pdfFile = file self.file = file.fh self.compressobj = None if (extra is None): self.extra = dict() else: self.extra = extra self.pdfFile.recordXref(self.id) if rcParams['pdf.compression']: self.compressobj = zlib.compressobj(rcParams['pdf.compression']) if (self.len is None): self.file = StringIO() else: self._writeHeader() self.pos = self.file.tell()
'Finalize stream.'
def end(self):
self._flush() if (self.len is None): contents = self.file.getvalue() self.len = len(contents) self.file = self.pdfFile.fh self._writeHeader() self.file.write(contents) self.file.write('\nendstream\nendobj\n') else: length = (self.file.tell() - self.pos) self.file.write('\nendstream\nendobj\n') self.pdfFile.writeObject(self.len, length)
'Write some data on the stream.'
def write(self, data):
if (self.compressobj is None): self.file.write(data) else: compressed = self.compressobj.compress(data) self.file.write(compressed)
'Flush the compression object.'
def _flush(self):
if (self.compressobj is not None): compressed = self.compressobj.flush() self.file.write(compressed) self.compressobj = None
'Select a font based on fontprop and return a name suitable for Op.selectfont. If fontprop is a string, it will be interpreted as the filename of the font.'
def fontName(self, fontprop):
if is_string_like(fontprop): filename = fontprop elif rcParams['pdf.use14corefonts']: filename = findfont(fontprop, fontext='afm') else: filename = findfont(fontprop) Fx = self.fontNames.get(filename) if (Fx is None): Fx = Name(('F%d' % self.nextFont)) self.fontNames[filename] = Fx self.nextFont += 1 return Fx
'Embed the TTF font from the named file into the document.'
def embedTTF(self, filename, characters):
font = FT2Font(str(filename)) fonttype = rcParams['pdf.fonttype'] def cvt(length, upe=font.units_per_EM, nearest=True): 'Convert font coordinates to PDF glyph coordinates' value = ((length / upe) * 1000) if nearest: return round(value) if (value < 0): return floor(value) else: return ceil(value) def embedTTFType3(font, characters, descriptor): 'The Type 3-specific part of embedding a Truetype font' widthsObject = self.reserveObject('font widths') fontdescObject = self.reserveObject('font descriptor') fontdictObject = self.reserveObject('font dictionary') charprocsObject = self.reserveObject('character procs') differencesArray = [] (firstchar, lastchar) = (0, 255) bbox = [cvt(x, nearest=False) for x in font.bbox] fontdict = {'Type': Name('Font'), 'BaseFont': ps_name, 'FirstChar': firstchar, 'LastChar': lastchar, 'FontDescriptor': fontdescObject, 'Subtype': Name('Type3'), 'Name': descriptor['FontName'], 'FontBBox': bbox, 'FontMatrix': [0.001, 0, 0, 0.001, 0, 0], 'CharProcs': charprocsObject, 'Encoding': {'Type': Name('Encoding'), 'Differences': differencesArray}, 'Widths': widthsObject} from encodings import cp1252 if hasattr(cp1252, 'decoding_map'): def decode_char(charcode): return (cp1252.decoding_map[charcode] or 0) else: def decode_char(charcode): return ord(cp1252.decoding_table[charcode]) def get_char_width(charcode): unicode = decode_char(charcode) width = font.load_char(unicode, flags=(LOAD_NO_SCALE | LOAD_NO_HINTING)).horiAdvance return cvt(width) widths = [get_char_width(charcode) for charcode in range(firstchar, (lastchar + 1))] descriptor['MaxWidth'] = max(widths) cmap = font.get_charmap() glyph_ids = [] differences = [] multi_byte_chars = set() for c in characters: ccode = c gind = (cmap.get(ccode) or 0) glyph_ids.append(gind) glyph_name = font.get_glyph_name(gind) if (ccode <= 255): differences.append((ccode, glyph_name)) else: multi_byte_chars.add(glyph_name) differences.sort() last_c = (-2) for (c, name) in differences: if (c != (last_c + 1)): differencesArray.append(c) differencesArray.append(Name(name)) last_c = c rawcharprocs = ttconv.get_pdf_charprocs(filename, glyph_ids) charprocs = {} charprocsRef = {} for (charname, stream) in rawcharprocs.items(): charprocDict = {'Length': len(stream)} if (charname in multi_byte_chars): charprocDict['Type'] = Name('XObject') charprocDict['Subtype'] = Name('Form') charprocDict['BBox'] = bbox stream = stream[(stream.find('d1') + 2):] charprocObject = self.reserveObject('charProc') self.beginStream(charprocObject.id, None, charprocDict) self.currentstream.write(stream) self.endStream() if (charname in multi_byte_chars): name = self._get_xobject_symbol_name(filename, charname) self.multi_byte_charprocs[name] = charprocObject else: charprocs[charname] = charprocObject self.writeObject(fontdictObject, fontdict) self.writeObject(fontdescObject, descriptor) self.writeObject(widthsObject, widths) self.writeObject(charprocsObject, charprocs) return fontdictObject def embedTTFType42(font, characters, descriptor): 'The Type 42-specific part of embedding a Truetype font' fontdescObject = self.reserveObject('font descriptor') cidFontDictObject = self.reserveObject('CID font dictionary') type0FontDictObject = self.reserveObject('Type 0 font dictionary') cidToGidMapObject = self.reserveObject('CIDToGIDMap stream') fontfileObject = self.reserveObject('font file stream') wObject = self.reserveObject('Type 0 widths') toUnicodeMapObject = self.reserveObject('ToUnicode map') cidFontDict = {'Type': Name('Font'), 'Subtype': Name('CIDFontType2'), 'BaseFont': ps_name, 'CIDSystemInfo': {'Registry': 'Adobe', 'Ordering': 'Identity', 'Supplement': 0}, 'FontDescriptor': fontdescObject, 'W': wObject, 'CIDToGIDMap': cidToGidMapObject} type0FontDict = {'Type': Name('Font'), 'Subtype': Name('Type0'), 'BaseFont': ps_name, 'Encoding': Name('Identity-H'), 'DescendantFonts': [cidFontDictObject], 'ToUnicode': toUnicodeMapObject} descriptor['FontFile2'] = fontfileObject length1Object = self.reserveObject('decoded length of a font') self.beginStream(fontfileObject.id, self.reserveObject('length of font stream'), {'Length1': length1Object}) fontfile = open(filename, 'rb') length1 = 0 while True: data = fontfile.read(4096) if (not data): break length1 += len(data) self.currentstream.write(data) fontfile.close() self.endStream() self.writeObject(length1Object, length1) cid_to_gid_map = ([u'\x00'] * 65536) cmap = font.get_charmap() unicode_mapping = [] widths = [] max_ccode = 0 for c in characters: ccode = c gind = (cmap.get(ccode) or 0) glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) widths.append((ccode, (glyph.horiAdvance / 6))) if (ccode < 65536): cid_to_gid_map[ccode] = unichr(gind) max_ccode = max(ccode, max_ccode) widths.sort() cid_to_gid_map = cid_to_gid_map[:(max_ccode + 1)] last_ccode = (-2) w = [] max_width = 0 unicode_groups = [] for (ccode, width) in widths: if (ccode != (last_ccode + 1)): w.append(ccode) w.append([width]) unicode_groups.append([ccode, ccode]) else: w[(-1)].append(width) unicode_groups[(-1)][1] = ccode max_width = max(max_width, width) last_ccode = ccode unicode_bfrange = [] for (start, end) in unicode_groups: unicode_bfrange.append(('<%04x> <%04x> [%s]' % (start, end, ' '.join([('<%04x>' % x) for x in range(start, (end + 1))])))) unicode_cmap = (self._identityToUnicodeCMap % (len(unicode_groups), '\n'.join(unicode_bfrange))) cid_to_gid_map = ''.join(cid_to_gid_map).encode('utf-16be') self.beginStream(cidToGidMapObject.id, None, {'Length': len(cid_to_gid_map)}) self.currentstream.write(cid_to_gid_map) self.endStream() self.beginStream(toUnicodeMapObject.id, None, {'Length': unicode_cmap}) self.currentstream.write(unicode_cmap) self.endStream() descriptor['MaxWidth'] = max_width self.writeObject(cidFontDictObject, cidFontDict) self.writeObject(type0FontDictObject, type0FontDict) self.writeObject(fontdescObject, descriptor) self.writeObject(wObject, w) return type0FontDictObject ps_name = Name(font.get_sfnt()[(1, 0, 0, 6)]) pclt = (font.get_sfnt_table('pclt') or {'capHeight': 0, 'xHeight': 0}) post = (font.get_sfnt_table('post') or {'italicAngle': (0, 0)}) ff = font.face_flags sf = font.style_flags flags = 0 symbolic = False if (ff & FIXED_WIDTH): flags |= (1 << 0) if 0: flags |= (1 << 1) if symbolic: flags |= (1 << 2) else: flags |= (1 << 5) if (sf & ITALIC): flags |= (1 << 6) if 0: flags |= (1 << 16) if 0: flags |= (1 << 17) if 0: flags |= (1 << 18) descriptor = {'Type': Name('FontDescriptor'), 'FontName': ps_name, 'Flags': flags, 'FontBBox': [cvt(x, nearest=False) for x in font.bbox], 'Ascent': cvt(font.ascender, nearest=False), 'Descent': cvt(font.descender, nearest=False), 'CapHeight': cvt(pclt['capHeight'], nearest=False), 'XHeight': cvt(pclt['xHeight']), 'ItalicAngle': post['italicAngle'][1], 'StemV': 0} if is_opentype_cff_font(filename): fonttype = 42 warnings.warn((("'%s' can not be subsetted into a Type 3 font. " + 'The entire font will be embedded in the output.') % os.path.basename(filename))) if (fonttype == 3): return embedTTFType3(font, characters, descriptor) elif (fonttype == 42): return embedTTFType42(font, characters, descriptor)
'Return name of an ExtGState that sets alpha to the given value'
def alphaState(self, alpha):
state = self.alphaStates.get(alpha, None) if (state is not None): return state[0] name = Name(('A%d' % self.nextAlphaState)) self.nextAlphaState += 1 self.alphaStates[alpha] = (name, {'Type': Name('ExtGState'), 'CA': alpha, 'ca': alpha}) return name
'Return name of an image XObject representing the given image.'
def imageObject(self, image):
pair = self.images.get(image, None) if (pair is not None): return pair[0] name = Name(('I%d' % self.nextImage)) ob = self.reserveObject(('image %d' % self.nextImage)) self.nextImage += 1 self.images[image] = (name, ob) return name
'Return name of a marker XObject representing the given path.'
def markerObject(self, path, trans, fillp, lw):
key = (path, trans, (fillp is not None), lw) result = self.markers.get(key) if (result is None): name = Name(('M%d' % len(self.markers))) ob = self.reserveObject(('marker %d' % len(self.markers))) self.markers[key] = (name, ob, path, trans, fillp, lw) else: name = result[0] return name
'Reserve an ID for an indirect object. The name is used for debugging in case we forget to print out the object with writeObject.'
def reserveObject(self, name=''):
id = self.nextObject self.nextObject += 1 self.xrefTable.append([None, 0, name]) return Reference(id)
'Write out the xref table.'
def writeXref(self):
self.startxref = self.fh.tell() self.write(('xref\n0 %d\n' % self.nextObject)) i = 0 borken = False for (offset, generation, name) in self.xrefTable: if (offset is None): print >>sys.stderr, ('No offset for object %d (%s)' % (i, name)) borken = True else: self.write(('%010d %05d n \n' % (offset, generation))) i += 1 if borken: raise AssertionError, 'Indirect object does not exist'
'Write out the PDF trailer.'
def writeTrailer(self):
self.write('trailer\n') self.write(pdfRepr({'Size': self.nextObject, 'Root': self.rootObject, 'Info': self.infoObject})) self.write(('\nstartxref\n%d\n%%%%EOF\n' % self.startxref))
'Keeps track of which characters are required from each font.'
def track_characters(self, font, s):
if isinstance(font, (str, unicode)): fname = font else: fname = font.fname (realpath, stat_key) = get_realpath_and_stat(fname) used_characters = self.used_characters.setdefault(stat_key, (realpath, set())) used_characters[1].update([ord(x) for x in s])
'Set clip rectangle. Calls self.pop() and self.push().'
def clip_cmd(self, cliprect, clippath):
cmds = [] while (((self._cliprect, self._clippath) != (cliprect, clippath)) and (self.parent is not None)): cmds.extend(self.pop()) if ((self._cliprect, self._clippath) != (cliprect, clippath)): cmds.extend(self.push()) if (self._cliprect != cliprect): cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath]) if (self._clippath != clippath): cmds.extend((PdfFile.pathOperations(*clippath.get_transformed_path_and_affine()) + [Op.clip, Op.endpath])) return cmds
'Copy properties of other into self and return PDF commands needed to transform self into other.'
def delta(self, other):
cmds = [] for (params, cmd) in self.commands: different = False for p in params: ours = getattr(self, p) theirs = getattr(other, p) try: different = bool((ours != theirs)) except ValueError: ours = npy.asarray(ours) theirs = npy.asarray(theirs) different = ((ours.shape != theirs.shape) or npy.any((ours != theirs))) if different: break if different: theirs = [getattr(other, p) for p in params] cmds.extend(cmd(self, *theirs)) for p in params: setattr(self, p, getattr(other, p)) return cmds
'Copy properties of other into self.'
def copy_properties(self, other):
GraphicsContextBase.copy_properties(self, other) self._fillcolor = other._fillcolor
'Make sure every pushed graphics state is popped.'
def finalize(self):
cmds = [] while (self.parent is not None): cmds.extend(self.pop()) return cmds
'Although postscript itself is dpi independent, we need to imform the image code about a requested dpi to generate high res images and them scale them before embeddin them'
def __init__(self, width, height, pswriter, imagedpi=72):
RendererBase.__init__(self) self.width = width self.height = height self._pswriter = pswriter if rcParams['text.usetex']: self.textcnt = 0 self.psfrag = [] self.imagedpi = imagedpi if rcParams['path.simplify']: self.simplify = ((width * imagedpi), (height * imagedpi)) else: self.simplify = None self.color = None self.linewidth = None self.linejoin = None self.linecap = None self.linedash = None self.fontname = None self.fontsize = None self.hatch = None self.image_magnification = (imagedpi / 72.0) self._clip_paths = {} self._path_collection_id = 0 self.used_characters = {} self.mathtext_parser = MathTextParser('PS')
'Keeps track of which characters are required from each font.'
def track_characters(self, font, s):
(realpath, stat_key) = get_realpath_and_stat(font.fname) used_characters = self.used_characters.setdefault(stat_key, (realpath, set())) used_characters[1].update([ord(x) for x in s])
'hatch can be one of: / - diagonal hatching \ - back diagonal | - vertical - - horizontal + - crossed X - crossed diagonal letters can be combined, in which case all the specified hatchings are done if same letter repeats, it increases the density of hatching in that direction'
def set_hatch(self, hatch):
hatches = {'horiz': 0, 'vert': 0, 'diag1': 0, 'diag2': 0} for letter in hatch: if (letter == '/'): hatches['diag2'] += 1 elif (letter == '\\'): hatches['diag1'] += 1 elif (letter == '|'): hatches['vert'] += 1 elif (letter == '-'): hatches['horiz'] += 1 elif (letter == '+'): hatches['horiz'] += 1 hatches['vert'] += 1 elif (letter.lower() == 'x'): hatches['diag1'] += 1 hatches['diag2'] += 1 def do_hatch(angle, density): if (density == 0): return '' return (' gsave\n eoclip %s rotate 0.0 0.0 0.0 0.0 setrgbcolor 0 setlinewidth\n /hatchgap %d def\n pathbbox /hatchb exch def /hatchr exch def /hatcht exch def /hatchl exch def\n hatchl cvi hatchgap idiv hatchgap mul\n hatchgap\n hatchr cvi hatchgap idiv hatchgap mul\n {hatcht m 0 hatchb hatcht sub r }\n for\n stroke\n grestore\n ' % (angle, (12 / density))) self._pswriter.write('gsave\n') self._pswriter.write(do_hatch(90, hatches['horiz'])) self._pswriter.write(do_hatch(0, hatches['vert'])) self._pswriter.write(do_hatch(45, hatches['diag1'])) self._pswriter.write(do_hatch((-45), hatches['diag2'])) self._pswriter.write('grestore\n')
'return the canvas width and height in display coords'
def get_canvas_width_height(self):
return (self.width, self.height)
'get the width and height in display coords of the string s with FontPropertry prop'
def get_text_width_height_descent(self, s, prop, ismath):
if rcParams['text.usetex']: texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() (l, b, r, t) = texmanager.get_ps_bbox(s, fontsize) w = (r - l) h = (t - b) return (w, h, 0) if ismath: (width, height, descent, pswriter, used_characters) = self.mathtext_parser.parse(s, 72, prop) return (width, height, descent) if rcParams['ps.useafm']: if ismath: s = s[1:(-1)] font = self._get_font_afm(prop) (l, b, w, h, d) = font.get_str_bbox_and_descent(s) fontsize = prop.get_size_in_points() scale = (0.001 * fontsize) w *= scale h *= scale d *= scale return (w, h, d) font = self._get_font_ttf(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) (w, h) = font.get_width_height() w /= 64.0 h /= 64.0 d = font.get_descent() d /= 64.0 return (w, h, d)
'return true if small y numbers are top for renderer'
def flipy(self):
return False
'Get the factor by which to magnify images passed to draw_image. Allows a backend to have images at a different resolution to other artists.'
def get_image_magnification(self):
return self.image_magnification
'Draw the Image instance into the current axes; x is the distance in pixels from the left hand side of the canvas and y is the distance from bottom bbox is a matplotlib.transforms.BBox instance for clipping, or None'
def draw_image(self, x, y, im, bbox, clippath=None, clippath_trans=None):
im.flipud_out() if im.is_grayscale: (h, w, bits) = self._gray(im) imagecmd = 'image' else: (h, w, bits) = self._rgb(im) imagecmd = 'false 3 colorimage' hexlines = '\n'.join(self._hex_lines(bits)) (xscale, yscale) = ((w / self.image_magnification), (h / self.image_magnification)) figh = (self.height * 72) clip = [] if (bbox is not None): (clipx, clipy, clipw, cliph) = bbox.bounds clip.append(('%s clipbox' % _nums_to_str(clipw, cliph, clipx, clipy))) if (clippath is not None): id = self._get_clip_path(clippath, clippath_trans) clip.append(('%s' % id)) clip = '\n'.join(clip) ps = ('gsave\n%(clip)s\n%(x)s %(y)s translate\n%(xscale)s %(yscale)s scale\n/DataString %(w)s string def\n%(w)s %(h)s 8 [ %(w)s 0 0 -%(h)s 0 %(h)s ]\n{\ncurrentfile DataString readhexstring pop\n} bind %(imagecmd)s\n%(hexlines)s\ngrestore\n' % locals()) self._pswriter.write(ps) im.flipud_out()
'Draws a Path instance using the given affine transform.'
def draw_path(self, gc, path, transform, rgbFace=None):
ps = self._convert_path(path, transform, self.simplify) self._draw_ps(ps, gc, rgbFace)
'Draw the markers defined by path at each of the positions in x and y. path coordinates are points, x and y coords will be transformed by the transform'
def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
if debugPS: self._pswriter.write('% draw_markers \n') write = self._pswriter.write if rgbFace: if ((rgbFace[0] == rgbFace[1]) and (rgbFace[0] == rgbFace[2])): ps_color = ('%1.3f setgray' % rgbFace[0]) else: ps_color = ('%1.3f %1.3f %1.3f setrgbcolor' % rgbFace) ps_cmd = ['/o {', 'gsave', 'newpath', 'translate'] ps_cmd.append(self._convert_path(marker_path, marker_trans)) if rgbFace: ps_cmd.extend(['gsave', ps_color, 'fill', 'grestore']) ps_cmd.extend(['stroke', 'grestore', '} bind def']) tpath = trans.transform_path(path) for (vertices, code) in tpath.iter_segments(): if len(vertices): (x, y) = vertices[(-2):] ps_cmd.append(('%g %g o' % (x, y))) ps = '\n'.join(ps_cmd) self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
'draw a Text instance'
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!'):
(w, h, bl) = self.get_text_width_height_descent(s, prop, ismath) fontsize = prop.get_size_in_points() corr = 0 pos = _nums_to_str((x - corr), y) thetext = ('psmarker%d' % self.textcnt) color = ('%1.3f,%1.3f,%1.3f' % gc.get_rgb()[:3]) fontcmd = {'sans-serif': '{\\sffamily %s}', 'monospace': '{\\ttfamily %s}'}.get(rcParams['font.family'], '{\\rmfamily %s}') s = (fontcmd % s) tex = ('\\color[rgb]{%s} %s' % (color, s)) self.psfrag.append(('\\psfrag{%s}[bl][bl][1][%f]{\\fontsize{%f}{%f}%s}' % (thetext, angle, fontsize, (fontsize * 1.25), tex))) ps = ('gsave\n%(pos)s moveto\n(%(thetext)s)\nshow\ngrestore\n ' % locals()) self._pswriter.write(ps) self.textcnt += 1
'draw a Text instance'
def draw_text(self, gc, x, y, s, prop, angle, ismath):
write = self._pswriter.write if debugPS: write('% text\n') if (ismath == 'TeX'): return self.tex(gc, x, y, s, prop, angle) elif ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) elif isinstance(s, unicode): return self.draw_unicode(gc, x, y, s, prop, angle) elif rcParams['ps.useafm']: font = self._get_font_afm(prop) (l, b, w, h) = font.get_str_bbox(s) fontsize = prop.get_size_in_points() l *= (0.001 * fontsize) b *= (0.001 * fontsize) w *= (0.001 * fontsize) h *= (0.001 * fontsize) if (angle == 90): (l, b) = ((- b), l) pos = _nums_to_str((x - l), (y - b)) thetext = ('(%s)' % s) fontname = font.get_fontname() fontsize = prop.get_size_in_points() rotate = ('%1.1f rotate' % angle) setcolor = ('%1.3f %1.3f %1.3f setrgbcolor' % gc.get_rgb()[:3]) ps = ('gsave\n/%(fontname)s findfont\n%(fontsize)s scalefont\nsetfont\n%(pos)s moveto\n%(rotate)s\n%(thetext)s\n%(setcolor)s\nshow\ngrestore\n ' % locals()) self._draw_ps(ps, gc, None) else: font = self._get_font_ttf(prop) font.set_text(s, 0, flags=LOAD_NO_HINTING) self.track_characters(font, s) self.set_color(*gc.get_rgb()) self.set_font(font.get_sfnt()[(1, 0, 0, 6)], prop.get_size_in_points()) write(('%s m\n' % _nums_to_str(x, y))) if angle: write('gsave\n') write(('%s rotate\n' % _num_to_str(angle))) descent = (font.get_descent() / 64.0) if descent: write(('0 %s rmoveto\n' % _num_to_str(descent))) write(('(%s) show\n' % quote_ps_string(s))) if angle: write('grestore\n')
'draw a unicode string. ps doesn\'t have unicode support, so we have to do this the hard way'
def draw_unicode(self, gc, x, y, s, prop, angle):
if rcParams['ps.useafm']: self.set_color(*gc.get_rgb()) font = self._get_font_afm(prop) fontname = font.get_fontname() fontsize = prop.get_size_in_points() scale = (0.001 * fontsize) thisx = 0 thisy = (font.get_str_bbox_and_descent(s)[4] * scale) last_name = None lines = [] for c in s: name = uni2type1.get(ord(c), 'question') try: width = font.get_width_from_char_name(name) except KeyError: name = 'question' width = font.get_width_char('?') if (last_name is not None): kern = font.get_kern_dist_from_name(last_name, name) else: kern = 0 last_name = name thisx += (kern * scale) lines.append(('%f %f m /%s glyphshow' % (thisx, thisy, name))) thisx += (width * scale) thetext = '\n'.join(lines) ps = ('gsave\n/%(fontname)s findfont\n%(fontsize)s scalefont\nsetfont\n%(x)f %(y)f translate\n%(angle)f rotate\n%(thetext)s\ngrestore\n ' % locals()) self._pswriter.write(ps) else: font = self._get_font_ttf(prop) font.set_text(s, 0, flags=LOAD_NO_HINTING) self.track_characters(font, s) self.set_color(*gc.get_rgb()) self.set_font(font.get_sfnt()[(1, 0, 0, 6)], prop.get_size_in_points()) cmap = font.get_charmap() lastgind = None lines = [] thisx = 0 thisy = (font.get_descent() / 64.0) for c in s: ccode = ord(c) gind = cmap.get(ccode) if (gind is None): ccode = ord('?') name = '.notdef' gind = 0 else: name = font.get_glyph_name(gind) glyph = font.load_char(ccode, flags=LOAD_NO_HINTING) if (lastgind is not None): kern = font.get_kerning(lastgind, gind, KERNING_DEFAULT) else: kern = 0 lastgind = gind thisx += (kern / 64.0) lines.append(('%f %f m /%s glyphshow' % (thisx, thisy, name))) thisx += (glyph.linearHoriAdvance / 65536.0) thetext = '\n'.join(lines) ps = ('gsave\n%(x)f %(y)f translate\n%(angle)f rotate\n%(thetext)s\ngrestore\n' % locals()) self._pswriter.write(ps)
'Draw the math text using matplotlib.mathtext'
def draw_mathtext(self, gc, x, y, s, prop, angle):
if debugPS: self._pswriter.write('% mathtext\n') (width, height, descent, pswriter, used_characters) = self.mathtext_parser.parse(s, 72, prop) self.merge_used_characters(used_characters) self.set_color(*gc.get_rgb()) thetext = pswriter.getvalue() ps = ('gsave\n%(x)f %(y)f translate\n%(angle)f rotate\n%(thetext)s\ngrestore\n' % locals()) self._pswriter.write(ps)
'Emit the PostScript sniplet \'ps\' with all the attributes from \'gc\' applied. \'ps\' must consist of PostScript commands to construct a path. The fill and/or stroke kwargs can be set to False if the \'ps\' string already includes filling and/or stroking, in which case _draw_ps is just supplying properties and clipping.'
def _draw_ps(self, ps, gc, rgbFace, fill=True, stroke=True, command=None):
write = self._pswriter.write if (debugPS and command): write((('% ' + command) + '\n')) mightstroke = ((gc.get_linewidth() > 0.0) and ((len(gc.get_rgb()) <= 3) or (gc.get_rgb()[3] != 0.0))) stroke = (stroke and mightstroke) fill = (fill and (rgbFace is not None) and ((len(rgbFace) <= 3) or (rgbFace[3] != 0.0))) if mightstroke: self.set_linewidth(gc.get_linewidth()) jint = gc.get_joinstyle() self.set_linejoin(jint) cint = gc.get_capstyle() self.set_linecap(cint) self.set_linedash(*gc.get_dashes()) self.set_color(*gc.get_rgb()[:3]) write('gsave\n') cliprect = gc.get_clip_rectangle() if cliprect: (x, y, w, h) = cliprect.bounds write(('%1.4g %1.4g %1.4g %1.4g clipbox\n' % (w, h, x, y))) (clippath, clippath_trans) = gc.get_clip_path() if clippath: id = self._get_clip_path(clippath, clippath_trans) write(('%s\n' % id)) write(ps.strip()) write('\n') if fill: if stroke: write('gsave\n') self.set_color(store=0, *rgbFace[:3]) write('fill\ngrestore\n') else: self.set_color(store=0, *rgbFace[:3]) write('fill\n') hatch = gc.get_hatch() if hatch: self.set_hatch(hatch) if stroke: write('stroke\n') write('grestore\n')
'Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you\'ll probably want to override this on hardcopy If outfile is a string, it is interpreted as a file name. If the extension matches .ep* write encapsulated postscript, otherwise write a stand-alone PostScript file. If outfile is a file object, a stand-alone PostScript file is written into this file object.'
def _print_figure(self, outfile, format, dpi=72, facecolor='w', edgecolor='w', orientation='portrait', isLandscape=False, papertype=None):
isEPSF = (format == 'eps') passed_in_file_object = False if is_string_like(outfile): title = outfile tmpfile = os.path.join(gettempdir(), md5(outfile).hexdigest()) elif is_writable_file_like(outfile): title = None tmpfile = os.path.join(gettempdir(), md5(str(hash(outfile))).hexdigest()) passed_in_file_object = True else: raise ValueError('outfile must be a path or a file-like object') fh = file(tmpfile, 'w') (width, height) = self.figure.get_size_inches() if (papertype == 'auto'): if isLandscape: papertype = _get_papertype(height, width) else: papertype = _get_papertype(width, height) if isLandscape: (paperHeight, paperWidth) = papersize[papertype] else: (paperWidth, paperHeight) = papersize[papertype] if (rcParams['ps.usedistiller'] and (not (papertype == 'auto'))): if ((width > paperWidth) or (height > paperHeight)): if isLandscape: papertype = _get_papertype(height, width) (paperHeight, paperWidth) = papersize[papertype] else: papertype = _get_papertype(width, height) (paperWidth, paperHeight) = papersize[papertype] xo = ((72 * 0.5) * (paperWidth - width)) yo = ((72 * 0.5) * (paperHeight - height)) (l, b, w, h) = self.figure.bbox.bounds llx = xo lly = yo urx = (llx + w) ury = (lly + h) rotation = 0 if isLandscape: (llx, lly, urx, ury) = (lly, llx, ury, urx) (xo, yo) = (((72 * paperHeight) - yo), xo) rotation = 90 bbox = (llx, lly, urx, ury) origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) self._pswriter = StringIO() renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) self.figure.draw(renderer) self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) if isEPSF: print >>fh, '%!PS-Adobe-3.0 EPSF-3.0' else: print >>fh, '%!PS-Adobe-3.0' if title: print >>fh, ('%%Title: ' + title) print >>fh, (('%%Creator: matplotlib version ' + __version__) + ', http://matplotlib.sourceforge.net/') print >>fh, ('%%CreationDate: ' + time.ctime(time.time())) print >>fh, ('%%Orientation: ' + orientation) if (not isEPSF): print >>fh, ('%%DocumentPaperSizes: ' + papertype) print >>fh, ('%%%%BoundingBox: %d %d %d %d' % bbox) if (not isEPSF): print >>fh, '%%Pages: 1' print >>fh, '%%EndComments' Ndict = len(psDefs) print >>fh, '%%BeginProlog' if (not rcParams['ps.useafm']): Ndict += len(renderer.used_characters) print >>fh, ('/mpldict %d dict def' % Ndict) print >>fh, 'mpldict begin' for d in psDefs: d = d.strip() for l in d.split('\n'): print >>fh, l.strip() if (not rcParams['ps.useafm']): for (font_filename, chars) in renderer.used_characters.values(): if len(chars): font = FT2Font(font_filename) cmap = font.get_charmap() glyph_ids = [] for c in chars: gind = (cmap.get(c) or 0) glyph_ids.append(gind) if is_opentype_cff_font(font_filename): raise RuntimeError('OpenType CFF fonts can not be saved using the internal Postscript backend at this time.\nConsider using the Cairo backend.') else: fonttype = rcParams['ps.fonttype'] convert_ttf_to_ps(font_filename, fh, rcParams['ps.fonttype'], glyph_ids) print >>fh, 'end' print >>fh, '%%EndProlog' if (not isEPSF): print >>fh, '%%Page: 1 1' print >>fh, 'mpldict begin' print >>fh, ('%s translate' % _nums_to_str(xo, yo)) if rotation: print >>fh, ('%d rotate' % rotation) print >>fh, ('%s clipbox' % _nums_to_str((width * 72), (height * 72), 0, 0)) print >>fh, self._pswriter.getvalue() print >>fh, 'end' print >>fh, 'showpage' if (not isEPSF): print >>fh, '%%EOF' fh.close() if (rcParams['ps.usedistiller'] == 'ghostscript'): gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) elif (rcParams['ps.usedistiller'] == 'xpdf'): xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) if passed_in_file_object: fh = file(tmpfile) print >>outfile, fh.read() else: shutil.move(tmpfile, outfile)
'If text.usetex is True in rc, a temporary pair of tex/eps files are created to allow tex to manage the text layout via the PSFrags package. These files are processed to yield the final ps or eps file.'
def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor, orientation, isLandscape, papertype):
isEPSF = (format == 'eps') title = outfile tmpfile = os.path.join(gettempdir(), md5(outfile).hexdigest()) fh = file(tmpfile, 'w') self.figure.dpi = 72 (width, height) = self.figure.get_size_inches() xo = 0 yo = 0 (l, b, w, h) = self.figure.bbox.bounds llx = xo lly = yo urx = (llx + w) ury = (lly + h) bbox = (llx, lly, urx, ury) origfacecolor = self.figure.get_facecolor() origedgecolor = self.figure.get_edgecolor() self.figure.set_facecolor(facecolor) self.figure.set_edgecolor(edgecolor) self._pswriter = StringIO() renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) self.figure.draw(renderer) self.figure.set_facecolor(origfacecolor) self.figure.set_edgecolor(origedgecolor) print >>fh, '%!PS-Adobe-3.0 EPSF-3.0' if title: print >>fh, ('%%Title: ' + title) print >>fh, (('%%Creator: matplotlib version ' + __version__) + ', http://matplotlib.sourceforge.net/') print >>fh, ('%%CreationDate: ' + time.ctime(time.time())) print >>fh, ('%%%%BoundingBox: %d %d %d %d' % bbox) print >>fh, '%%EndComments' Ndict = len(psDefs) print >>fh, '%%BeginProlog' print >>fh, ('/mpldict %d dict def' % Ndict) print >>fh, 'mpldict begin' for d in psDefs: d = d.strip() for l in d.split('\n'): print >>fh, l.strip() print >>fh, 'end' print >>fh, '%%EndProlog' print >>fh, 'mpldict begin' print >>fh, ('%s translate' % _nums_to_str(xo, yo)) print >>fh, ('%s clipbox' % _nums_to_str((width * 72), (height * 72), 0, 0)) print >>fh, self._pswriter.getvalue() print >>fh, 'end' print >>fh, 'showpage' fh.close() if isLandscape: isLandscape = True (width, height) = (height, width) bbox = (lly, llx, ury, urx) temp_papertype = _get_papertype(width, height) if (papertype == 'auto'): papertype = temp_papertype (paperWidth, paperHeight) = papersize[temp_papertype] else: (paperWidth, paperHeight) = papersize[papertype] if (((width > paperWidth) or (height > paperHeight)) and isEPSF): (paperWidth, paperHeight) = papersize[temp_papertype] verbose.report(('Your figure is too big to fit on %s paper. %s paper will be used to prevent clipping.' % (papertype, temp_papertype)), 'helpful') texmanager = renderer.get_texmanager() font_preamble = texmanager.get_font_preamble() custom_preamble = texmanager.get_custom_preamble() convert_psfrags(tmpfile, renderer.psfrag, font_preamble, custom_preamble, paperWidth, paperHeight, orientation) if (rcParams['ps.usedistiller'] == 'ghostscript'): gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) elif (rcParams['ps.usedistiller'] == 'xpdf'): xpdf_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) elif rcParams['text.usetex']: if False: pass else: gs_distill(tmpfile, isEPSF, ptype=papertype, bbox=bbox) if isinstance(outfile, file): fh = file(tmpfile) print >>outfile, fh.read() else: shutil.move(tmpfile, outfile)
'Override by GTK backends to select a different renderer Renderer should provide the methods: set_pixmap () set_width_height () that are used by _render_figure() / _pixmap_prepare()'
def _renderer_init(self):
self._renderer = RendererGDK(self, self.figure.dpi)
'Make sure _._pixmap is at least width, height, create new pixmap if necessary'
def _pixmap_prepare(self, width, height):
if _debug: print ('FigureCanvasGTK.%s' % fn_name()) create_pixmap = False if (width > self._pixmap_width): self._pixmap_width = max(int((self._pixmap_width * 1.1)), width) create_pixmap = True if (height > self._pixmap_height): self._pixmap_height = max(int((self._pixmap_height * 1.1)), height) create_pixmap = True if create_pixmap: self._pixmap = gdk.Pixmap(self.window, self._pixmap_width, self._pixmap_height) self._renderer.set_pixmap(self._pixmap)
'used by GTK and GTKcairo. GTKAgg overrides'
def _render_figure(self, pixmap, width, height):
self._renderer.set_width_height(width, height) self.figure.draw(self._renderer)
'Expose_event for all GTK backends. Should not be overridden.'
def expose_event(self, widget, event):
if _debug: print ('FigureCanvasGTK.%s' % fn_name()) if GTK_WIDGET_DRAWABLE(self): if self._need_redraw: (x, y, w, h) = self.allocation self._pixmap_prepare(w, h) self._render_figure(self._pixmap, w, h) self._need_redraw = False (x, y, w, h) = event.area self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, x, y, x, y, w, h) return False
'set the canvas size in pixels'
def resize(self, width, height):
self.window.resize(width, height)
'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744'
def draw_rubberband(self, event, x0, y0, x1, y1):
drawable = self.canvas.window if (drawable is None): return gc = drawable.new_gc() height = self.canvas.figure.bbox.height y1 = (height - y1) y0 = (height - y0) w = abs((x1 - x0)) h = abs((y1 - y0)) rect = [int(val) for val in (min(x0, x1), min(y0, y1), w, h)] try: (lastrect, imageBack) = self._imageBack except AttributeError: if (event.inaxes is None): return ax = event.inaxes (l, b, w, h) = [int(val) for val in ax.bbox.bounds] b = (int(height) - (b + h)) axrect = (l, b, w, h) self._imageBack = (axrect, drawable.get_image(*axrect)) drawable.draw_rectangle(gc, False, *rect) self._idle_draw_id = 0 else: def idle_draw(*args): drawable.draw_image(gc, imageBack, 0, 0, *lastrect) drawable.draw_rectangle(gc, False, *rect) self._idle_draw_id = 0 return False if (self._idle_draw_id == 0): self._idle_draw_id = gobject.idle_add(idle_draw)
'figManager is the FigureManagerGTK instance that contains the toolbar, with attributes figure, window and drawingArea'
def __init__(self, canvas, window):
gtk.Toolbar.__init__(self) self.canvas = canvas self.win = window self.set_style(gtk.TOOLBAR_ICONS) if (gtk.pygtk_version >= (2, 4, 0)): self._create_toolitems_2_4() self.update = self._update_2_4 self.fileselect = FileChooserDialog(title='Save the figure', parent=self.win, filetypes=self.canvas.get_supported_filetypes(), default_filetype=self.canvas.get_default_filetype()) else: self._create_toolitems_2_2() self.update = self._update_2_2 self.fileselect = FileSelection(title='Save the figure', parent=self.win) self.show_all() self.update()
'panx in direction'
def panx(self, button, direction):
for a in self._active: a.xaxis.pan(direction) self.canvas.draw() return True
'pany in direction'
def pany(self, button, direction):
for a in self._active: a.yaxis.pan(direction) self.canvas.draw() return True
'zoomx in direction'
def zoomx(self, button, direction):
for a in self._active: a.xaxis.zoom(direction) self.canvas.draw() return True
'zoomy in direction'
def zoomy(self, button, direction):
for a in self._active: a.yaxis.zoom(direction) self.canvas.draw() return True
'populate the combo box'
def show(self):
self._updateson = False cbox = self.cbox_lineprops for i in range((self._lastcnt - 1), (-1), (-1)): cbox.remove_text(i) for line in self.lines: cbox.append_text(line.get_label()) cbox.set_active(0) self._updateson = True self._lastcnt = len(self.lines) self.dlg.show()
'get the active line'
def get_active_line(self):
ind = self.cbox_lineprops.get_active() line = self.lines[ind] return line
'get the active lineinestyle'
def get_active_linestyle(self):
ind = self.cbox_linestyles.get_active() ls = self.linestyles[ind] return ls
'get the active lineinestyle'
def get_active_marker(self):
ind = self.cbox_markers.get_active() m = self.markers[ind] return m
'update the active line props from the widgets'
def _update(self):
if ((not self._inited) or (not self._updateson)): return line = self.get_active_line() ls = self.get_active_linestyle() marker = self.get_active_marker() line.set_linestyle(ls) line.set_marker(marker) button = self.wtree.get_widget('colorbutton_linestyle') color = button.get_color() (r, g, b) = [(val / 65535.0) for val in (color.red, color.green, color.blue)] line.set_color((r, g, b)) button = self.wtree.get_widget('colorbutton_markerface') color = button.get_color() (r, g, b) = [(val / 65535.0) for val in (color.red, color.green, color.blue)] line.set_markerfacecolor((r, g, b)) line.figure.canvas.draw()
'update the widgets from the active line'
def on_combobox_lineprops_changed(self, item):
if (not self._inited): return self._updateson = False line = self.get_active_line() ls = line.get_linestyle() if (ls is None): ls = 'None' self.cbox_linestyles.set_active(self.linestyled[ls]) marker = line.get_marker() if (marker is None): marker = 'None' self.cbox_markers.set_active(self.markerd[marker]) (r, g, b) = colorConverter.to_rgb(line.get_color()) color = gtk.gdk.Color(*[int((val * 65535)) for val in (r, g, b)]) button = self.wtree.get_widget('colorbutton_linestyle') button.set_color(color) (r, g, b) = colorConverter.to_rgb(line.get_markerfacecolor()) color = gtk.gdk.Color(*[int((val * 65535)) for val in (r, g, b)]) button = self.wtree.get_widget('colorbutton_markerface') button.set_color(color) self._updateson = True
'called colorbutton marker clicked'
def on_colorbutton_markerface_color_set(self, button):
self._update()
'width: The width of the canvas in logical units height: The height of the canvas in logical units dpi: The dpi of the canvas vector_renderer: An instance of a subclass of RendererBase that will be used for the vector drawing. raster_renderer_class: The renderer class to use for the raster drawing. If not provided, this will use the Agg backend (which is currently the only viable option anyway.)'
def __init__(self, width, height, dpi, vector_renderer, raster_renderer_class=None):
if (raster_renderer_class is None): raster_renderer_class = RendererAgg self._raster_renderer_class = raster_renderer_class self._width = width self._height = height self.dpi = dpi assert (not vector_renderer.option_image_nocomposite()) self._vector_renderer = vector_renderer self._raster_renderer = None self._rasterizing = 0 self._set_current_renderer(vector_renderer)
'Enter "raster" mode. All subsequent drawing commands (until stop_rasterizing is called) will be drawn with the raster backend. If start_rasterizing is called multiple times before stop_rasterizing is called, this method has no effect.'
def start_rasterizing(self):
if (self._rasterizing == 0): self._raster_renderer = self._raster_renderer_class((self._width * self.dpi), (self._height * self.dpi), self.dpi) self._set_current_renderer(self._raster_renderer) self._rasterizing += 1
'Exit "raster" mode. All of the drawing that was done since the last start_rasterizing command will be copied to the vector backend by calling draw_image. If stop_rasterizing is called multiple times before start_rasterizing is called, this method has no effect.'
def stop_rasterizing(self):
self._rasterizing -= 1 if (self._rasterizing == 0): self._set_current_renderer(self._vector_renderer) (width, height) = ((self._width * self.dpi), (self._height * self.dpi)) (buffer, bounds) = self._raster_renderer.tostring_rgba_minimized() (l, b, w, h) = bounds if ((w > 0) and (h > 0)): image = frombuffer(buffer, w, h, True) image.is_grayscale = False image.flipud_out() self._renderer.draw_image(l, ((height - b) - h), image, None) self._raster_renderer = None self._rasterizing = False
'Draw the figure using the renderer'
def draw(self):
renderer = RendererTemplate(self.figure.dpi) self.figure.draw(renderer)
'Write out format foo. The dpi, facecolor and edgecolor are restored to their original values after this call, so you don\'t need to save and restore them.'
def print_foo(self, filename, *args, **kwargs):
pass
'return the style string. style is generated from the GraphicsContext, rgbFace and clippath'
def _get_style(self, gc, rgbFace):
if (rgbFace is None): fill = 'none' else: fill = rgb2hex(rgbFace[:3]) (offset, seq) = gc.get_dashes() if (seq is None): dashes = '' else: dashes = ('stroke-dasharray: %s; stroke-dashoffset: %f;' % (','.join([('%f' % val) for val in seq]), offset)) linewidth = gc.get_linewidth() if linewidth: return ('fill: %s; stroke: %s; stroke-width: %f; stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %f' % (fill, rgb2hex(gc.get_rgb()[:3]), linewidth, gc.get_joinstyle(), _capstyle_d[gc.get_capstyle()], dashes, gc.get_alpha())) else: return ('fill: %s; opacity: %f' % (fill, gc.get_alpha()))
'if svg.image_noscale is True, compositing multiple images into one is prohibited'
def option_image_nocomposite(self):
return rcParams['svg.image_noscale']
'Draw math text using matplotlib.mathtext'
def _draw_mathtext(self, gc, x, y, s, prop, angle):
(width, height, descent, svg_elements, used_characters) = self.mathtext_parser.parse(s, 72, prop) svg_glyphs = svg_elements.svg_glyphs svg_rects = svg_elements.svg_rects color = rgb2hex(gc.get_rgb()[:3]) write = self._svgwriter.write style = ('fill: %s' % color) if rcParams['svg.embed_char_paths']: new_chars = [] for (font, fontsize, thetext, new_x, new_y_mtc, metrics) in svg_glyphs: path = self._add_char_def(font, thetext) if (path is not None): new_chars.append(path) if len(new_chars): write('<defs>\n') for path in new_chars: write(path) write('</defs>\n') svg = [('<g style="%s" transform="' % style)] if (angle != 0): svg.append(('translate(%f,%f)rotate(%1.1f)' % (x, y, (- angle)))) else: svg.append(('translate(%f,%f)' % (x, y))) svg.append('">\n') for (font, fontsize, thetext, new_x, new_y_mtc, metrics) in svg_glyphs: charid = self._get_char_def_id(font, thetext) svg.append(('<use xlink:href="#%s" transform="translate(%f,%f)scale(%f)"/>\n' % (charid, new_x, (- new_y_mtc), (fontsize / self.FONT_SCALE)))) svg.append('</g>\n') else: svg = [('<text style="%s" x="%f" y="%f"' % (style, x, y))] if (angle != 0): svg.append((' transform="translate(%f,%f) rotate(%1.1f) translate(%f,%f)"' % (x, y, (- angle), (- x), (- y)))) svg.append('>\n') (curr_x, curr_y) = (0.0, 0.0) for (font, fontsize, thetext, new_x, new_y_mtc, metrics) in svg_glyphs: new_y = (- new_y_mtc) style = ('font-size: %f; font-family: %s' % (fontsize, font.family_name)) svg.append(('<tspan style="%s"' % style)) xadvance = metrics.advance svg.append((' textLength="%f"' % xadvance)) dx = (new_x - curr_x) if (dx != 0.0): svg.append((' dx="%f"' % dx)) dy = (new_y - curr_y) if (dy != 0.0): svg.append((' dy="%f"' % dy)) thetext = escape_xml_text(thetext) svg.append(('>%s</tspan>\n' % thetext)) curr_x = (new_x + xadvance) curr_y = new_y svg.append('</text>\n') if len(svg_rects): style = ('fill: %s; stroke: none' % color) svg.append(('<g style="%s" transform="' % style)) if (angle != 0): svg.append(('translate(%f,%f) rotate(%1.1f)' % (x, y, (- angle)))) else: svg.append(('translate(%f,%f)' % (x, y))) svg.append('">\n') for (x, y, width, height) in svg_rects: svg.append(('<rect x="%f" y="%f" width="%f" height="%f" fill="black" stroke="none" />' % (x, ((- y) + height), width, height))) svg.append('</g>') self.open_group('mathtext') write(''.join(svg)) self.close_group('mathtext')
'Initialize the renderer with a gd image instance'
def __init__(self, outfile, width, height, dpi):
self.outfile = outfile self._cached = {} self._fontHandle = {} self.lastHandle = {'font': (-1), 'pen': (-1), 'brush': (-1)} self.emf = pyemf.EMF(width, height, dpi, 'in') self.width = int((width * dpi)) self.height = int((height * dpi)) self.dpi = dpi self.pointstodpi = (dpi / 72.0) self.hackPointsForMathExponent = 2.0 self.emf.SetBkMode(pyemf.TRANSPARENT) self.emf.SetTextAlign((pyemf.TA_BOTTOM | pyemf.TA_LEFT)) if debugPrint: print ('RendererEMF: (%f,%f) %s dpi=%f' % (self.width, self.height, outfile, dpi))
'Draw an arc using GraphicsContext instance gcEdge, centered at x,y, with width and height and angles from 0.0 to 360.0 0 degrees is at 3-o\'clock positive angles are anti-clockwise If the color rgbFace is not None, fill the arc with it.'
def draw_arc(self, gcEdge, rgbFace, x, y, width, height, angle1, angle2, rotation):
if debugPrint: print ('draw_arc: (%f,%f) angles=(%f,%f) w,h=(%f,%f)' % (x, y, angle1, angle2, width, height)) pen = self.select_pen(gcEdge) brush = self.select_brush(rgbFace) hw = (width / 2) hh = (height / 2) x1 = int((x - (width / 2))) y1 = int((y - (height / 2))) if brush: self.emf.Pie(int((x - hw)), int((self.height - (y - hh))), int((x + hw)), int((self.height - (y + hh))), int((x + (math.cos(((angle1 * math.pi) / 180.0)) * hw))), int((self.height - (y + (math.sin(((angle1 * math.pi) / 180.0)) * hh)))), int((x + (math.cos(((angle2 * math.pi) / 180.0)) * hw))), int((self.height - (y + (math.sin(((angle2 * math.pi) / 180.0)) * hh))))) else: self.emf.Arc(int((x - hw)), int((self.height - (y - hh))), int((x + hw)), int((self.height - (y + hh))), int((x + (math.cos(((angle1 * math.pi) / 180.0)) * hw))), int((self.height - (y + (math.sin(((angle1 * math.pi) / 180.0)) * hh)))), int((x + (math.cos(((angle2 * math.pi) / 180.0)) * hw))), int((self.height - (y + (math.sin(((angle2 * math.pi) / 180.0)) * hh)))))
'Draw the Image instance into the current axes; x is the distance in pixels from the left hand side of the canvas. y is the distance from the origin. That is, if origin is upper, y is the distance from top. If origin is lower, y is the distance from bottom bbox is a matplotlib.transforms.BBox instance for clipping, or None'
def draw_image(self, x, y, im, bbox):
pass
'Draw a single line from x1,y1 to x2,y2'
def draw_line(self, gc, x1, y1, x2, y2):
if debugPrint: print ('draw_line: (%f,%f) - (%f,%f)' % (x1, y1, x2, y2)) if self.select_pen(gc): self.emf.Polyline([(long(x1), long((self.height - y1))), (long(x2), long((self.height - y2)))]) elif debugPrint: print ('draw_line: optimizing away (%f,%f) - (%f,%f)' % (x1, y1, x2, y2))
'x and y are equal length arrays, draw lines connecting each point in x, y'
def draw_lines(self, gc, x, y):
if debugPrint: print ('draw_lines: %d points' % len(str(x))) if self.select_pen(gc): points = [(long(x[i]), long((self.height - y[i]))) for i in range(len(x))] self.emf.Polyline(points)
'Draw a single point at x,y Where \'point\' is a device-unit point (or pixel), not a matplotlib point'
def draw_point(self, gc, x, y):
if debugPrint: print ('draw_point: (%f,%f)' % (x, y)) pen = EMFPen(self.emf, gc) self.emf.SetPixel(long(x), long((self.height - y)), (pen.r, pen.g, pen.b))
'Draw a polygon using the GraphicsContext instance gc. points is a len vertices tuple, each element giving the x,y coords a vertex If the color rgbFace is not None, fill the polygon with it'
def draw_polygon(self, gcEdge, rgbFace, points):
if debugPrint: print ('draw_polygon: %d points' % len(points)) pen = self.select_pen(gcEdge) brush = self.select_brush(rgbFace) if (pen or brush): points = [(long(x), long((self.height - y))) for (x, y) in points] self.emf.Polygon(points) else: points = [(long(x), long((self.height - y))) for (x, y) in points] if debugPrint: print ('draw_polygon: optimizing away polygon: %d points = %s' % (len(points), str(points)))
'Draw a non-filled rectangle using the GraphicsContext instance gcEdge, with lower left at x,y with width and height. If rgbFace is not None, fill the rectangle with it.'
def draw_rectangle(self, gcEdge, rgbFace, x, y, width, height):
if debugPrint: print ('draw_rectangle: (%f,%f) w=%f,h=%f' % (x, y, width, height)) pen = self.select_pen(gcEdge) brush = self.select_brush(rgbFace) if (pen or brush): self.emf.Rectangle(int(x), int((self.height - y)), (int(x) + int(width)), (int((self.height - y)) - int(height))) elif debugPrint: print ('draw_rectangle: optimizing away (%f,%f) w=%f,h=%f' % (x, y, width, height))
'Draw the text.Text instance s at x,y (display coords) with font properties instance prop at angle in degrees, using GraphicsContext gc **backend implementers note** When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py if 0: bbox_artist(self, renderer) to if 1, and then the actual bounding box will be blotted along with your text.'
def draw_text(self, gc, x, y, s, prop, angle, ismath=False):
if debugText: print ("draw_text: (%f,%f) %d degrees: '%s'" % (x, y, angle, s)) if ismath: self.draw_math_text(gc, x, y, s, prop, angle) else: self.draw_plain_text(gc, x, y, s, prop, angle)