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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# SPDX-License-Identifier: LGPL-2.1-or-later

# ***************************************************************************
# *   Copyright (c) 2011, 2012 Jose Luis Cercos Pita <jlcercos@gmail.com>   *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   This program is distributed in the hope that it will be useful,       *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Library General Public License for more details.                  *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with this program; if not, write to the Free Software   *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************

import FreeCAD

import PySide
from PySide import QtCore, QtGui
import sys

try:
    import matplotlib

    matplotlib.use("QtAgg")

    # Force matplotlib to use PySide backend by temporarily unloading PyQt
    pyqt5_unloaded = False
    pyqt6_unloaded = False
    if "PyQt5.QtCore" in sys.modules:
        del sys.modules["PyQt5.QtCore"]
        pyqt5_unloaded = True
    if "PyQt6.QtCore" in sys.modules:
        del sys.modules["PyQt6.QtCore"]
        pyqt6_unloaded = True

    import matplotlib.pyplot as plt

    # restore PyQt if unloaded
    if pyqt5_unloaded:
        import PyQt5.QtCore
    if pyqt6_unloaded:
        import PyQt6.QtCore

    from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qtagg import NavigationToolbar2QT as NavigationToolbar

    from matplotlib.figure import Figure
except ImportError:
    FreeCAD.Console.PrintWarning(
        "The 'matplotlib' Python package was not found. Plot module cannot be loaded\n"
    )
    raise ImportError("matplotlib not installed")


def getMainWindow():
    """Return the FreeCAD main window."""
    toplevel = PySide.QtGui.QApplication.topLevelWidgets()
    for i in toplevel:
        if i.metaObject().className() == "Gui::MainWindow":
            return i
    return None


def getMdiArea():
    """Return FreeCAD MdiArea."""
    mw = getMainWindow()
    if not mw:
        return None
    childs = mw.children()
    for c in childs:
        if isinstance(c, PySide.QtGui.QMdiArea):
            return c
    return None


def getPlot():
    """Return the selected Plot document if exist."""
    # Get active tab
    mdi = getMdiArea()
    if not mdi:
        return None
    sub = mdi.activeSubWindow()
    if not sub:
        return None
    # Explore childrens looking for Plot class
    for i in sub.children():
        if i.metaObject().className() == "Plot":
            return i
    return None


def closePlot():
    """closePlot(): Close the active plot window."""
    # Get active tab
    mdi = getMdiArea()
    if not mdi:
        return None
    sub = mdi.activeSubWindow()
    if not sub:
        return None
    # Explore childrens looking for Plot class
    for i in sub.children():
        if i.metaObject().className() == "Plot":
            sub.close()


def figure(winTitle="plot"):
    """Create a new plot subwindow/tab.

    Keyword arguments:
    winTitle -- Plot tab title.
    """
    mdi = getMdiArea()
    if not mdi:
        return None
    win = Plot(winTitle)
    sub = mdi.addSubWindow(win)
    sub.show()
    return win


def plot(x, y, name=None):
    """Plots a new serie (as line plot)

    Keyword arguments:
    x -- X values
    y -- Y values
    name -- Data serie name (for legend).
    """
    # Get active plot, or create another one if don't exist
    plt = getPlot()
    if not plt:
        plt = figure()
    # Call to plot
    return plt.plot(x, y, name)


def series():
    """Return all the lines from a selected plot."""
    plt = getPlot()
    if not plt:
        return []
    return plt.series


def removeSerie(index):
    """Remove a data serie from the active plot.

    Keyword arguments:
    index -- Index of the serie to remove.
    """
    # Get active series
    plt = getPlot()
    if not plt:
        return
    plots = plt.series
    if not plots:
        return
    # Remove line from plot
    axes = plots[index].axes
    axes.lines.pop(plots[index].lid)
    # Remove serie from list
    del plt.series[index]
    # Update GUI
    plt.update()


