Ejemplo n.º 1
0
def screen_resize():
    global snek_edit_win, snek_repl_win
    curses.update_lines_cols()
    (edit_lines, edit_y, repl_lines, repl_y) = screen_get_sizes()
    screen_paint()
    snek_edit_win.resize(edit_lines, curses.COLS, edit_y, 0)
    snek_repl_win.resize(repl_lines, curses.COLS, repl_y, 0)
Ejemplo n.º 2
0
def main(stdscr):
    stdscr.clear()
    stdscr.refresh()

    curses.update_lines_cols()
    curses.curs_set(0)

    curses.noecho()

    global_consts.GAMESIZE = [curses.LINES - 8, curses.COLS - 1]

    gamemap = GameMap(global_consts.GAMESIZE, stdscr)

    while True:
        inp = [0, 0]

        c = stdscr.getch()
        if c == curses.KEY_UP:
            inp = [-1, 0]
        if c == curses.KEY_DOWN:
            inp = [1, 0]
        if c == curses.KEY_LEFT:
            inp = [0, -1]
        if c == curses.KEY_RIGHT:
            inp = [0, 1]

        gamemap.move_player(inp)
        gamemap.update_entity_map()
        gamemap.update_entities()

        gamemap.draw(stdscr)

        stdscr.refresh()
Ejemplo n.º 3
0
 def get_key_pressed(self):
     char = self.screen.getch()
     if char == curses.KEY_RESIZE:
         curses.update_lines_cols()
         self.width = curses.COLS
         self.height = curses.LINES
     return char
Ejemplo n.º 4
0
	def checkTermSize(self):

		curses.update_lines_cols()
		self.termY = curses.LINES
		self.termX = curses.COLS
		# self.stdscr.addstr(9,0 ,str((self.termY, self.termX)))
		self.stdscr.refresh()
Ejemplo n.º 5
0
    def draw_heap_map(self):
        """ Draw the window to represent the current snapshot

        :returns bool: success of the operation
        """
        window_lines, window_cols = self.__window.getmaxyx()
        if hasattr(curses, "update_lines_cols"):
            curses.update_lines_cols()
        self.__window.clear()
        self.__map_cords = None

        add_space, true_rows, true_cols = self.__get_map_size()

        # check for the minimal screen size
        rows_cond = window_lines < self.__MIN_ROWS
        cols_cond = window_cols - add_space < self.__MIN_COLS
        if rows_cond or cols_cond:
            return False

        # creating the heap map screen decomposition
        decomposition = self.create_map_matrix(true_rows, true_cols)
        # update map information and coordinates
        self.__map_cords = {
            'row': 1,
            'col': add_space + 1,
            'map': decomposition
        }

        # printing heap map decomposition to the console window
        self.print_matrix(self.__MIN_ROWS, window_cols, add_space)

        # printing heap info to the console window
        self.print_map_info(add_space)

        return True
Ejemplo n.º 6
0
 def get_key_pressed(self):
     char = self.screen.getch()
     if char == curses.KEY_RESIZE:
         curses.update_lines_cols()
         self.width  = curses.COLS
         self.height = curses.LINES
     return char
Ejemplo n.º 7
0
    def __get_graph_size(self):
        """ Calculates the true graph's size.

            Also check the screen's size limitations.

        :returns tuple: address info length, map's rows, map's columns
        :raises curses.error: when minimal screen's size is not respected
        """
        window_lines, window_cols = self.__window.getmaxyx()

        if hasattr(curses, 'update_lines_cols'):
            curses.update_lines_cols()

        # calculate space for the Y-axis information
        max_y_axis_len = len(str(self.__heap['stats']['max_amount']))
        if max_y_axis_len < len(self.__Y_AXIS_TEXT):
            max_y_axis_len = len(self.__Y_AXIS_TEXT)

        # check for the minimal screen size
        rows_cond = window_lines < self.__MIN_ROWS
        cols_cond = window_cols - max_y_axis_len < self.__MIN_COLS
        if rows_cond or cols_cond:
            raise curses.error

        # number of the screen's rows == (minimum of rows)
        # - 2(border lines) - 1 (info line)
        graph_rows = self.__MIN_ROWS - 3
        # number of the screen's columns ==
        # (terminal's current number of the columns)
        # - (size of Y-axis info) - 2(border columns)
        graph_cols = window_cols - max_y_axis_len - 2

        return graph_rows, graph_cols, max_y_axis_len
