Exemple #1
0
 def run(self):
     app = Application(
         layout=Layout(self.container,
                       focused_element=self.container.input_area),
         key_bindings=self.key_bindings,
         style=self.styles,
         mouse_support=False,
         full_screen=True,
     )
     return app.run()
Exemple #2
0
def mock_app(mocker):
    app = Application(
        input=create_pipe_input(),
        output=DummyOutput(),
    )
    mocker.patch('upsies.uis.tui.tui.TUI._make_app', Mock(return_value=app))
    mocker.patch('upsies.uis.tui.tui.TUI._jobs_container',
                 Mock(children=[]),
                 create=True)
    mocker.patch('upsies.uis.tui.tui.TUI._layout', Mock(), create=True)
Exemple #3
0
def set_dummy_app():
    """
    Return a context manager that makes sure that this dummy application is
    active. This is important, because we need an `Application` with
    `is_done=False` flag, otherwise no keys will be processed.
    """
    app = Application(layout=Layout(Window()),
                      output=DummyOutput(),
                      input=create_pipe_input())
    return set_app(app)
Exemple #4
0
def build_cluster_status():
    ctx = context()
    build_cluster_status_command()
    # building pods container
    bad_pod_text_control = FormattedTextControl(
        text=lambda: CONTENT_VENDERER['pod_text'])
    bad_pod_win = Win(content=bad_pod_text_control)
    bad_pod_title = ctx.obj['watch_bad_pod_title']
    bad_pod_container = HSplit([
        Win(
            height=1,
            content=Title(bad_pod_title),
        ),
        bad_pod_win,
    ])
    # building nodes container
    bad_node_text_control = FormattedTextControl(
        text=lambda: CONTENT_VENDERER['node_text'])
    bad_node_window = Win(content=bad_node_text_control)
    bad_node_container = HSplit([
        Win(
            height=1,
            content=Title('bad nodes'),
        ),
        bad_node_window,
    ])
    parts = [bad_pod_container, bad_node_container]
    global_urls = ctx.obj.get('global_urls')
    if global_urls:
        ingress_text_control = FormattedTextControl(
            text=lambda: CONTENT_VENDERER['ingress_text'])
        ingress_window = Win(content=ingress_text_control,
                             height=lambda: tell_screen_height(0.4))
        ingress_container = HSplit([
            Win(height=1, content=Title('bad url requests')),
            ingress_window,
        ])
        parts.append(ingress_container)

    # building root container
    root_container = HSplit(parts)
    kb = KeyBindings()

    @kb.add('c-c', eager=True)
    @kb.add('c-q', eager=True)
    def _(event):
        event.app.exit()

    app = Application(
        key_bindings=kb,
        layout=Layout(root_container),
        full_screen=True,
    )
    app.create_background_task(refresh_admin_content())
    return app
Exemple #5
0
def repl(parser, interpreter, style_name='default'):
    registry = load_key_bindings()

    @registry.add_binding(Keys.Escape, Keys.Enter)  # meta-enter/alt-enter
    def _(event):
        '''Evaluate the buffer
        '''
        code = buffers[DEFAULT_BUFFER].text
        try:
            ast = parser.parse(code)
        except (UnexpectedToken, UnexpectedInput) as e:
            toolbar_value = str(e)
            return

        try:
            start_eval_time = time.time()
            retval = interpreter.eval(ast)
        except Exception as e:
            toolbar_value = "Error: %s" % e.args
            return
        else:
            buffers['RESULT'].text = str(retval)
            toolbar_value = "Time: {:0.4f}, Value: {}".format(
                time.time() - start_eval_time, str(retval))

    @registry.add_binding(Keys.ControlC, eager=True)
    @registry.add_binding(Keys.ControlQ, eager=True)
    def _(event):
        '''Exit the REPL
        '''
        event.cli.set_return_value(None)

    buffers = {
        DEFAULT_BUFFER: Buffer(is_multiline=True),
        'RESULT': Buffer(is_multiline=True),
    }
    style = style_from_pygments(get_style_by_name(style_name))

    application = Application(layout=layout,
                              buffers=buffers,
                              mouse_support=True,
                              style=style,
                              use_alternate_screen=True,
                              key_bindings_registry=registry)

    eventloop = create_eventloop()

    try:
        cli = CommandLineInterface(application=application,
                                   eventloop=eventloop)
        cli.run()

    finally:
        eventloop.close()
