summaryrefslogtreecommitdiff
path: root/silx/gui/plot/utils/axis.py
blob: 80e1dc462f575bbff67a5b9567e4a05c8250437d (plain)
1
2
3
4
5
6
7
8
9
10
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
"""This module contains utils class for axes management.
"""

__authors__ = ["V. Valls"]
__license__ = "MIT"
__date__ = "23/02/2018"

import functools
import logging
from contextlib import contextmanager
import weakref
import silx.utils.weakref as silxWeakref

_logger = logging.getLogger(__name__)


class SyncAxes(object):
    """Synchronize a set of plot axes together.

    It is created with the expected axes and starts to synchronize them.

    It can be customized to synchronize limits, scale, and direction of axes
    together. By default everything is synchronized.

    The API :meth:`start` and :meth:`stop` can be used to enable/disable the
    synchronization while this object is still alive.

    If this object is destroyed the synchronization stop.

    .. versionadded:: 0.6
    """

    def __init__(self, axes, syncLimits=True, syncScale=True, syncDirection=True):
        """
        Constructor

        :param list(Axis) axes: A list of axes to synchronize together
        :param bool syncLimits: Synchronize axes limits
        :param bool syncScale: Synchronize axes scale
        :param bool syncDirection: Synchronize axes direction
        """
        object.__init__(self)
        self.__locked = False
        self.__axes = []
        self.__syncLimits = syncLimits
        self.__syncScale = syncScale
        self.__syncDirection = syncDirection
        self.__callbacks = None

        qtCallback = silxWeakref.WeakMethodProxy(self.__deleteAxisQt)
        for axis in axes:
            ref = weakref.ref(axis)
            self.__axes.append(ref)
            callback = functools.partial(qtCallback, ref)
            axis.destroyed.connect(callback)

        self.start()

    def start(self):
        """Start synchronizing axes together.

        The first axis is used as the reference for the first synchronization.
        After that, any changes to any axes will be used to synchronize other
        axes.
        """
        if self.__callbacks is not None:
            raise RuntimeError("Axes already synchronized")
        self.__callbacks = {}

        # register callback for further sync
        for refAxis in self.__axes:
            axis = refAxis()
            callbacks = []
            if self.__syncLimits:
                # the weakref is needed to be able ignore self references
                callback = silxWeakref.WeakMethodProxy(self.__axisLimitsChanged)
                callback = functools.partial(callback, refAxis)
                sig = axis.sigLimitsChanged
                sig.connect(callback)
                callbacks.append(("sigLimitsChanged", callback))
            if self.__syncScale:
                # the weakref is needed to be able ignore self references
                callback = silxWeakref.WeakMethodProxy(self.__axisScaleChanged)
                callback = functools.partial(callback, refAxis)
                sig = axis.sigScaleChanged
                sig.connect(callback)
                callbacks.append(("sigScaleChanged", callback))
            if self.__syncDirection:
                # the weakref is needed to be able ignore self references
                callback = silxWeakref.WeakMethodProxy(self.__axisInvertedChanged)
                callback = functools.partial(callback, refAxis)
                sig = axis.sigInvertedChanged
                sig.connect(callback)
                callbacks.append(("sigInvertedChanged", callback))

            self.__callbacks[refAxis] = callbacks

        # sync the current state
        refMainAxis = self.__axes[0]
        mainAxis = refMainAxis()
        if self.__syncLimits:
            self.__axisLimitsChanged(refMainAxis, *mainAxis.getLimits())
        if self.__syncScale:
            self.__axisScaleChanged(refMainAxis, mainAxis.getScale())
        if self.__syncDirection:
            self.__axisInvertedChanged(refMainAxis, mainAxis.isInverted())

    def __deleteAxis(self, ref):
        _logger.debug("Delete axes ref %s", ref)
        self.__axes.remove(ref)
        del self.__callbacks[ref]

    def __deleteAxisQt(self, ref, qobject):
        self.__deleteAxis(ref)

    def stop(self):
        """Stop the synchronization of the axes"""
        if self.__callbacks is None:
            raise RuntimeError("Axes not synchronized")
        for ref, callbacks in self.__callbacks.items():
            axes = ref()
            for sigName, callback in callbacks:
                sig = getattr(axes, sigName)
                sig.disconnect(callback)
        self.__callbacks = None

    def __del__(self):
        """Destructor"""
        # clean up references
        if self.__callbacks is not None:
            self.stop()

    @contextmanager
    def __inhibitSignals(self):
        self.__locked = True
        yield
        self.__locked = False

    def __otherAxes(self, changedAxis):
        for axis in self.__axes:
            axis = axis()
            if axis is changedAxis:
                continue
            yield axis

    def __axisLimitsChanged(self, changedAxis, vmin, vmax):
        if self.__locked:
            return
        changedAxis = changedAxis()
        with self.__inhibitSignals():
            for axis in self.__otherAxes(changedAxis):
                axis.setLimits(vmin, vmax)

    def __axisScaleChanged(self, changedAxis, scale):
        if self.__locked:
            return
        changedAxis = changedAxis()
        with self.__inhibitSignals():
            for axis in self.__otherAxes(changedAxis):
                axis.setScale(scale)

    def __axisInvertedChanged(self, changedAxis, isInverted):
        if self.__locked:
            return
        changedAxis = changedAxis()
        with self.__inhibitSignals():
            for axis in self.__otherAxes(changedAxis):
                axis.setInverted(isInverted)