Ejemplo n.º 8
0
    def draw_heat_map(self):
        """ Draw the window to represent HEAT map """
        window_lines, window_cols = self.__window.getmaxyx()
        if hasattr(curses, "update_lines_cols"):
            curses.update_lines_cols()
        self.__window.clear()
        self.__map_cords = None

        add_space, true_rows, true_cols = self.__get_map_size()

        # check for the minimal screen size
        rows_cond = window_lines < self.__MIN_ROWS
        cols_cond = window_cols - add_space < self.__MIN_COLS
        if rows_cond or cols_cond:
            self.print_resize_req()
            return

        # creating the heat map screen decomposition
        decomposition = self.create_heat_matrix(true_rows, true_cols)
        # update map information and coordinates
        self.__map_cords = {
            'row': 1,
            'col': add_space + 1,
            'map': decomposition
        }

        # printing heat map decomposition to the console window
        self.print_matrix(self.__MIN_ROWS, window_cols, add_space)

        self.print_menu(self.__HEAT_MENU_TEXT)

        self.reset_cursor()
        self.print_field_info()
Ejemplo n.º 9
0
def main(stdscr):
    stdscr.clear()
    stdscr.refresh()

    curses.update_lines_cols()
    curses.curs_set(0)

    mainmenu = Menu(25, "Main Menu")

    mainmenu.addchoice("Generate Map")
    mainmenu.addchoice("New Character")
    mainmenu.addchoice("Start Game")
    mainmenu.addchoice("Exit")

    while True:
        c = chr(stdscr.getch())

        if c == "w":
            mainmenu.select(-1)
        if c == "s":
            mainmenu.select(1)

        mainmenu.updatemenu(c)
        mainmenu.draw([0, 0])
        stdscr.refresh()
Ejemplo n.º 10
0
    def draw_frame():
        """Draw the data's viewinfo model"""
        # curses sets some global vars when initialized so disable pylint
        # pylint: disable=no-member
        curses.update_lines_cols()
        curses.curs_set(0)
        stdscr.clear()
        half_point = int(curses.COLS / 2)
        stdscr.vline(0, half_point, "|", curses.LINES - 2)

        l1_len = min(curses.LINES - 2, len(viewinfo[0]))
        for line in range(l1_len):
            draw_obj(line, 0, 0, line + windows_loc, half_point)

        l2_len = min(curses.LINES - 2, len(viewinfo[1]))
        for line in range(l2_len):
            max_linesize = curses.COLS - half_point - 1
            draw_obj(line, half_point + 1, 1, line + windows_loc, max_linesize)

        # Put 2 or 3 simple info tips in the lowest position
        stdscr.hline(curses.LINES - 2, 0, "-", curses.COLS - 1)
        stdscr.addstr(
            curses.LINES - 1,
            0,
            " - ".join(help_info)[:curses.COLS - 1],
        )

        stdscr.refresh()
Ejemplo n.º 11
0
    def find(self):
        self.init_screen()
        left = LeftWin(self.screen)
        right = RightWin(self.screen)
        attr = Attributes(self.screen)
        menu = [[d, left.start] for d in self.data.keys()]
        left.draw(menu)
        right.draw()
        border = Separator(self.screen)
        border.draw(right.x-2)
        attr.draw()
        key = ''

        while key != ord('q'):
            self.screen.redrawwin()

            if key == curses.KEY_RESIZE:
                self.screen.clear()
                curses.update_lines_cols()
                left.draw(menu)
                border.draw(right.x-2)
                right.draw()

            left.listen(key)
            right.draw_info(self.data[left.selected_item])
            self.init_border()
            attr.draw()
            key = self.screen.getch()

        curses.endwin()
Ejemplo n.º 12
0
def resize(content, logo, sidebar, menu, messages):
    curses.update_lines_cols()  # Requires Python 3.5.

    logo.resize(*logo_dimensions())
    sidebar.resize(*sidebar_dimensions())
    menu.resize(*menu_dimensions())
    content.resize(*content_dimensions())
    messages.resize(*message_dimensions())
Ejemplo n.º 13
0
def init_curses():
    """initialize curses"""
    screen = curses.initscr()
    curses.start_color()
    screen.border()
    screen.nodelay(True)
    curses.update_lines_cols()
    curses.curs_set(False)
