Esempio n. 1
0

def exit_on_q(key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()


palette = [
    ('banner', '', '', '', '#ffa', '#60d'),
    ('streak', '', '', '', 'g50', '#60a'),
    ('inside', '', '', '', 'g38', '#808'),
    ('outside', '', '', '', 'g27', '#a06'),
    ('bg', '', '', '', 'g7', '#d06'),
]
placeholder = urwid.SolidFill()
loop = urwid.MainLoop(placeholder, palette, unhandled_input=exit_on_q)
loop.screen.set_terminal_properties(colors=256)
loop.widget = urwid.AttrMap(placeholder, 'bg')
loop.widget.original_widget = urwid.Filler(urwid.Pile([]))

div = urwid.Divider()
outside = urwid.AttrMap(div, 'outside')
inside = urwid.AttrMap(div, 'inside')
txt = urwid.Text(('banner', u" Hello World "), align='center')
streak = urwid.AttrMap(txt, 'streak')
pile = loop.widget.base_widget  # .base_widget skips the decorations

for item in [outside, inside, streak, inside, outside]:
    pile.contents.append((item, pile.options()))
loop.run()
Esempio n. 2
0
 def main(self):
     self.loop = urwid.MainLoop(self.view,
                                self.palette,
                                unhandled_input=self.unhandled_keypress)
     self.loop.run()
Esempio n. 3
0
def main():

    data = AttrDict([('Adipisci eius dolore consectetur.', 34),
                     ('Aliquam consectetur velit dolore', 19),
                     ('Amet ipsum quaerat numquam.', 25),
                     ('Amet quisquam labore dolore.', 30),
                     ('Amet velit consectetur.', 20),
                     ('Consectetur consectetur aliquam voluptatem', 23),
                     ('Consectetur ipsum aliquam.', 28),
                     ('Consectetur sit neque est', 15),
                     ('Dolore voluptatem etincidunt sit', 40),
                     ('Dolorem porro tempora tempora.', 37),
                     ('Eius numquam dolor ipsum', 26),
                     ('Eius tempora etincidunt est', 12),
                     ('Est adipisci numquam adipisci', 7),
                     ('Est aliquam dolor.', 38),
                     ('Etincidunt amet quisquam.', 33),
                     ('Etincidunt consectetur velit.', 29),
                     ('Etincidunt dolore eius.', 45),
                     ('Etincidunt non amet.', 14),
                     ('Etincidunt velit adipisci labore', 6),
                     ('Ipsum magnam velit quiquia', 21),
                     ('Ipsum modi eius.', 3),
                     ('Labore voluptatem quiquia aliquam', 18),
                     ('Magnam etincidunt porro magnam', 39),
                     ('Magnam numquam amet.', 44),
                     ('Magnam quisquam sit amet.', 27),
                     ('Magnam voluptatem ipsum neque', 32),
                     ('Modi est ipsum adipisci', 2),
                     ('Neque eius voluptatem voluptatem', 42),
                     ('Neque quisquam ipsum.', 10),
                     ('Neque quisquam neque.', 48),
                     ('Non dolore voluptatem.', 41),
                     ('Non numquam consectetur voluptatem.', 35),
                     ('Numquam eius dolorem.', 43),
                     ('Numquam sed neque modi', 9),
                     ('Porro voluptatem quaerat voluptatem', 11),
                     ('Quaerat eius quiquia.', 17),
                     ('Quiquia aliquam etincidunt consectetur.', 0),
                     ('Quiquia ipsum sit.', 49),
                     ('Quiquia non dolore quiquia', 8),
                     ('Quisquam aliquam numquam dolore.', 1),
                     ('Quisquam dolorem voluptatem adipisci.', 22),
                     ('Sed magnam dolorem quisquam', 4),
                     ('Sed tempora modi est.', 16),
                     ('Sit aliquam dolorem.', 46), ('Sit modi dolor.', 31),
                     ('Sit quiquia quiquia non.', 5),
                     ('Sit quisquam numquam quaerat.', 36),
                     ('Tempora etincidunt quiquia dolor', 13),
                     ('Tempora velit etincidunt.', 24),
                     ('Velit dolor velit.', 47)])

    NORMAL_FG = 'light gray'
    NORMAL_BG = 'black'

    if os.environ.get("DEBUG"):
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            "%(asctime)s [%(levelname)8s] %(message)s",
            datefmt='%Y-%m-%d %H:%M:%S')
        fh = logging.FileHandler("dropdown.log")
        fh.setFormatter(formatter)
        logger.addHandler(fh)
    else:
        logger.addHandler(logging.NullHandler())

    entries = {
        "dropdown_text":
        PaletteEntry(
            foreground="light gray",
            background="dark blue",
            foreground_high="light gray",
            background_high="#003",
        ),
        "dropdown_focused":
        PaletteEntry(
            foreground="white",
            background="light blue",
            foreground_high="white",
            background_high="#009",
        ),
        "dropdown_highlight":
        PaletteEntry(
            foreground="yellow",
            background="light blue",
            foreground_high="yellow",
            background_high="#009",
        ),
        "dropdown_label":
        PaletteEntry(foreground="white", background="black"),
        "dropdown_prompt":
        PaletteEntry(foreground="light blue", background="black"),
    }

    entries = DataTable.get_palette_entries(user_entries=entries)
    palette = Palette("default", **entries)
    screen = urwid.raw_display.Screen()
    screen.set_terminal_properties(256)

    boxes = [
        TestDropdown(
            data,
            label="Foo",
            border=True,
            scrollbar=True,
            right_chars_top=u" \N{BLACK DOWN-POINTING TRIANGLE}",
            auto_complete=True,
        ),
        TestDropdown(
            data,
            border=False,
            margin=2,
            left_chars=u"\N{LIGHT LEFT TORTOISE SHELL BRACKET ORNAMENT}",
            right_chars=u"\N{LIGHT RIGHT TORTOISE SHELL BRACKET ORNAMENT}",
            auto_complete=True),
        TestDropdown(
            data,
            initial_value=list(data.values())[10],
            label="Foo",
            border=True,
            scrollbar=False,
            auto_complete=False,
        ),
        TestDropdown([], ),
    ]

    grid = urwid.GridFlow([urwid.Padding(b) for b in boxes], 60, 1, 1, "left")

    main = urwid.Frame(urwid.Filler(grid))

    def global_input(key):
        if key in ('q', 'Q'):
            raise urwid.ExitMainLoop()
        else:
            return False

    loop = urwid.MainLoop(main,
                          palette,
                          screen=screen,
                          unhandled_input=global_input,
                          pop_ups=True)
    loop.run()
