prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  Crash on closing Matplotlib export
  E.g. when opening the Matplotlib exporter multiple times, and closing the windows again, Python crashes with a segmentation fault.
  
  This is caused by the Matplotlib QMainWindow listening to the closeEvent and deleting the only reference of the window before it is closed properly.
  
  </issue>
  <code>
  [start of pyqtgraph/exporters/Matplotlib.py]
  1 from ..Qt import QtGui, QtCore
  2 from .Exporter import Exporter
  3 from .. import PlotItem
  4 from .. import functions as fn
  5 
  6 __all__ = ['MatplotlibExporter']
  7 
  8 """
  9 It is helpful when using the matplotlib Exporter if your
  10 .matplotlib/matplotlibrc file is configured appropriately.
  11 The following are suggested for getting usable PDF output that
  12 can be edited in Illustrator, etc.
  13 
  14 backend      : Qt4Agg
  15 text.usetex : True  # Assumes you have a findable LaTeX installation
  16 interactive : False
  17 font.family : sans-serif
  18 font.sans-serif : 'Arial'  # (make first in list)
  19 mathtext.default : sf
  20 figure.facecolor : white  # personal preference
  21 # next setting allows pdf font to be readable in Adobe Illustrator
  22 pdf.fonttype : 42   # set fonts to TrueType (otherwise it will be 3
  23                     # and the text will be vectorized.
  24 text.dvipnghack : True  # primarily to clean up font appearance on Mac
  25 
  26 The advantage is that there is less to do to get an exported file cleaned and ready for
  27 publication. Fonts are not vectorized (outlined), and window colors are white.
  28 
  29 """
  30     
  31 class MatplotlibExporter(Exporter):
  32     Name = "Matplotlib Window"
  33     windows = []
  34     def __init__(self, item):
  35         Exporter.__init__(self, item)
  36         
  37     def parameters(self):
  38         return None
  39 
  40     def cleanAxes(self, axl):
  41         if type(axl) is not list:
  42             axl = [axl]
  43         for ax in axl:
  44             if ax is None:
  45                 continue
  46             for loc, spine in ax.spines.items():
  47                 if loc in ['left', 'bottom']:
  48                     pass
  49                 elif loc in ['right', 'top']:
  50                     spine.set_color('none')
  51                     # do not draw the spine
  52                 else:
  53                     raise ValueError('Unknown spine location: %s' % loc)
  54                 # turn off ticks when there is no spine
  55                 ax.xaxis.set_ticks_position('bottom')
  56     
  57     def export(self, fileName=None):
  58         
  59         if isinstance(self.item, PlotItem):
  60             mpw = MatplotlibWindow()
  61             MatplotlibExporter.windows.append(mpw)
  62 
  63             stdFont = 'Arial'
  64             
  65             fig = mpw.getFigure()
  66             
  67             # get labels from the graphic item
  68             xlabel = self.item.axes['bottom']['item'].label.toPlainText()
  69             ylabel = self.item.axes['left']['item'].label.toPlainText()
  70             title = self.item.titleLabel.text
  71 
  72             ax = fig.add_subplot(111, title=title)
  73             ax.clear()
  74             self.cleanAxes(ax)
  75             #ax.grid(True)
  76             for item in self.item.curves:
  77                 x, y = item.getData()
  78                 opts = item.opts
  79                 pen = fn.mkPen(opts['pen'])
  80                 if pen.style() == QtCore.Qt.NoPen:
  81                     linestyle = ''
  82                 else:
  83                     linestyle = '-'
  84                 color = tuple([c/255. for c in fn.colorTuple(pen.color())])
  85                 symbol = opts['symbol']
  86                 if symbol == 't':
  87                     symbol = '^'
  88                 symbolPen = fn.mkPen(opts['symbolPen'])
  89                 symbolBrush = fn.mkBrush(opts['symbolBrush'])
  90                 markeredgecolor = tuple([c/255. for c in fn.colorTuple(symbolPen.color())])
  91                 markerfacecolor = tuple([c/255. for c in fn.colorTuple(symbolBrush.color())])
  92                 markersize = opts['symbolSize']
  93                 
  94                 if opts['fillLevel'] is not None and opts['fillBrush'] is not None:
  95                     fillBrush = fn.mkBrush(opts['fillBrush'])
  96                     fillcolor = tuple([c/255. for c in fn.colorTuple(fillBrush.color())])
  97                     ax.fill_between(x=x, y1=y, y2=opts['fillLevel'], facecolor=fillcolor)
  98                 
  99                 pl = ax.plot(x, y, marker=symbol, color=color, linewidth=pen.width(), 
  100                         linestyle=linestyle, markeredgecolor=markeredgecolor, markerfacecolor=markerfacecolor,
  101                         markersize=markersize)
  102                 xr, yr = self.item.viewRange()
  103                 ax.set_xbound(*xr)
  104                 ax.set_ybound(*yr)
  105             ax.set_xlabel(xlabel)  # place the labels.
  106             ax.set_ylabel(ylabel)
  107             mpw.draw()
  108         else:
  109             raise Exception("Matplotlib export currently only works with plot items")
  110                 
  111 MatplotlibExporter.register()        
  112         
  113 
  114 class MatplotlibWindow(QtGui.QMainWindow):
  115     def __init__(self):
  116         from ..widgets import MatplotlibWidget
  117         QtGui.QMainWindow.__init__(self)
  118         self.mpl = MatplotlibWidget.MatplotlibWidget()
  119         self.setCentralWidget(self.mpl)
  120         self.show()
  121         
  122     def __getattr__(self, attr):
  123         return getattr(self.mpl, attr)
  124         
  125     def closeEvent(self, ev):
  126         MatplotlibExporter.windows.remove(self)
  127 
  128 
  129
  [end of pyqtgraph/exporters/Matplotlib.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/pyqtgraph/exporters/Matplotlib.py b/pyqtgraph/exporters/Matplotlib.py
  --- a/pyqtgraph/exporters/Matplotlib.py
  +++ b/pyqtgraph/exporters/Matplotlib.py
  @@ -124,5 +124,4 @@
           
       def closeEvent(self, ev):
           MatplotlibExporter.windows.remove(self)
  -
  -
  +        self.deleteLater()
  
verification_info: {"golden_diff": "diff --git a/pyqtgraph/exporters/Matplotlib.py b/pyqtgraph/exporters/Matplotlib.py\n--- a/pyqtgraph/exporters/Matplotlib.py\n+++ b/pyqtgraph/exporters/Matplotlib.py\n@@ -124,5 +124,4 @@\n         \n     def closeEvent(self, ev):\n         MatplotlibExporter.windows.remove(self)\n-\n-\n+        self.deleteLater()\n", "issue": "Crash on closing Matplotlib export\nE.g. when opening the Matplotlib exporter multiple times, and closing the windows again, Python crashes with a segmentation fault.\r\n\r\nThis is caused by the Matplotlib QMainWindow listening to the closeEvent and deleting the only reference of the window before it is closed properly.\n", "before_files": [{"content": "from ..Qt import QtGui, QtCore\nfrom .Exporter import Exporter\nfrom .. import PlotItem\nfrom .. import functions as fn\n\n__all__ = ['MatplotlibExporter']\n\n\"\"\"\nIt is helpful when using the matplotlib Exporter if your\n.matplotlib/matplotlibrc file is configured appropriately.\nThe following are suggested for getting usable PDF output that\ncan be edited in Illustrator, etc.\n\nbackend      : Qt4Agg\ntext.usetex : True  # Assumes you have a findable LaTeX installation\ninteractive : False\nfont.family : sans-serif\nfont.sans-serif : 'Arial'  # (make first in list)\nmathtext.default : sf\nfigure.facecolor : white  # personal preference\n# next setting allows pdf font to be readable in Adobe Illustrator\npdf.fonttype : 42   # set fonts to TrueType (otherwise it will be 3\n                    # and the text will be vectorized.\ntext.dvipnghack : True  # primarily to clean up font appearance on Mac\n\nThe advantage is that there is less to do to get an exported file cleaned and ready for\npublication. Fonts are not vectorized (outlined), and window colors are white.\n\n\"\"\"\n    \nclass MatplotlibExporter(Exporter):\n    Name = \"Matplotlib Window\"\n    windows = []\n    def __init__(self, item):\n        Exporter.__init__(self, item)\n        \n    def parameters(self):\n        return None\n\n    def cleanAxes(self, axl):\n        if type(axl) is not list:\n            axl = [axl]\n        for ax in axl:\n            if ax is None:\n                continue\n            for loc, spine in ax.spines.items():\n                if loc in ['left', 'bottom']:\n                    pass\n                elif loc in ['right', 'top']:\n                    spine.set_color('none')\n                    # do not draw the spine\n                else:\n                    raise ValueError('Unknown spine location: %s' % loc)\n                # turn off ticks when there is no spine\n                ax.xaxis.set_ticks_position('bottom')\n    \n    def export(self, fileName=None):\n        \n        if isinstance(self.item, PlotItem):\n            mpw = MatplotlibWindow()\n            MatplotlibExporter.windows.append(mpw)\n\n            stdFont = 'Arial'\n            \n            fig = mpw.getFigure()\n            \n            # get labels from the graphic item\n            xlabel = self.item.axes['bottom']['item'].label.toPlainText()\n            ylabel = self.item.axes['left']['item'].label.toPlainText()\n            title = self.item.titleLabel.text\n\n            ax = fig.add_subplot(111, title=title)\n            ax.clear()\n            self.cleanAxes(ax)\n            #ax.grid(True)\n            for item in self.item.curves:\n                x, y = item.getData()\n                opts = item.opts\n                pen = fn.mkPen(opts['pen'])\n                if pen.style() == QtCore.Qt.NoPen:\n                    linestyle = ''\n                else:\n                    linestyle = '-'\n                color = tuple([c/255. for c in fn.colorTuple(pen.color())])\n                symbol = opts['symbol']\n                if symbol == 't':\n                    symbol = '^'\n                symbolPen = fn.mkPen(opts['symbolPen'])\n                symbolBrush = fn.mkBrush(opts['symbolBrush'])\n                markeredgecolor = tuple([c/255. for c in fn.colorTuple(symbolPen.color())])\n                markerfacecolor = tuple([c/255. for c in fn.colorTuple(symbolBrush.color())])\n                markersize = opts['symbolSize']\n                \n                if opts['fillLevel'] is not None and opts['fillBrush'] is not None:\n                    fillBrush = fn.mkBrush(opts['fillBrush'])\n                    fillcolor = tuple([c/255. for c in fn.colorTuple(fillBrush.color())])\n                    ax.fill_between(x=x, y1=y, y2=opts['fillLevel'], facecolor=fillcolor)\n                \n                pl = ax.plot(x, y, marker=symbol, color=color, linewidth=pen.width(), \n                        linestyle=linestyle, markeredgecolor=markeredgecolor, markerfacecolor=markerfacecolor,\n                        markersize=markersize)\n                xr, yr = self.item.viewRange()\n                ax.set_xbound(*xr)\n                ax.set_ybound(*yr)\n            ax.set_xlabel(xlabel)  # place the labels.\n            ax.set_ylabel(ylabel)\n            mpw.draw()\n        else:\n            raise Exception(\"Matplotlib export currently only works with plot items\")\n                \nMatplotlibExporter.register()        \n        \n\nclass MatplotlibWindow(QtGui.QMainWindow):\n    def __init__(self):\n        from ..widgets import MatplotlibWidget\n        QtGui.QMainWindow.__init__(self)\n        self.mpl = MatplotlibWidget.MatplotlibWidget()\n        self.setCentralWidget(self.mpl)\n        self.show()\n        \n    def __getattr__(self, attr):\n        return getattr(self.mpl, attr)\n        \n    def closeEvent(self, ev):\n        MatplotlibExporter.windows.remove(self)\n\n\n", "path": "pyqtgraph/exporters/Matplotlib.py"}]}