Ejemplo n.º 14
0
    def printer(stdscr):
        try:
            refresh_count = 0

            def plot_window():
                nonlocal refresh_count
                refresh_count += 1
                if refresh_count >= 1000:
                    refresh_count = 0
                    stdscr.clear()
                stdscr.move(0, 0)
                stdscr.addstr(0, 0, "Process")
                stdscr.addstr(0, 14, "PID")
                stdscr.addstr(0, 21, "Activity")
                stdscr.addstr(0, 45, "Progress")
                stdscr.move(0, 0)
                stdscr.chgat(curses.A_REVERSE)

                for i in range(min(curses.LINES - 1, num_process)):
                    items = processes[i + 1].state_str()
                    stdscr.move(i + 1, 0)
                    stdscr.clrtoeol()
                    stdscr.addstr(i + 1, 0, items[0])
                    stdscr.addstr(i + 1, 14, items[1])
                    stdscr.addstr(i + 1, 21, items[2])
                    stdscr.addstr(i + 1, 45, items[3])
                if num_process + 1 <= curses.LINES:
                    stdscr.move(num_process + 1, 0)
                stdscr.refresh()

            print("Printer initialized")
            for n in unterminated_processes:
                processes[n] = ProcessState(n, "-", "Waiting", "-")
            old_lines = curses.LINES
            while len(unterminated_processes) > 0:
                curses.update_lines_cols()
                if curses.LINES != old_lines:
                    plot_window()
                    old_lines = curses.LINES
                while not q.empty():
                    state = q.get()
                    processes[state.id_process] = state
                    if state.activity == "Terminated" or state.activity == "DB error":
                        unterminated_processes.remove(state.id_process)
                    plot_window()

            import os
            from loacore.conf import OUTPUT_PATH
            f = open(os.path.join(OUTPUT_PATH, "result.log"), "w")
            for i in processes.keys():
                items = processes[i].state_str()
                f.write(items[0] + '\t' + items[1] + '\t' + items[2] + '\t' +
                        items[3] + '\t\n')
            f.close()
        except:
            from loacore.conf import OUTPUT_PATH
            file = open(os.path.join(OUTPUT_PATH, "debug_curse.txt"))
            file.close()
Ejemplo n.º 15
0
	def update(self):
		entities = self.scene.entities
		
		self.screen.clear()
		curses.update_lines_cols()
		self.update_dimensions()
		for e in entities:
			self.draw(e.graphic.render(), e.position, e.graphic.size)
		self.screen.refresh()
Ejemplo n.º 16
0
def main(stdscr):
    COLS, LINES = curses.COLS, curses.LINES

    pad_loc, rectangle_loc, editwin_loc = defineWindowArea(
        LINES, COLS)  # define all localisation of elements

    #### the recv message screen
    writemessage = WriteMessage()
    edit_writemessage_pad(pad_loc, writemessage)

    o_pubnub = initPubNub(
        stdscr)  # PubNub object initialized in assets/myfunc/initPubNub.py

    edit_stdscr_window(stdscr)  # header
    writemessage.write_start_up_message(f"{o_pubnub.uuid}")  # welcome message
    draw_rectangle(
        stdscr, rectangle_loc,
        "message :")  # draw rectangle (from assets/myfunc/draw_rectangle.py)

    o_pubnub.add_listener(
        MessageListener(writemessage))  # set message listener
    o_pubnub.add_listener(
        PresenceListener(writemessage))  # set presence listener

    o_pubnub.subscribe().channels(
        "general").with_presence().execute()  # subscribe to the main channel
    o_pubnub._channel_name = "general"  # we create a custom variable to keep
    #a trace of the channel subscribed
    # (in order to switch channel[not availible now])

    #### the send message screen
    commandSlash_handler = SlashCommand(
        writemessage,
        o_pubnub)  # SlashCommand object from assets/myclass/slashCommand.py

    stay_connected = True
    while stay_connected:
        editwin, box = feditwin(editwin_loc)
        message = box.gather()
        message = sanitizeStr(message)
        if message == '':  # empty message -> dont send it
            pass
        elif message.startswith('/'):
            stay_connected = commandSlash_handler.run_command(message)
        else:
            channel = o_pubnub._channel_name
            o_pubnub.publish().channel(channel).message(message).sync()
        editwin.erase()
        curses.update_lines_cols()

        if curses.LINES != LINES or curses.COLS != COLS:  # resize the window localisation if size of the terminal is modified (after send a message)
            LINES, COLS = curses.LINES, curses.COLS
            pad_loc, rectangle_loc, editwin_loc = defineWindowArea(LINES, COLS)
            draw_rectangle(stdscr, rectangle_loc, "message :")
            edit_writemessage_pad(pad_loc, writemessage)
            edit_stdscr_window(stdscr)
