8000 Backend refactor by tacaswell · Pull Request #8777 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Backend refactor #8777

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 58 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
9813e43
Refactor pass 1. Refactoring Gcf out of specific backend (backend_gt…
OceanWolf Feb 21, 2015
91cbffc
Refactor Pass 2. Refactored Gcf out of all backend code.
OceanWolf Feb 22, 2015
aa3ff59
Quick fix to figure for safe unpickling.
OceanWolf Feb 25, 2015
f046e01
GTK3Agg
OceanWolf Feb 26, 2015
39ff708
Refactored making `FigureManager` a *figure* manager, plus added miss…
OceanWolf Feb 27, 2015
45c5fc2
keyword
OceanWolf Feb 27, 2015
ebf0c57
Make add_element more general, and make sure the code complies with it.
OceanWolf Feb 27, 2015
9d25441
Better destroy order.
OceanWolf Feb 27, 2015
6ae52f2
GTK simplifications
OceanWolf Feb 28, 2015
1a47d3b
Added doc and cleaned backend_managers, don't want our new file dirty.
OceanWolf Mar 3, 2015
bc17372
Improve layout!
OceanWolf Apr 6, 2015
3fb46f2
Move knowledge of the backend to the manager.
8000 OceanWolf Apr 7, 2015
2758f3f
Incorporate MEP22 into MEP27
OceanWolf Apr 12, 2015
f354d3c
Improved new toolbar and updated tool_manager example accoridingly.
OceanWolf Apr 12, 2015
51c0598
fullscreen
OceanWolf Apr 13, 2015
6b35d85
MEP update
OceanWolf Apr 14, 2015
724b622
Finish MEP22 conversion
OceanWolf Apr 14, 2015
0b42bbe
rename window method
OceanWolf Apr 17, 2015
ef65740
Add backend anme to widgets
OceanWolf Apr 17, 2015
fb5202a
Handle FigureManager destroy internaly without pyplot.
OceanWolf Jun 4, 2015
26ce3e6
Make functionality more consistant for embedded applications
OceanWolf Jun 7, 2015
1cfebc4
Backend getter method for FigureManager
OceanWolf Jun 13, 2015
bc32fb1
Improve example after new method
OceanWolf Jun 13, 2015
81b9e69
Clean up the code a bit
OceanWolf Jun 13, 2015
85f0668
Remove old code from backend_managers
OceanWolf Jun 15, 2015
6535148
Cleanup
OceanWolf Jun 22, 2015
73e1122
Explicity get set manager as None if appropiate.
OceanWolf Jun 22, 2015
592c49b
figure attribute and canvas property
fariza Jun 22, 2015
b5d7f57
Fix FigureCanvasBase
OceanWolf Jun 23, 2015
b842bdc
super
OceanWolf Jun 25, 2015
92de15e
figure setter
fariza Jun 25, 2015
b619923
Improve MEP22 Tool Searching Structure
OceanWolf Jun 25, 2015
a07e482
adding example file
fariza Jun 25, 2015
2dd8895
super dooper
OceanWolf Jun 26, 2015
ce9c8e7
Revert old example and fix new one.
OceanWolf Jun 26, 2015
5542c5a
Improve MEP22 tool-searching method.
OceanWolf Jun 27, 2015
a975717
MEP22 Save Figure Tool
OceanWolf Jun 27, 2015
ecf1f23
pep8
OceanWolf Jun 27, 2015
4531085
Make ToolConfigureSubplots a generic tool
OceanWolf Jun 28, 2015
87fbd59
Improve flow handling and make it a lot more generic
OceanWolf Jun 28, 2015
f7eb33d
Missing resize method
OceanWolf Jun 28, 2015
0a2aa5c
Convert to new structure for finding tools
OceanWolf Jun 28, 2015
777b162
doc
OceanWolf Jun 29, 2015
468bdd7
Add ExpandableBase
OceanWolf Jun 29, 2015
209af6b
Template Backend plus fix FigManager for non-GUI backends and add gen…
OceanWolf Jun 29, 2015
06686c7
rcParam and Travis
OceanWolf Jul 19, 2015
2d93df8
test always MEP27
OceanWolf Jul 20, 2015
6b15982
Fix FigureManager to allow pyplot to work for non GUI backends
OceanWolf Jul 27, 2015
61f61f6
Fix Gcf.show_all()
OceanWolf Jul 27, 2015
71f4813
doc
OceanWolf Jul 27, 2015
d3064b6
pep8
OceanWolf Jul 27, 2015
2ca898c
remove show_popup
OceanWolf Jul 27, 2015
a567af6
AttributeError
OceanWolf Sep 22, 2015
09fc887
Fixes for MEP27
OceanWolf Aug 3, 2016
f60333d
STY: replace \ with () for line continuation
tacaswell Jun 19, 2017
072c47a
ENH: make MainLoopBase a context manager
tacaswell Jun 19, 2017
214b684
MNT: further simplify MainLoopBase
tacaswell Jun 25, 2017
35838c9
WIP:
tacaswell Jun 27, 2017
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Refactor Pass 2. Refactored Gcf out of all backend code.
  • Loading branch information
OceanWolf authored and tacaswell committed Jun 19, 2017
commit 91cbffc5dc1428440a7ac93f9d8c4edd67cc08cf
60 changes: 59 additions & 1 deletion lib/matplotlib/_pylab_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import gc
import atexit

from matplotlib import is_interactive


def error_msg(msg):
print(msg, file=sys.stderr)
Expand All @@ -35,6 +37,16 @@ class Gcf(object):
_activeQue = []
figs = {}

@classmethod
def add_figure_manager(cls, manager):
cls.figs[manager.num] = manager
try: # TODO remove once all backends converted to use the new manager.
manager.mpl_connect('window_destroy_event', cls.destroy_cbk)
except:
pass

cls.set_active(manager)

@classmethod
def get_fig_manager(cls, num):
"""
Expand All @@ -46,6 +58,49 @@ def get_fig_manager(cls, num):
cls.set_active(manager)
return manager

@classmethod
def show_all(cls, block=None):
"""
Show all figures. If *block* is not None, then
it is a boolean that overrides all other factors
determining whether show blocks by calling mainloop().
The other factors are:
it does not block if run inside ipython's "%pylab" mode
it does not block in interactive mode.
"""
managers = cls.get_all_fig_managers()
if not managers:
return

for manager in managers:
manager.show()

if block is not None:
if block:
manager.mainloop()
return

from matplotlib import pyplot
try:
ipython_pylab = not pyplot.show._needmain
# IPython versions >= 0.10 tack the _needmain
# attribute onto pyplot.show, and always set
# it to False, when in %pylab mode.
ipython_pylab = ipython_pylab and get_backend() != 'WebAgg'
# TODO: The above is a hack to get the WebAgg backend
# working with ipython's `%pylab` mode until proper
# integration is implemented.
except AttributeError:
ipython_pylab = False

# Leave the following as a separate step in case we
# want to control this behavior with an rcParam.
if ipython_pylab:
block = False

if not is_interactive() or get_backend() == 'WebAgg':
manager.mainloop()

@classmethod
def destroy(cls, num):
"""
Expand Down Expand Up @@ -137,7 +192,6 @@ def set_active(cls, manager):
if m != manager:
cls._activeQue.append(m)
cls._activeQue.append(manager)
cls.figs[manager.num] = manager

@classmethod
def draw_all(cls, force=False):
Expand All @@ -149,4 +203,8 @@ def draw_all(cls, force=False):
if force or f_mgr.canvas.figure.stale:
f_mgr.canvas.draw_idle()

@classmethod
def destroy_cbk(cls, event):
cls.destroy(event.figure_manager.num)

atexit.register(Gcf.destroy_all)
145 changes: 35 additions & 110 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
import warnings

import numpy as np
import matplotlib # temporary )assuming we refactor where marked below)
import matplotlib.cbook as cbook
import matplotlib.colors as colors
import matplotlib.transforms as transforms
Expand Down Expand Up @@ -143,6 +142,33 @@ def get_registered_canvas_class(format):
return backend_class


class MainLoopBase(object):
"""This gets used as a key maintaining the event loop.
Backends should only need to override begin and end.
It should not matter if this gets used as a singleton or not due to
clever magic.
"""
_instance_count = {}
def __init__(self):
MainLoopBase._instance_count.setdefault(self.__class__, 0)
MainLoopBase._instance_count[self.__class__] += 1

def begin(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in the other PR this should probably be a contextmanager instead, which also avoids the need of "clever magic".

pass

def end(self):
pass

def __call__(self):
self.begin()

def __del__(self):
MainLoopBase._instance_count[self.__class__] -= 1
if (MainLoopBase._instance_count[self.__class__] <= 0 and
not is_interactive()):
self.end()


class ShowBase(object):
"""
Simple base class to generate a show() callable in backends.
Expand Down Expand Up @@ -2483,7 +2509,10 @@ def key_press_handler(event, canvas, toolbar=None):

# quit the figure (defaut key 'ctrl+w')
if event.key in quit_keys:
Gcf.destroy_fig(canvas.figure)
if isinstance(canvas.manager.mainloop, MainLoopBase): # If new no Gcf.
canvas.manager._destroy('window_destroy_event')
else:
Gcf.destroy_fig(canvas.figure)

if toolbar is not None:
# home or reset mnemonic (default key 'h', 'home' and 'r')
Expand Down Expand Up @@ -2610,20 +2639,16 @@ def _get_uniform_gridstate(ticks):
class NonGuiException(Exception):
pass


class WindowEvent(object):
def __init__(self, name, window):
self.name = name
self.window = window

class WindowBase(object):
def __init__(self, title):
self._callbacks = cbook.CallbackRegistry()

def mpl_connect(self, s, func):
return self._callbacks.connect(s, func)

def mpl_disconnect(self, cid):
return self._callbacks.disconnect(cid)
class WindowBase(cbook.EventEmitter):
def __init__(self, title):
cbook.EventEmitter.__init__(self)

def show(self):
"""
Expand Down Expand Up @@ -2664,112 +2689,12 @@ def add_element_to_window(self, element, expand, fill, padding, from_start=False
10000 """
pass

def terminate_backend(self):
"""Method to terminate the usage of the backend
"""
# TODO refactor me out on second pass
pass

def destroy_event(self, *args):
s = 'window_destroy_event'
event = WindowEvent(s, self)
self._callbacks.process(s, event)


class FigureManager(object):
def __init__(self, canvas, num, classes):
self._classes = classes
self.canvas = canvas
canvas.manager = self
self.num = num

self.key_press_handler_id = self.canvas.mpl_connect('key_press_event',
self.key_press)

self.window = classes['Window']('Figure %d' % num)
self.window.mpl_connect('window_destroy_event', self._destroy)

w = int(self.canvas.figure.bbox.width)
h = int(self.canvas.figure.bbox.height)

self.window.add_element_to_window(self.canvas, True, True, 0, True)

self.toolbar = self._get_toolbar(canvas)
if self.toolbar is not None:
h += self.window.add_element_to_window(self.toolbar, False, False, 0)

self.window.set_default_size(w,h)

# Refactor this? If so, delete import matplotlib from above.
if matplotlib.is_interactive():
self.window.show()

def notify_axes_change(fig):
'this will be called whenever the current axes is changed'
if self.toolbar is not None: self.toolbar.update()
self.canvas.figure.add_axobserver(notify_axes_change)

self.canvas.grab_focus()

def key_press(self, event):
"""
Implement the default mpl key bindings defined at
:ref:`key-event-handling`
"""
key_press_handler(event, self.canvas, self.canvas.toolbar)

def _destroy(self, event):
Gcf.destroy(self.num) # TODO refactor me out of here on second pass!

def destroy(self, *args):
self.window.destroy()
self.canvas.destroy()
if self.toolbar:
self.toolbar.destroy()

# TODO refactor out on second pass
if Gcf.get_num_fig_managers()==0 and not matplotlib.is_interactive():
self.window.terminate_backend()

def show(self):
self.window.show()

def full_screen_toggle(self):
self._full_screen_flag = not self._full_screen_flag
self.window.set_fullscreen(self._full_screen_flag)

def resize(self, w, h):
self.window.resize(w,h)

def get_window_title(self):
"""
Get the title text of the window containing the figure.
Return None for non-GUI backends (e.g., a PS backend).
"""
return self.window.get_window_title()

def set_window_title(self, title):
"""
Set the title text of the window containing the figure. Note that
this has no effect for non-GUI backends (e.g., a PS backend).
"""
self.window.set_window_title(title)

def show_popup(self, msg):
"""
Display message in a popup -- GUI only
"""
pass

def _get_toolbar(self, canvas):
# must be inited after the window, drawingArea and figure
# attrs are set
if rcParams['toolbar'] == 'toolbar2':
toolbar = self._classes['Toolbar2'](canvas, self.window)
else:
toolbar = None
return toolbar

class FigureManagerBase(object):
"""
Helper class for pyplot mode, wraps everything up into a neat bundle
Expand Down 4327
Loading
0