Esempio n. 4
0
import urwid
import application

frame = MainFrame()
loop = urwid.MainLoop(
    frame,
    palette=PALETTE,
    unhandled_input=handle_unhandled_input,
)
loop.screen.set_terminal_properties(colors=256)
loop.run()

class Model():
    

class MainApplication():
    def __init__():
        self.model = 
        self.view = ApplicationView()
        

    def run(

MainApplication.run()
Esempio n. 5
0
        Stack.buttons.insert(0, button)

    def show():
        global userstack
        userstack_uniq = []
        text = ''
        for i in userstack:
            if i not in userstack_uniq:
                userstack_uniq.insert(0, i)
            # text = i['NickName']+ '\n' + text
        for i in userstack_uniq:
            text = i['CustomName'] + '\n' + text

        return text


# Start loops

msg_thread = threading.Thread(target=msg_receiver)
msg_thread.daemon = True
msg_thread.start()

async_loop = asyncio.get_event_loop()

# UI loop - apparently I shouldn't run in a separate thread
loop = urwid.MainLoop(program,
                      palette=palette,
                      pop_ups=True,
                      unhandled_input=program.key_input,
                      event_loop=urwid.AsyncioEventLoop(loop=async_loop))
loop.run()
Esempio n. 6
0
        else:
            self.set_attr_map(self.default_attr_map)


class ResultWidget(urwid.Columns):
    def __init__(self, init_status, result_map):
        self.status = ResultStatusWidgetWrapper(init_status, result_map)
        self.description = ResultDescriptionWidget()
        super(ResultWidget, self).__init__([("pack", self.status),
                                            self.description])

    def update(self, status, description):
        self.status.update(status)
        self.description.update(description)
        self._invalidate()


if __name__ == "__main__":
    from programstatus import ProgramStatus
    from palette import palette

    program_status = ProgramStatus(
        "parent/directory/is/far/far/down/in/the/file/structure/working-dir",
        "cmd")
    program_status.description = "That really did not go very well. Try something different next time!"
    parent = ParentDirectoryWidget(program_status)
    result = ResultWidget(program_status)
    widget = urwid.Pile([parent, result])

    urwid.MainLoop(urwid.Filler(widget, valign="top"), palette=palette).run()
Esempio n. 7
0
#!/usr/bin/env python
#! -*- coding:utf-8 -*-

import urwid

__author__ = "Paweł Siergiejuk"
__date__ = "08/03/2018"
__version__ = "v0.0"
__email__ = "*****@*****.**"
__status__ = "Development"


def show_or_exit(key):
    if key in ("q", "Q"):
        raise urwid.ExitMainLoop()
    txt.set_text(repr(key))


if __name__ == "__main__":
    txt = urwid.Text(u"Hello World\nAdd new line")
    fill = urwid.Filler(txt, "top")
    loop = urwid.MainLoop(fill, unhandled_input=show_or_exit)
    loop.run()
Esempio n. 8
0
 def main(self):
     self.loop = urwid.MainLoop(self.view, self.palette)
     try:
         self.loop.run()
     except DialogExit as e:
         return self.on_exit(e.args[0])
        password = urwid.Edit(caption='password: '******'bottom')
            self.main_widget.change_main_widget(whole_window)

        button = urwid.Padding(urwid.Button('ok', on_press=_callback),
                               align='center',
                               min_width=6,
                               width=6)
        body.append(urwid.AttrMap(button, None, focus_map='reversed'))
        return urwid.ListBox(urwid.SimpleFocusListWalker(body))


if __name__ == '__main__':
    main = urwid.Padding(LoginMenu(), left=2, right=2)
    top = urwid.Overlay(main,
                        urwid.SolidFill(u'\N{MEDIUM SHADE}'),
                        align='center',
                        width=('relative', 60),
                        valign='middle',
                        height=('relative', 60),
                        min_width=20,
                        min_height=9)
    urwid.MainLoop(top, palette=[('reversed', 'standout', '')]).run()
Esempio n. 10
0
import subprocess
import urwid
import urwidtrees

root_node = [urwid.Text('root'), None]
tree_widget = urwidtrees.widgets.TreeBox(
    urwidtrees.decoration.ArrowTree(urwidtrees.tree.SimpleTree([root_node])))


def exit_on_q(key):
    if key in ['q', 'Q']:
        raise urwid.ExitMainLoop()


loop = urwid.MainLoop(tree_widget, unhandled_input=exit_on_q)


def on_stdout(data):
    if not root_node[1]:
        root_node[1] = []
    root_node[1].append((urwid.Text(data), None))
    tree_widget.refresh()


proc = subprocess.Popen(['ping', '127.0.0.1'],
                        stdout=loop.watch_pipe(on_stdout),
                        close_fds=True)

loop.run()
proc.kill()
Esempio n. 11
0
    def __init__(self, dbman, initialcmdline):
        """
        :param dbman: :class:`~alot.db.DBManager`
        :param initialcmdline: commandline applied after setting up interface
        :type initialcmdline: str
        :param colourmode: determines which theme to chose
        :type colourmode: int in [1,16,256]
        """
        self.dbman = dbman
        """Database Manager (:class:`~alot.db.manager.DBManager`)"""
        self.buffers = []
        """list of active buffers"""
        self.current_buffer = None
        """points to currently active :class:`~alot.buffers.Buffer`"""
        self.db_was_locked = False
        """flag used to prevent multiple 'index locked' notifications"""
        self.mode = 'global'
        """interface mode identifier - type of current buffer"""
        self.commandprompthistory = []
        """history of the command line prompt"""
        self.senderhistory = []
        """history of the sender prompt"""
        self.recipienthistory = []
        """history of the recipients prompt"""
        self.input_queue = []
        """stores partial keyboard input"""
        self.last_commandline = None
        """saves the last executed commandline"""

        # define empty notification pile
        self._notificationbar = None
        # should we show a status bar?
        self._show_statusbar = settings.get('show_statusbar')
        # pass keypresses to the root widget and never interpret bindings
        self._passall = False
        # indicates "input lock": only focus move commands are interpreted
        self._locked = False
        self._unlock_callback = None  # will be called after input lock ended
        self._unlock_key = None  # key that ends input lock

        # alarm handle for callback that clears input queue (to cancel alarm)
        self._alarm = None

        # force urwid to pass key events as unicode, independent of LANG
        urwid.set_encoding('utf-8')

        # create root widget
        global_att = settings.get_theming_attribute('global', 'body')
        mainframe = urwid.Frame(urwid.SolidFill())
        self.root_widget = urwid.AttrMap(mainframe, global_att)

        signal.signal(signal.SIGINT, self.handle_signal)
        signal.signal(signal.SIGUSR1, self.handle_signal)

        # load histories
        self._cache = os.path.join(
            get_xdg_env('XDG_CACHE_HOME', os.path.expanduser('~/.cache')),
            'alot', 'history')
        self._cmd_hist_file = os.path.join(self._cache, 'commands')
        self._sender_hist_file = os.path.join(self._cache, 'senders')
        self._recipients_hist_file = os.path.join(self._cache, 'recipients')
        size = settings.get('history_size')
        self.commandprompthistory = self._load_history_from_file(
            self._cmd_hist_file, size=size)
        self.senderhistory = self._load_history_from_file(
            self._sender_hist_file, size=size)
        self.recipienthistory = self._load_history_from_file(
            self._recipients_hist_file, size=size)

        # set up main loop
        self.mainloop = urwid.MainLoop(
            self.root_widget,
            handle_mouse=settings.get('handle_mouse'),
            event_loop=urwid.TwistedEventLoop(),
            unhandled_input=self._unhandled_input,
            input_filter=self._input_filter)

        loop = asyncio.get_event_loop()
        # Create a task for the periodic hook
        loop_hook = settings.get_hook('loop_hook')
        if loop_hook:
            # In Python 3.7 a nice aliase `asyncio.create_task` was added
            loop.create_task(
                periodic(loop_hook,
                         settings.get('periodic_hook_frequency'),
                         ui=self))

        # set up colours
        colourmode = int(settings.get('colourmode'))
        logging.info('setup gui in %d colours', colourmode)
        self.mainloop.screen.set_terminal_properties(colors=colourmode)

        logging.debug('fire first command')
        loop.create_task(self.apply_commandline(initialcmdline))

        # start urwids mainloop
        self.mainloop.run()
Esempio n. 12
0
    from subiquitycore.log import setup_logger
    setup_logger('.subiquity')
    v = TablePile(
        [
            TableRow([
                urwid.Text("aa"),
                (2, urwid.Text("0123456789" * 5, wrap='clip')),
                urwid.Text('eeee')
            ]),
            TableRow([
                urwid.Text("ccc"),
                urwid.Text("0123456789" * 4, wrap='clip'),
                urwid.Text('fff' * 10),
                urwid.Text('g')
            ]),
        ], {
            1: ColSpec(can_shrink=True, min_width=10),
            0: ColSpec(omittable=True, rpad=1),
        },
        spacing=4)
    v = Pile([
        ('pack', v),
        urwid.SolidFill('x'),
    ])

    def unhandled_input(*args):
        raise urwid.ExitMainLoop

    loop = urwid.MainLoop(v, unhandled_input=unhandled_input)
    loop.run()
Esempio n. 13
0
    def battle_main(self):
        field_offset = self.game_controller.length

        # Constructing shooting field
        shooting_line = []
        f = []
        for y_pos in range(field_offset):
            for x_pos in range(field_offset):
                ship_cell = ShootingCell(x_pos, y_pos, self.game_controller, self.lobby_controller, self.loop)
                shooting_line.append(ship_cell)
                self.shoot_button_list.append(ship_cell)
                ShipsList.shoot_matrix__buttons_dic[(x_pos, y_pos)] = ship_cell
            ship_zeil = urwid.GridFlow(shooting_line, 1, 1, 0, 'center')
            f.append(ship_zeil)
            shooting_line.clear()

        # Constructing ships field
        ship_button_list = []
        ship_f = []
        for y_pos in range(field_offset):
            for x_pos in range(field_offset):
                ship_cell = ButtonWithAPopUp(x_pos, y_pos, self.game_controller, self.lobby_controller, self.loop)
                ship_button_list.append(ship_cell)
                # Dictionary with all cells
                ShipsList.ship_buttons_dic[(x_pos, y_pos)] = ship_cell

            ship_zeil = urwid.GridFlow(ship_button_list, 1, 1, 0, 'center')
            ship_f.append(ship_zeil)
            ship_button_list.clear()

        # Draw ships on the field
        for x_pos_1 in range(field_offset):
            for y_pos_2 in range(field_offset):
                if (x_pos_1, y_pos_2) in self.placed_ships:
                    ship_id = self.game_controller.get_ship_id_from_location(x_pos_1, y_pos_2)
                    ship_type = self.game_controller.get_ship_type_by_id(ship_id)

                    tmp_ship_list = []
                    if self.game_controller.get_ship_orientation_by_id(ship_id) == Orientation.NORTH:
                        for s in range(ShipsList.length_dictionary[ship_type]):
                            ShipsList.ship_buttons_dic[(x_pos_1, y_pos_2+s)].cell.set_label("@")
                            tmp_ship_list.append((x_pos_1, y_pos_2+s))
                        ShipsList.ships_dictionary[ship_id] = tmp_ship_list
                        tmp_ship_list = []

                    elif self.game_controller.get_ship_orientation_by_id(ship_id) == Orientation.EAST:
                        for s in range(ShipsList.length_dictionary[ship_type]):
                            ShipsList.ship_buttons_dic[(x_pos_1+s, y_pos_2)].cell.set_label("@")
                            tmp_ship_list.append((x_pos_1+s, y_pos_2))
                        ShipsList.ships_dictionary[ship_id] = tmp_ship_list
                        tmp_ship_list = []

                    if ship_type == "carrier":
                        if self.game_controller.get_ship_orientation_by_id(ship_id) == Orientation.NORTH:
                            for s in range(ShipsList.length_dictionary[ship_type]):
                                ShipsList.ship_buttons_dic[(x_pos_1+1, y_pos_2+s)].cell.set_label("@")
                                tmp_ship_list.append((x_pos_1+1, y_pos_2+s))
                            tmp_cords = ShipsList.ships_dictionary.get(ship_id)
                            for tmp_ship in tmp_ship_list:
                                tmp_cords.append(tmp_ship)
                            ShipsList.ships_dictionary[ship_id] = tmp_cords
                            tmp_ship_list = []
                        elif self.game_controller.get_ship_orientation_by_id(ship_id) == Orientation.EAST:
                            for s in range(ShipsList.length_dictionary[ship_type]):
                                ShipsList.ship_buttons_dic[(x_pos_1+s, y_pos_2+1)].cell.set_label("@")
                                tmp_ship_list.append((x_pos_1+s, y_pos_2+1))
                            tmp_cords = ShipsList.ships_dictionary.get(ship_id)
                            for tmp_ship in tmp_ship_list:
                                tmp_cords.append(tmp_ship)
                            ShipsList.ships_dictionary[ship_id] = tmp_cords
                            tmp_ship_list = []

        # Insert the matrix in piles
        shooting_pile = urwid.Pile(f)
        ship_pile = urwid.Pile(ship_f)

        # The rendered layout
        blank = urwid.Divider()
        widget_list = [
            urwid.Columns([
                ShipsList.battle_notifications,
                urwid.Pile([urwid.Text("Your field")]),
                self.turn,
            ], 2),
            blank,
            urwid.Columns([
                shooting_pile,
                ship_pile,
                self.chat.render_chat(),
            ], 2),
            blank,
            urwid.Columns([
                urwid.Text(""),
                urwid.Text(""),
                urwid.LineBox(urwid.Button('Abort', on_press=self.abort)),
            ], 2),
            blank,
            # Uncomment if you want to see what the the client gets from the UI (uncomment the needed variable as well)
            #urwid.Button(str(self.placed_ships)),
            # ShipsList.test_refs_pile,
            # blank,
            self.round_time_pile
        ]

        header = urwid.AttrWrap(urwid.Text("Battleship+"), 'header')
        listbox = urwid.ListBox(urwid.SimpleListWalker(widget_list))
        frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header)

        palette = [
            ('body', 'white', 'black', 'standout'),
            ('turn', 'dark blue', 'black'),
            ('hit', 'dark green', 'black'),
            ('notturn', 'dark red', 'black'),
            ('header', 'white', 'dark red', 'bold'),
            ('popbg', 'white', 'dark gray'),
        ]

        # use appropriate Screen class
        if urwid.web_display.is_web_request():
            screen = urwid.web_display.Screen()
        else:
            screen = urwid.raw_display.Screen()

        self.loop.create_task(self.end_screen())
        urwid.MainLoop(frame, palette, screen,
                       unhandled_input=self.unhandled, pop_ups=True,
                       event_loop=urwid.AsyncioEventLoop(loop=self.loop)).run()