Ejemplo n.º 17
0
 def resize(self):
     curses.update_lines_cols()
     self.item_length = curses.COLS - 2
     self.item_windows = [
         curses.newwin(self.item_height, self.item_length,
                       self.item_height * i, 1)
         for i in range(len(self.items))
     ]
     self.window.clear()
     self.window.refresh()
Ejemplo n.º 18
0
    def update_sizes(self):
        # OKAY. Definitively, these guys are the right ones.
        #
        # GetConsoleScreenBufferInfo will return the size of the _main_
        # buffer, which _isn't_  resized till the buffer exits....
        curses.update_lines_cols()
        self.window_width = curses.COLS - 1
        self.window_height = curses.LINES - 1

        self.title_height = 1
        raw_title = self._get_raw_title()
        self.title = raw_title + (" " * (self.window_width - len(raw_title)))

        # self.message_box_height = 2
        self.message_box_width = self.window_width - len(self.prompt)
        self._edit_box.resize(self.message_box_width)
        new_height = max(2, self._edit_box.get_height())
        old_height = self.message_box_height
        if new_height != old_height:
            self.message_box_height = new_height
            # print(f'{self._edit_box.get_rows()}')
            # print(f'msg_box_h: {self.message_box_height}')
            self.msg_box_origin_row = self.window_height - self.message_box_height
            # print(f'msg_box_y: {self.msg_box_origin_row}')
            self.msg_box_origin_col = len(self.prompt) + 1
            clear_win = curses.newwin(
                self.message_box_height,
                self.message_box_width,
                self.msg_box_origin_row,
                0,
            )
            clear_win.clear()
            clear_win.addstr(0, 0, self.prompt)
            clear_win.refresh()
            # self.draw_prompt()
            self.stdscr.refresh()
            self.editwin = curses.newwin(
                self.message_box_height,
                self.message_box_width,
                self.msg_box_origin_row,
                self.msg_box_origin_col,
            )

        self.keybinding_labels_height = 1
        self.keybinding_labels_width = self.window_width
        self.keybinding_labels_origin_row = self.window_height
        self.keybinding_labels_origin_col = 0

        self.chat_history_height = self.window_height - (
            (self.message_box_height - 1) + self.title_height +
            self.keybinding_labels_height)

        self._pad_height = self.chat_history_height + 100
        self.pad = curses.newpad(self._pad_height, self.window_width + 1)
Ejemplo n.º 19
0
def mainloop(screen, page):
    current_cell = [0, 0]
    while True:
        c = screen.getch()
        if (c == ord('q') or c == 'q'):
            break
        if c == -1:
            continue
        page.callback_char(c)
        curses.update_lines_cols()
        page.refresh(point(curses.LINES, curses.COLS))
Ejemplo n.º 20
0
 def _set_coords(self):
     curses.update_lines_cols()
     if positions.STATUS_BAR_POSITION == positions.SCREEN_TOP:
         positions.STATUS_BAR_COORDS = (0, 0)
         positions.BROWSER_UPPER_LEFT_COORDS = (1, 0)
         positions.BROWSER_BOTTOM_RIGHT_COORDS = (curses.LINES - 1,
                                                  curses.COLS - 1)
     else:
         positions.STATUS_BAR_COORDS = (curses.LINES - 1, 0)
         positions.BROWSER_UPPER_LEFT_COORDS = (0, 0)
         positions.BROWSER_BOTTOM_RIGHT_COORDS = (curses.LINES - 2,
                                                  curses.COLS - 1)
Ejemplo n.º 21
0
    def _handle_screen_resize(self,
                              append: str = None,
                              attr: int = curses.A_NORMAL):
        # Re-apply the history to the back-scroll with the new screen dimensions
        curses.update_lines_cols()
        self._apply_history_to_back_scroll()
        self._redraw_screen()

        if append is not None:
            self._std_scr.addstr(append, attr)

        self._std_scr.refresh()
Ejemplo n.º 22
0
 def promptResize(screen,lines,columns):
     screen.addstr("Resize terminal to atleast {height} Lines and {width} columns\n".format(
         height = lines, width = columns))
     isGoodSize = False
     while not isGoodSize:
         keyIn = screen.getch()
         if(keyIn == curses.KEY_RESIZE):
             curses.update_lines_cols()
             if curses.LINES >= lines and curses.COLS >= columns:
                 screen.resize(curses.LINES,curses.COLS)
                 isGoodSize = True
                 UI.clearScreen(screen)