Exemple #6
0
    def __init__(self, client=None, messages=None):
        self.client = client
        self.send = self.client.send

        # Style.
        self.classic_style = Style([
            ("output-field", "bg:#000044 #ffffff"),
            ("input-field", "bg:#000000 #ffffff"),
            ("line", "#004400"),
        ])

        self.dark_mode = Style([
            ("output-field", "bg:#2b2b2b #ffffff"),
            ("input-field", "bg:#000000 #ffffff"),
            ("line", "#004400"),
        ])

        self.dakes_theme = Style([
            ("output-field", "bg:#004400 #ffffff"),
            ("input-field", "bg:#000000 #ffffff"),
            ("line", "#aa007f"),
        ])

        self.themes = ["classic style", "dark mode", "dakes theme"]

        self.themes_help_txt = "Available themes  are: \n" + str(self.themes) + \
                               '\nYou select a theme by typing: "!theme classic style"'

        self.themes_help_msg = Message(Message.server_user,
                                       self.themes_help_txt)

        self.style = self.classic_style

        self.welcome_txt = """
        Welcome to honkuru. The peer-to-peer text chat. 
        To send a message just type it and send with 'enter'. 
        To display the help message type '!help'\n
        """
        self.welcome_msg = Message(Message.server_user, self.welcome_txt)

        self.help_txt = """To display this help type: {}
        To display all available color themes type: {}
        To disconnect type: {}
        or Press Ctrl+C or Ctrl+Q""".format(Message.help, Message.theme,
                                            Message.disconnect)
        self.help_msg = Message(Message.server_user, self.help_txt)

        # reference to messages object of client
        self.manager = multiprocessing.Manager()

        self.messages = messages
        self.messages.append(self.welcome_msg)

        self.application = Application()
Exemple #7
0
 async def run(self):
     self.app = Application(
         layout=self.layout,
         full_screen=True,
         key_bindings=self.bindings,
         style=load_style(self.client_config_map),
         mouse_support=True,
         clipboard=PyperclipClipboard(),
     )
     await self.app.run_async(pre_run=self.did_start_ui)
     self._stdout_redirect_context.close()
Exemple #8
0
    def create_application(self):
        self.application = Application(
            layout=Layout(self.root_container),
            key_bindings=self.kb,

            # Let's add mouse support!
            mouse_support=True,

            # Using an alternate screen buffer means as much as: "run full screen".
            # It switches the terminal to an alternate screen.
            full_screen=True)
Exemple #9
0
    def run(self):
        lira = LiraApp()
        lira.setup()

        self.app = Application(
            layout=Layout(self.container),
            key_bindings=get_key_bindings(),
            mouse_support=True,
            full_screen=True,
        )

        self.app.run()
Exemple #10
0
def prompt(
    title: str, options: Sequence[Tuple[RadioListType,
                                        AnyFormattedText]]) -> RadioListType:
    control = RadioList(options_to_html(options))

    application: Application[None] = Application(
        layout=Layout(HSplit([Label(HTML(title)), control])),
        mouse_support=False,
        full_screen=False,
    )

    return cast(RadioListType, application.run())