Esempio n. 14
0
def ui(runner: MonitorRunner, empty_column_timeout: int):
    monitor_columns = {m.pod_name: MonitorColumn(m) for m in runner.monitors}

    text_header = (u"Cilium Microscope."
                   u"UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 exits. "
                   u"s dumps nodes output to disk. LEFT / RIGHT to switch "
                   u"columns. z to zoom into column. z again to disable zoom")

    columns = urwid.Columns([c.widget for c in monitor_columns.values()],
                            5,
                            min_width=20)

    header = urwid.AttrWrap(urwid.Text(text_header), 'header')
    listbox = urwid.ListBox(urwid.SimpleListWalker([columns]))
    frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header)

    palette = [
        ('body', 'black', 'light gray', 'standout'),
        ('reverse', 'light gray', 'black'),
        ('header', 'white', 'dark red', 'bold'),
        ('important', 'dark blue', 'light gray', ('standout', 'underline')),
        ('editfc', 'white', 'dark blue', 'bold'),
        ('editbx', 'light gray', 'dark blue'),
        ('editcp', 'black', 'light gray', 'standout'),
        ('bright', 'dark gray', 'light gray', ('bold', 'standout')),
        ('buttn', 'black', 'dark cyan'),
        ('buttnf', 'white', 'dark blue', 'bold'),
    ]

    screen = urwid.raw_display.Screen()

    def dump_data():
        timestamp = time.time()
        outputs = {}
        for m in runner.monitors:
            if m.output_lock.acquire():
                outputs[m.pod_name] = m.output
                m.output_lock.release()

        for name, o in outputs.items():
            with open(name + "-" + str(timestamp), 'w') as f:
                f.write(o)

    def unhandled(key):
        global zoom
        if key == 'f8':
            raise urwid.ExitMainLoop()
        elif key == 's':
            dump_data()
        elif key == 'right':
            columns.focus_position = ((columns.focus_position + 1) %
                                      len(columns.contents))
        elif key == 'left':
            columns.focus_position = ((columns.focus_position - 1) %
                                      len(columns.contents))
        elif key == 'z':
            width = os.get_terminal_size().columns
            if not zoom:
                for k, v in enumerate(columns.contents):
                    columns.contents[k] = (v[0],
                                           columns.options("given", width))
            else:
                for k, v in enumerate(columns.contents):
                    columns.contents[k] = (v[0], columns.options("weight", 1))

            zoom = not zoom
        else:
            runner.data_queue.put({})

    mainloop = urwid.MainLoop(frame,
                              palette,
                              screen,
                              unhandled_input=unhandled,
                              handle_mouse=False)

    def wait_for_values(monitor_columns, queue, close_queue):
        while (close_queue.empty()):
            try:
                output = queue.get(True, 1)
            except queuemodule.Empty:
                continue

            if ("name" in output and "output" in output
                    and output["name"] in monitor_columns):
                c = monitor_columns[output["name"]]
                if c.monitor.output_lock.acquire():
                    c.monitor.output += output["output"]
                    c.set_text(c.monitor.output)
                    c.monitor.output_lock.release()

            remove_stale_columns(columns.contents, monitor_columns,
                                 empty_column_timeout)
            try:
                mainloop.draw_screen()
            except AssertionError as e:
                # this error is encountered when program is closing
                # or screen is not ready to draw
                # continue so it doesn't clutter the output
                continue

    update_thread = threading.Thread(target=wait_for_values,
                                     args=(monitor_columns, runner.data_queue,
                                           runner.close_queue))

    # hack to ensure that ssl errors log before mainloop.run call
    time.sleep(3)
    update_thread.start()
    mainloop.run()
    update_thread.join()