def legend(status=True, pos=None, fontsize=None):
    """Show/Hide the legend from the active plot.

    Keyword arguments:
    status -- True if legend must be shown, False otherwise.
    pos -- Legend position.
    fontsize -- Font size
    """
    plt = getPlot()
    if not plt:
        return
    plt.legend = status
    if fontsize:
        plt.legSiz = fontsize
    # Hide all legends
    for axes in plt.axesList:
        axes.legend_ = None
    # Legend must be activated on last axes
    axes = plt.axesList[-1]
    if status:
        # Setup legend handles and names
        lines = series()
        handles = []
        names = []
        for l in lines:
            if l.name is not None:
                handles.append(l.line)
                names.append(l.name)
        # Show the legend (at selected position or at best)
        if pos:
            l = axes.legend(handles, names, bbox_to_anchor=pos)
            plt.legPos = pos
        else:
            l = axes.legend(handles, names, loc="best")
            # Update canvas in order to compute legend data
            plt.canvas.draw()
            # Get resultant position
            try:
                fax = axes.get_frame().get_extents()
            except Exception:
                fax = axes.patch.get_extents()
            fl = l.get_frame()
            plt.legPos = (
                (fl._x + fl._width - fax.x0) / fax.width,
                (fl._y + fl._height - fax.y0) / fax.height,
            )
        # Set fontsize
        for t in l.get_texts():
            t.set_fontsize(plt.legSiz)
    plt.update()


def grid(status=True):
    """Show/Hide the grid from the active plot.

    Keyword arguments:
    status -- True if grid must be shown, False otherwise.
    """
    plt = getPlot()
    if not plt:
        return
    plt.grid = status
    axes = plt.axes
    axes.grid(status)
    plt.update()


def title(string):
    """Setup the plot title.

    Keyword arguments:
    string -- Plot title.
    """
    plt = getPlot()
    if not plt:
        return
    axes = plt.axes
    axes.set_title(string)
    plt.update()


def xlabel(string):
    """Setup the x label.

    Keyword arguments:
    string -- Title to set.
    """
    plt = getPlot()
    if not plt:
        return
    axes = plt.axes
    axes.set_xlabel(string)
    plt.update()


def ylabel(string):
    """Setup the y label.

    Keyword arguments:
    string -- Title to set.
    """
    plt = getPlot()
    if not plt:
        return
    axes = plt.axes
    axes.set_ylabel(string)
    plt.update()


def axesList():
    """Return the plot axes sets list."""
    plt = getPlot()
    if not plt:
        return []
    return plt.axesList


def axes():
    """Return the active plot axes."""
    plt = getPlot()
    if not plt:
        return None
    return plt.axes


def addNewAxes(rect=None, frameon=True, patchcolor="none"):
    """Add new axes to plot, setting it as the active one.

    Keyword arguments:
    rect -- Axes area, None to copy from the last axes data.
    frameon -- True to show frame, False otherwise.
    patchcolor -- Patch color, 'none' for transparent plot.
    """
    plt = getPlot()
    if not plt:
        return None
    fig = plt.fig
    if rect is None:
        rect = plt.axes.get_position()
    ax = fig.add_axes(rect, frameon=frameon)
    ax.xaxis.set_ticks_position("bottom")
    ax.spines["top"].set_color("none")
    ax.yaxis.set_ticks_position("left")
    ax.spines["right"].set_color("none")
    ax.patch.set_facecolor(patchcolor)
    plt.axesList.append(ax)
    plt.setActiveAxes(-1)
    plt.update()
    return ax


def save(path, figsize=None, dpi=None):
    """Save plot.

    Keyword arguments:
    path -- Destination file path.
    figsize -- w,h figure size tuple in inches.
    dpi -- Dots per inch.
    """
    plt = getPlot()
    if not plt:
        return
    # Backup figure options
    fig = plt.fig
    sizeBack = fig.get_size_inches()
    dpiBack = fig.get_dpi()
    # Save figure with new options
    if figsize:
        fig.set_size_inches(figsize[0], figsize[1])
    if dpi:
        fig.set_dpi(dpi)
    plt.canvas.print_figure(path)
    # Restore figure options
    fig.set_size_inches(sizeBack[0], sizeBack[1])
    fig.set_dpi(dpiBack)
    plt.update()