Ejemplo n.º 23
0
 def init_screen(self):
     curses.update_lines_cols()
     self.y = curses.LINES
     self.x = curses.COLS
     if self.y < 4:
         raise WindowTooSmallExeception()
     self.input_height = 1
     if self.y > 40:
         self.input_height = 3
     elif self.y > 20:
         self.input_height = 2
     self.win_history = curses.newwin(self.y - self.input_height - 3, self.x - 2, 1, 1)
     self.win_edit = curses.newwin(self.input_height, self.x - 2, self.y - self.input_height - 1, 1)
Ejemplo n.º 24
0
def prepare_screen(scr):
    """Draw border, make async key input and other prep."""
    scr.border()
    scr.nodelay(True)  # noqa: Z425
    curses.curs_set(False)  # noqa: Z425
    curses.update_lines_cols()
    # needed to get black character background for terminals with color support
    # https://stackoverflow.com/questions/18551558/how-to-use-terminal-color-palette-with-curses
    if curses.can_change_color():
        curses.start_color()
        curses.use_default_colors()
        for color in range(0, getattr(curses, 'COLORS')):
            curses.init_pair(color + 1, color, -1)
Ejemplo n.º 25
0
def main(screen, panels, callbacks, modal_callbacks, loop_delay):
    """
    Main loop. See start_helm for more information.
    """

    # mode is used for switching between different input modes
    # this is controlled entirely by the provided callbacks
    assert 'default' in modal_callbacks
    mode = 'default'

    curses.curs_set(False)
    screen.nodelay(True)

    while True:
        # detect resizes
        screen_height, screen_width = screen.getmaxyx()

        # process all buffered key presses
        key = screen.getch()
        while key != curses.ERR:
            callback = None

            if key == curses.KEY_RESIZE:
                curses.update_lines_cols()
            elif key in callbacks:
                callback = callbacks[key]
            elif chr(key) in callbacks:
                callback = callbacks[chr(key)]
            elif key in modal_callbacks[mode]:
                callback = modal_callbacks[mode][key]
            elif chr(key) in modal_callbacks[mode]:
                callback = modal_callbacks[mode][chr(key)]

            if callback is not None:
                # invoke callback
                # may optionally return a value to change the mode
                ret = callback()
                if ret is not None:
                    if not ret in modal_callbacks:
                        raise Exception('{} is not a valid mode'.format(ret))
                    mode = ret

            key = screen.getch()

        screen.erase()

        panel_draw(screen, panels, Position(0, 0, screen_width, screen_height))

        screen.refresh()
        time.sleep(loop_delay)
Ejemplo n.º 26
0
def loop_coroutines(canvas):
    curses.update_lines_cols()
    curses.initscr()
    curses.curs_set(0)
    canvas.nodelay(True)
    while globals_vars.coroutines:
        for coroutine in globals_vars.coroutines:
            try:
                coroutine.send(None)
                canvas.border()
            except StopIteration:
                globals_vars.coroutines.remove(coroutine)
        canvas.refresh()
        time.sleep(TIC_TIMEOUT)
Ejemplo n.º 27
0
    def resize(self):
        log.debug(self.__screen.getmaxyx())

        curses.update_lines_cols()
        self.__height = curses.LINES - self.__statusbar_height
        self.__width = curses.COLS - 1

        self.__main_window.resize(self.__height, curses.COLS)

        self.__statusbar.mvwin(self.__height, 0)
        self.__statusbar.resize(self.__statusbar_height, curses.COLS)

        self.__screen.clear()
        self.__screen.refresh()
Ejemplo n.º 28
0
 def _resize(self, key):
     curses.update_lines_cols()
     self.maxy, self.maxx = self.stdscr.getmaxyx()
     self.stdscr.clear()
     self.stdscr.refresh()
     self.win.resize(self.maxy - self.LOG_HEIGHT - 1, self.maxx)
     self.win.clear()
     self.log_win.mvwin(self.maxy - self.LOG_HEIGHT - 1, 0)
     self.log_win.resize(self.LOG_HEIGHT, self.maxx)
     self.log_win.setscrreg(1, self.LOG_HEIGHT-2)
     self.log_win.clear()
     self.log_win.refresh()
     logging.info("Window resized")
     self.dirty = True