Esempio n. 15
0
 def main(self):
     """Run the program."""
     
     self.loop = urwid.MainLoop(self.view, self.palette,
         unhandled_input=self.unhandled_input)
     self.loop.run()
Esempio n. 16
0
File: main.py Progetto: andyv/tbug
    def nop(self):
        return



# keypress()-- Intercept keys.

    def keypress(self, size, key):
        if self.seen_escape:
            self.process_escape(size, key)
            self.seen_escape = False

        elif key == config.escape:
            self.seen_escape = True

        else:
            return super().keypress(size, key)
            
        self.status.set_esc_status(self.seen_escape)
        return None

    pass


main = urwid.MainLoop(None, palette=config.palette, pop_ups=True)
main.widget = top_frame(main)

main.run()

Esempio n. 17
0
import urwid
import urwid.curses_display

log = []


def inputCallback(widget, text):
    log.append(text + ", " + inputWidget.get_edit_text())
    if text.endswith("\n"):
        raise urwid.ExitMainLoop()


inputWidget = urwid.Edit(caption="yo: ", multiline=True)

urwid.connect_signal(inputWidget, "change", inputCallback)

topWidget = urwid.Filler(inputWidget)

loop = urwid.MainLoop(topWidget, screen=urwid.curses_display.Screen())
loop.run()