def addNavigationToolbar():
    """Add the matplotlib QT navigation toolbar to the plot."""
    plt = getPlot()
    if not plt:
        return
    # Check that the navigation toolbar has not been already created
    if plt.mpl_toolbar is not None:
        return
    # Create the navigation toolbar and add it
    plt.mpl_toolbar = NavigationToolbar(plt.canvas, plt)
    vbox = plt.layout()
    vbox.addWidget(plt.mpl_toolbar)


def delNavigationToolbar():
    """Remove the matplotlib QT navigation toolbar from the plot."""
    plt = getPlot()
    if not plt:
        return
    # Check that the navigation toolbar already exist
    if plt.mpl_toolbar is None:
        return
    # Remove the widget from the layout
    vbox = plt.layout()
    vbox.removeWidget(plt.mpl_toolbar)
    # Destroy the navigation toolbar
    plt.mpl_toolbar.deleteLater()
    plt.mpl_toolbar = None


class Line:
    def __init__(self, axes, x, y, name):
        """Construct a new plot serie.

        Keyword arguments:
        axes -- Active axes
        x -- X values
        y -- Y values
        name -- Data serie name (for legend).
        """
        self.axes = axes
        self.x = x
        self.y = y
        self.name = name
        self.lid = len(axes.lines)
        (self.line,) = axes.plot(x, y)

    def setp(self, prop, value):
        """Change a line property value.

        Keyword arguments:
        prop -- Property name.
        value -- New property value.
        """
        plt.setp(self.line, prop, value)

    def getp(self, prop):
        """Get line property value.

        Keyword arguments:
        prop -- Property name.
        """
        return plt.getp(self.line, prop)


class Plot(PySide.QtGui.QWidget):
    def __init__(self, winTitle="plot", parent=None, flags=PySide.QtCore.Qt.WindowFlags(0)):
        """Construct a new plot widget.

        Keyword arguments:
        winTitle -- Tab title.
        parent -- Widget parent.
        flags -- QWidget flags
        """
        PySide.QtGui.QWidget.__init__(self, parent, flags)
        self.setWindowTitle(winTitle)
        # Create matplotlib canvas
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        # Get axes
        self.axes = self.fig.add_subplot(111)
        self.axesList = [self.axes]
        self.axes.xaxis.set_ticks_position("bottom")
        self.axes.spines["top"].set_color("none")
        self.axes.yaxis.set_ticks_position("left")
        self.axes.spines["right"].set_color("none")
        # Add the navigation toolbar by default
        self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        # Setup layout
        vbox = PySide.QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        self.setLayout(vbox)
        # Active series
        self.series = []
        # Indicators
        self.skip = False
        self.legend = False
        self.legPos = (1.0, 1.0)
        self.legSiz = 14
        self.grid = False

    def plot(self, x, y, name=None):
        """Plot a new line and return it.

        Keyword arguments:
        x -- X values
        y -- Y values
        name -- Serie name (for legend)."""
        l = Line(self.axes, x, y, name)
        self.series.append(l)
        # Update window
        self.update()
        return l

    def update(self):
        """Update the plot, redrawing the canvas."""
        if not self.skip:
            self.skip = True
            if self.legend:
                legend(self.legend, self.legPos, self.legSiz)
            self.canvas.draw()
            self.skip = False

    def isGrid(self):
        """Return True if Grid is active, False otherwise."""
        return bool(self.grid)

    def isLegend(self):
        """Return True if Legend is active, False otherwise."""
        return bool(self.legend)

    def setActiveAxes(self, index):
        """Change the current active axes.

        Keyword arguments:
        index -- Index of the new active axes set.
        """
        self.axes = self.axesList[index]
        self.fig.sca(self.axes)