Ejemplo n.º 29
0
def loop(full_screen):
    full_screen.keypad(False)
    full_screen.leaveok(True)

    height, width = full_screen.getmaxyx()
    window = curses.newwin(height - 1, width, 0, 0)
    bottom = curses.newwin(1, width, height - 1, 0)
    bottom.addstr(0, 0, INSTRUCTIONS)
    bottom.refresh()

    setup_logging()
    curses.curs_set(0)
    window.nodelay(True)
    drops = set()
    umbrella = Umbrella(window)
    state = "open"
    while True:
        umbrella_dx = 0
        keypress = get_keypress(window)
        if keypress == curses.KEY_LEFT:
            umbrella_dx = -1
        elif keypress == curses.KEY_RIGHT:
            umbrella_dx = 1
        elif keypress == curses.KEY_UP:
            state = "open"
        elif keypress == curses.KEY_DOWN:
            state = "close"
        else:
            keypress = None

        height, width = window.getmaxyx()
        if width < MIN_SIZE[0] or height < MIN_SIZE[1]:
            raise ScreenTooSmall

        if len(drops) < height * height * DROPS_RATIO:
            drops.add(Drop(window))

        for drop in list(drops):
            try:
                drop.fall(bottom)
            except Drop.FellOnSomething:
                drops.remove(drop)
                drops.add(Drop(window))
        umbrella.loop(dx=umbrella_dx, state=state)

        window.refresh()
        bottom.refresh()
        time.sleep(REFRESH_TIME)
        curses.update_lines_cols()
Ejemplo n.º 30
0
    def mainloop(stdscr):
        stdscr.timeout(REFRESH_SECONDS * 1000)
        curses.curs_set(0)
        while True:
            stdscr.noutrefresh()
            stdscr.erase()
            refresh(stdscr, client)
            curses.doupdate()

            key = stdscr.getch()
            if key == curses.KEY_RESIZE:
                curses.update_lines_cols()
                stdscr.redrawwin()
            if key == ord("q"):
                break
Ejemplo n.º 31
0
    def mainloop(stdscr):
        stdscr.timeout(REFRESH_SECONDS * 1000)
        curses.curs_set(0)
        while True:
            stdscr.noutrefresh()
            stdscr.erase()
            refresh(stdscr, client)
            curses.doupdate()

            key = stdscr.getch()
            if key == curses.KEY_RESIZE:
                curses.update_lines_cols()
                stdscr.redrawwin()
            if key == ord("q"):
                break
Ejemplo n.º 32
0
def main(stdscr):
    stdscr.clear()
    stdscr.refresh()

    curses.update_lines_cols()
    curses.curs_set(0)

    gamemap = GameMap([curses.LINES - 8, curses.COLS - 1])

    while True:
        gamemap.update_player(stdscr)

        gamemap.draw(stdscr)

        stdscr.refresh()
Ejemplo n.º 33
0
    def resize(self):
        height, width = get_hw(sys.stdout)
        curses.resizeterm(height, width)
        curses.update_lines_cols()

        self.screen.resize(height, width)
        self.banner.resize(1, width, height - 1, 0)
        self.console.resize(height - 1, width, 0, 0)

        set_hw(self.proc.stdout, self.console.height, self.console.width)
        self.proc.send_signal(signal.SIGWINCH)

        self.resize_event = False

        self.screen.clear()
        self.refresh()
Ejemplo n.º 34
0
def resize_screen():
    global needs_refreshing

    global win_status_bar
    global list_view_pad
    global command_bar

    curses.update_lines_cols()

    win_status_bar = curses.newwin(1, curses.COLS)
    list_view_pad = curses.newpad((100 + 2)*3, curses.COLS)
    # The length of posts is not always going to be 100, account for this.

    # One factor that can change the required size of this pad is stickies, as
    # they are not included in the 100 post limit. Also, reddit might increase
    # the post limit (maybe for gold users), but that hasn't been done yet.
    # Plus, subreddits which have less than 100 total posts will have some
    # space unused, but the code handles that well already.

    command_bar = curses.newwin(1, curses.COLS, curses.LINES-1, 0)

    
    needs_refreshing = ["viewing", "status-bar", "list-view"]