print(log)
Esempio n. 18
0
 def main(self):
     self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_key)
     try:
         self.loop.run()
     except DialogExit as e:
         return self.on_exit(e.args[0])
Esempio n. 19
0
import sys

factor_me = 362923067964327863989661926737477737673859044111968554257667
run_me = os.path.join(os.path.dirname(sys.argv[0]), 'subproc2.py')

output_widget = urwid.Text("Factors of %d:\n" % factor_me)
edit_widget = urwid.Edit("Type anything or press enter to exit:")
frame_widget = urwid.Frame(header=edit_widget,
                           body=urwid.Filler(output_widget, valign='bottom'),
                           focus_part='header')


def exit_on_enter(key):
    if key == 'enter': raise urwid.ExitMainLoop()


#loop = urwid.MainLoop(frame_widget, unhandled_input=exit_on_enter, screen=curses_display.Screen())
loop = urwid.MainLoop(frame_widget, unhandled_input=exit_on_enter)


def received_output(data):
    output_widget.set_text(output_widget.text + data)


write_fd = loop.watch_pipe(received_output)
proc = subprocess.Popen(
    ['python2', '-u', run_me, str(factor_me)], stdout=write_fd, close_fds=True)

loop.run()
proc.kill()
Esempio n. 20
0
    def keypress(self, size, key):
        return key

