source: sasview/src/sas/sasgui/plottools/toolbar.py @ 5251ec6

magnetic_scattrelease-4.2.2ticket-1009ticket-1249
Last change on this file since 5251ec6 was 5251ec6, checked in by Paul Kienzle <pkienzle@…>, 6 years ago

improved support for py37 in sasgui

  • Property mode set to 100644
File size: 6.6 KB
Line 
1"""
2    This module overwrites matplotlib toolbar
3"""
4import wx
5from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg
6from matplotlib.backends.backend_wx import _load_bitmap
7import logging
8
9logger = logging.getLogger(__name__)
10
11# Event binding code changed after version 2.5
12if wx.VERSION_STRING >= '2.5':
13    def bind(actor, event, action, **kw):
14        actor.Bind(event, action, **kw)
15else:
16    def bind(actor, event, action, id=None):
17        if id is not None:
18            event(actor, id, action)
19        else:
20            event(actor, action)
21
22class NavigationToolBar(NavigationToolbar2WxAgg):
23    _NTB2_HOME = wx.NewId()
24    _NTB2_BACK = wx.NewId()
25    _NTB2_FORWARD = wx.NewId()
26    _NTB2_PAN = wx.NewId()
27    _NTB2_ZOOM = wx.NewId()
28    _NTB2_SAVE = wx.NewId()
29    _NTB2_PRINT = wx.NewId()
30    _NTB2_RESET = wx.NewId()
31    _NTB2_COPY = wx.NewId()
32    """
33    Overwrite matplotlib toolbar
34    """
35    def __init__(self, canvas, parent=None):
36        NavigationToolbar2WxAgg.__init__(self, canvas)
37
38    # CRUFT: mpl 1.1 uses save rather than save_figure
39    try: save_figure = NavigationToolbar2WxAgg.save
40    except AttributeError: pass
41   
42    def _init_toolbar(self):
43        self._parent = self.canvas.GetParent()
44
45        # for mpl 1.2+ compatibility
46        self.wx_ids = {}
47        self.wx_ids['Back'] = self._NTB2_BACK
48        self.wx_ids['Forward'] = self._NTB2_FORWARD
49        self.wx_ids['Pan'] = self._NTB2_PAN
50        self.wx_ids['Zoom'] = self._NTB2_ZOOM
51
52        self.SetToolBitmapSize(wx.Size(24, 24))
53
54        context_tip = 'Graph Menu: \n'
55        context_tip += '    For more menu options, \n'
56        context_tip += '    right-click the data symbols.'
57        context = wx.ArtProvider.GetBitmap(wx.ART_LIST_VIEW, wx.ART_TOOLBAR)
58        self.AddSimpleTool(self._NTB2_HOME, context, context_tip, context_tip)
59
60        self.InsertSeparator(1)
61
62        self.AddSimpleTool(self._NTB2_BACK, _load_bitmap('back.png'),
63                           'Back', 'Back navigation view')
64        self.AddSimpleTool(self._NTB2_FORWARD, _load_bitmap('forward.png'),
65                           'Forward', 'Forward navigation view')
66        # todo: get new bitmap
67        # todo: update with code from matplotlib/backends/backend_wx.py
68        is_phoenix = 'phoenix' in wx.PlatformInfo
69        if is_phoenix: # wx phoenix >= 4.0.0b2
70            self.AddCheckTool(self._NTB2_PAN, "Pan", _load_bitmap('move.png'),
71                              shortHelp='Pan',
72                              longHelp='Pan with left, zoom with right')
73            self.AddCheckTool(self._NTB2_ZOOM, "Zoom", _load_bitmap('zoom_to_rect.png'),
74                              shortHelp='Zoom', longHelp='Zoom to rectangle')
75        else:
76            self.AddCheckTool(self._NTB2_PAN, _load_bitmap('move.png'),
77                              shortHelp='Pan',
78                              longHelp='Pan with left, zoom with right')
79            self.AddCheckTool(self._NTB2_ZOOM, _load_bitmap('zoom_to_rect.png'),
80                              shortHelp='Zoom', longHelp='Zoom to rectangle')
81
82        self.AddSeparator()
83        self.AddSimpleTool(self._NTB2_SAVE, _load_bitmap('filesave.png'),
84                           'Save', 'Save plot contents to file')
85
86        print_bmp = wx.ArtProvider.GetBitmap(wx.ART_PRINT, wx.ART_TOOLBAR)
87        self.AddSimpleTool(self._NTB2_PRINT, print_bmp, 'Print', 'Print plot')
88
89        reset_bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_HOME, wx.ART_TOOLBAR)
90        self.AddSimpleTool(self._NTB2_RESET, reset_bmp, 'Reset', 'Reset graph range')
91
92        bind(self, wx.EVT_TOOL, self.context_menu, id=self._NTB2_HOME)
93        bind(self, wx.EVT_TOOL, self.forward, id=self._NTB2_FORWARD)
94        bind(self, wx.EVT_TOOL, self.back, id=self._NTB2_BACK)
95        bind(self, wx.EVT_TOOL, self.zoom, id=self._NTB2_ZOOM)
96        bind(self, wx.EVT_TOOL, self.pan, id=self._NTB2_PAN)
97        bind(self, wx.EVT_TOOL, self.save_figure, id=self._NTB2_SAVE)
98        bind(self, wx.EVT_TOOL, self.print_figure, id=self._NTB2_PRINT)
99        bind(self, wx.EVT_TOOL, self.home, id=self._NTB2_RESET)
100
101        self.Realize()
102
103    def on_menu(self, event):
104        try:
105            self._parent.onToolContextMenu(event=event)
106        except:
107            logger.error("Plot toolbar could not show menu")
108
109    def context_menu(self, event):
110        """
111        Default context menu for a plot panel
112
113        """
114        # Slicer plot popup menu
115        popup = wx.Menu()
116        popup.Append(self._NTB2_SAVE, '&Save image', 'Save image as PNG')
117        wx.EVT_MENU(self, self._NTB2_SAVE, self.save_figure)
118
119        popup.Append(self._NTB2_PRINT, '&Print image', 'Print image ')
120        wx.EVT_MENU(self, self._NTB2_PRINT, self.print_figure)
121
122        popup.Append(self._NTB2_COPY, '&Copy to Clipboard', 'Copy image to the clipboard')
123        wx.EVT_MENU(self, self._NTB2_COPY, self.copy_figure)
124
125        # Show the popup menu relative to the location of the toolbar
126        self.PopupMenu(popup, (0,0))
127
128
129    def print_figure(self, event):
130        try:
131            _printer = wx.Printer()
132            _printer.Print(self.canvas, PlotPrintout(self.canvas), True)
133        except:
134            import traceback
135            logger.error(traceback.format_exc())
136
137    def copy_figure(self, event):
138        copy_image_to_clipboard(self.canvas)
139
140class PlotPrintout(wx.Printout):
141    """
142    Create the wx.Printout object for matplotlib figure from the PlotPanel.
143    Provides the required OnPrintPage and HasPage overrides.  Other methods
144    may be added/overriden in the future.
145    :TODO: this needs LOTS of TLC .. but fixes immediate problem
146    """
147    def __init__(self, canvas):
148        """
149        Initialize wx.Printout and get passed figure object
150        """
151        wx.Printout.__init__(self)
152        self.canvas = canvas
153
154    def OnPrintPage(self, page):
155        """
156        Most rudimentry OnPrintPage override.  instatiates a dc object, gets
157        its size, gets the size of the figure object, scales it to the dc
158        canvas size keeping the aspect ratio intact, then prints as bitmap
159        """
160        _dc = self.GetDC()
161        (_dcX, _dcY) = _dc.GetSizeTuple()
162        (_bmpX,_bmpY) = self.canvas.GetSize()
163        _scale = min(_dcX/_bmpX, _dcY/_bmpY)
164        _dc.SetUserScale(_scale, _scale)
165        _dc.DrawBitmap(self.canvas.bitmap, 0, 0, False,)
166        return True
167
168    def GetPageInfo(self):
169        """
170        just sets the page to 1 - no flexibility for now
171        """
172        return (1, 1, 1, 1)
173
174
175def copy_image_to_clipboard(canvas):
176    bmp = wx.BitmapDataObject()
177    bmp.SetBitmap(canvas.bitmap)
178
179    wx.TheClipboard.Open()
180    wx.TheClipboard.SetData(bmp)
181    wx.TheClipboard.Close()
182
183
Note: See TracBrowser for help on using the repository browser.