Ejemplo n.º 35
0
    def resize(self):
        old_sidebar_nlines, old_sidebar_ncols = self._sidebar_window_yx()
        old_main_nlines, old_main_ncols = self._main_window_yx()

        curses.endwin()
        self._stdscr.refresh()
        curses.update_lines_cols()
        self._reset_stdscr()

        sidebar_nlines, sidebar_ncols = self._sidebar_window_yx()
        if sidebar_nlines <= 0 or sidebar_ncols <= 0:
            self._sidebar_view.hide()
        else:
            self._sidebar_view.resize(curses.LINES - 3, SIDEBAR_WIDTH)
            if old_sidebar_nlines <= 0 or old_sidebar_ncols <= 0:
                window = self._new_sidebar_window()
                assert window is not None
                self._sidebar_view.show(window)

        main_nlines, main_ncols = self._main_window_yx()
        if main_nlines <= 0 or main_ncols <= 0:
            if self._message_view:
                self._message_view.hide()
            if self._index_view:
                self._index_view.hide()
        else:
            if self._message_view:
                self._message_view.resize(main_nlines, main_ncols)
            if self._index_view:
                self._index_view.resize(main_nlines, main_ncols)
            if old_main_nlines <= 0 or old_main_ncols <= 0:
                window = self._new_main_window()
                assert window is not None
                if self._message_view:
                    self._message_view.show(window)
                elif self._index_view:
                    self._index_view.show(window)
Ejemplo n.º 36
0
import curses
import random
import math
import time


# INITIALIZING THE SCREEN #####################################################

stdscr = curses.initscr()  # initialize curses window
curses.noecho()
curses.cbreak()  # app reacts to keys immediately without pressing enter
# set the cursor state. Can be set to 0,1,or2,for invisible,normal,or very
# visible
curses.curs_set(0)
curses.update_lines_cols()

# COLORS ######################################################################

if curses.has_colors():
    curses.start_color()

curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLACK)

# VARIABLES ###################################################################

max_y, max_x = stdscr.getmaxyx()
Ejemplo n.º 37
0
Archivo: cli.py Proyecto: bcj/painterm
def painterm(screen, image, palette):
    """
    The painterm application.

    screen: The curses screen.
    image: The image being edited.
    palette: the values the terminal can display.
    """
    screen.keypad(True)
    curses.start_color()
    curses.curs_set(0)
    initialize_pairs(palette)

    colour_codes = OrderedDict()

    iterator = iter(palette)
    for first in LETTERS:
        for second in LETTERS.lower():
            colour_codes[(first, second)] = next(iterator)

    colour_stack = ColourStack()
    for index in DEFAULT_COLOUR_INDICES:
        colour_stack.push(palette[index])

    translator = Translator(palette)

    picker = Picker(0, 0, colour_codes, colour_stack, translator)
    canvas = Canvas(PICKER_WIDTH, 0, image, colour_stack, translator)

    screen.refresh()
    picker.refresh()
    canvas.refresh()

    state = States.normal
    snail = False
    letter = None

    while True:
        try:
            key = screen.getkey()
        except curses.error:
            curses.update_lines_cols()
            picker.refresh()
            canvas.refresh()
        else:
            if state == States.normal:
                if key in DIRECTIONS:
                    x_change, y_change = DIRECTIONS[key]
                    canvas.move(x_change, y_change, snail=snail)

                    canvas.refresh()
                elif key == DRAW:
                    canvas.draw()
                    canvas.refresh()
                elif key == FILL:
                    canvas.fill()
                    canvas.refresh()
                elif key == UNDO:
                    canvas.undo()
                    canvas.refresh()
                elif key == REDO:
                    canvas.redo()
                    canvas.refresh()
                elif key == SNAIL:
                    snail = not snail
                elif key == DROPPER:
                    colour_stack.push(canvas.current_colour())
                    picker.refresh()
                    canvas.refresh()
                elif key in LETTERS:
                    letter = key
                    state = States.colour_change
                elif key in RECENT:
                    try:
                        colour_stack.push(
                            colour_stack.most_recent[int(key)]
                        )
                    except IndexError:
                        pass
                    else:
                        picker.refresh()
                        canvas.refresh()
                elif key == QUIT:
                    return
            elif state == States.colour_change:
                if key in LETTERS.lower():
                    colour_stack.push(colour_codes[(letter, key.lower())])

                    picker.refresh()
                    canvas.refresh()

                letter = None
                state = States.normal
            elif state == States.command:
                pass
