1# Copyright 2021 The Pigweed Authors 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); you may not 4# use this file except in compliance with the License. You may obtain a copy of 5# the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12# License for the specific language governing permissions and limitations under 13# the License. 14"""Functions for handling mouse events.""" 15 16from typing import Callable, TYPE_CHECKING 17 18from prompt_toolkit.layout.mouse_handlers import MouseHandlers 19from prompt_toolkit.mouse_events import MouseEvent, MouseEventType 20 21if TYPE_CHECKING: 22 # pylint: disable=ungrouped-imports 23 from prompt_toolkit.key_binding.key_bindings import NotImplementedOrNone 24 25 26def on_click(on_click_function: Callable, mouse_event: MouseEvent): 27 """Run a function on mouse click. 28 29 Here is an example of how to add add click functionality to a piece of 30 formatted text. :: 31 32 import functools 33 import pw_console.widgets.mouse_handlers 34 35 def get_tokens(self): 36 mouse_handler = functools.partial( 37 pw_console.widgets.mouse_handlers.on_click, 38 self.your_widget.do_something) 39 return [ 40 ( 41 'class:text-button', 42 ' Click Here to Do Something ', 43 mouse_handler, 44 ), 45 ] 46 47 """ 48 if mouse_event.event_type == MouseEventType.MOUSE_UP: 49 on_click_function() 50 return None 51 return NotImplemented 52 53 54class EmptyMouseHandler(MouseHandlers): 55 """MouseHandler that does not propagate events.""" 56 57 def set_mouse_handler_for_range( 58 self, 59 x_min: int, 60 x_max: int, 61 y_min: int, 62 y_max: int, 63 handler: Callable[[MouseEvent], 'NotImplementedOrNone'], 64 ) -> None: 65 return 66