palette = [
    ('body','dark cyan', '', 'standout','#0f6',''),
    ('focus','dark red', '', 'standout','light red',''),
    ]

def keystroke (input):
    if input in ('q', 'Q'):
        raise urwid.ExitMainLoop()

items=[ArRow()]#,ArRow(),ArRow(),ArRow(),ArRow()]
listbox = urwid.ListBox(urwid.SimpleListWalker(items))
view = urwid.Frame(urwid.AttrWrap(listbox, 'body'))
loop = urwid.MainLoop(view, palette, unhandled_input=keystroke)
loop.screen.set_terminal_properties(colors=256)

def live_report(*a):
    while True:
        items[0].refresh()
        loop.draw_screen()
        sleep(2)
def refresh(_loop,_data):
    for item in items:
        item.refresh()
    #loop.draw_screen()
    _loop.set_alarm_in(2,refresh)

loop.set_alarm_in(2,refresh)
loop.run()
Esempio n. 21
0
import urwid


def exit_program(key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()
    txt.set_text(repr(key))


txt = urwid.Text("")
fill = urwid.Filler(txt, 'top')
loop = urwid.MainLoop(fill, unhandled_input=exit_program)
loop.run()
Esempio n. 22
0
 def loop(self, *args, **kwargs):
     kwargs.setdefault('unhandled_input', self.unhandled_input)
     loop = urwid.MainLoop(self.widget, self.palette, *args, **kwargs)
     return loop
 def start(self):
     self.loop = urwid.MainLoop(self.view,
                                self.palette,
                                unhandled_input=self.on_input)
     self.loop.set_alarm_in(0.1, self.update)
     self.loop.run()
Esempio n. 24
0
    def main(self):
        self.fields = {}
        text_header = (u"OpenChronos config  \u2503  "
                       u"UP / DOWN / PAGE UP / PAGE DOWN scroll.  F8 aborts.")

        self.list_content = list_content = []

        for key, field in DATA.iteritems():
            # generate gui forms depending on type
            if field.get("type", "bool") == "bool":
                f = urwid.AttrWrap(
                    urwid.CheckBox(field["name"], state=field["value"]),
                    'buttn', 'buttnf')
                f._datafield = field
                self.fields[key] = f
                list_content.append(f)

            elif field["type"] == "choices":
                try:
                    value = field["values"].index(field["value"])
                except ValueError:
                    value = field["default"]
                field["radio_button_group"] = []
                f = urwid.Text(field["name"])
                f._datafield = field
                choice_items = [f]
                for dat in field["values"]:
                    txt = value = dat
                    if isinstance(dat, tuple):
                        value, txt = dat
                    f = urwid.AttrWrap(
                        urwid.RadioButton(field["radio_button_group"],
                                          unicode(txt),
                                          state=value == field["value"]),
                        'buttn', 'buttnf')
                    f._datafield = field
                    f.value = value
                    choice_items.append(f)
                hgf = HelpGridFlow(self, choice_items, 20, 3, 1, 'left')
                self.fields[key] = choice_items
                hgf.focus_cell = hgf.cells[1]
                list_content.append(hgf)

            elif field["type"] == "text":
                f = urwid.AttrWrap(
                    urwid.Edit("%s: " % field["name"], field["value"]),
                    'editbx', 'editfc')
                f._datafield = field
                self.fields[key] = f
                list_content.append(f)

            elif field["type"] == "info":
                f = urwid.Text(field["name"])
                f._datafield = field
                self.fields[key] = f
                list_content.append(f)

        def ok_pressed(*args, **kwargs):
            raise urwid.ExitMainLoop()

        def abort_pressed(*args, **kwargs):
            sys.exit(0)

        list_content.append(urwid.Divider(div_char=u"\u2550", top=1, bottom=1))
        list_content.append(
            urwid.Padding(
                urwid.GridFlow([
                    urwid.AttrWrap(urwid.Button("Save", ok_pressed), 'buttn',
                                   'buttnf'),
                    urwid.AttrWrap(urwid.Button("Abort", abort_pressed),
                                   'buttn', 'buttnf')
                ], 15, 4, 4, 'center'), ('fixed left', 4), ('fixed right', 3)))

        header = urwid.AttrWrap(urwid.Text(text_header), 'header')
        #header = urwid.Padding(urwid.BigText("OpenChronos", urwid.HalfBlock5x4Font()))
        walker = HelpListWalker(self, list_content)
        listbox = urwid.ListBox(walker)
        self.help_widget = urwid.Text("")
        footer = urwid.AttrWrap(self.help_widget, 'footer')
        frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'),
                            header=header,
                            footer=footer)

        screen = urwid.raw_display.Screen()
        palette = [
            ('body', 'black', 'light gray', 'standout'),
            ('reverse', 'light gray', 'black'),
            ('header', 'white', 'dark red', 'bold'),
            ('important', 'dark blue', 'light gray', ('standout',
                                                      'underline')),
            ('editfc', 'white', 'dark blue', 'bold'),
            ('editbx', 'light gray', 'dark blue'),
            ('editcp', 'black', 'light gray', 'standout'),
            ('bright', 'dark gray', 'light gray', ('bold', 'standout')),
            ('buttn', 'black', 'dark cyan'),
            ('buttnf', 'white', 'dark blue', 'bold'),
        ]

        def unhandled(key):
            if key == 'f8':
                #raise urwid.ExitMainLoop()
                sys.exit(0)

        urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled).run()
def has_symbols(password):
    return any(character.isdigit() and not character.isalpha()
               for character in password)


def doesnt_consist_of_symbols(password):
    return any(character.isdigit() or character.isalpha()
               for character in password)


def on_ask_change(edit, new_edit_text):
    score = 0
    for callback in callbacks:
        if callback(new_edit_text):
            score += 2
    reply.set_text("Рейтинг пароля: {}".format(score))


if __name__ == '__main__':
    callbacks = [
        is_very_long, has_digit, has_letters, has_upper_letters,
        has_lower_letters, has_symbols, doesnt_consist_of_symbols
    ]
    ask = urwid.Edit('Тайный ввод: ', mask='*')
    reply = urwid.Text("")
    menu = urwid.Pile([ask, reply])
    menu = urwid.Filler(menu, valign='top')
    urwid.connect_signal(ask, 'change', on_ask_change)
    urwid.MainLoop(menu).run()
Esempio n. 26
0
def main():
    import argparse

    load_locale()

    parser = argparse.ArgumentParser(
        "TUIJam", description=_("A fancy TUI client for Google Play Music."))
    parser.add_argument("action",
                        choices=["", "configure_last_fm"],
                        default="",
                        nargs="?")
    parser.add_argument("-v", "--verbose",
                        action="store_true")  # TODO: use this
    args = parser.parse_args()

    print(_("starting up."))
    makedirs(CONFIG_DIR, exist_ok=True)

    log_file = join(CONFIG_DIR, "log.txt")
    logging.basicConfig(filename=log_file, filemode="w", level=logging.WARNING)

    if args.action == "configure_last_fm":
        LastFMAPI.configure()
        exit(0)
    elif args.action != "":
        print(f"Unrecognized option: {args.action}")
        exit(0)

    app = App()
    print(_("logging in."))
    app.login()

    if app.mpris_enabled:
        from .mpris import setup_mpris

        print(_("enabling external control."))
        app.mpris = setup_mpris(app)
        if not app.mpris:
            print(_("Failed."))

    if app.persist_queue:
        print(_("restoring queue"))
        app.restore_queue()

    print(_("restoring history"))
    app.restore_history()

    if app.video:
        app.player["vid"] = "auto"

    import signal

    signal.signal(signal.SIGINT, app.cleanup)

    loop = urwid.MainLoop(app, event_loop=urwid.GLibEventLoop())
    loop.screen.set_terminal_properties(256)
    loop.screen.register_palette([(k.replace("-", " "), "", "", "", fg, bg)
                                  for k, (fg, bg) in palette.items()])
    app.loop = loop

    try:
        loop.run()
    except Exception as e:
        logging.exception(e)
        print(
            _("Something bad happened! :( see log file ($HOME/.config/tuijam/log.txt) for more information."
              ))
        app.cleanup()
Esempio n. 27
0
                                       '.urmpc.conf')
            if not os.path.isfile(config_file):
                config_file = os.path.join('urmpclib', 'urmpc.conf.example')
                if not os.path.isfile(config_file):
                    raise IOError('Configuration file not found.')

    config.read(config_file)
    palette = configuration.extract_palette(config, 'palette')
    mpc = urmpd.MPDClient()
    mpc.connect(config.mpd.host, int(config.mpd.port))
    event_loop = urwid.SelectEventLoop()

    # Get urwid set up
    #FIXME: Passing None in here is ugly and will eventually break if urwid decides
    #       to be more strict about it.
    loop = urwid.MainLoop(None, palette, event_loop=event_loop)
    signals._mainloop = loop

    # Main widget uses mpd
    frame = MainFrame(mpc)
    loop.widget = frame

    # Idler runs cloned mpc connection, uses MainLoop to force redraw on MPD events
    idler = urmpd.Idler(mpc, loop)
    event_loop.watch_file(idler, idler)

    try:
        loop.run()
    except KeyboardInterrupt as e:
        pass
Esempio n. 28
0
    main.original_widget = urwid.Filler(
        urwid.Pile([response,
                    urwid.AttrMap(done, None, focus_map='reversed')]))


def exit_program(button):
    raise urwid.ExitMainLoop()


def open_browser(button):
    webbrowser.open_new('http://www.python.org')


def get_track_listing():
    tracks = get_recent(20)
    track_listing = []
    for track in tracks:
        track_listing.append(f"{track.artist} - {track.name}")
    return track_listing


track_listing = get_track_listing()
main = urwid.Padding(menu(u"Recent tracks", track_listing), left=3, right=3)
#top = urwid.Overlay(main, urwid.SolidFill(u'\N{MEDIUM SHADE}'),
#	align='center', width=('relative', 60),
#	valign='middle', height=('relative', 60),
#	min_width=20, min_height=9)
#urwid.MainLoop(top, palette=[('reversed', 'standout', '')]).run()
loop = urwid.MainLoop(main, palette=[('reversed', 'standout', 'default')])
loop.run()
Esempio n. 29
0
def start_pane(pane, callback, program_info='', quit_keys=None):
    """Open the user interface with the given initial pane."""
    quit_keys = quit_keys or ['q']

    frame = Window(
        footer=program_info + f' | {quit_keys[0]}: quit, ?: help',
        quit_keys=quit_keys,
    )

    class LogPaneFormatter(logging.Formatter):
        def get_prefix(self, level):
            if level >= 50:
                return 'CRITICAL'
            if level >= 40:
                return 'ERROR'
            if level >= 30:
                return 'WARNING'
            if level >= 20:
                return 'INFO'
            else:
                return 'DEBUG'

        def format(self, record):
            return (self.get_prefix(record.levelno) + ': ' + record.msg)

    class HeaderFormatter(LogPaneFormatter):
        def format(self, record):
            return (
                super().format(record)[:30] + '... '
                f"[Press `{pane._conf['keybindings']['log'][0]}` to view log]")

    class LogPaneHandler(logging.Handler):
        def emit(self, record):
            frame.log(self.format(record))

    class LogHeaderHandler(logging.Handler):
        def emit(self, record):
            frame.alert(self.format(record))

    if len(logger.handlers) > 0 and not isinstance(logger.handlers[-1],
                                                   logging.FileHandler):
        logger.handlers.pop()

    pane_handler = LogPaneHandler()
    pane_handler.setFormatter(LogPaneFormatter())
    logger.addHandler(pane_handler)

    header_handler = LogHeaderHandler()
    header_handler.setFormatter(HeaderFormatter())
    logger.addHandler(header_handler)

    frame.open(pane, callback)
    palette = _add_calendar_colors(
        getattr(colors, pane._conf['view']['theme']), pane.collection)
    loop = urwid.MainLoop(frame,
                          palette,
                          unhandled_input=frame.on_key_press,
                          pop_ups=True)
    frame.loop = loop

    def redraw_today(loop, pane, meta=None):
        meta = meta or {'last_today': None}
        # XXX TODO this currently assumes, today moves forward by exactly one
        # day, but it could either move forward more (suspend-to-disk/ram) or
        # even move backwards
        today = dt.date.today()
        if meta['last_today'] != today:
            meta['last_today'] = today
            pane.calendar.original_widget.reset_styles_range(
                today - dt.timedelta(days=1), today)
            pane.eventscolumn.original_widget.update_date_line()
        loop.set_alarm_in(60, redraw_today, pane)

    loop.set_alarm_in(60, redraw_today, pane)

    def check_for_updates(loop, pane):
        if pane.collection.needs_update():
            pane.window.alert(
                'detected external vdir modification, updating...')
            pane.collection.update_db()
            pane.eventscolumn.base_widget.update(None, None, everything=True)
            pane.window.alert('detected external vdir modification, updated.')
        loop.set_alarm_in(60, check_for_updates, pane)

    loop.set_alarm_in(60, check_for_updates, pane)
    # Make urwid use 256 color mode.
    loop.screen.set_terminal_properties(
        colors=256, bright_is_bold=pane._conf['view']['bold_for_light_color'])

    def ctrl_c(signum, f):
        raise urwid.ExitMainLoop()

    signal.signal(signal.SIGINT, ctrl_c)
    try:
        loop.run()
    except Exception:
        import traceback
        tb = traceback.format_exc()
        try:  # Try to leave terminal in usable state
            loop.stop()
        except Exception:
            pass
        print(tb)
        sys.exit(1)
Esempio n. 30
0
    def __init__(self, server=None, palette='default',
                 keymap='default', debug=False, verbose=False,
                 disable_sync=False, disable_background_sync=False,
                 fetch_missing_refs=False,
                 path=config.DEFAULT_CONFIG_PATH):
        self.server = server
        self.config = config.Config(server, palette, keymap, path)
        if debug:
            level = logging.DEBUG
        elif verbose:
            level = logging.INFO
        else:
            level = logging.WARNING
        logging.basicConfig(filename=self.config.log_file, filemode='w',
                            format='%(asctime)s %(message)s',
                            level=level)
        # Python2.6 Logger.setLevel doesn't convert string name
        # to integer code. Here, we set the requests logger level to
        # be less verbose, since our logging output duplicates some
        # requests logging content in places.
        req_level_name = 'WARN'
        req_logger = logging.getLogger('requests')
        if sys.version_info < (2, 7):
            level = logging.getLevelName(req_level_name)
            req_logger.setLevel(level)
        else:
            req_logger.setLevel(req_level_name)
        self.log = logging.getLogger('gertty.App')
        self.log.debug("Starting")

        self.project_cache = ProjectCache()
        self.ring = mywid.KillRing()
        self.input_buffer = []
        webbrowser.register('xdg-open', None, BackgroundBrowser("xdg-open"))

        self.fetch_missing_refs = fetch_missing_refs
        self.config.keymap.updateCommandMap()
        self.search = search.SearchCompiler(self.config.username)
        self.db = db.Database(self, self.config.dburi, self.search)
        self.sync = sync.Sync(self, disable_background_sync)

        self.screens = []
        self.status = StatusHeader(self)
        self.header = urwid.AttrMap(self.status, 'header')
        screen = view_project_list.ProjectListView(self)
        self.status.update(title=screen.title)
        self.updateStatusQueries()
        self.loop = urwid.MainLoop(screen, palette=self.config.palette.getPalette(),
                                   handle_mouse=self.config.handle_mouse,
                                   unhandled_input=self.unhandledInput)

        self.sync_pipe = self.loop.watch_pipe(self.refresh)
        self.error_queue = queue.Queue()
        self.error_pipe = self.loop.watch_pipe(self._errorPipeInput)
        self.logged_warnings = set()
        self.command_pipe = self.loop.watch_pipe(self._commandPipeInput)
        self.command_queue = queue.Queue()

        warnings.showwarning = self._showWarning

        has_subscribed_projects = False
        with self.db.getSession() as session:
            if session.getProjects(subscribed=True):
                has_subscribed_projects = True
        if not has_subscribed_projects:
            self.welcome()

        self.loop.screen.tty_signal_keys(start='undefined', stop='undefined')
        #self.loop.screen.set_terminal_properties(colors=88)

        self.startSocketListener()

        if not disable_sync:
            self.sync_thread = threading.Thread(target=self.sync.run, args=(self.sync_pipe,))
            self.sync_thread.daemon = True
            self.sync_thread.start()
        else:
            self.sync_thread = None
            self.sync.offline = True
            self.status.update(offline=True)