Exemple #11
0
    def __init__(self, use_theme):
        self.statusbar = Window(height=1,
                                char='/',
                                style='class:line',
                                content=FormattedTextControl(text='druid////'),
                                align=WindowAlign.RIGHT)

        self.content = HSplit([
            Window(),
            self.statusbar,
            Window(height=1),
        ])
        self.container = FloatContainer(
            content=self.content,
            floats=[
                Float(
                    xcursor=True,
                    ycursor=True,
                    content=CompletionsMenu(max_height=16, scroll_offset=1),
                ),
            ],
        )
        self.key_bindings = KeyBindings()

        @self.key_bindings.add('c-c', eager=True)
        @self.key_bindings.add('c-q', eager=True)
        def quit_druid(event):
            event.app.exit()

        if use_theme:
            self.style = Style([
                ('capture-field', '#747369'),
                ('output-field', '#d3d0c8'),
                ('input-field', '#f2f0ec'),
                ('line', '#747369'),
                ('scrollbar.background', 'bg:#000000'),
                ('scrollbar.button', 'bg:#747369'),
            ])
        else:
            self.style = Style([])

        self.layout = Layout(self.container)

        self.app = Application(
            layout=self.layout,
            key_bindings=self.key_bindings,
            style=self.style,
            mouse_support=True,
            full_screen=True,
        )

        self.pages = dict()
        self.current_page = None
Exemple #12
0
def main():
    app = Application(layout=Layout(root_container.create(),
                                    focused_element=servers.content),
                      key_bindings=kb,
                      editing_mode=EditingMode.VI,
                      style=style,
                      mouse_support=True,
                      full_screen=True,
                      after_render=on_startup)

    asyncio.get_event_loop().run_until_complete(
        app.run_async().to_asyncio_future())
Exemple #13
0
    def __init__(self, loop, txClbk, vehListClk, vehObjClk, cmdProcessClk,
                 prntr, settingsDir, isGUI, wxAppPersistMgr):
        BaseModule.__init__(self, loop, txClbk, vehListClk, vehObjClk,
                            cmdProcessClk, prntr, settingsDir, isGUI,
                            wxAppPersistMgr)
        self.tabs = []  # all the vehicles, one in each tab

        # commands
        self.shortName = "terminal"

        self.tabbar = []

        self.style_extensions = {
            # Tabs
            'tabbar': 'noinherit',
            'tabbar.tab': '',
            'tabbar.tab.active': 'bold noinherit reverse',
        }

        self.current_style = Style.from_dict(self.style_extensions)

        # make the screen
        self.hscreen = []
        self.hscreen.append(
            Window(height=1,
                   content=FormattedTextControl(self.tabbar,
                                                style='class:tabbar'),
                   align=WindowAlign.LEFT))
        self.hscreen.append(Window(height=1, char='-', style='class:line'))
        self.hscreen.append(Window(content=None, wrap_lines=True))
        self.hscreen.append(Window(height=1, char='-', style='class:line'))
        self.hscreen.append(Window(height=1, content=None))

        self.root_container = HSplit(self.hscreen)
        self.layout = Layout(self.root_container)

        self.application = Application(layout=self.layout,
                                       key_bindings=KB,
                                       full_screen=True,
                                       style=self.current_style)

        # event linkages
        self.application.nextTab = self.nextTab

        # initial layout
        self.tabbar.append(('class:tabbar.tab', ' {0} '.format("tmp")))
        self.tabbar.append(('class:tabbar', ' '))
        self.hscreen[0].content = FormattedTextControl(self.tabbar,
                                                       style='class:tabbar')
        self.hscreen[2].content = BufferControl(focusable=False)
        self.hscreen[4].content = BufferControl(focusable=True)

        asyncio.ensure_future(self.runUI())
Exemple #14
0
def _create_app(dialog: AnyContainer, style: Optional[BaseStyle]) -> Application[Any]:
    # Key bindings.
    bindings = KeyBindings()
    bindings.add("tab")(focus_next)
    bindings.add("s-tab")(focus_previous)

    return Application(
        layout=Layout(dialog),
        key_bindings=merge_key_bindings([load_key_bindings(), bindings]),
        mouse_support=True,
        style=style,
        full_screen=True,
    )
