Last active
December 27, 2022 07:57
-
-
Save SealtielFreak/8edc7126639d2bb2cf27bac975652c28 to your computer and use it in GitHub Desktop.
terminal.py is a library for interactive terminal in brython or cpython
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
MIT License | |
Copyright (c) 2022 SealtielFreak | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
import time | |
import typing | |
class Terminal: | |
def __init__(self) -> None: | |
async def empty_f(): | |
pass | |
self.is_done = False | |
self._load_f = empty_f | |
self._close_f = empty_f | |
@property | |
def running(self): | |
return not self.is_done | |
async def sleep(self, sec: float=0.0) -> None: | |
await time.sleep(sec) | |
def finalize(self): | |
self.is_done = True | |
def load(self, f): | |
async def inner(): | |
await f() | |
self._load_f = inner | |
def close(self, f): | |
async def inner(): | |
self.is_done = True | |
await f() | |
self._close_f = inner | |
def main(self, f): | |
raise NotImplemented | |
def loop(self, f): | |
raise NotImplemented | |
class UserEmulator: | |
def __init__(self, terminal: typing.Any) -> None: | |
self._terminal = terminal | |
class Ouput: | |
def log(self, txt: str, **style) -> None: | |
raise NotImplemented | |
class Input: | |
async def get(self, prompt='', *args, **kwargs) -> str: | |
raise NotImplemented | |
try: | |
from browser import document, html, bind, aio, window, bind | |
class TerminalEmulator(Terminal): | |
def __init__(self, id: str, colors_like_decorator='html') -> None: | |
super().__init__() | |
self._colors_like_decorator = colors_like_decorator | |
self._root = document[id] | |
self._output = html.DIV(Class='output-console') | |
self._input = html.DIV(Class='input-console') | |
self._root <= self._output | |
self._root <= self._input | |
async def sleep(self, sec: float=0.0) -> None: | |
await aio.sleep(sec) | |
def main(self, f): | |
def inner(): | |
async def inner_loop(): | |
await self._load_f() | |
await f() | |
await self._close_f() | |
aio.run(inner_loop()) | |
return inner | |
def loop(self, f): | |
def inner(): | |
async def inner_loop(): | |
await self._load_f() | |
while not self.is_done: | |
await f() | |
await self._close_f() | |
aio.run(inner_loop()) | |
return inner | |
class UserInterfaceEmulator(UserEmulator): | |
def __init__(self, terminal: TerminalEmulator) -> None: | |
super().__init__(terminal) | |
self.formarter_color = lambda fg, bg: f"{fg}-{bg}" | |
def _format_style_output(self, element, txt='', **style) -> typing.Any: | |
elm = None | |
def create_element_style_html(element, **style): | |
return element( | |
style=dict( | |
color=style['color'] if 'color' in style else '', | |
background=style['background'] if 'background' in style else '', | |
) | |
) | |
try: | |
if self._terminal._colors_like_decorator == 'html': | |
elm = create_element_style_html(element, **style) | |
elif self._terminal._colors_like_decorator == 'css': | |
fg, bg = style['color'], style['background'] | |
elm = element( | |
Class=self.formarter_color(fg, bg) | |
) | |
except: | |
pass | |
elm.innerHTML = txt | |
return elm | |
class ConsoleOutput(UserInterfaceEmulator, Ouput): | |
def __init__(self, terminal: TerminalEmulator) -> None: | |
super().__init__(terminal) | |
def log(self, txt: str, **style) -> None: | |
elm = self._format_style_output(html.P, txt, **style) | |
self._terminal._output <= elm | |
elm.scrollIntoView() | |
class UserInput(UserInterfaceEmulator, Input): | |
def __init__(self, terminal: TerminalEmulator) -> None: | |
super().__init__(terminal) | |
async def get(self, prompt='', **style): | |
group = html.DIV(Class='usr-input') | |
input = html.INPUT() | |
btn = html.BUTTON() | |
def evt_keydown(evt): | |
if evt.key == 'Enter': | |
btn.click() | |
group <= input | |
group <= btn | |
btn.innerHTML = 'enter' | |
input.attrs['placeholder'] = prompt | |
self._terminal._output <= group | |
document.bind('keydown', evt_keydown) | |
await aio.event(btn, "click") | |
document.unbind('keydown', evt_keydown) | |
btn.disabled = True | |
input.disabled = True | |
btn.scrollIntoView() | |
return input.value | |
class ButtonInput(UserInterfaceEmulator, Input): | |
def __init__(self, terminal: TerminalEmulator) -> None: | |
super().__init__(terminal) | |
async def get(self, prompt: str, *options, **style) -> str: | |
pushed = [] | |
buttons = [] | |
def pushed_evt(evt): | |
pushed.append(evt.target.name) | |
group_btns = html.DIV(Class="group-buttons") | |
for name in options: | |
btn = html.BUTTON() | |
btn.innerHTML = name | |
btn.attrs['name'] = name | |
btn.bind("click", pushed_evt) | |
buttons.append(btn) | |
group_btns <= btn | |
p = self._format_style_output(html.P, prompt, **style) | |
self._terminal._output <= p | |
self._terminal._output <= group_btns | |
buttons[0].scrollIntoView() | |
while len(pushed) == 0: | |
await self._terminal.sleep() | |
for btn in buttons: | |
btn.attrs['disabled'] = False | |
return pushed.pop() | |
except ImportError: | |
import asyncio | |
import colorama | |
class TerminalEmulator(Terminal): | |
def __init__(self, *args, **kwargs) -> None: | |
super().__init__() | |
colorama.init() | |
def main(self, f): | |
def inner(): | |
async def inner_loop(): | |
try: | |
await self._load_f() | |
await f() | |
await self._close_f() | |
except KeyboardInterrupt: | |
await self._close_f() | |
asyncio.run(inner_loop()) | |
return inner | |
def loop(self, f): | |
def inner(): | |
async def inner_loop(): | |
try: | |
await self._load_f() | |
while not self.is_done: | |
await f() | |
await self._close_f() | |
except KeyboardInterrupt: | |
await self._close_f() | |
asyncio.run(inner_loop()) | |
return inner | |
class UserInterfaceEmulator(UserEmulator): | |
_fg_colors = { | |
'black': colorama.Fore.BLACK, | |
'red': colorama.Fore.RED, | |
'green': colorama.Fore.GREEN, | |
'yellow': colorama.Fore.YELLOW, | |
'blue': colorama.Fore.BLUE, | |
'magenta': colorama.Fore.MAGENTA, | |
'cyan': colorama.Fore.CYAN, | |
'white': colorama.Fore.WHITE, | |
'': '' | |
} | |
_bg_colors = { | |
'black': colorama.Back.BLACK, | |
'red': colorama.Back.RED, | |
'green': colorama.Back.GREEN, | |
'yellow': colorama.Back.YELLOW, | |
'blue': colorama.Back.BLUE, | |
'magenta': colorama.Back.MAGENTA, | |
'cyan': colorama.Back.CYAN, | |
'white': colorama.Back.WHITE, | |
'': '' | |
} | |
def _formarter_color(self, txt: str, **style): | |
formarter_txt = lambda txt, fg, bg: fg + bg + txt + colorama.Style.RESET_ALL | |
fg, bg = ( | |
style['color'] if 'color' in style else '', | |
style['background'] if 'background' in style else '' | |
) | |
return formarter_txt( | |
txt, | |
self._fg_colors[fg], | |
self._bg_colors[bg], | |
) | |
class ConsoleOutput(UserInterfaceEmulator, Ouput): | |
def __init__(self, terminal: TerminalEmulator) -> None: | |
super().__init__(terminal) | |
def log(self, txt: str, **style) -> None: | |
print(self._formarter_color(txt, **style)) | |
class UserInput(UserInterfaceEmulator, Input): | |
def __init__(self, terminal: TerminalEmulator) -> None: | |
super().__init__(terminal) | |
async def get(self, prompt='', *args, **style): | |
if prompt != '': | |
print(self._formarter_color(prompt, **style), end='') | |
return input(':') | |
class ButtonInput(UserInterfaceEmulator, Input): | |
def __init__(self, terminal: TerminalEmulator) -> None: | |
super().__init__(terminal) | |
async def get(self, prompt: str, *options, **style) -> str: | |
prompt = self._formarter_color(prompt, **style) | |
while True: | |
print(prompt) | |
print('\n'.join([f"[{i}]: {name}" for i, name, in enumerate(options)])) | |
try: | |
opt = int(input(':')) | |
return options[opt] | |
except: | |
print("Invalid option, try again") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment