示例#1
0
文件: game.py 项目: unRARed/mpf
    def exit(self, signum=None, frame=None, exception=None):
        """Handle MPF exit from either a clean shutdown or from a crash.

        Cleanly shuts down logging and restores the console window if the Text
        UI option is used.
        """
        del signum, frame

        if self.args.text_ui:
            # restore the console to the old state
            Screen.open().close(True)

        if exception:
            logger = logging.getLogger()

            if self.args.text_ui:
                # Re-enable console logging to show the exception
                logger.addHandler(logging.StreamHandler())

            logging.exception(exception)

        logging.shutdown()
        self.console_queue_listener.stop()
        self.file_queue_listener.stop()

        if self.args.pause:
            input('Press ENTER to continue...')

        sys.exit()
示例#2
0
    async def file_size_worker(self):
        """
        Prints the sizes and rates 1 and 2 rows up from the bottom, respectively.
        :return:
        :rtype:
        """
        # Want to give the other coroutines a chance to increment the semaphore

        screen = Screen.open()
        self.size = screen.dimensions
        try:
            # I wish asyncio.Semaphore made the value public. I know it's probably to prevent people from doing stupid
            # things, but sometimes it's nice to be dumb. Doing this so we can die when all of our captures have died.
            # noinspection PyProtectedMember
            while not self.shutdown_event.is_set() or self.semaphore._value < self.host_count:
                if screen.has_resized():
                    screen.close(restore=False)
                    screen = Screen.open()
                self.size = screen.dimensions
                screen.print_at(self.file_names, 0, self.terminal_height - 3)
                screen.print_at(self.capture_file_sizes, 0, self.terminal_height - 2)
                screen.print_at(self.file_growth_rates, 0, self.terminal_height - 1)
                self.old_values = self.file_sizes.copy()
                screen.refresh()
                await asyncio.wait([self.shutdown_event.wait()], timeout=self.refresh_interval)
        finally:
            screen.close()
            print("\n")
            print(self.file_names)
            print(self.capture_file_sizes)
            print(self.file_growth_rates)
            print("\n")
示例#3
0
def art():
    # generate a planet graphic
    planet()
    size = random.randint(10, 20)
    screen = Screen.open(None)
    effects = [
        PrintInSpace(
            screen,
            ImageFile('./tmp/planet.png', size, screen.height / 2 - size / 2),
            (screen.width + screen.height) // 4),
    ]
    screen.set_scenes([Scene(effects, 500)])
    for i in range(0, 10):
        screen.draw_next_frame()
    # screen.play([Scene(effects, duration=5, clear=False)], repeat=False)
    # print(screen)
    # print(screen.dimensions)
    doc = ""
    for y in range(0, screen.dimensions[0]):
        doc += "\n"
        for x in range(0, screen.dimensions[1]):
            code = screen.get_from(x, y)  # returns a tuple, ascii = 0
            # if code is not None:
            doc += chr(code[0])
    f = open("./tmp/planet.txt", "w")
    f.write(doc)
    screen.close(True)
    f.close()
示例#4
0
        def __init__(self, nodes, cpn, gpn, tasks, chunk=128):

            Viz.__init__(self)

            self._screen = Screen.open()
            self._msg = 'FOO'

            try:
                self._header = TextBox(msg=self._msg)
                self._nodes = NodeChart(nodes=nodes, cpn=cpn, gpn=gpn)
                self._tasks = TaskChart(tasks=tasks, chunk=chunk)
                effects = [
                    Print(self._screen, self._header, x=1, y=1),
                    Print(self._screen, self._nodes, x=1, y=4),
                    Print(self._screen,
                          self._tasks,
                          x=1,
                          y=3 + self._nodes.height)
                ]

                self._scenes = [Scene(effects, -1)]
                self._screen.set_scenes(self._scenes)

            except Exception:
                self._screen.close()
                self._screen = None
                raise
示例#5
0
def new_start_python(canvas_id: int = None):
    global obj_dict, counter, mouse_position

    try:
        screen = Screen.open(None,
                             catch_interrupt=False,
                             unicode_aware=None)
        counter += 1 if canvas_id is None else 0
        obj_dict[canvas_id or counter] = screen
        mouse_position[canvas_id or counter] = [-1, -1]

        scenes = []

        effects = [
            Print(screen,
                  MyNiceLire(screen.height, screen.width,  "*" * 70, 0.8, 60, screen.colours,  bg=screen.colours >= 256),
                  0,
                  speed=1,
                  transparent=False),
        ]
        scenes.append(Scene(effects, -1))
        screen.start_play(scenes, stop_on_resize=True)
        # screen.no_while_play(stop_on_resize=True)

    except StopApplication:
        return canvas_id or counter
    return canvas_id or counter
示例#6
0
    async def _run(self, root_element: DOMElement = None):
        if root_element is None:
            raise ValueError("The root element must be set")

        atexit.register(lambda: self._exit())

        self.screen = Screen.open()
        self.input.set_screen(self.screen)
        self.root_element = root_element
        self.root_element._set_parent(self, None)
        self.root_element.focus()
        self.render(True)
        self._ready.set()
        while True:
            if not self.screen:
                break
            if self.screen.has_resized():
                self.render()
            await asyncio.sleep(0.01)
            try:
                self.input.check_value()
            except CLIWindowExit:
                self._exit()
                break
            except Exception as e:
                self._exit()
                logging.error("Fatal error", exc_info=True)
示例#7
0
def iniciar():
    #Ajustamos el tamaño de la ventana
    #os.system('mode con: cols={} lines={}'.format(mundo.MUNDO_ANCHO, mundo.MUNDO_ALTO + 4))
    os.system('printf \'\e[8;{};{}t\''.format(mundo.MUNDO_ALTO + 4,
                                              mundo.MUNDO_ANCHO))
    global pantalla
    pantalla = Screen.open()
示例#8
0
文件: text_ui.py 项目: Clohman11/mpf
    def _create_window(self):
        self.screen = Screen.open()
        self.frame = Frame(self.screen,
                           self.screen.height,
                           self.screen.width,
                           has_border=False,
                           title="Test")
        self.frame.set_theme("mpf_theme")

        title_layout = Layout([1, 5, 1])
        self.frame.add_layout(title_layout)

        title_left = Label("")
        title_left.custom_colour = "title"
        title_layout.add_widget(title_left, 0)

        title = 'Mission Pinball Framework v{}'.format(
            mpf._version.__version__)  # noqa
        title_text = Label(title, align="^")
        title_text.custom_colour = "title"
        title_layout.add_widget(title_text, 1)

        exit_label = Label("< CTRL + C > TO EXIT", align=">")
        exit_label.custom_colour = "title_exit"

        title_layout.add_widget(exit_label, 2)

        self.layout = MpfLayout([1, 1, 1, 1], fill_frame=True)
        self.frame.add_layout(self.layout)

        footer_layout = Layout([1, 1, 1])
        self.frame.add_layout(footer_layout)
        self.footer_memory = Label("", align=">")
        self.footer_memory.custom_colour = "footer_memory"
        self.footer_uptime = Label("", align=">")
        self.footer_uptime.custom_colour = "footer_memory"
        self.footer_mc_cpu = Label("")
        self.footer_mc_cpu.custom_colour = "footer_mc_cpu"
        self.footer_cpu = Label("")
        self.footer_cpu.custom_colour = "footer_cpu"
        footer_path = Label(self.machine.machine_path)
        footer_path.custom_colour = "footer_path"
        footer_empty = Label("")
        footer_empty.custom_colour = "footer_memory"

        footer_layout.add_widget(footer_path, 0)
        footer_layout.add_widget(self.footer_cpu, 0)
        footer_layout.add_widget(footer_empty, 1)
        footer_layout.add_widget(self.footer_mc_cpu, 1)
        footer_layout.add_widget(self.footer_uptime, 2)
        footer_layout.add_widget(self.footer_memory, 2)

        self.scene = Scene([self.frame], -1)
        self.screen.set_scenes([self.scene], start_scene=self.scene)

        # prevent main from scrolling out the footer
        self.layout.set_max_height(self.screen.height - 2)
示例#9
0
文件: text_ui.py 项目: lunareve/mpf
    def _tick(self):
        if self.screen.has_resized():
            self.screen = Screen.open()
            self._update_switch_layout()
            self._update_modes()
            self._draw_screen()
            self._draw_player_header()

        self.machine.bcp.transport.send_to_all_clients("status_request")
        self._update_stats()
        self._update_ball_devices()
        self.screen.refresh()
示例#10
0
def open_screen():
    from logic import EVENTS

    def get_lift_events(self):
        for event in EVENTS:
            if event.is_set():
                return event
        return self.__class__.get_event(self)

    screen = Screen.open()
    screen.get_event = types.MethodType(get_lift_events, screen)
    return screen
示例#11
0
 def __init__(self, title, width, height, scale=50):
     self.title = title
     self.w = width
     self.h = height
     self.scl = 2
     self.screen = Screen.open(height,
                               catch_interrupt=False,
                               unicode_aware=None)
     if self.screen.colours < 16:
         self._rgb_to_color = self._rgb_to_8
     else:
         self._rgb_to_color = self._rgb_to_256
示例#12
0
    def __enter__(self):
        self.screen = Screen.open()

        if isinstance(self.screen, _CursesScreen):
            import curses

            self.screen.A_ITALIC = 5
            self.screen._a_italic = curses.tigetstr("sitm").decode("utf-8")
            self.screen._ATTRIBUTES[
                self.screen.A_ITALIC] = self.screen._a_italic

        return self
示例#13
0
def create_canvas(h=None, weight=None) -> int:
    screen = Screen.open(None,
                         catch_interrupt=False,
                         unicode_aware=None)

    # print(screen.height, screen.width)
    global obj_dict, counter
    counter += 1
    obj_dict[counter] = screen
    mouse_position[counter] = [-1, -1]

    return counter
示例#14
0
    def __init__(self):
        self.loop = asyncio.get_event_loop()
        self.screen = Screen.open()
        self.effects = []

        frame = Frame(self.screen, 80, 20, has_border=False)
        layout = Layout([1, 1, 1, 1])
        frame.add_layout(layout)

        end_time = self.loop.time() + 5.0
        self.loop.call_soon(self.update_screen, end_time, self.loop, self.screen)
        self.screen.set_scenes([Scene(frame,500)])
        self.screen.set_title()
示例#15
0
 def __init__(self):
     self.screen = Screen.open()
     self.color = {
         1: Screen.COLOUR_CYAN,
         2: Screen.COLOUR_BLUE,
         3: Screen.COLOUR_YELLOW,
         4: Screen.COLOUR_YELLOW,
         5: Screen.COLOUR_GREEN,
         6: Screen.COLOUR_RED,
         7: Screen.COLOUR_RED,
         8: Screen.COLOUR_BLUE,
         99: Screen.COLOUR_BLACK
     }
示例#16
0
    def __init__(self):
        self.screen = Screen.open()
        self.scenes = []
        self.akt_sender_str = "Deutschlandradio"
        self.akt_sender_nr = 0
        self.volume = 25
        self.number_of_stations = 0

        # Prepare frame for the presets
        self.preset_frame = Frame(self.screen,
                                  7,
                                  29,
                                  can_scroll=False,
                                  title="Tastenbelegung",
                                  x=0,
                                  y=10,
                                  reduce_cpu=True)
        self.pr_layout = Layout([10, 90], fill_frame=True)
        self.preset_frame.add_layout(self.pr_layout)

        # Prepare frame for the sender list
        self.sender_frame = Frame(self.screen,
                                  17,
                                  50,
                                  can_scroll=False,
                                  title="Senderliste",
                                  x=30,
                                  y=0,
                                  reduce_cpu=True)
        self.sender_layout0 = Layout([10, 80, 10], fill_frame=True)
        self.sender_frame.add_layout(self.sender_layout0)

        # Load the json config-file
        self.cfg = self.load_config()

        # Prepare the layouts, add spaces etc
        self.format_sl_layout(self.sender_layout0)

        # Nicht mehr nötig nach aktuellem Stand
        # format_pr_layout(pr_layout)

        # Create the sender-labels and fill them initially. Return them for
        # later changing
        self.sender_labels = self.gen_and_add_sender_labels(
            self.sender_layout0, self.parse_sender())
        self.preset_labels = self.gen_and_add_preset_labels(
            self.pr_layout, self.parse_presets())

        self.preset_frame.fix()
        self.sender_frame.fix()
示例#17
0
文件: visualizer.py 项目: mrbads/das
 def visualize(self):
     """
     Wrapper for self._visualize.
     Sets up the screen environment from a asciimatics
     """
     screen = Screen.open()
     restore = True
     try:
         try:
             self._visualize(screen)
         except ResizeScreenError:
             restore = False
             raise
     finally:
         screen.close(restore)
示例#18
0
def preinit():
    
    screen = Screen.open()
    test1.intro(screen)
    junk = Frame(screen,
                                        screen.height * 2 // 3,
                                        screen.width * 2 // 3,
                                        hover_focus=True,
                                        has_border=True,
                                        title="Game Settings",
                                        reduce_cpu=False)
    oldpalette = copy.deepcopy(junk.palette)
    Scenes = []
    debug = [True]
    game = []
    data = MainMenu(game,screen,debug,oldpalette)
示例#19
0
def main_loop(controller):
    screen = None
    while True:
        if screen is None or screen.has_resized():
            if screen is not None:
                screen.close(False)
            screen = Screen.open()
            controller.build_ui(screen, None)
            # effects = create_effect(screen)
            # screen.set_scenes([Scene(effects, 500)])
        try:
            screen.draw_next_frame()
        except StopApplication:
            screen.close(True)
            break
        gevent.sleep(0.05)
示例#20
0
文件: tui_hsm.py 项目: dwhall/HeyMac
 def _new_screen(self, start_scene):
     screen = Screen.open()
     screen.clear()
     self._msgs_view = MsgsView(screen, self._msgs_model, self._ident_model,
                                self._stngs_model, self._status_model)
     self._ident_view = IdentView(screen, self._ident_model)
     self._stngs_view = RadioStngsView(screen, self._stngs_model)
     self._status_view = StatusView(screen, self._stngs_model)
     scenes = [
         Scene([self._msgs_view], -1, name="Messages"),
         Scene([self._ident_view], -1, name="Identity"),
         Scene([self._stngs_view], -1, name="Settings"),
         Scene([self._status_view], -1, name="Status"),
     ]
     screen.set_scenes(scenes, start_scene=start_scene)
     self._screen = screen
示例#21
0
文件: logic.py 项目: LoganWalls/sekai
 def run(self, wait_time: float = 0.5):
     if self.renderer:
         self.screen = Screen.open()
         self.screen.clear()
     try:
         while not self.state.terminal_state:
             try:
                 self.tick(self.state)
             except EpisodeTerminated:
                 self.state.terminal_state = True
             if self.renderer:
                 self.render(self.state)
             if wait_time:
                 sleep(wait_time)
     finally:
         if self.renderer:
             self.screen.close()
示例#22
0
    def test_cjk_glyphs_overwrite(self):
        """
        Check that CJK languages delete half-glyphs correctly.
        """
        screen = Screen.open(unicode_aware=True)
        screen.print_at("aaaa", 0, 0)
        screen.print_at("你確", 0, 1)
        screen.print_at("bbbb", 0, 2)
        screen.refresh()
        screen.print_at("cccc", 0, 0)
        screen.print_at("你確", 1, 1)
        screen.print_at("dddd", 0, 2)
        screen.refresh()

        # Half-glyph appears as an "x" to show error and then double-width glyphs are returned
        # twice, reflecting their extra width.
        self.assert_line_equals(screen, u"x你你確確 ", y=1, length=6)
示例#23
0
文件: text_ui.py 项目: lunareve/mpf
    def __init__(self, machine: "MachineController") -> None:
        """Initialize TextUi."""
        super().__init__(machine)

        self.screen = None

        if not machine.options['text_ui']:
            return

        self.start_time = datetime.now()
        self.machine = machine
        self._tick_task = self.machine.clock.schedule_interval(self._tick, 1)
        self.screen = Screen.open()
        self.mpf_process = Process()
        self.ball_devices = list()  # type: List[BallDevice]

        self.switches = OrderedDict(
        )  # type: Dict[Switch, Tuple[str, int, int]]
        self.player_start_row = 0
        self.column_positions = [0, .25, .5, .75]
        self.columns = [0] * len(self.column_positions)

        self.machine.events.add_handler('init_phase_2', self._init)
        self.machine.events.add_handler('init_phase_3', self._update_switches)
        # self.machine.events.add_handler('init_phase_3', self._init2)
        self.machine.events.add_handler('loading_assets',
                                        self._asset_load_change)
        self.machine.events.add_handler('bcp_connection_attempt',
                                        self._bcp_connection_attempt)
        self.machine.events.add_handler('asset_loading_complete',
                                        self._asset_load_complete)
        self.machine.events.add_handler('bcp_clients_connected',
                                        self._bcp_connected)
        self.machine.events.add_handler('shutdown', self.stop)
        self.machine.events.add_handler('player_number', self._update_player)
        self.machine.events.add_handler('player_ball', self._update_player)
        self.machine.events.add_handler('player_score', self._update_player)
        self.machine.events.add_handler('ball_ended',
                                        self._update_player_no_game)

        self._pending_bcp_connection = False
        self._asset_percent = 0
        self._bcp_status = (0, 0, 0)  # type: Tuple[float, int, int]

        self._draw_screen()
        self.screen.refresh()
示例#24
0
    def test_cjk_glyphs_overwrite(self):
        """
        Check that CJK languages delete half-glyphs correctly.
        """
        screen = Screen.open(unicode_aware=True)
        screen.print_at("aaaa", 0, 0)
        screen.print_at("你確", 0, 1)
        screen.print_at("bbbb", 0, 2)
        screen.refresh()
        screen.print_at("cccc", 0, 0)
        screen.print_at("你確", 1, 1)
        screen.print_at("dddd", 0, 2)
        screen.refresh()

        # Half-glyph appears as an "x" to show error and then double-width glyphs are returned
        # twice, reflecting their extra width.
        self.assert_line_equals(screen, u"x你你確確 ", y=1, length=6)
示例#25
0
    def test_open_close(self):
        """
        Check Screen.open works.
        """
        def check_screen(local_screen):
            # If we get here there's not much new to test.  Check that we can
            # draw something without hitting an Exception.
            local_screen.print_at("Hello world!",
                                  0, 0,
                                  colour=Screen.COLOUR_CYAN,
                                  attr=Screen.A_BOLD,
                                  bg=Screen.COLOUR_BLUE)
            local_screen.refresh()

        screen = Screen.open()
        check_screen(screen)
        screen.close()
示例#26
0
    def test_open_close(self):
        """
        Check Screen.open works.
        """
        def check_screen(local_screen):
            # If we get here there's not much new to test.  Check that we can
            # draw something without hitting an Exception.
            local_screen.print_at("Hello world!",
                                  0, 0,
                                  colour=Screen.COLOUR_CYAN,
                                  attr=Screen.A_BOLD,
                                  bg=Screen.COLOUR_BLUE)
            local_screen.refresh()

        screen = Screen.open()
        check_screen(screen)
        screen.close()
示例#27
0
            button = (event.ButtonState if type(event.ButtonState) == int
                      and button == 0 else button)
            return MouseEvent(event.MousePosition.X, event.MousePosition.Y,
                              button)

    # If we get here, we've fully processed the event queue and found
    # nothing interesting.
    return None


setattr(Screen, "start_play", start_play)
setattr(Screen, "no_while_play", no_while_play)
setattr(Screen, "my_get_event", my_get_event)

try:
    screen = Screen.open(None, catch_interrupt=False, unicode_aware=None)

    scenes = []

    effects = [
        # Print(screen,
        #       MyNiceLire(screen.height, screen.width, "*" * 70, 0.8, 60, screen.colours, bg=screen.colours >= 256),
        #       0,
        #       speed=1,
        #       transparent=False),
    ]
    scenes.append(Scene(effects, -1))
    screen.start_play(scenes, stop_on_resize=True)
    # screen.no_while_play(stop_on_resize=True)
    while True:
        # screen.no_while_play(stop_on_resize=True)
示例#28
0
 def __init__(self, screen=None, **kwargs):
     self.screen = screen or Screen.open(**kwargs)
     self.screen.refresh()
示例#29
0
    def __init__(self, *args, **kwargs):
        dkwargsForSelf = {
            'title': "Ascui App",
            'data': {},
            'name': None,
            'exitCode': 0,
            'theme': None,
            'autoExampleWidgets': True,
            'quitLabel': 'Quit',
            'quitIsAtTop': False,
            'parent': None,
            'quitAskMsg': 'Quit? Are you sure?',
        }
        Easy.DictOfDefaultsOntoObj(self, dkwargsForSelf, kwargs)

        #self.lastReturnInfo = None

        self.initChainable()

        #self.returns = []

        if self.name is None:
            self.name = self.title.replace(' ', '')

        self.screen = Screen.open()

        self.frameWidth = int(self.screen.width * 9 // 10)
        self.frameHeight = int(self.screen.height * 9 // 10)

        ## AscuiFrame is subclass of frame but auto exits on esc
        self.frame = AscuiFrame(
            self.screen,
            self.frameHeight,
            self.frameWidth,
            ## frame can auto create its data dict, but it's
            ## better to pass our own in
            parent=self,
            data=self.data,
            has_shadow=False,  #was self.hasShadowRef,
            name=self.name,
            quitAskMsg=self.quitAskMsg,
        )
        self.data = self.frame.data  ## this is kinda redundant now
        if self.theme is not None:
            self.frame.set_theme(self.theme)

        self.background = Background(self.screen)

        #self.widgets={}
        #self.layouts = {}
        #self.layouts['default'] =

        #self.layout = self.frame.layouts["DefaultLayout"]
        #Layout(  self.layoutColumnWidths ) #[1, 18, 1])

        self.frame.createWidget("Label", "AppTitle", self.title)
        if self.quitIsAtTop == True:
            self.frame.createQuitButton(label=self.quitLabel, inFooter=True)
            self.frame.createWidget("Divider", "Divider01", "", height=3)

        self.initWidgets()

        if self.quitIsAtTop == False:
            #self.frame.createWidget( "Spacer", height=1, inFooter=True)
            self.frame.createWidget("Divider",
                                    "Divider01",
                                    "",
                                    height=3,
                                    inFooter=True)
            self.frame.createQuitButton(label=self.quitLabel, inFooter=True)

        ## Frame is a subclass of Effect, and Scenes are collections of effects
        self.scene = Scene([
            self.background,
            self.frame,
        ], -1)  ## what is the -1 for? investigate
示例#30
0

async def play_order_book(screen: Screen):
    while True:
        screen.draw_next_frame()
        await asyncio.sleep(0.05)


if __name__ == '__main__':
    logging.basicConfig(level=logging.ERROR, format="%(asctime)s: %(message)s")
    conn = Connection(Configuration())
    demo_cp = 'BTC_USDT'
    order_book = LocalOrderBook(demo_cp)
    channel = SpotOrderBookUpdateChannel(conn, order_book.ws_callback)
    channel.subscribe([demo_cp, "100ms"])

    loop = asyncio.get_event_loop()

    screen = Screen.open()
    screen.set_scenes([Scene([OrderBookFrame(screen, order_book)], -1)])
    loop.create_task(order_book.run())
    loop.create_task(conn.run())
    loop.create_task(play_order_book(screen))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        for task in asyncio.Task.all_tasks(loop):
            task.cancel()
        screen.close()
        loop.close()
示例#31
0
 def __enter__(self):
     self.screen = Screen.open()
     return self
示例#32
0
 def open(*args, **kwargs):
     return Screen.open(*args, **kwargs)