Exemple #15
0
def main():
    style = Style([
        ('terminal focused', 'bg:#aaaaaa'),
        ('title', 'bg:#000044 #ffffff underline'),
    ])

    term1 = Terminal()

    text_area = TextArea(text='Press Control-W to switch focus.\n'
                         'Then you can edit this text area.\n'
                         'Press Control-X to exit')

    kb = KeyBindings()

    @kb.add('c-w')
    def _(event):
        switch_focus()

    @kb.add('c-x', eager=True)
    def _(event):
        event.app.exit()

    def switch_focus():
        " Change focus when Control-W is pressed."
        if application.layout.has_focus(term1):
            application.layout.focus(text_area)
        else:
            application.layout.focus(term1)

    application = Application(
        layout=Layout(container=HSplit([
            Window(height=1,
                   style='class:title',
                   content=FormattedTextControl(
                       ' Press Control-W to switch focus.')),
            VSplit([
                term1,
                Window(style='bg:#aaaaff', width=1),
                text_area,
            ]),
        ]),
                      focused_element=term1),
        style=style,
        key_bindings=merge_key_bindings([
            load_key_bindings(),
            kb,
        ]),
        full_screen=True,
        mouse_support=True,
    )
    application.run()
Exemple #16
0
async def start_application(tab_completer):

    ui.core.input_field.accept_handler = c.handle_input
    ui.core.input_field.completer = tab_completer

    application = Application(
        layout=Layout(ui.core.container, focused_element=ui.core.input_field),
        key_bindings=ui.core.kb,
        style=ui.core.style,
        mouse_support=True,
        full_screen=True,
    )

    await application.run_async(set_exception_handler=True)
Exemple #17
0
    def main(self):
        # The layout.
        self.output_field = TextArea(style="class:output-field",
                                     text=self.welcome_msg.message)
        self.input_field = TextArea(
            height=1,
            prompt=">>> ",
            style="class:input-field",
            multiline=False,
            wrap_lines=False,
        )

        container = HSplit([
            self.output_field,
            Window(height=1, char="-", style="class:line"),
            self.input_field,
        ])

        self.input_field.accept_handler = self.send_message

        # The key bindings.
        kb = KeyBindings()

        @kb.add("c-c")
        @kb.add("c-q")
        def _(event):
            """ Pressing Ctrl-Q or Ctrl-C will exit the user interface. """
            self.client.client_socket.send(Message.close_connection_client)
            sleep(2)
            event.app.exit()

        # Run application.
        self.application = Application(
            layout=Layout(container, focused_element=self.input_field),
            key_bindings=kb,
            style=self.style,
            mouse_support=True,
            full_screen=True,
        )

        # _thread.start_new_thread(self.render_messages, ("Thread-1", 2,))

        t = threading.Thread(
            target=self.render_messages,
            args=(),
        )
        t.daemon = True
        t.start()

        self.application.run()
Exemple #18
0
    def _create_ui(self):
        btn_start = Button("Start", handler=self.tomato.start)
        btn_pause = Button("Pause", handler=self.tomato.pause)
        btn_reset = Button("Reset", handler=self.tomato.reset)
        btn_reset_all = Button("Reset All", handler=self.tomato.reset_all)
        btn_exit = Button("Exit", handler=self._exit_clicked)
        # All the widgets for the UI.
        self.text_area = FormattedTextControl(focusable=False,
                                              show_cursor=False)
        text_window = Window(
            content=self.text_area,
            dont_extend_height=True,
            height=11,
            style="bg:#ffffff #000000",
        )
        root_container = Box(
            HSplit([
                Label(text="Press `Tab` to move the focus."),
                HSplit([
                    VSplit(
                        [
                            btn_start,
                            btn_pause,
                            btn_reset,
                            btn_reset_all,
                            btn_exit,
                        ],
                        padding=1,
                        style="bg:#cccccc",
                    ),
                    text_window,
                ]),
            ]))
        layout = Layout(container=root_container, focused_element=btn_start)
        self._set_key_bindings()

        # Styling.
        style = Style([
            ("left-pane", "bg:#888800 #000000"),
            ("right-pane", "bg:#00aa00 #000000"),
            ("button", "#000000"),
            ("button-arrow", "#000000"),
            ("button focused", "bg:#ff0000"),
            ("red", "#ff0000"),
            ("green", "#00ff00"),
        ])
        self.application = Application(layout=layout,
                                       key_bindings=self.kb,
                                       style=style,
                                       full_screen=True)
