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