• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"""Example text input-output Plugin."""
15
16from typing import TYPE_CHECKING
17
18from prompt_toolkit.document import Document
19from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
20from prompt_toolkit.layout import Window
21from prompt_toolkit.widgets import SearchToolbar, TextArea
22
23from pw_console.widgets import ToolbarButton, WindowPane, WindowPaneToolbar
24
25if TYPE_CHECKING:
26    from pw_console.console_app import ConsoleApp
27
28
29class CalcPane(WindowPane):
30    """Example plugin that accepts text input and displays output.
31
32    This plugin is similar to the full-screen calculator example provided in
33    prompt_toolkit:
34    https://github.com/prompt-toolkit/python-prompt-toolkit/blob/3.0.23/examples/full-screen/calculator.py
35
36    It's a full window that can be moved around the user interface like other
37    Pigweed Console window panes. An input prompt is displayed on the bottom of
38    the window where the user can type in some math equation. When the enter key
39    is pressed the input is processed and the result shown in the top half of
40    the window.
41
42    Both input and output fields are prompt_toolkit TextArea objects which can
43    have their own options like syntax highlighting.
44    """
45    def __init__(self):
46        # Call WindowPane.__init__ and set the title to 'Calculator'
47        super().__init__(pane_title='Calculator')
48
49        # Create a TextArea for the output-field
50        # TextArea is a prompt_toolkit widget that can display editable text in
51        # a buffer. See the prompt_toolkit docs for all possible options:
52        # https://python-prompt-toolkit.readthedocs.io/en/latest/pages/reference.html#prompt_toolkit.widgets.TextArea
53        self.output_field = TextArea(
54            # Optional Styles to apply to this TextArea
55            style='class:output-field',
56            # Initial text to put into the buffer.
57            text='Calculator Output',
58            # Allow this buffer to be in focus. This lets you drag select text
59            # contained inside, and edit the contents unless readonly.
60            focusable=True,
61            # Focus on mouse click.
62            focus_on_click=True,
63        )
64
65        # This is the search toolbar and only appears if the user presses ctrl-r
66        # to do reverse history search (similar to bash or zsh). Its used by the
67        # input_field below.
68        self.search_field = SearchToolbar()
69
70        # Create a TextArea for the user input.
71        self.input_field = TextArea(
72            # The height is set to 1 line
73            height=1,
74            # Prompt string that appears before the cursor.
75            prompt='>>> ',
76            # Optional Styles to apply to this TextArea
77            style='class:input-field',
78            # We only allow one line input for this example but multiline is
79            # supported by prompt_toolkit.
80            multiline=False,
81            wrap_lines=False,
82            # Allow reverse history search
83            search_field=self.search_field,
84            # Allow this input to be focused.
85            focusable=True,
86            # Focus on mouse click.
87            focus_on_click=True,
88        )
89
90        # The TextArea accept_handler function is called by prompt_toolkit (the
91        # UI) when the user presses enter. Here we override it to our own accept
92        # handler defined in this CalcPane class.
93        self.input_field.accept_handler = self.accept_input
94
95        # Create a toolbar for display at the bottom of this window. It will
96        # show the window title and toolbar buttons.
97        self.bottom_toolbar = WindowPaneToolbar(self)
98        self.bottom_toolbar.add_button(
99            ToolbarButton(
100                key='Enter',  # Key binding for this function
101                description='Run Calculation',  # Button name
102                # Function to run when clicked.
103                mouse_handler=self.run_calculation,
104            ))
105        self.bottom_toolbar.add_button(
106            ToolbarButton(
107                key='Ctrl-c',  # Key binding for this function
108                description='Copy Output',  # Button name
109                # Function to run when clicked.
110                mouse_handler=self.copy_all_output,
111            ))
112
113        # self.container is the root container that contains objects to be
114        # rendered in the UI, one on top of the other.
115        self.container = self._create_pane_container(
116            # Show the output_field on top
117            self.output_field,
118            # Draw a separator line with height=1
119            Window(height=1, char='─', style='class:line'),
120            # Show the input field just below that.
121            self.input_field,
122            # If ctrl-r reverse history is active, show the search box below the
123            # input_field.
124            self.search_field,
125            # Lastly, show the toolbar.
126            self.bottom_toolbar,
127        )
128
129    def pw_console_init(self, app: 'ConsoleApp') -> None:
130        """Set the Pigweed Console application instance.
131
132        This function is called after the Pigweed Console starts up and allows
133        access to the user preferences. Prefs is required for creating new
134        user-remappable keybinds."""
135        self.application = app
136        self.set_custom_keybinds()
137
138    def set_custom_keybinds(self) -> None:
139        # Fetch ConsoleApp preferences to load user keybindings
140        prefs = self.application.prefs
141        # Register a named keybind function that is user re-mappable
142        prefs.register_named_key_function(
143            'calc-pane.copy-selected-text',
144            # default bindings
145            ['c-c'])
146
147        # For setting additional keybindings to the output_field.
148        key_bindings = KeyBindings()
149
150        # Map the 'calc-pane.copy-selected-text' function keybind to the
151        # _copy_all_output function below. This will set
152        @prefs.register_keybinding('calc-pane.copy-selected-text',
153                                   key_bindings)
154        def _copy_all_output(_event: KeyPressEvent) -> None:
155            """Copy selected text from the output buffer."""
156            self.copy_selected_output()
157
158        # Set the output_field controls key_bindings to the new bindings.
159        self.output_field.control.key_bindings = key_bindings
160
161    def run_calculation(self):
162        """Trigger the input_field's accept_handler.
163
164        This has the same effect as pressing enter in the input_field.
165        """
166        self.input_field.buffer.validate_and_handle()
167
168    def accept_input(self, _buffer):
169        """Function run when the user presses enter in the input_field.
170
171        Takes a buffer argument that contains the user's input text.
172        """
173        # Evaluate the user's calculator expression as Python and format the
174        # output result.
175        try:
176            output = "\n\nIn:  {}\nOut: {}".format(
177                self.input_field.text,
178                # NOTE: Don't use 'eval' in real code (this is just an example)
179                eval(self.input_field.text))  # pylint: disable=eval-used
180        except BaseException as exception:  # pylint: disable=broad-except
181            output = "\n\n{}".format(exception)
182
183        # Append the new output result to the existing output_field contents.
184        new_text = self.output_field.text + output
185
186        # Update the output_field with the new contents and move the
187        # cursor_position to the end.
188        self.output_field.buffer.document = Document(
189            text=new_text, cursor_position=len(new_text))
190
191    def copy_selected_output(self):
192        """Copy highlighted text in the output_field to the system clipboard."""
193        clipboard_data = self.output_field.buffer.copy_selection()
194        self.application.application.clipboard.set_data(clipboard_data)
195
196    def copy_all_output(self):
197        """Copy all text in the output_field to the system clipboard."""
198        self.application.application.clipboard.set_text(
199            self.output_field.buffer.text)
200