def _create_app(dialog, style):
    # Key bindings.
    bindings = KeyBindings()
    bindings.add('tab')(focus_next)
    bindings.add('s-tab')(focus_previous)

    return Application(layout=Layout(dialog),
                       key_bindings=merge_key_bindings([
                           load_key_bindings(),
                           bindings,
                       ]),
                       mouse_support=True,
                       style=style,
                       full_screen=True)
Exemple #20
0
def main():
    # The layout.
    output_field = TextArea(style='class:output-field', text=help_text)
    input_field = TextArea(height=1, prompt='>>> ', style='class:input-field')

    container = HSplit([
        output_field,
        Window(height=1, char='-', style='class:line'), input_field
    ])

    # The key bindings.
    kb = KeyBindings()

    @kb.add('c-c')
    @kb.add('c-q')
    def _(event):
        " Pressing Ctrl-Q or Ctrl-C will exit the user interface. "
        event.app.exit()

    @kb.add('enter', filter=has_focus(input_field))
    def _(event):
        try:
            output = '\n\nIn:  {}\nOut: {}'.format(
                input_field.text,
                eval(input_field.text))  # Don't do 'eval' in real code!
        except BaseException as e:
            output = '\n\n{}'.format(e)
        new_text = output_field.text + output

        output_field.buffer.document = Document(text=new_text,
                                                cursor_position=len(new_text))
        input_field.text = ''

    # Style.
    style = Style([
        ('output-field', 'bg:#000044 #ffffff'),
        ('input-field', 'bg:#000000 #ffffff'),
        ('line', '#004400'),
    ])

    # Run application.
    application = Application(layout=Layout(container,
                                            focused_element=input_field),
                              key_bindings=kb,
                              style=style,
                              mouse_support=True,
                              full_screen=True)

    application.run()
Exemple #21
0
def conf_dialog(**kwargs):
    def row(label, default):
        buffer=Buffer()
        buffer.text = default
        return VSplit([
            Label(HTML(f'{label}'), width=10),
            Window(width=2, char=": "),
            Window(content=BufferControl(buffer=buffer)),
        ])
    
    help = Label(HTML(f'(Press {ansired("Tab][Down][Up")} to move cursor. {ansired("Ctrl+C][Esc")} to quit)'))
    rows = [row(k, v) for k, v in kwargs.items()]
    
    root_container = HSplit([
        help,
        Window(height=1, char="-", width=10), 
        *rows
    ])
    kb = KeyBindings()
    
    
    @kb.add("c-c")
    @kb.add("escape")
    def _(event):
        event.app.exit()
    
    @kb.add('tab')
    @kb.add('down')
    def _(event):
        event.app.layout.focus_next()
    
    @kb.add("up")
    def _(event):
        event.app.layout.focus_previous()
    
    @kb.add("enter")
    def _(event):
        data = []
        for child in root_container.children[2:]:
            value = child.children[-1].content.buffer.text
            data.append(value)
        return event.app.exit(data)
    
    
    layout = Layout(root_container)
    
    application = Application(layout=layout, full_screen=False, key_bindings=kb)
    return application.run()  
    
Exemple #22
0
    def get_app(self):
        bindings = KeyBindings()

        @bindings.add(Keys.ControlC)
        def _ctrl_c(event):
            get_app().exit(exception=KeyboardInterrupt)

        @bindings.add(Keys.Enter)
        def _enter(event):
            get_app().exit(result=self.get_answer())

        return Application(layout=Layout(self.get_layout()),
                           key_bindings=merge_key_bindings(
                               [load_key_bindings(), bindings]),
                           style=get_theme_manager().get_current_style())
Exemple #23
0
 def setup_application(self):
     """docstring for setup_application"""
     self._clipboard = InMemoryClipboard()
     self._application = Application(key_bindings_registry=self._key_binding_registry,
             layout=self._layout,
             mouse_support=bool(egc.EDITOR_MOUSE_SUPPORT),
             use_alternate_screen=True,
             initial_focussed_buffer=self._editor_buffer_name,
             clipboard=self._clipboard,
             get_title=self.get_editor_title,
             editing_mode=EditingMode.VI if egc.EDITOR_EDITING_MODE == 'VI' else EditingMode.EMACS,
             on_initialize=self.editor_started_callback,
             on_render=self.editor_rendered_callback,
             on_buffer_changed=self.editor_content_changed
             )
