def test_click_event_handler( peak_list, capsys, advanced_file_regression: AdvancedFileRegressionFixture, ): fig, ax = plt.subplots() # Setup up the ClickEventHandler handler = ClickEventHandler(peak_list, fig, ax) assert handler.fig is fig assert handler.ax is ax assert handler.cid is not None callbacks: CallbackRegistry = fig.canvas.callbacks assert "button_press_event" in callbacks.callbacks event = MouseEvent("button_press_event", fig.canvas, peak_list[0].rt, 100, button=1) event.xdata = peak_list[0].rt # FIXME callbacks.process("button_press_event", event) advanced_file_regression.check(capsys.readouterr().out)
def test_contains(): fig = plt.figure() ax = plt.axes() mevent = MouseEvent('button_press_event', fig.canvas, 0.5, 0.5, 1, None) xs = np.linspace(0.25, 0.75, 30) ys = np.linspace(0.25, 0.75, 30) xs, ys = np.meshgrid(xs, ys) txt = plt.text( 0.5, 0.4, 'hello world', ha='center', fontsize=30, rotation=30) # uncomment to draw the text's bounding box # txt.set_bbox(dict(edgecolor='black', facecolor='none')) # draw the text. This is important, as the contains method can only work # when a renderer exists. fig.canvas.draw() for x, y in zip(xs.flat, ys.flat): mevent.x, mevent.y = plt.gca().transAxes.transform_point([x, y]) contains, _ = txt.contains(mevent) color = 'yellow' if contains else 'red' # capture the viewLim, plot a point, and reset the viewLim vl = ax.viewLim.frozen() ax.plot(x, y, 'o', color=color) ax.viewLim.set(vl)
def test_contains(): fig = plt.figure() ax = plt.axes() mevent = MouseEvent('button_press_event', fig.canvas, 0.5, 0.5, 1, None) xs = np.linspace(0.25, 0.75, 30) ys = np.linspace(0.25, 0.75, 30) xs, ys = np.meshgrid(xs, ys) txt = plt.text(0.5, 0.4, 'hello world', ha='center', fontsize=30, rotation=30) # uncomment to draw the text's bounding box # txt.set_bbox(dict(edgecolor='black', facecolor='none')) # draw the text. This is important, as the contains method can only work # when a renderer exists. fig.canvas.draw() for x, y in zip(xs.flat, ys.flat): mevent.x, mevent.y = plt.gca().transAxes.transform([x, y]) contains, _ = txt.contains(mevent) color = 'yellow' if contains else 'red' # capture the viewLim, plot a point, and reset the viewLim vl = ax.viewLim.frozen() ax.plot(x, y, 'o', color=color) ax.viewLim.set(vl)
def test_cursor_data(): from matplotlib.backend_bases import MouseEvent fig, ax = plt.subplots() im = ax.imshow(np.arange(100).reshape(10, 10), origin='upper') x, y = 4, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 44 ax.clear() im = ax.imshow(np.arange(100).reshape(10, 10), origin='lower') x, y = 4, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 44 fig, ax = plt.subplots() im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5]) x, y = 0.25, 0.25 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 55
def test_quadmesh_cursor_data(): fig, ax = plt.subplots() *_, qm = ax.hist2d(np.arange(11)**2, 100 + np.arange(11)**2) # width-10 bins x, y = ax.transData.transform([1, 101]) event = MouseEvent('motion_notify_event', fig.canvas, x, y) assert qm.get_cursor_data(event) == 4 # (0**2, 1**2, 2**2, 3**2) for out_xydata in []: x, y = ax.transData.transform([-1, 101]) event = MouseEvent('motion_notify_event', fig.canvas, x, y) assert qm.get_cursor_data(event) is None
def test_onZoomIn1(self): """ Test zoom in on bottom-right quadrant """ currentZoom = self.app.canvas.plotter.zoom event = MouseEvent(name = "button_press_event", button = MouseButton.LEFT, canvas = self.app.canvas.canvas, x = 503, y = 670) event.xdata = 90 event.ydata = -45 event.button = MouseButton.LEFT self.app.canvas.onZoomIn(event) self.assertEqual(self.app.canvas.plotter.zoom, currentZoom + 1)
def test_interactive_colorbar(plot_func, orientation, tool, button, expected): fig, ax = plt.subplots() data = np.arange(12).reshape((4, 3)) vmin0, vmax0 = 0, 10 coll = getattr(ax, plot_func)(data, vmin=vmin0, vmax=vmax0) cb = fig.colorbar(coll, ax=ax, orientation=orientation) if plot_func == "contourf": # Just determine we can't navigate and exit out of the test assert not cb.ax.get_navigate() return assert cb.ax.get_navigate() # Mouse from 4 to 6 (data coordinates, "d"). vmin, vmax = 4, 6 # The y coordinate doesn't matter, it just needs to be between 0 and 1 # However, we will set d0/d1 to the same y coordinate to test that small # pixel changes in that coordinate doesn't cancel the zoom like a normal # axes would. d0 = (vmin, 0.5) d1 = (vmax, 0.5) # Swap them if the orientation is vertical if orientation == "vertical": d0 = d0[::-1] d1 = d1[::-1] # Convert to screen coordinates ("s"). Events are defined only with pixel # precision, so round the pixel values, and below, check against the # corresponding xdata/ydata, which are close but not equal to d0/d1. s0 = cb.ax.transData.transform(d0).astype(int) s1 = cb.ax.transData.transform(d1).astype(int) # Set up the mouse movements start_event = MouseEvent("button_press_event", fig.canvas, *s0, button) stop_event = MouseEvent("button_release_event", fig.canvas, *s1, button) tb = NavigationToolbar2(fig.canvas) if tool == "zoom": tb.zoom() tb.press_zoom(start_event) tb.drag_zoom(stop_event) tb.release_zoom(stop_event) else: tb.pan() tb.press_pan(start_event) tb.drag_pan(stop_event) tb.release_pan(stop_event) # Should be close, but won't be exact due to screen integer resolution assert (cb.vmin, cb.vmax) == pytest.approx(expected, abs=0.15)
def test_arrow_contains_point(): # fix bug (#8384) fig, ax = plt.subplots() ax.set_xlim((0, 2)) ax.set_ylim((0, 2)) # create an arrow with Curve style arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75), arrowstyle='->', mutation_scale=40) ax.add_patch(arrow) # create an arrow with Bracket style arrow1 = patches.FancyArrowPatch((0.5, 1), (1.5, 1.25), arrowstyle=']-[', mutation_scale=40) ax.add_patch(arrow1) # create an arrow with other arrow style arrow2 = patches.FancyArrowPatch((0.5, 1.5), (1.5, 1.75), arrowstyle='fancy', fill=False, mutation_scale=40) ax.add_patch(arrow2) patches_list = [arrow, arrow1, arrow2] # generate some points X, Y = np.meshgrid(np.arange(0, 2, 0.1), np.arange(0, 2, 0.1)) for k, (x, y) in enumerate(zip(X.ravel(), Y.ravel())): xdisp, ydisp = ax.transData.transform([x, y]) event = MouseEvent('button_press_event', fig.canvas, xdisp, ydisp) for m, patch in enumerate(patches_list): # set the points to red only if the arrow contains the point inside, res = patch.contains(event) if inside: ax.scatter(x, y, s=5, c="r")
def test_picker(): from ctapipe.visualization import CameraDisplay from matplotlib.backend_bases import MouseEvent, MouseButton geom = CameraGeometry.from_name("LSTCam") clicked_pixels = [] class PickingCameraDisplay(CameraDisplay): def on_pixel_clicked(self, pix_id): print(f"YOU CLICKED PIXEL {pix_id}") clicked_pixels.append(pix_id) fig = plt.figure(figsize=(10, 10), dpi=100) ax = fig.add_axes([0, 0, 1, 1]) disp = PickingCameraDisplay(geom, ax=ax) disp.enable_pixel_picker() fig.canvas.draw() # emulate someone clicking the central pixel event = MouseEvent("button_press_event", fig.canvas, x=500, y=500, button=MouseButton.LEFT) disp.pixels.pick(event) assert len(clicked_pixels) > 0
def just_runs(self, ngl_wdg, button=None): # Create the linked objects plt.plot(self.pos[:, 0], self.pos[:, 1]) iax = plt.gca() # Prepare a mouse event in the middle of the plot x, y = np.array(iax.get_window_extent()).mean(0) # Prepare event lineh = iax.axhline(iax.get_ybound()[0]) setattr(lineh, 'whatisthis', 'lineh') dot = iax.plot(self.pos[0, 0], self.pos[0, 1])[0] setattr(dot, 'whatisthis', 'dot') # Instantiate the ClickOnAxisListener and call it with the event return molpx._linkutils.ClickOnAxisListener( ngl_wdg, True, [lineh], iax, self.pos, [dot])(MouseEvent(" ", plt.gcf().canvas, x, y, button=button, key=None, step=0, dblclick=False, guiEvent=None))
def test_just_runs_recomputes_kdtree(self): plt.plot(self.pos[:, 0], self.pos[:, 1]) iax = plt.gca() # Prepare a mouse event in the middle of the plot x, y = np.array(iax.get_window_extent()).mean(0) # Prepare event lineh = iax.axhline(iax.get_ybound()[0]) setattr(lineh, 'whatisthis', 'lineh') dot = iax.plot(self.pos[0, 0], self.pos[0, 1])[0] setattr(dot, 'whatisthis', 'dot') CLAL = molpx._linkutils.ClickOnAxisListener( nglview.show_mdtraj(self.MD_trajectory), True, [lineh], iax, self.pos, [dot]) # Resize the figure CLAL.ax.figure.set_size_inches(1, 1) # Send an event CLAL( MouseEvent(" ", CLAL.ax.figure.canvas, x, y, button=1, key=None, step=0, dblclick=False, guiEvent=None))
def test_interactive_zoom(): fig, ax = plt.subplots() ax.set(xscale="logit") assert ax.get_navigate_mode() is None tb = NavigationToolbar2(fig.canvas) tb.zoom() assert ax.get_navigate_mode() == 'ZOOM' xlim0 = ax.get_xlim() ylim0 = ax.get_ylim() # Zoom from x=1e-6, y=0.1 to x=1-1e-5, 0.8 (data coordinates, "d"). d0 = (1e-6, 0.1) d1 = (1 - 1e-5, 0.8) # Convert to screen coordinates ("s"). Events are defined only with pixel # precision, so round the pixel values, and below, check against the # corresponding xdata/ydata, which are close but not equal to d0/d1. s0 = ax.transData.transform(d0).astype(int) s1 = ax.transData.transform(d1).astype(int) # Zoom in. start_event = MouseEvent("button_press_event", fig.canvas, *s0, MouseButton.LEFT) fig.canvas.callbacks.process(start_event.name, start_event) stop_event = MouseEvent("button_release_event", fig.canvas, *s1, MouseButton.LEFT) fig.canvas.callbacks.process(stop_event.name, stop_event) assert ax.get_xlim() == (start_event.xdata, stop_event.xdata) assert ax.get_ylim() == (start_event.ydata, stop_event.ydata) # Zoom out. start_event = MouseEvent("button_press_event", fig.canvas, *s1, MouseButton.RIGHT) fig.canvas.callbacks.process(start_event.name, start_event) stop_event = MouseEvent("button_release_event", fig.canvas, *s0, MouseButton.RIGHT) fig.canvas.callbacks.process(stop_event.name, stop_event) # Absolute tolerance much less than original xmin (1e-7). assert ax.get_xlim() == pytest.approx(xlim0, rel=0, abs=1e-10) assert ax.get_ylim() == pytest.approx(ylim0, rel=0, abs=1e-10) tb.zoom() assert ax.get_navigate_mode() is None assert not ax.get_autoscalex_on() and not ax.get_autoscaley_on()
def matplotlib_mouse_event(self, x, y): '''Used for detecting clicked matplotlib canvas item using Artist.contains().''' h = self.tool_window.ui_area.height() # TODO: matplotlib 2.0.2 bug on mac retina displays, requires 2x scaling # for picking objects to work. ChimeraX ticket #762. pr = self.tool_window.ui_area.devicePixelRatio() from matplotlib.backend_bases import MouseEvent e = MouseEvent('context menu', self.canvas, pr * x, pr * (h - y)) return e
def test_format_cursor_data(data, text): from matplotlib.backend_bases import MouseEvent fig, ax = plt.subplots() im = ax.imshow(data) xdisp, ydisp = ax.transData.transform([0, 0]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.format_cursor_data(im.get_cursor_data(event)) == text
def test_quadmesh_cursor_data(): fig, ax = plt.subplots() *_, qm = ax.hist2d(np.arange(11)**2, 100 + np.arange(11)**2) # width-10 bins x, y = ax.transData.transform([1, 101]) event = MouseEvent('motion_notify_event', fig.canvas, x, y) assert qm.get_show_cursor_data() is False assert qm.get_cursor_data(event) is None qm.set_show_cursor_data(True) assert qm.get_cursor_data(event) == 4 # (0**2, 1**2, 2**2, 3**2) # Outside the quadmesh bounds x, y = ax.transData.transform([-1, 101]) event = MouseEvent('motion_notify_event', fig.canvas, x, y) assert qm.get_cursor_data(event) is None
def test_annotation_contains(): # Check that Annotation.contains looks at the bboxes of the text and the # arrow separately, not at the joint bbox. fig, ax = plt.subplots() ann = ax.annotate( "hello", xy=(.4, .4), xytext=(.6, .6), arrowprops={"arrowstyle": "->"}) fig.canvas.draw() # Needed for the same reason as in test_contains. event = MouseEvent( "button_press_event", fig.canvas, *ax.transData.transform((.5, .6))) assert ann.contains(event) == (False, {})
def test_pick(): fig = plt.figure() fig.text(.5, .5, "hello", ha="center", va="center", picker=True) fig.canvas.draw() picks = [] fig.canvas.mpl_connect("pick_event", lambda event: picks.append(event)) start_event = MouseEvent("button_press_event", fig.canvas, *fig.transFigure.transform((.5, .5)), MouseButton.LEFT) fig.canvas.callbacks.process(start_event.name, start_event) assert len(picks) == 1
def mock_click(fig, data_position): pos = fig.axes[0].transData.transform(data_position) fig.canvas.callbacks.process( "button_press_event", MouseEvent("button_press_event", fig.canvas, pos[0], pos[1], 1)) images = [ obj for obj in mpl.pyplot.gca().get_children() if isinstance(obj, mpl.image.AxesImage) ] assert len(images) == 1 return images[0].get_array()
def test_clip_deselect(self): timeline_container = common.create_timeline_container() timeline = timeline_container.timeline ges_layer = timeline.ges_timeline.append_layer() ges_clip1 = self.add_clip(ges_layer, 0, duration=Gst.SECOND) ges_clip2 = self.add_clip(ges_layer, Gst.SECOND, duration=Gst.SECOND) # Select clip1 to show its keyframes widget. timeline.selection.select([ges_clip1]) # Select both clips. Now clip1 still has the keyframes visible. timeline.selection.select([ges_clip1, ges_clip2]) ges_video_source = ges_clip1.find_track_element(None, GES.VideoSource) binding = ges_video_source.get_control_binding("alpha") control_source = binding.props.control_source keyframe_curve = ges_video_source.ui.keyframe_curve # Simulate a mouse click. xdata, ydata = 1, LAYER_HEIGHT // 2 x, y = keyframe_curve._ax.transData.transform((xdata, ydata)) event = MouseEvent(name="button_press_event", canvas=keyframe_curve, x=x, y=y, button=1) keyframe_curve.translate_coordinates = mock.Mock(return_value=(1, None)) with mock.patch.object(Gtk, "get_event_widget") as get_event_widget: get_event_widget.return_value = keyframe_curve event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.name = "button_release_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_RELEASE) keyframe_curve._mpl_button_release_event_cb(event) self.assertListEqual( [item.timestamp for item in control_source.get_all()], [0, 1000000000])
def test_imshow_with_origin_lower(self): image = self.ax.imshow(self.ws2d_histo, origin="lower") # 0,0 in ax coordinates is the bottom left of figure, add 0.5 to move into canvas xy_pixels = self.ax.transAxes.transform((0, 0)) + (0.5, 0.5) bottom_left_corner = MouseEvent("motion_notify_event", self.fig.canvas, x=xy_pixels[0], y=xy_pixels[1]) self.assertEqual(image.get_extent(), (10.0, 30.0, 3.0, 9.0)) self.assertEqual(image.get_cursor_data(bottom_left_corner), 2.0)
def pickItems(self, x, y): self._picked = [] # Weird way to do an explicit picking: Simulate a button press event mouseEvent = MouseEvent('button_press_event', self, x, y) cid = self.mpl_connect('pick_event', self._onPick) self.fig.pick(mouseEvent) self.mpl_disconnect(cid) picked = self._picked del self._picked return picked
def test_picking_callbacks_overlap(big_on_axes, small_on_axes, click_on): """Test pick events on normal, host or parasite axes.""" # Two rectangles are drawn and "clicked on", a small one and a big one # enclosing the small one. The axis on which they are drawn as well as the # rectangle that is clicked on are varied. # In each case we expect that both rectangles are picked if we click on the # small one and only the big one is picked if we click on the big one. # Also tests picking on normal axes ("gca") as a control. big = plt.Rectangle((0.25, 0.25), 0.5, 0.5, picker=5) small = plt.Rectangle((0.4, 0.4), 0.2, 0.2, facecolor="r", picker=5) # Machinery for "receiving" events received_events = [] def on_pick(event): received_events.append(event) plt.gcf().canvas.mpl_connect('pick_event', on_pick) # Shortcut rectangles_on_axes = (big_on_axes, small_on_axes) # Axes setup axes = {"gca": None, "host": None, "parasite": None} if "gca" in rectangles_on_axes: axes["gca"] = plt.gca() if "host" in rectangles_on_axes or "parasite" in rectangles_on_axes: axes["host"] = host_subplot(111) axes["parasite"] = axes["host"].twin() # Add rectangles to axes axes[big_on_axes].add_patch(big) axes[small_on_axes].add_patch(small) # Simulate picking with click mouse event if click_on == "big": click_axes = axes[big_on_axes] axes_coords = (0.3, 0.3) else: click_axes = axes[small_on_axes] axes_coords = (0.5, 0.5) # In reality mouse events never happen on parasite axes, only host axes if click_axes is axes["parasite"]: click_axes = axes["host"] (x, y) = click_axes.transAxes.transform(axes_coords) m = MouseEvent("button_press_event", click_axes.figure.canvas, x, y, button=1) click_axes.pick(m) # Checks expected_n_events = 2 if click_on == "small" else 1 assert len(received_events) == expected_n_events event_rects = [event.artist for event in received_events] assert big in event_rects if click_on == "small": assert small in event_rects
def scroll_event(self, x, y, step=1, guiEvent=None): """ Backend derived classes should call this function on any scroll wheel event. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in MouseEvent """ button = 'up' if step >= 0 else 'down' self._button = button s = 'scroll_event' event = MouseEvent(s, self, x, y, button, self._key, guiEvent=guiEvent) setattr(event,'step',step) self.callbacks.process(s, event)
def find_all_axes(self, canvas, x=None, y=None): """ Return a list of all axes in canvas """ axeslist = [] evt = MouseEvent('', canvas, x, y) for a in canvas.get_figure().get_axes(): if x is None and y is None: axeslist.append(a) elif a.in_axes(evt): axeslist.append(a) return axeslist
def test_axescreator_select(self): """Test the :class:`psyplot_gui.plot_creator.AxesSelector`""" import matplotlib.pyplot as plt import numpy as np from matplotlib.backend_bases import MouseEvent, PickEvent from psyplot_gui.plot_creator import AxesCreatorCollection # load dataset self.test_load_external_file() # create arrays self.test_plusplus() # use all items atab = self.pc.array_table items = [atab.item(i, atab.axes_col) for i in range(2)] # create the widget to select the subplots ax1 = plt.axes([0.3, 0.4, 0.6, 0.3]) plt.figure() ax2 = plt.subplot(211) ac = AxesCreatorCollection('choose') w = ac.tb.currentWidget() fig = ax1.get_figure() mouseevent1 = MouseEvent( 'button_release_event', fig.canvas, *np.mean(ax1.get_position().get_points().T, axis=1)) w.get_picked_ax(PickEvent('pick', fig.canvas, mouseevent1, artist=ax1)) fig = ax2.get_figure() mouseevent2 = MouseEvent( 'button_release_event', ax2.get_figure().canvas, *np.mean(ax2.get_position().get_points().T, axis=1)) w.get_picked_ax(PickEvent('pick', fig.canvas, mouseevent2, artist=ax2)) ac.okpressed.connect(lambda it: atab._change_axes(items, it)) QTest.mouseClick(ac.bt_ok, Qt.LeftButton) # create the subplots axes = self.pc.array_table.axes # check them self.assertIs(axes[0], ax1) self.assertIs(axes[1], ax2) # close figures plt.close('all')
def test_cursor_data(): from matplotlib.backend_bases import MouseEvent fig, ax = plt.subplots() im = ax.imshow(np.arange(100).reshape(10, 10), origin='upper') x, y = 4, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 44 # Now try for a point outside the image # Tests issue #4957 x, y = 10.1, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) is None # Hmm, something is wrong here... I get 0, not None... # But, this works further down in the tests with extents flipped #x, y = 0.1, -0.1 #xdisp, ydisp = ax.transData.transform_point([x, y]) #event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) #z = im.get_cursor_data(event) #assert z is None, "Did not get None, got %d" % z ax.clear() # Now try with the extents flipped. im = ax.imshow(np.arange(100).reshape(10, 10), origin='lower') x, y = 4, 4 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 44 fig, ax = plt.subplots() im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5]) x, y = 0.25, 0.25 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) == 55 # Now try for a point outside the image # Tests issue #4957 x, y = 0.75, 0.25 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) is None x, y = 0.01, -0.01 xdisp, ydisp = ax.transData.transform_point([x, y]) event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp) assert im.get_cursor_data(event) is None
def pickItems(self, x, y, kinds): self._picked = [] # Weird way to do an explicit picking: Simulate a button press event mouseEvent = MouseEvent('button_press_event', self, x, y) cid = self.mpl_connect('pick_event', self._onPick) self.fig.pick(mouseEvent) self.mpl_disconnect(cid) picked = [p for p in self._picked if p['kind'] in kinds] self._picked = None return picked
def test_zoomInBottomRightAndZoomOut(self): """ Tests the zoomIn and zoomOut function for the bottom-right quadrant """ event = MouseEvent(name = "button_press_event", button = MouseButton.LEFT, canvas = self.app.canvas.canvas, x = 503, y = 670) event.xdata = 90 event.ydata = -45 event.button = MouseButton.LEFT currentZoom = self.app.canvas.plotter.zoom currentCenterX = self.app.canvas.plotter.centerX currentCenterY = self.app.canvas.plotter.centerY width = self.app.canvas.plotter.width height = self.app.canvas.plotter.height self.app.canvas.plotter.zoomIn(event) self.assertEqual(self.app.canvas.plotter.zoom, currentZoom + 1) self.assertEqual(self.app.canvas.plotter.centerX, currentCenterX + width/4) self.assertEqual(self.app.canvas.plotter.centerY, currentCenterY - height/4) self.app.canvas.plotter.zoomOut(event) self.assertEqual(self.app.canvas.plotter.zoom, currentZoom) self.assertEqual(self.app.canvas.plotter.centerX, currentCenterX) self.assertEqual(self.app.canvas.plotter.centerY, currentCenterY)
def select(self): """ Cause this widget to be the selected widget in its MPL axes. This assumes that the widget has its patch added to the MPL axes. """ if not self.patch or not self.is_on() or not self.ax: return canvas = self.ax.figure.canvas # Simulate a pick event x, y = self.patch[0].get_transform().transform_point((0, 0)) mouseevent = MouseEvent('pick_event', canvas, x, y) canvas.pick_event(mouseevent, self.patch[0]) self.picked = False
def find_axes(self, canvas, x, y): """ Override the wxmpl.find_axes function """ #return wxmpl.find_axes(canvas, x, y) evt = MouseEvent('', canvas, x, y) axes = None for a in canvas.get_figure().get_axes(): if a.in_axes(evt): if axes is None: axes = a if axes is None: return None, None, None xdata, ydata = axes.transData.inverted().transform((x, y)) return axes, xdata, ydata
def _process_event(name, ax, coords, *args): if name == "__mouse_click__": # So that the dragging callbacks don't go crazy. _process_event("button_press_event", ax, coords, *args) _process_event("button_release_event", ax, coords, *args) return display_coords = ax.transData.transform_point(coords) if name in ["button_press_event", "button_release_event", "motion_notify_event", "scroll_event"]: event = MouseEvent(name, ax.figure.canvas, *display_coords, *args) elif name in ["key_press_event", "key_release_event"]: event = KeyEvent(name, ax.figure.canvas, *args, *display_coords) else: raise ValueError("Unknown event name {!r}".format(name)) ax.figure.canvas.callbacks.process(name, event)
def check_keyframe_ui_toggle(self, ges_clip, timeline_container): """Checks keyframes toggling by click events.""" timeline = timeline_container.timeline inpoint = ges_clip.props.in_point duration = ges_clip.props.duration offsets = (1, int(duration / 2), int(duration) - 1) timeline.selection.select([ges_clip]) ges_video_source = ges_clip.find_track_element(None, GES.VideoSource) binding = ges_video_source.get_control_binding("alpha") control_source = binding.props.control_source keyframe_curve = ges_video_source.ui.keyframe_curve values = [item.timestamp for item in control_source.get_all()] self.assertEqual(values, [inpoint, inpoint + duration]) # Add keyframes. for offset in offsets: xdata, ydata = inpoint + offset, 1 x, y = keyframe_curve._ax.transData.transform((xdata, ydata)) event = MouseEvent( name = "button_press_event", canvas = keyframe_curve, x = x, y = y, button = 1 ) event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.name = "button_release_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_RELEASE) keyframe_curve._mpl_button_release_event_cb(event) values = [item.timestamp for item in control_source.get_all()] self.assertIn(inpoint + offset, values) # Remove keyframes. for offset in offsets: xdata, ydata = inpoint + offset, 1 x, y = keyframe_curve._ax.transData.transform((xdata, ydata)) event = MouseEvent( name="button_press_event", canvas=keyframe_curve, x=x, y=y, button=1 ) event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.name = "button_release_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_RELEASE) keyframe_curve._mpl_button_release_event_cb(event) event.name = "button_press_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.guiEvent = Gdk.Event.new(Gdk.EventType._2BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.name = "button_release_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_RELEASE) keyframe_curve._mpl_button_release_event_cb(event) values = [item.timestamp for item in control_source.get_all()] self.assertNotIn(inpoint + offset, values)
def check_keyframe_ui_toggle(self, ges_clip, timeline_container): """Checks keyframes toggling by click events.""" timeline = timeline_container.timeline start = ges_clip.props.start start_px = Zoomable.nsToPixel(start) inpoint = ges_clip.props.in_point duration = ges_clip.props.duration duration_px = Zoomable.nsToPixel(duration) offsets_px = (1, int(duration_px / 2), int(duration_px) - 1) timeline.selection.select([ges_clip]) ges_video_source = ges_clip.find_track_element(None, GES.VideoSource) binding = ges_video_source.get_control_binding("alpha") control_source = binding.props.control_source keyframe_curve = ges_video_source.ui.keyframe_curve values = [item.timestamp for item in control_source.get_all()] self.assertEqual(values, [inpoint, inpoint + duration]) # Add keyframes by simulating mouse clicks. for offset_px in offsets_px: offset = Zoomable.pixelToNs(start_px + offset_px) - start xdata, ydata = inpoint + offset, 1 x, y = keyframe_curve._ax.transData.transform((xdata, ydata)) event = MouseEvent( name="button_press_event", canvas=keyframe_curve, x=x, y=y, button=1 ) keyframe_curve.translate_coordinates = \ mock.Mock(return_value=(start_px+offset_px, None)) with mock.patch.object(Gtk, "get_event_widget") as get_event_widget: get_event_widget.return_value = keyframe_curve event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.name = "button_release_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_RELEASE) keyframe_curve._mpl_button_release_event_cb(event) values = [item.timestamp for item in control_source.get_all()] self.assertIn(inpoint + offset, values) # Remove keyframes by simulating mouse double-clicks. for offset_px in offsets_px: offset = Zoomable.pixelToNs(start_px + offset_px) - start xdata, ydata = inpoint + offset, 1 x, y = keyframe_curve._ax.transData.transform((xdata, ydata)) event = MouseEvent( name="button_press_event", canvas=keyframe_curve, x=x, y=y, button=1 ) keyframe_curve.translate_coordinates = \ mock.Mock(return_value=(start_px + offset_px, None)) with mock.patch.object(Gtk, "get_event_widget") as get_event_widget: get_event_widget.return_value = keyframe_curve event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.name = "button_release_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_RELEASE) keyframe_curve._mpl_button_release_event_cb(event) event.name = "button_press_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.guiEvent = Gdk.Event.new(Gdk.EventType._2BUTTON_PRESS) keyframe_curve._mpl_button_press_event_cb(event) event.name = "button_release_event" event.guiEvent = Gdk.Event.new(Gdk.EventType.BUTTON_RELEASE) keyframe_curve._mpl_button_release_event_cb(event) values = [item.timestamp for item in control_source.get_all()] self.assertNotIn(inpoint + offset, values)