Ejemplo n.º 38
0
def scheduler(scr,args):
	#Setup the screen
	curses.start_color();
	curses.use_default_colors();	
	scr.nodelay(True);
	scr.keypad(1);
	#Timing Related Variables	
	interval=args.refresh;
	currTime=int(time.time());
	lastTime = 0;
	lastScreenRefresh = 0;
	#Debug Related Variables
	upCount=0;
	downCount=0;
	#Index Variables
	topIndex = 0;
	botIndex = 0;
	maxDisplyed = 0;

	quakeData=[];
	#limit
	limit=args.limit
	if(limit < 0):
		limit=math.inf;
	eventsDisplayed = -1;
	eventsAvail = -1;

	#Long Press Functionality
	pressLoops = 0;
	pressThreshold = 30;
	pressStep = 1; #Step Size
	pressStepFF = 2; #Fast Forward Speed
	pressNoPressLoops = 0;
	pressNoPressMax = 100;

	screenSize=scr.getmaxyx();
	while (True): # Main Loop
		currTime = int(time.time());
		#Fetch Data
		if((currTime - lastTime) > interval):
			lastTime = int(time.time());
			quakeData = fetchData(args,scr);
			#Populate the Quake List
			quakeList = earthquakeList(quakeData);	
			eventsAvail = quakeList.parseArgs(args);
			scr.erase();
	
		scr.move(0,0);
		scr.clrtoeol();
		#scr.addstr(0,0,"Top Index:"+str(topIndex));
		#scr.addstr(0,14,"Bot Index:"+str(botIndex));
		#scr.addstr(0,28,"DOWN Arrow Pressed ("+str(downCount)+")");
		#scr.addstr(0,56,"UP Arrow Pressed ("+str(upCount)+")");
		#scr.addstr(0,81,"Screen Height:"+str(screenSize[0]));

		#Check on Screen Size
		curses.update_lines_cols();
		screenSize=scr.getmaxyx();
		scr.resize(screenSize[0],screenSize[1]);
		#botIndex=topIndex+(screenSize[0] if screenSize[0]<args.limit and args.limit>0 else args.limit)-2;
		botIndex=topIndex+screenSize[0];# -1 so that there is one row available at the bottom

		#Info Bar
		scr.addstr(0,0,"{:}".format("Earthquake Data - Data Source: USGS"),curses.A_REVERSE);

		#Key Capture Behavior	
		keyPress = scr.getch();
		if(keyPress == curses.KEY_DOWN):
			pressLoops += 1;
			pressNoPressLoops = 0;
			if(pressLoops >= pressThreshold):
				pressStep = pressStepFF;
			scr.erase();
			downCount+=1;
			if(botIndex > eventsAvail):# or (quakeList.events()< args.limit and  quakeList.events() < screenSize[0]-2):
				curses.beep();
			else:
				topIndex += pressStep;
				botIndex += pressStep;
		elif(keyPress == curses.KEY_UP):
			pressLoops += 1;
			pressNoPressLoops = 0;
			if(pressLoops >= pressThreshold):
				pressStep = pressStepFF;
			scr.erase();
			upCount+=1;
			if(topIndex<=1):#1 so that there is 1 row buffer at the top
				topIndex=0;	
				curses.beep();
			else:
				topIndex -= pressStep;
				botIndex -= pressStep;
		elif(keyPress == ord('t') or keyPress == ord('T')):
			topIndex = 0;
			botIndex=topIndex+screenSize[0];# -1 so that there is one row available at the bottom
			scr.erase();
		elif(keyPress == ord('q') or keyPress == ord('Q')):
			return;
		elif(keyPress == -1):
			pressNoPressLoops += 1;
			if(pressNoPressLoops > pressNoPressMax):
				pressLoops = 0;
				pressStep = 1;

		#This is to make sure that the speed step won't go out of bounds
		#if(botIndex > quakeList.events()):
		#	temp = botIndex - quakeList.events();
		#	topIndex -= temp;

		#Print the quake list
		displayValues = quakeList.display(scr,args,topIndex,botIndex,screenSize[0]);
		#topIndex = displayValues[0];
		eventsDisplayed = displayValues[1];	
		if(int(time.time()) - int(lastTime) < 5):
			scr.addstr(screenSize[0]-2,0,"Updated: " + str(datetime.datetime.fromtimestamp(lastTime).strftime('%Y-%m-%d %H:%M:%S')),curses.A_BLINK);
		else:
			scr.addstr(screenSize[0]-2,0,"Updated: " + str(datetime.datetime.fromtimestamp(lastTime).strftime('%Y-%m-%d %H:%M:%S')));
		scr.addstr(screenSize[0]-2,29,'Events: '+str(quakeList.events()));
		#scr.addstr(screenSize[0]-1,45,"Press Loops:" + str(pressLoops));
		#scr.addstr(screenSize[0]-1,62,"PressStep: "+ str(pressStep));
		
		#Bottom Bar
		#scr.addstr(screenSize[0]-1,0,"Test", curses.A_REVERSE());	


		#Refresh the Page
		scr.refresh();