Exemple #24
0
    def __init__(self, python_input, original_document):
        """
        Create an `Application` for the history screen.
        This has to be run as a sub application of `python_input`.

        When this application runs and returns, it retuns the selected lines.
        """
        self.python_input = python_input

        history_mapping = HistoryMapping(self, python_input.history,
                                         original_document)
        self.history_mapping = history_mapping

        document = Document(history_mapping.concatenated_history)
        document = Document(
            document.text,
            cursor_position=document.cursor_position +
            document.get_start_of_line_position(),
        )

        self.history_buffer = Buffer(
            document=document,
            on_cursor_position_changed=self._history_buffer_pos_changed,
            accept_handler=(
                lambda buff: get_app().exit(result=self.default_buffer.text)),
            read_only=True,
        )

        self.default_buffer = Buffer(
            name=DEFAULT_BUFFER,
            document=history_mapping.get_new_document(),
            on_cursor_position_changed=self._default_buffer_pos_changed,
            read_only=True,
        )

        self.help_buffer = Buffer(document=Document(HELP_TEXT, 0),
                                  read_only=True)

        self.history_layout = HistoryLayout(self)

        self.app = Application(
            layout=self.history_layout.layout,
            full_screen=True,
            style=python_input._current_style,
            mouse_support=Condition(lambda: python_input.enable_mouse_support),
            key_bindings=create_key_bindings(self, python_input,
                                             history_mapping),
        )
Exemple #25
0
    def _create_application(self, editing_mode, erase_when_done):

        prompt_bindings = self._create_prompt_bindings()
        search_mode_bindings = self._create_search_mode_bindings()

        application = Application(
            layout=self.layout,
            full_screen=True,
            key_bindings=merge_key_bindings([
                merge_key_bindings([search_mode_bindings, prompt_bindings]),
            ]),
            color_depth=lambda: self.color_depth,
            input=self.input,
            output=self.output)

        return application
Exemple #26
0
def main():
    # Create a big layout of many text areas, then wrap them in a `ScrollablePane`.
    root_container = VSplit([
        Label("<left column>"),
        HSplit([
            Label("ScrollContainer Demo"),
            Frame(
                ScrollablePane(
                    HSplit([
                        Frame(
                            TextArea(
                                text=f"label-{i}",
                                completer=animal_completer,
                            )) for i in range(20)
                    ])), ),
        ]),
    ])

    root_container = FloatContainer(
        root_container,
        floats=[
            Float(
                xcursor=True,
                ycursor=True,
                content=CompletionsMenu(max_height=16, scroll_offset=1),
            ),
        ],
    )

    layout = Layout(container=root_container)

    # Key bindings.
    kb = KeyBindings()

    @kb.add("c-c")
    def exit(event) -> None:
        get_app().exit()

    kb.add("tab")(focus_next)
    kb.add("s-tab")(focus_previous)

    # Create and run application.
    application = Application(layout=layout,
                              key_bindings=kb,
                              full_screen=True,
                              mouse_support=True)
    application.run()
Exemple #27
0
    def __init__(self, opt_ns, srv_c, inst_xml):
        manager = KeyBindingManager()  # Start with the `KeyBindingManager`.

        self.srv_text = ServiceOutput(opt_ns, srv_c, inst_xml)
        layout = HSplit(
            [
                # One window that holds the BufferControl with the default buffer on the
                # left.
                Window(
                    height=D.exact(1),
                    content=TokenListControl(
                        self.get_title_line,
                        default_char=Char(" ", token=Token.String.ICSW.Header)
                    )
                ),
                Window(
                    height=D.exact(1),
                    content=FillControl('-', token=Token.Line)
                ),
                # Display the text 'Hello world' on the right.
                Window(
                    content=TokenListControl(
                        self.get_icsw_output,
                    )
                ),
            ]
        )

        self._updating = False

        @manager.registry.add_binding(Keys.ControlC, eager=True)
        @manager.registry.add_binding("q", eager=True)
        def _handler_data(event):
            event.cli.set_return_value(0)

        our_style = style_from_dict(logging_tools.get_icsw_prompt_styles())
        application = Application(
            layout=layout,
            use_alternate_screen=True,
            style=our_style,
            on_input_timeout=self.input_timeout,
            key_bindings_registry=manager.registry,
        )
        event_loop = create_eventloop()
        self.application = application
        self.event_loop = event_loop
