### Creating Screen with Wrapper Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst This snippet demonstrates the recommended way to initialize an asciimatics Screen using the `Screen.wrapper` static method. It handles setup and teardown, passing the Screen object to a specified function. The example prints 'Hello world!' at the top-left, refreshes the screen, and then pauses. ```python from asciimatics.screen import Screen from time import sleep def demo(screen): screen.print_at('Hello world!', 0, 0) screen.refresh() sleep(10) Screen.wrapper(demo) ``` -------------------------------- ### Building Documentation - Bash Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/contributing.rst Installs necessary development dependencies listed in `requirements/dev.txt`, changes directory into `doc`, and executes the `build.sh` script to generate the project documentation. ```bash $ pip install -r requirements/dev.txt $ cd doc $ ./build.sh ``` -------------------------------- ### Creating Screen with ManagedScreen Decorator Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst This example shows how to use the `ManagedScreen` class as a function decorator. This provides an alternative, concise syntax for initializing and managing the Screen lifecycle, achieving the same result as the `Screen.wrapper` method. ```python from asciimatics.screen import ManagedScreen from asciimatics.scene import Scene from asciimatics.effects import Cycle, Stars from asciimatics.renderers import FigletText @ManagedScreen def demo(screen=None): screen.print_at('Hello world!', 0, 0) screen.refresh() sleep(10) demo() ``` -------------------------------- ### Installing asciimatics on Termux (bash) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/troubleshooting.rst Provides the bash commands required to update packages, install dependencies (clang, python-dev, libjpeg-turbo-dev, Pillow), and finally install asciimatics within the Termux environment on Android. These steps are necessary due to native library dependencies of Pillow. ```bash apt update apt-get install clang python-dev libjpeg-turbo-dev LDFLAGS=-L/system/lib pip install Pillow pip install asciimatics ``` -------------------------------- ### Installing Asciimatics Library using pip (Bash) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/intro.rst This snippet shows the standard command-line instruction to install the asciimatics Python library using the pip package manager. It automatically fetches and installs the library along with its required dependencies. ```bash $ pip install asciimatics ``` -------------------------------- ### Running Standard Tests - Bash Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/contributing.rst Installs development dependencies from `requirements/dev.txt` and runs the standard Python unit tests using the `unittest` module. This typically skips tests requiring a TTY. ```bash $ pip install -r requirements/dev.txt $ python -m unittest ``` -------------------------------- ### Installing Asciimatics using Pip (Bash) Source: https://github.com/peterbrittain/asciimatics/blob/master/README.rst This snippet provides the command to install the asciimatics Python library using the pip package manager. Running this command downloads and installs the latest stable version of asciimatics along with its required dependencies from the Python Package Index (PyPI). ```bash $ pip install asciimatics ``` -------------------------------- ### Drawing and Clearing Lines in Asciimatics Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst Shows how to draw a straight line using `screen.move(x, y)` to set the starting point and `screen.draw(x, y)` to set the ending point. It also demonstrates clearing the drawn line by redrawing it with a space character (`char=' '`). ```python # Draw a diagonal line from the top-left of the screen. screen.move(0, 0) screen.draw(10, 10) # Clear the line screen.move(0, 0) screen.draw(10, 10, char=' ') ``` -------------------------------- ### Creating Sprite with StaticRenderer and Path in Asciimatics Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/animation.rst This snippet demonstrates how to define a path for a Sprite using `Path` and its methods like `jump_to` and `move_round_to`. It then shows how to instantiate a `Sprite` object, providing the screen, a dictionary of renderers (here a simple StaticRenderer), and the defined path. The example creates a Sprite that follows an elliptical trajectory, rendering an 'X' at each step. ```python # Sample Sprite that plots an "X" for each step along an elliptical path. centre = (screen.width // 2, screen.height // 2) curve_path = [] for i in range(0, 11): curve_path.append( (centre[0] + (screen.width / 4 * math.sin(i * math.pi / 5)), centre[1] - (screen.height / 4 * math.cos(i * math.pi / 5)))) path = Path() path.jump_to(centre[0], centre[1] - screen.height // 4), path.move_round_to(curve_path, 60) sprite = Sprite( screen, renderer_dict={ "default": StaticRenderer(images=["X"]) }, path=path, colour=Screen.COLOUR_RED, clear=False) ``` -------------------------------- ### Printing Unicode Text Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst This example shows how asciimatics supports printing Unicode characters using the `screen.print_at` method. It demonstrates displaying a Unicode telephone character (☎) followed by text, using specified colour and attribute parameters. ```python # Should have a telephone at the start... screen.print_at(u'☎ Call me!', 0, 0, COLOUR_GREEN, A_BOLD) ``` -------------------------------- ### Transitioning to Named Scene using NextScene Exception in Asciimatics (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This snippet demonstrates how to switch to a specific scene within an `asciimatics` application using the `NextScene` exception. After defining a list of `Scene` objects, each with a unique `name`, raising `NextScene("Main")` will instruct the animation engine to stop the current scene and start playing the scene named "Main". This is used for controlling application flow between different UI states. ```python # Given this scene list... scenes = [ Scene([ListView(screen, contacts)], -1, name="Main"), Scene([ContactView(screen, contacts)], -1, name="Edit Contact") ] screen.play(scenes) # You can use this code to move back to the first scene at any time... raise NextScene("Main") ``` -------------------------------- ### Integrating Asciimatics Animation with asyncio Event Loop in Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/animation.rst This example shows how to manually drive asciimatics frame drawing within an asyncio event loop. It defines a recursive `update_screen` function called by `loop.call_later` to draw the next frame every 0.05 seconds (20 FPS). The snippet sets up a simple scene with `Cycle` and `Stars` effects and then runs the asyncio loop to manage the animation lifecycle. ```python import asyncio from asciimatics.effects import Cycle, Stars from asciimatics.renderers import FigletText from asciimatics.scene import Scene from asciimatics.screen import Screen def update_screen(end_time, loop, screen): screen.draw_next_frame() if loop.time() < end_time: loop.call_later(0.05, update_screen, end_time, loop, screen) else: loop.stop() # Define the scene that you'd like to play. screen = Screen.open() effects = [ Cycle( screen, FigletText("ASCIIMATICS", font='big'), screen.height // 2 - 8), Cycle( screen, FigletText("ROCKS!", font='big'), screen.height // 2 + 3), Stars(screen, (screen.width + screen.height) // 2) ] screen.set_scenes([Scene(effects, 500)]) # Schedule the first call to display_date() loop = asyncio.new_event_loop() end_time = loop.time() + 5.0 loop.call_soon(update_screen, end_time, loop, screen) # Blocking call interrupted by loop.stop() loop.run_forever() loop.close() screen.close() ``` -------------------------------- ### Example curses Error Traceback (bash) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/troubleshooting.rst Displays a typical Python traceback indicating a _curses.error: curs_set() returned ERR. This error commonly arises when running asciimatics on Linux or Mac with an old terminal configuration (TERM variable set to xterm-color), highlighting that a required curses function failed. ```bash Traceback (most recent call last): File "demo.py", line 18, in Screen.wrapper(demo) File "./lib/python3.6/site-packages/asciimatics/screen.py", line 1162, in wrapper unicode_aware=unicode_aware) File "./lib/python3.6/site-packages/asciimatics/screen.py", line 1131, in open unicode_aware=unicode_aware) File "./lib/python3.6/site-packages/asciimatics/screen.py", line 2001, in __init__ curses.curs_set(0) _curses.error: curs_set() returned ERR ``` -------------------------------- ### Fixing Backspace/Delete on Mac OS X (bash) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/troubleshooting.rst Provides bash commands to modify the terminal definition (terminfo) on Mac OS X. It uses infocmp to get the current definition, sed to update the kbs and kdch1 capabilities to standard values (\177 for backspace, \E[3~ for delete), tic to compile the new definition, and rm to clean up the temporary file. This resolves common issues with these keys in curses applications on the default Mac terminal. ```bash infocmp "$TERM" | sed -Ee 's/(kbs)=[^,]*/\1=\\177/' -e 's/(kdch1)=[^,]*/\1=\\E[3~/' > "$TERM" tic "$TERM" rm -f "$TERM" ``` -------------------------------- ### Basic Screen Manipulation with Asciimatics (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/README.rst This Python code demonstrates the low-level API for interacting with the console screen using asciimatics. It initializes a screen, prints 'Hello world!' at random locations with random foreground and background colours, refreshes the screen, and waits for a key press, exiting on 'Q' or 'q'. It showcases basic text output, positioning, colouring, and input handling. ```python from random import randint from asciimatics.screen import Screen def demo(screen): while True: screen.print_at('Hello world!', randint(0, screen.width), randint(0, screen.height), colour=randint(0, screen.colours - 1), bg=randint(0, screen.colours - 1)) ev = screen.get_key() if ev in (ord('Q'), ord('q')): return screen.refresh() Screen.wrapper(demo) ``` -------------------------------- ### Creating Frame and Layout (Asciimatics/Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst Shows how to instantiate a `Frame` with a specific size (80x20) and no border, and then create a `Layout` dividing the frame's width into four equal columns (represented by the `[1, 1, 1, 1]` list). This layout is then added to the frame, preparing it to receive widgets. ```python frame = Frame(screen, 80, 20, has_border=False) layout = Layout([1, 1, 1, 1]) frame.add_layout(layout) ``` -------------------------------- ### Creating an Animation Scene with Asciimatics (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/README.rst This Python snippet illustrates how to use the high-level API of asciimatics to create an animation scene. It defines a list of effects, including cycling `FigletText` renderings and a `Stars` effect, and then wraps the scene execution using `Screen.wrapper`. This demonstrates combining different effects to build dynamic console animations. ```python from asciimatics.effects import Cycle, Stars from asciimatics.renderers import FigletText from asciimatics.scene import Scene from asciimatics.screen import Screen def demo(screen): effects = [ Cycle( screen, FigletText("ASCIIMATICS", font='big'), int(screen.height / 2 - 8)), Cycle( screen, FigletText("ROCKS!", font='big'), int(screen.height / 2 + 3)), Stars(screen, 200) ] screen.play([Scene(effects, 500)]) Screen.wrapper(demo) ``` -------------------------------- ### Printing Text with Colour and Attribute Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst This snippet demonstrates using the `screen.print_at` method with colour and attribute parameters. It shows how to display text ('Hello world!') at a specific coordinate (0, 0) using a foreground colour (`COLOUR_GREEN`) and an attribute (`A_BOLD`). ```python # Bright green text screen.print_at('Hello world!', 0, 0, COLOUR_GREEN, A_BOLD) ``` -------------------------------- ### Initializing StaticRenderer with FigletText (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/rendering.rst Demonstrates creating a StaticRenderer instance using the FigletText helper class from asciimatics. This renderer pre-renders a large "ASCIIMATICS" text using the 'big' font for later display. It is used for static content that is calculated entirely in advance and requires the FigletText class. ```python renderer = FigletText("ASCIIMATICS", font='big') ``` -------------------------------- ### Creating Basic Asciimatics Animation (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/intro.rst This Python script demonstrates the core usage of asciimatics to create a simple terminal animation. It initializes a Screen, defines a list of Effect objects using Cycle and Stars with FigletText renderers, groups them into a Scene, and plays the scene using the Screen.wrapper helper function. ```python from asciimatics.screen import Screen from asciimatics.scene import Scene from asciimatics.effects import Cycle, Stars from asciimatics.renderers import FigletText def demo(screen): effects = [ Cycle( screen, FigletText("ASCIIMATICS", font='big'), screen.height // 2 - 8), Cycle( screen, FigletText("ROCKS!", font='big'), screen.height // 2 + 3), Stars(screen, (screen.width + screen.height) // 2) ] screen.play([Scene(effects, 500)]) Screen.wrapper(demo) ``` -------------------------------- ### Creating Screen with ManagedScreen Context Manager Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst This snippet illustrates using `ManagedScreen` as a context manager with the `with` keyword. This approach clearly defines the scope where the Screen is active, ensuring proper initialization and cleanup upon exiting the `with` block. ```python from asciimatics.screen import ManagedScreen from asciimatics.scene import Scene from asciimatics.effects import Cycle, Stars from asciimatics.renderers import FigletText def demo(): with ManagedScreen() as screen: screen.print_at('Hello world!', 0, 0) screen.refresh() sleep(10) demo() ``` -------------------------------- ### Creating a Contact View Frame (Asciimatics/Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst Defines a `ContactView` class, a subclass of `asciimatics.screen.Frame`, to display and edit contact details. It sets up the UI using `Layout` objects to position various widgets like `Text`, `TextBox`, and `Button`, demonstrating how to build interactive forms. The `_ok` method saves changes via a model and navigates to the "Main" scene, while `_cancel` simply navigates back. ```python class ContactView(Frame): def __init__(self, screen, model): super(ContactView, self).__init__(screen, screen.height * 2 // 3, screen.width * 2 // 3, hover_focus=True, title="Contact Details") # Save off the model that accesses the contacts database. self._model = model # Create the form for displaying the list of contacts. layout = Layout([100], fill_frame=True) self.add_layout(layout) layout.add_widget(Text("Name:", "name")) layout.add_widget(Text("Address:", "address")) layout.add_widget(Text("Phone number:", "phone")) layout.add_widget(Text("Email address:", "email")) layout.add_widget(TextBox(5, "Notes:", "notes", as_string=True)) layout2 = Layout([1, 1, 1, 1]) self.add_layout(layout2) layout2.add_widget(Button("OK", self._ok), 0) layout2.add_widget(Button("Cancel", self._cancel), 3) self.fix() def reset(self): # Do standard reset to clear out form, then populate with new data. super(ContactView, self).reset() self.data = self._model.get_current_contact() def _ok(self): self.save() self._model.update_current_contact(self.data) raise NextScene("Main") @staticmethod def _cancel(): raise NextScene("Main") ``` -------------------------------- ### Creating DynamicRenderer with BarChart (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/rendering.rst Shows how to initialize a DynamicRenderer using the BarChart class. It includes a helper function `fn` that provides random data (0-40) for two bars, demonstrating dynamic content generation based on program state. This requires the BarChart class and the `randint` function. ```python def fn(): return randint(0, 40) renderer = BarChart(10, 40, [fn, fn], char='=') ``` -------------------------------- ### Adding Input Widgets to Single Column Layout (Asciimatics/Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst Demonstrates creating a `Layout` with a single column that occupies the entire frame width. It then adds multiple labeled input widgets (`Text` for single-line fields and `TextBox` for multi-line notes) to this layout, showing how Asciimatics automatically handles label alignment in a single column. ```python layout = Layout([100]) frame.add_layout(layout) layout.add_widget(Text("Name:", "name")) layout.add_widget(Text("Address:", "address")) layout.add_widget(Text("Phone number:", "phone")) layout.add_widget(Text("Email address:", "email")) layout.add_widget(TextBox(5, "Notes:", "notes", as_string=True)) ``` -------------------------------- ### Combining Effects and Frames in an Asciimatics Scene (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This snippet shows how to create an `asciimatics` scene that combines multiple effects, specifically placing a `Frame` (representing an input form) on top of another effect (`Julia`, an animated visual). Effects are added to a list, and their order determines their Z-order; effects later in the list are drawn on top. ```python scenes = [] effects = [ Julia(screen), InputFormFrame(screen) ] scenes.append(Scene(effects, -1)) screen.play(scenes) ``` -------------------------------- ### Using Multiple Layouts in a Frame (Asciimatics/Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst Illustrates the use of multiple `Layout` objects within a single `Frame` to organize different sections of the UI vertically. It creates `layout1` (a single column) and adds a `Text` and a `TextBox` widget to it. It then creates `layout2` (also a single column) and adds it to the frame, demonstrating how layouts stack, although `layout2` remains empty in this specific snippet. ```python layout1 = Layout([100]) frame.add_layout(layout1) layout1.add_widget(Text(label="Search:", name="search_string")) layout2 = Layout([100]) frame.add_layout(layout2) layout1.add_widget(TextBox(Widget.FILL_FRAME, name="results")) ``` -------------------------------- ### Re-applying Pywal Theme on Resize (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/troubleshooting.rst Shows a Python snippet using asciimatics.screen.ManagedScreen. It checks if the terminal has been resized and, if so, reads and writes the pywal color sequences file (~/.cache/wal/sequences) back to standard output to restore the external theme. This work-around is needed because asciimatics resize handling doesn't re-invoke external theme applications. ```python from pathlib import Path from asciimatics.screen import ManagedScreen with ManagedScreen() as screen: # do stuff if screen.has_resized(): wal_sequences = Path.home() / ".cache" / "wal" / "sequences" try: with wal_sequences.open("rb") as fd: contents = fd.read() sys.stdout.buffer.write(contents) except Exception: pass ``` -------------------------------- ### Handling Screen Resizing with Screen.wrapper Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This standard boilerplate code demonstrates how to structure an asciimatics application's main loop to automatically handle terminal resizing. It uses `Screen.wrapper` to manage the screen and `ResizeScreenError` to catch resize events, allowing the application to rebuild scenes and restart from the last active one. ```python def main(screen, scene): # Define your Scenes here scenes = ... # Run your program screen.play(scenes, stop_on_resize=True, start_scene=scene) last_scene = None while True: try: Screen.wrapper(main, arguments=[last_scene]) sys.exit(0) except ResizeScreenError as e: last_scene = e.scene ``` -------------------------------- ### Creating Contact List View Frame with Asciimatics Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst Implements an `asciimatics` `Frame` subclass, `ListView`, to display contacts. It uses `ListBox` for the contact list and `Button` widgets for actions, managing layouts and interacting with a `ContactModel` instance to fetch and manipulate data. It handles user selections and button clicks to navigate or perform actions. ```python class ListView(Frame): def __init__(self, screen, model): super(ListView, self).__init__(screen, screen.height * 2 // 3, screen.width * 2 // 3, on_load=self._reload_list, hover_focus=True, title="Contact List") # Save off the model that accesses the contacts database. self._model = model # Create the form for displaying the list of contacts. self._list_view = ListBox( Widget.FILL_FRAME, model.get_summary(), name="contacts", on_select=self._on_pick) self._edit_button = Button("Edit", self._edit) self._delete_button = Button("Delete", self._delete) layout = Layout([100], fill_frame=True) self.add_layout(layout) layout.add_widget(self._list_view) layout.add_widget(Divider()) layout2 = Layout([1, 1, 1, 1]) self.add_layout(layout2) layout2.add_widget(Button("Add", self._add), 0) layout2.add_widget(self._edit_button, 1) layout2.add_widget(self._delete_button, 2) layout2.add_widget(Button("Quit", self._quit), 3) self.fix() def _on_pick(self): self._edit_button.disabled = self._list_view.value is None self._delete_button.disabled = self._list_view.value is None def _reload_list(self): self._list_view.options = self._model.get_summary() self._model.current_id = None def _add(self): self._model.current_id = None raise NextScene("Edit Contact") def _edit(self): self.save() self._model.current_id = self.data["contacts"] raise NextScene("Edit Contact") def _delete(self): self.save() self._model.delete_contact(self.data["contacts"]) self._reload_list() @staticmethod def _quit(): raise StopApplication("User pressed quit") ``` -------------------------------- ### Defining Basic Terminal Colours Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst This code block lists the basic 8 colour constants defined within the `Screen` class. These constants represent standard colours guaranteed to work across most terminal types and systems, serving as reliable values for foreground and background colours. ```python COLOUR_BLACK = 0 COLOUR_RED = 1 COLOUR_GREEN = 2 COLOUR_YELLOW = 3 COLOUR_BLUE = 4 COLOUR_MAGENTA = 5 COLOUR_CYAN = 6 COLOUR_WHITE = 7 ``` -------------------------------- ### Implementing Global Keyboard Shortcuts in Asciimatics (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This snippet defines a function `global_shortcuts` that checks for `KeyboardEvent` instances. If Ctrl+Q (key code 17) or Ctrl+X (key code 24) is pressed and not handled by a widget, it raises a `StopApplication` exception to terminate the program. The function is then registered as the `unhandled_input` handler when calling `screen.play()`. This allows defining application-wide keyboard shortcuts. ```python # Event handler for global keys def global_shortcuts(event): if isinstance(event, KeyboardEvent): c = event.key_code # Stop on ctrl+q or ctrl+x if c in (17, 24): raise StopApplication("User terminated app") # Pass this to the screen... screen.play(scenes, unhandled_input=global_shortcuts) ``` -------------------------------- ### Scraping Text and Printing in Asciimatics Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst Demonstrates how to use `screen.get_from(x, y)` to read the character and attributes at a specific screen location. It checks if the location is not empty (character code 32 is space) and prints 'X' if it is occupied. `get_from` returns a 4-tuple: character code, foreground color, attributes, and background color. ```python # Check we've not already displayed something before updating. current_char, fg, attr, bg = screen.get_from(x, y) if current_char != 32: screen.print_at('X', x, y) ``` -------------------------------- ### Defining asciimatics Colour Tuple Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This snippet demonstrates the structure of a colour tuple used in asciimatics palettes. It consists of a foreground colour, an attribute (like bold or underline), and a background colour, using constants provided by the Screen object. These tuples define how different UI components should be rendered. ```python (Screen.COLOUR_GREEN, Screen.A_BOLD, Screen.COLOUR_BLUE) ``` -------------------------------- ### Adding Buttons to Layout Columns (Asciimatics/Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst Illustrates how to add `Button` widgets to a previously defined `Layout`. The `add_widget` method takes the widget instance, and an optional column index (0-based) to specify its horizontal position within the layout. Here, an "OK" button is placed in column 0 and a "Cancel" button in column 3. ```python layout.add_widget(Button("OK", self._ok), 0) layout.add_widget(Button("Cancel", self._cancel), 3) ``` -------------------------------- ### Printing DynamicRenderer Output (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/rendering.rst Demonstrates how a DynamicRenderer can be used outside of the standard asciimatics Screen context by simply printing the renderer object. The renderer's string representation is generated on demand when `print()` is called. This requires the DynamicRenderer class and any dependencies for its rendering logic. ```python def fn(): return randint(0, 40) renderer = BarChart(10, 40, [fn, fn], char='=') print(renderer) ``` -------------------------------- ### Running asciimatics in a Real Terminal (Windows) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/troubleshooting.rst Provides a command-line workaround for executing asciimatics applications outside of an IDE's potentially incompatible terminal. This command launches a new Windows Command Prompt window (`cmd /c`) to run the specified Python script, ensuring it uses a native terminal environment. ```Shell start cmd /c "python " ``` -------------------------------- ### Implementing Contact Data Model in Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst Defines a Python class `ContactModel` that uses an in-memory SQLite database to store and manage contact details. It provides methods for adding, retrieving, updating, and deleting contact records, serving as the data layer for a UI application. It requires the `sqlite3` module. ```python class ContactModel(): def __init__(self): # Create a database in RAM self._db = sqlite3.connect(':memory:') self._db.row_factory = sqlite3.Row # Create the basic contact table. self._db.cursor().execute(''' CREATE TABLE contacts( id INTEGER PRIMARY KEY, name TEXT, phone TEXT, address TEXT, email TEXT, notes TEXT) ''') self._db.commit() # Current contact when editing. self.current_id = None def add(self, contact): self._db.cursor().execute(''' INSERT INTO contacts(name, phone, address, email, notes) VALUES(:name, :phone, :address, :email, :notes)''', contact) self._db.commit() def get_summary(self): return self._db.cursor().execute( "SELECT name, id from contacts").fetchall() def get_contact(self, contact_id): return self._db.cursor().execute( "SELECT * from contacts where id=?", str(contact_id)).fetchone() def get_current_contact(self): if self.current_id is None: return {"name": "", "address": "", "phone": "", "email": "", "notes": ""} else: return self.get_contact(self.current_id) def update_current_contact(self, details): if self.current_id is None: self.add(details) else: self._db.cursor().execute(''' UPDATE contacts SET name=:name, phone=:phone, address=:address, email=:email, notes=:notes WHERE id=:id''', details) self._db.commit() def delete_contact(self, contact_id): self._db.cursor().execute(''' DELETE FROM contacts WHERE id=:id''', {"id": contact_id}) self._db.commit() ``` -------------------------------- ### Defining asciimatics Form Layout and Widgets Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This Python code illustrates how to define a simple form layout within an asciimatics Frame. It creates a single-column Layout, adds it to the frame, and then adds Text and TextBox widgets to the layout, assigning labels and unique names for data access. This sets up the basic UI structure for user input. ```python # Form definition layout = Layout([100]) frame.add_layout(layout) layout.add_widget(Text("Name:", "name")) layout.add_widget(Text("Address:", "address")) layout.add_widget(TextBox(5, "Notes:", "notes", as_string=True)) ``` -------------------------------- ### Defining Basic Terminal Attributes Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst This code block lists the basic text attribute constants defined within the `Screen` class. These constants (`A_BOLD`, `A_NORMAL`, etc.) are used to modify text appearance in ways supported by older hardware terminals and native console APIs, typically used as parameters for output methods. ```python A_BOLD = 1 A_NORMAL = 2 A_REVERSE = 3 A_UNDERLINE = 4 ``` -------------------------------- ### Running TTY-Required Tests - Bash Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/contributing.rst Sets the `FORCE_TTY` environment variable to `Y` and runs the Python unit tests. This command forces the execution of tests that specifically require a functioning TTY, commonly used on Linux systems where a TTY is available. ```bash $ FORCE_TTY=Y python -m unittest ``` -------------------------------- ### Assigning Button Click Callback in Asciimatics (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This Python snippet demonstrates how to associate a method (`_add`) of a `Frame` subclass (`SomeForm`) with the `on_click` event of an `asciimatics` `Button`. When the "Add" button is clicked, the `_add` method is automatically executed, allowing the application to react to the user action. The callback function reference (`self._add`) is passed without parentheses. ```python class SomeForm(Frame): def __init__(self): # Code omitted to create Frame and Layouts... # The following line creates a Button that will call self._add when clicked. layout.add_widget(Button("Add", on_click=self._add), 0) def _add(self): # Do stuff here to react to Add button being clicked. ``` -------------------------------- ### Setting UTF-8 Code Page for Unicode (Windows) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/troubleshooting.rst Explains how to set the console's active code page to 65001 (UTF-8) on Windows using the `chcp` command. This command should be run in the Command Prompt before executing an asciimatics application to ensure proper display of Unicode characters. ```Shell chcp 65001 ``` -------------------------------- ### Defining Effect Clone Method for State Restoration Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/widgets.rst This code defines the required signature for the `clone` method on custom `Effect` objects. This method is called by asciimatics when a `Scene` is rebuilt after terminal resizing, allowing the effect to recreate itself and restore its state on the new `Screen` within the new `Scene`. It must be implemented by any custom effect needing state preservation across resizes. ```python def clone(self, screen, scene): """ Create a clone of this Effect into a new Screen. :param screen: The new Screen object to clone into. :param scene: The new Scene object to clone into. """ ``` -------------------------------- ### Using Inline Colour Codes in StaticRenderer (Python) Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/rendering.rst Illustrates how to define static rendered output with inline colour codes using the StaticRenderer. The escape sequence ${c,a,b} is used within the text string to change foreground color (c), attribute (a), and background color (b), creating a colour map for the text. This method is supported by the StaticRenderer class and requires understanding of asciimatics colour constants. ```python StaticRenderer(images=[r""" ${3,1}* / \ /${1}o${2} \ /_ _\ / \${4}b / \ / ${1}o${2} \ /__ __\ ${1}d${2} / ${4}o${2} \ / \ / ${4}o ${1}o${2}. /___________\ ${3}||| ${3}||| """]) ``` -------------------------------- ### Drawing Filled Polygons with Holes in Asciimatics Python Source: https://github.com/peterbrittain/asciimatics/blob/master/doc/source/io.rst Illustrates the use of `screen.fill_polygon` to draw filled shapes, including complex ones with holes. The method takes a list of polygons, where each polygon is a list of (x, y) coordinate tuples. Inner polygons are treated as holes. ```python # Draw a large with a smaller rectangle hole in the middle. screen.fill_polygon([[(60, 0), (70, 0), (70, 10), (60, 10)], [(63, 2), (67, 2), (67, 8), (63, 8)]]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.