Exemple #28
0
    def __enter__(self):
        # Create UI Application.
        title_toolbar = ConditionalContainer(
            Window(FormattedTextControl(lambda: self.title), height=1),
            filter=Condition(lambda: self.title is not None))

        bottom_toolbar = ConditionalContainer(
            Window(FormattedTextControl(lambda: self.bottom_toolbar,
                                        style='class:bottom-toolbar.text'),
                   style='class:bottom-toolbar',
                   height=1),
            filter=~is_done & renderer_height_is_known
            & Condition(lambda: self.bottom_toolbar is not None))

        self.app = Application(min_redraw_interval=.05,
                               layout=Layout(
                                   HSplit([
                                       title_toolbar,
                                       Window(
                                           content=_ProgressControl(self),
                                           height=lambda: len(self.counters)),
                                       Window(),
                                       bottom_toolbar,
                                   ])),
                               style=self.style)

        # Run application in different thread.
        def run():
            try:
                self.app.run()
            except Exception as e:
                import traceback
                traceback.print_exc()
                print(e)

        self._thread = threading.Thread(target=run)
        self._thread.start()

        # Attach WINCH signal handler in main thread.
        # (Interrupt that we receive during resize events.)
        self._has_sigwinch = hasattr(signal, 'SIGWINCH') and in_main_thread()
        if self._has_sigwinch:
            self._previous_winch_handler = self._loop.add_signal_handler(
                signal.SIGWINCH, self.app.invalidate)

        return self
Exemple #29
0
    def __init__(self,
                #  input_handler: Callable,
                #  completer: Completer):
                ):

        completer = None
        self.process_usage = create_process_monitor()
        
        self.search_log_field = create_search_field("logs")
        self.search_out_field = create_search_field("ouput")
        self.input_field = create_input_field(completer=completer)
        self.output_field = create_output_field(self.search_out_field)

        # right hand window
        self.log_field = create_log_field(self.search_log_field)

        self.timer = create_timer()
        self.layout = generate_layout(self.input_field, self.output_field, self.log_field, self.search_log_field, self.search_out_field, self.timer, self.process_usage)
        # add self.to_stop_config to know if cancel is triggered
        self.to_stop_config: bool = False

        self.live_updates = False
        self.bindings = load_key_bindings(self)

        self.input_handler = self._input_handler
        self.input_field.accept_handler = self.accept
        self.app = Application(layout=self.layout, full_screen=True, key_bindings=self.bindings, style=load_style(),
                               mouse_support=True, clipboard=PyperclipClipboard())

        # settings
        self.prompt_text = ">>> "
        self.pending_input = None
        self.input_event = None
        self.hide_input = False

        # start ui tasks
        self.loop = asyncio.get_event_loop()
        self.loop.create_task(start_timer(self.timer))

        #! maximaus added
        self.argparser = load_parser(self)
        self.client = httpx.AsyncClient()
        # TODO update type annotation
        self.ws: typing.Dict[str, KrakenWsPublic] = {}
        # TODO we dont want to hardcode this for every exchange
        self.symbols: typing.Dict = {}
Exemple #30
0
def print_container(container):
    """
    Print any layout to the output in a non-interactive way.

    Example usage::

        from prompt_toolkit.widgets import Frame, TextArea
        print_container(
            Frame(TextArea(text='Hello world!')))
    """
    def exit_immediately():
        # Use `call_from_executor` to exit "soon", so that we still render one
        # initial time, before exiting the application.
        get_event_loop().call_from_executor(lambda: app.exit())

    app = Application(layout=Layout(container=container))
    app.run(pre_run=exit_immediately)