Esempio n. 1
0
def chrxp(stdscr):
    curs_set(0)
    init_pair(1, COLOR_RED, COLOR_BLUE)
    init_pair(2, COLOR_BLACK, COLOR_WHITE)
    mousemask(1)
    while 1:
        stdscr.clear()
        t = "Hello World"
        h, w = stdscr.getmaxyx()
        x = w // 2 - len(t) // 2
        y = h // 2
        k = h - 4
        l = (w - 3) // 2

        textpad.rectangle(stdscr, 3, 3, h - 3, w - 3)
        stdscr.attron(color_pair(2))
        stdscr.addstr(k, l, "Exit")
        stdscr.attroff(color_pair(2))

        stdscr.attron(color_pair(1))
        stdscr.addstr(y, x, t)
        stdscr.attroff(color_pair(1))

        stdscr.refresh()

        ky = stdscr.getch()
        if ky == KEY_MOUSE:
            _, a, b, _, _ = getmouse()
            stdscr.addstr(0, 0, str(a) + ' ' + str(b))
            stdscr.refresh()
            if a > l - 1 and a < (l + 4) and b == k:
                break
Esempio n. 2
0
def box_status(stdscr, x, y, name, status=False, color=curses.A_REVERSE):
    # Draw background rectangle
    rectangle(stdscr, y, x, y + 2, x + 3 + len(name))
    # Default status
    status = color if status else curses.A_NORMAL
    # Write letter
    stdscr.addstr(y + 1, x + 2, name, status)
Esempio n. 3
0
def main_control(screen, event, inception_level):
    if event == ord("Q"):
        curses.endwin()
        exit(0)
    if event == ord("D"):
        window_for_done_task(screen)
    if event == ord("T"):
        window_for_undone_task(screen)
    if event == ord("F"):
        curses.flash()
    if event == ord("A"):
        editwin = curses.newwin(1,
                                screen.getmaxyx()[1] - 6,
                                screen.getmaxyx()[0] - 4, 1)
        rectangle(screen,
                  screen.getmaxyx()[0] - 5, 0,
                  screen.getmaxyx()[0] - 3,
                  screen.getmaxyx()[1] - 5)
        screen.refresh()
        box = Textbox(editwin)
        # Let the user edit until Ctrl-G is struck.
        box.edit()
        # Get resulting contents
        message = box.gather()
        Tache().ajouter_tache(message, datetime.now())
        screen.clear()
        print_main_screen(screen)
        print_taches(screen, Tache().get_tache_undone(), "Taches a faire :")
        deal_with_selected(screen, 33, 45,
                           Tache().get_tache_undone(), window_for_undone_task)
Esempio n. 4
0
def test_textpad(stdscr, insert_mode=False):
    ncols, nlines = 8, 3
    uly, ulx = 3, 2
    if insert_mode:
        mode = 'insert mode'
    else:
        mode = 'overwrite mode'

    stdscr.addstr(uly-3, ulx, "Use Ctrl-G to end editing (%s)." % mode)
    stdscr.addstr(uly-2, ulx, "Be sure to try typing in the lower-right corner.")
    win = curses.newwin(nlines, ncols, uly, ulx)
    textpad.rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols)
    stdscr.refresh()

    box = textpad.Textbox(win, insert_mode)
    contents = box.edit()
    stdscr.addstr(uly+ncols+2, 0, "Text entered in the box\n")
    stdscr.addstr(repr(contents))
    stdscr.addstr('\n')
    stdscr.addstr('Press any key')
    stdscr.getch()

    for i in range(3):
        stdscr.move(uly+ncols+2 + i, 0)
        stdscr.clrtoeol()
Esempio n. 5
0
def toggle_dropdown():
    global global_stdscr, options, last_key_pressed, selected_option, chosen_move_index, chosen_option, post_request_body_boxes, PLUS_POS_Y
    rectangle(global_stdscr, TOP + 3, LEFT - PADDING,
              TOP + len(options) * PADDING + 1, LEFT + 4 * PADDING)
    unselected_options = [
        option for option in options if option != chosen_option[2:]
    ]
    for i, option in enumerate(unselected_options):
        global_stdscr.addstr(TOP + 2 + PADDING * (i + 1), LEFT, option)
        if selected_option == i:
            global_stdscr.chgat(TOP + 2 + PADDING * (i + 1), LEFT, len(option),
                                curses.A_REVERSE)

    last_key_pressed = global_stdscr.getch()
    if last_key_pressed == curses.KEY_DOWN:
        selected_option += 1
        if selected_option > 2:
            selected_option = 2
    elif last_key_pressed == curses.KEY_UP:
        selected_option -= 1
        if selected_option < 0:
            selected_option = 0
            chosen_move_index = move_indexes["move_to_dropdown"]
    elif last_key_pressed == ENTER:
        chosen_option = "▼ " + unselected_options[selected_option]
        selected_option = 0
        chosen_move_index = move_indexes["move_to_dropdown"]
        post_request_body_boxes = []
        PLUS_POS_Y = 1
Esempio n. 6
0
    def enter_edit_mode(self, value=None):

        if self.items[self.position]['field'] == 'Comments':
            editwin = curses.newwin(10, 60, self.position + 2, 27)
            rectangle(self.window, self.position + 1, 26, self.position + 12,
                      26 + 61)
        else:
            editwin = curses.newwin(1, 30, self.position + 2, 27)

        editwin.attron(curses.color_pair(2))
        curses.curs_set(1)
        if value:
            box = _Textbox(editwin, True, text=value)
        else:
            box = _Textbox(editwin,
                           True,
                           text=self.items[self.position]['value'])

        _Textbox.stripspaces = True

        self.window.refresh()

        while True:
            edit_field = box.edit()
            if not edit_field is None:
                result = self.validate(edit_field.strip())
                if result:
                    self.navigate(1)
                    break
            else:
                break

        curses.curs_set(0)

        self.window.clear()
def main(stdscr):
    # initial settings
    curses.curs_set(0)
    stdscr.nodelay(1)
    stdscr.timeout(100)

    # create a game box
    sy, sx = stdscr.getmaxyx()
    box = [[3, 3], [sy - 3, sx - 3]]  # [[ul_y, ul_x], [dr_y, dr_x]]
    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])

    # print score
    score = 0
    score_text = "Score: {}".format(score)
    stdscr.addstr(1, sx // 2 - len(score_text) // 2, score_text)

    while 1:
        # non-blocking input
        key = stdscr.getch()
        stdscr.addstr(1, 3, str(sy))  #46
        stdscr.addstr(2, 3, str(sx))  #183
        fmin = 150
        fstep = 50
        fmax = 1500
        df = fmax - fmin
        n = df // fstep
        count = 0

        for y in range(sy - 10, 10, -1):
            for x in range(10, sx - 10, 5):
                stdscr.addstr(y, x, '&')
                if y == (sy - 10):
                    stdscr.addstr(sy - 9, x, "-----")
                    stdscr.addstr(sy - 8, x, str(count * fstep + fmin))
                count += 1
Esempio n. 8
0
def main(stdscr):
    curses.curs_set(0)
    sh, sw = stdscr.getmaxyx()
    box = [[3,3], [sh-3, sw-3]]
    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])

    ppos = [sw//2, sh//2]
    pdir = curses.KEY_RIGHT
    papp = ".o."
    ptra = "   "
    stdscr.addstr(ppos[1], ppos[0], papp)
    
    while 1:
        key = stdscr.getch()
        
        if key in [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_UP, curses.KEY_DOWN]:
            pdir = key
            stdscr.addstr(ppos[1], ppos[0], ptra)
            papp = update_player_appearance(pdir)
            ppos = update_player_position(pdir, ppos)
            stdscr.addstr(ppos[1], ppos[0], papp)
        if key == curses.KEY_BACKSPACE:
            if ptra == "   ":
                ptra = " # "
            else :
                ptra = "   "
    stdscr.refresh()
Esempio n. 9
0
def main() :
    choice = raw_input("Enter filename : ")
    screen = curses.initscr()
    curses.noecho()

    with open(choice, 'w+') as rf:
        filedata = rf.read()
        
    editwin = curses.newwin(20,70, 2,1)
    editwin.addstr(1,1,filedata)
    rectangle(screen, 1,0, 1+20+1, 1+70+1)
    screen.refresh()

    box = Textbox(editwin)

    # Let the user edit until Ctrl-G is struck.
    box.edit()

    # Get resulting contents
    message = box.gather()
        
    curses.endwin()

    with open(choice,'w+') as wf:
        wf.write(message)
Esempio n. 10
0
def draw_philosopfers(win, win_h, win_w):
    coords = [
        [3, (win_w // 2), 8, (win_w // 2) + 12],
        [10, (win_w // 2) + 12, 15, (win_w // 2) + 24],
        [19, (win_w // 2) + 12, 24, (win_w // 2) + 24],
        [19, (win_w // 2) - 12, 24, (win_w // 2)],
        [10, (win_w // 2) - 12, 15, (win_w // 2)],
    ]

    for i in range(len(coords)):
        textpad.rectangle(win, coords[i][0], coords[i][1], coords[i][2],
                          coords[i][3])
        fill_rect(win, coords[i], 2)
        win.addstr(coords[i][0], coords[i][1] + 4, f"  {i+1}  ")

    coords_forks = [
        [6, (win_w // 2) - 6, 8, (win_w // 2) - 3],
        [6, (win_w // 2) + 15, 8, (win_w // 2) + 18],
        [16, (win_w // 2) + 15, 18, (win_w // 2) + 18],
        [26, (win_w // 2) + 4, 28, (win_w // 2) + 7],
        [16, (win_w // 2) - 6, 18, (win_w // 2) - 3],
    ]

    for i in range(len(coords_forks)):
        textpad.rectangle(win, coords_forks[i][0], coords_forks[i][1],
                          coords_forks[i][2], coords_forks[i][3])
        fill_rect(win, coords_forks[i], 2)

    global COORD_PHILOSOPHERS
    COORD_PHILOSOPHERS = coords
    global COORD_FORKS
    COORD_FORKS = coords_forks
Esempio n. 11
0
  def disp(self, rect):
    size = self.size(rect)

    rect_w = min(size[0], rect.w)
    rect_h = min(size[1], rect.h)

    if rect_w > 0 and rect_h > 0:
      x1 = rect.x + rect_w - 1
      y1 = rect.y + rect_h - 1

      # Make sure that we don't draw to the complete end of the screen, because that'll break
      screen_h = rect.screen.getmaxyx()[0]
      y1 = min(y1, screen_h - 2)

      try:
        rect.resize(rect_w, rect_h).clear()
        textpad.rectangle(rect.screen, rect.y, rect.x, y1, x1)
        if self.caption:
          self.caption.display(rect.adj_rect(3, 0))
        if self.underscript:
          s = self.underscript.size(rect)
          self.underscript.display(rect.adj_rect(max(3, rect_w - s[0] - 3), rect_h - 1))
      except curses.error, e:
        # We should not have sent this invalid draw command...
        logger.warn(e)
      try:
        self.inner.display(rect.adj_rect(1 + self.x_margin, 1 + self.y_margin, 1 + self.x_margin, 1 + self.y_margin))
      except curses.error, e:
        # We should not have sent this invalid draw command...
        logger.warn(e)
Esempio n. 12
0
    def show_all_headers(self):
        self.clear_headers()
        total_sum_x = 0
        active_total_sum_x = 0
        for i, file_name in enumerate(self.all_editors_display_names):
            if self.all_editors_display_names[
                    file_name] == self.current_editor:
                active_total_sum_x = total_sum_x
                total_sum_x += PADDING * 2 + len(file_name)
                continue
            rectangle(
                self.std_scr, self.origin_y - 1, self.origin_x + total_sum_x,
                self.origin_y + 1,
                self.origin_x + total_sum_x + PADDING * 2 + len(file_name))
            self.std_scr.addstr(self.origin_y,
                                self.origin_x + total_sum_x + PADDING,
                                file_name + " ×")
            total_sum_x += PADDING * 2 + len(file_name)

        # draw the active so it looks active
        current_file_name = self.all_editors[
            self.current_editor].get_file_name()
        rectangle(
            self.std_scr, self.origin_y - 1,
            self.origin_x + active_total_sum_x, self.origin_y + 1,
            self.origin_x + active_total_sum_x + PADDING * 2 +
            len(current_file_name))
        self.std_scr.addstr(self.origin_y,
                            self.origin_x + active_total_sum_x + PADDING,
                            current_file_name + " ×", curses.color_pair(1))
Esempio n. 13
0
	def _paintPool(self):
		uly, ulx = self.poolwin.getbegyx()
		lry, lrx = self.poolwin.getmaxyx()
		lry += uly; lrx += ulx
		rectangle(self.win, uly - 1, ulx - 1, lry, lrx - 1)
		self.pool.paint(self.poolwin)
		self.poolwin.refresh()
Esempio n. 14
0
def main(screen):
    while True:
        screen.clear()

        # command help
        screen.addstr(padding + 14, padding + 0, '* Commands')
        screen.addstr(padding + 15, padding + 0,
                      'Ctrl-G or Enter : send request / Ctrl-C : exit')

        # current resource usage
        screen.addstr(padding + 0, padding + 0, '* Current Usage of Entries')
        printResourceBar(screen)

        # input request
        screen.addstr(padding + 9, padding + 0, '* Enter the request ')
        edit_win = curses.newwin(1, BAR_SIZE, 11 + padding, 1 + padding)
        rectangle(screen, padding + 10, padding + 0, padding + 1 + 10 + 1,
                  padding + 1 + BAR_SIZE + 1)
        screen.refresh()
        box = Textbox(edit_win)
        box.edit()
        input_text = box.gather()

        if input_text != '':
            translateRules(input_text)
            populateRulesetToDP()  # if translation succeed
Esempio n. 15
0
    def format_confirmation(self, stdscr, text, selected):
        stdscr.clear()
        screen_height, screen_width = stdscr.getmaxyx()
        textpad.rectangle(
            stdscr,
            screen_height // 2 - 4,
            screen_width // 2 - len(text),
            screen_height // 2 + 4,
            screen_width // 2 + len(text),
        )
        stdscr.addstr(
            screen_height // 2,
            screen_width // 2 - len(text) // 2,
            text,
        )
        options_width = len(text) // 2

        option = "yes"
        y = screen_height // 2 + 1
        x = screen_width // 2 - options_width // 2 + len(option)
        stdscr.addstr(
            y, x, option,
            curses.color_pair(settings.COLOR_BLACK_WHITE if option ==
                              selected else 0))

        option = "no"
        x = screen_width // 2 + options_width // 2 - len(option)
        stdscr.addstr(
            y, x, option,
            curses.color_pair(settings.COLOR_BLACK_WHITE if option ==
                              selected else 0))
        stdscr.refresh()
        self.cursor_y = screen_height // 2 + 1
Esempio n. 16
0
def send(stdscr, contactId, contactName):
    draw_window(stdscr, "Briar Linux Client",
                "Type your message and press Ctrl+G to send")
    # Centering calculations
    height, width = stdscr.getmaxyx()
    z = 18
    x, y = int((width // 2) - (z // 2) - z % 2), 3
    stdscr.addstr(y - 1, x, "New message for: " + contactName,
                  curses.color_pair(2))

    ncols, nlines = 40, 5
    uly, ulx = 5, 2
    editwin = curses.newwin(nlines, ncols, uly, ulx)
    rectangle(stdscr, uly - 1, ulx - 1, uly + nlines, ulx + ncols)
    stdscr.refresh()

    box = Textbox(editwin)
    # Let the user edit until Ctrl-G is struck.
    box.edit()
    # Get resulting contents
    message = box.gather()

    if message != "":
        url_format = apiURL + "/v1/messages/" + contactId
        response = requests.post(url_format,
                                 headers=auth,
                                 json={"text": message})
        stdscr.addstr(20, 10, "Message sent")
    else:
        stdscr.addstr(20, 10, "Message empty", curses.color_pair(4))
    stdscr.refresh()
    stdscr.getch()

    messages(stdscr, contactId, contactName)
Esempio n. 17
0
def start_game(stdscr):
  sh, sw = stdscr.getmaxyx()
  box = [[0, 0], [sh - 2, sw - 1]]
  cursor_pos = [5,5]

  rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])
  stdscr.addstr(cursor_pos[0], cursor_pos[1], "*")

  stdscr.refresh()
  
  while True:
    
    key = stdscr.getch()
    
    if key == curses.KEY_UP:
      cursor_pos[0] -= 1
    elif key == curses.KEY_DOWN:
      cursor_pos[0] += 1
    elif key == curses.KEY_LEFT:
      cursor_pos[1] -= 1
    elif key == curses.KEY_RIGHT:
      cursor_pos[1] += 1
    elif key == curses.ascii.ESC:
      break

    stdscr.addstr(cursor_pos[0], cursor_pos[1], "*")
    
    stdscr.refresh()
Esempio n. 18
0
 def refresh(self):
     """
     Redraw border for EditBox and command an underlying window refresh.
     """
     if self.__border:
         rectangle(self.window, self.y-1, self.x-1, self.y+1, self.x+self.cols)
     Widget.refresh(self)
Esempio n. 19
0
    def display_puzzle(self):
        """
        Display the puzzle by adding lines of the puzzle as well as the status to the output screen
        :return:
        """
        self.screen.addstr(0, 0, "Sudoku Puzzle", curses.A_BOLD)

        # TODO: Sophisticated Line Formatting
        rectangle(self.screen, 4, 4, 9 + 5, 9 + 5)
        # For each row in the puzzle, get the items in a row, and display them.

        for row in range(0, 9):
            elements = [
                item for sublist in self.puzzle.get_row(row)
                for item in sublist
            ]
            for col in range(0, 9):
                self.screen.addstr(self.y_offset + row, self.x_offset + col,
                                   str(elements[col]))
        # Check if puzzle is solved
        reason = self.puzzle.check_puzzle()
        if reason:
            result = 'solved!'
        else:
            result = f'unsolved.\n{reason}'

        # Current status of puzzle
        self.screen.addstr(5, 20, f'Puzzle is {result}')
Esempio n. 20
0
def showPage(stdscr, pageName, sh, sw):
    curses.curs_set(0)
    stdscr.clear()
    box = [[3, 3], [sh - 3, sw - 3]]

    try:
        contents = getTextForPage(pageName)
    except wikipedia.DisambiguationError as e:
        title = 'Disambiguation error returned, which of these do you care about?'
        option, index = pick(e.options, title)
        showPage(stdscr, option, sh, sw)
        stdscr.refresh()
        return ""

    if contents == "":
        return

    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])

    stdscr.addstr(2, sw // 2 - len(pageName) // 2, pageName)
    lines = fitTextToScreen(contents, sw - 7)

    for i in range(sh - 7):
        stdscr.addstr(i + 4, 4, lines[i])

    stdscr.refresh()
Esempio n. 21
0
 def reset_box(self):
     self.screen.move(self.win_y-1, 0)
     self.screen.clrtoeol()
     textpad.rectangle(self.screen, self.win_y-1, self.win_x-1, self.win_y+1, self.win_x+16)
     self.win.clear()
     self.screen.move(self.win_y, self.win_x)
     self.screen.refresh()
Esempio n. 22
0
    def enter_room(self, name):
        self.chatroom = name
        self.screen.clear()
        self.screen.addstr(0, 0, "ROOM: %s" % name, curses.color_pair(1))
        self.clear_box()

        textpad.rectangle(self.screen, 3, 0, self.window_height - 7,
                          self.window_width - 2)
        self.view = self.screen.subwin(self.window_height - 11,
                                       self.window_width - 4, 4, 1)
        self.view.scrollok(1)
        self.view.immedok(True)

        view = threading.Thread(target=self.poller, args=())
        view.daemon = True
        view.start()

        self.print_status("Type and press ENTER to send a message.", False)
        while True:
            self.box.edit()
            message = (self.box.gather()).strip()
            if len(message) > 0 and message[0] == "!":
                name = message[1:]
                if name in self.db.get_members(self.chatroom):
                    self.db.approve_member(name, self.chatroom)
                    self.db.send(
                        self.chatroom, "admin",
                        "User %s accepted by %s." % (name, self.username))
            else:
                self.db.send(self.chatroom, self.username, message)
            self.clear_box()
        self.screen.getch()
Esempio n. 23
0
def loadPrintScreen(data): #Screen and actions for loading external files
  data.stdscr.clear()
  data.stdscr.addstr(0, 0, "Enter board file name (including '.txt')" +\
    " and press 'enter'")
  boxH,boxW = 1,30
  startY, startX = 3,1
  editwin = curses.newwin(boxH,boxW, startY,startX)
  rectULY, rectULX = 2, 0
  rectangle(data.stdscr, rectULY, rectULX, rectULY+boxH+1, rectULX+boxW+1)
  data.stdscr.addstr(rectULY+boxH+2,0, "Max size is %d x %d." % data.boardMax \
   + "If loaded board "+\
    "is smaller, rows and columns will be added. If too large, rows and"+\
    " columns will be removed until max dimensions acheived. If more space is"+\
    " needed, quit and resize the console window/reduce font size.")
  data.stdscr.refresh()

  box = Textbox(editwin)

  # Let the user edit until Ctrl-G is struck.
  box.edit()

  # Get resulting contents
  userInput = box.gather()
  try:#attempt to load user generated board
    data.lifeBoard = loadBoardState(userInput)
    data.loadedBoardTitle = userInput
    data.boardLoaded = True
    checkBoardSize(data) #fit to size
  except: #Something went wrong...
    data.stdscr.addstr(1,0, "Entered board state not found. "\
      +"Returning to main menu.", curses.color_pair(1) | curses.A_STANDOUT)
    curses.beep()
    data.stdscr.refresh()
    curses.napms(2000)
  data.loadScreen = False
Esempio n. 24
0
    def display_textpad(self, upper_left_y, nblines, nbcols):
        """

            Display a textpad enclosed in a rectangle, so it is visible.

            Arguments:

            upper_left_y: vertical coordinate of keypad upper left corner.

            nb_lines: number of lines of the keypad

            nb_cols: number of max of authorized characters + 1 for Curses

            Returns:

            content: values on ASCII format typed by the user.

            """
        self.win = self.inner_left_window.derwin(nblines, nbcols, upper_left_y,
                                                 1)
        self.win.clear()
        textpad.rectangle(self.inner_left_window, upper_left_y - 1, 0,
                          upper_left_y + nblines, nbcols + 1)
        curses.curs_set(1)
        self.win.refresh()
        box = textpad.Textbox(self.win, insert_mode=True)
        self.inner_left_window.refresh()
        content = box.edit()
        curses.curs_set(0)
        return content
Esempio n. 25
0
def print_tab(stdscr, title, active):
    """Print a new tab in the header"""
    uly = 0
    ulx = globvar.cur_pos
    lry = hsize
    lrx = globvar.cur_pos + wsize

    if lrx >= curses.COLS:
        # No enough space in the x row
        return

    rectangle(stdscr, uly, ulx, lry, lrx)

    if active:
        color = curses.color_pair(COLOR_SENSITIVE_SELECTED)
    else:
        color = curses.color_pair(COLOR_SENSITIVE_NOT_SELECTED)

    stdscr.addstr(uly + 1, globvar.cur_pos + 1, f"{title} ", color)
    globvar.cur_pos += wsize + 1

    current = tab.get_current_tab()
    if current.paused:
        stdscr.addstr(uly + 1, curses.COLS - 10, f"PAUSED",
                      curses.color_pair(COLOR_STOPPED))
Esempio n. 26
0
	def showWorkMsgRectangle(self):
		nLine  = 2
		nCol   = 100
		y      = self.scrh//2 - 1
		x      = self.scrw//2 - 1 - nCol//2
		rectangle(self.stdscr, y-1, x-1, y+nLine, x+nCol)
		self.stdscr.refresh()
Esempio n. 27
0
def company_details_screen(window, selected_element, buttons, company_name,
                           products_list):
    screen_size = window.getmaxyx()
    y_pos = 0
    x_pos = 0
    title_y_pos = 2
    title_x_pos = 3
    window.clear()
    window.addstr(title_y_pos, title_x_pos, company_name)

    for position, element in enumerate(buttons):
        if position == selected_element:
            window.attron(curses.color_pair(1))
            window.addstr(screen_size[0] - 2, title_x_pos + x_pos, element)
            window.attroff(curses.color_pair(1))
        else:
            window.addstr(screen_size[0] - 2, title_x_pos + x_pos, element)
        x_pos = x_pos + len(buttons[position]) + 2

    y_pos = 0

    for product in products_list:
        product = product.split(",")
        product = [f'{product_attribute} ' for product_attribute in product]
        window.addstr(title_y_pos + 3 + y_pos, title_x_pos, " ".join(product))
        y_pos = y_pos + 1

    rectangle(window, title_y_pos + 2, MENU_X_POSITION - 1, screen_size[0] - 3,
              screen_size[1] - 2)

    window.refresh()
Esempio n. 28
0
def main(stdscr):
    curses.raw()

    height, width = stdscr.getmaxyx()
    beg = (4, 10)
    end = (height - 4, width - 10)

    textpad.rectangle(stdscr, beg[0], beg[1], end[0], end[1])
    box_width = end[1] - beg[1]

    stdscr.move(beg[0] + 1, beg[1] + 1)

    line = str()
    lines = list()

    while True:
        key = stdscr.getch()
        cursor = stdscr.getyx()

        if key == 3:
            break

        elif key == 10:
            if cursor[0] + 1 == end[0]:
                continue

            lines.append(line + "\n")
            line = str()
            stdscr.move(cursor[0] + 1, beg[1] + 1)
            continue

        elif key == 263:
            if cursor[1] - 1 == beg[1]:
                continue
                # if len(lines) == 0:
                #     continue

                # else:
                #     stdscr.move(cursor[0] - 1, beg[1] + len(lines[-1]))
                #     lines.pop()
                #     continue
    
            stdscr.addstr(cursor[0], cursor[1] - 1, " ")
            stdscr.move(cursor[0], cursor[1] - 1)
            line = line[:-1]
            continue

        if len(line) + 1 == box_width:
            continue

        line += chr(key)
        stdscr.addstr(chr(key))

    if len(lines) == 0:
        lines = [line]

    buf = "".join(lines)

    with open("test_file", "w") as f:
        f.write(buf)
Esempio n. 29
0
    def render(self, options=None):
        rectangle(self.win, self.begin_y, self.begin_x, self.end_y, self.end_x)

        if options is not None:
            if 'merge_top_borders' in options:
                self.addstr(0, 0, "├", {'color': Colors.WHITE})
                self.addstr(0, self.width - 1, "┤")
    def menu_controller(self, stdscr):

        curses.curs_set(0)
        stdscr.nodelay(1)
        stdscr.timeout(100)

        box_height, box_width = stdscr.getmaxyx()
        box = [[1, 20], [box_height - 3, box_width - 3]]
        textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])

        self.draw_pattern(stdscr)
        self.print_menu(stdscr)

        while 1:
            key = stdscr.getch()
            if key in self.menu:
                self.board = np.zeros((self.height, self.width))
                if key == ord('r') or key == ord('R'):
                    self.board = np.random.randint(2,
                                                   size=(self.height,
                                                         self.width))
                else:
                    for i in range(len(self.patterns[self.menu[key]])):
                        for j in range(len(self.patterns[self.menu[key]][0])):
                            self.board[i + 3][j + 3] = self.patterns[
                                self.menu[key]][i][j]
                self.draw_pattern(stdscr)
            elif key == ord('p') or key == ord('P'):
                self.update_board()
                self.draw_pattern(stdscr)

            elif key == ord('e') or key == ord('E'):
                break
Esempio n. 31
0
def main_control(screen, event, inception_level):
    if event == ord("Q"):
        curses.endwin()
        exit(0)
    if event == ord("D"):
        window_for_done_task(screen)
    if event == ord("T"):
        window_for_undone_task(screen)
    if event == ord("F"):
        curses.flash()
    if event == ord("A"):
        editwin = curses.newwin(1,
                                screen.getmaxyx()[1]-6,
                                screen.getmaxyx()[0]-4,
                                1
                                )
        rectangle(screen,
                  screen.getmaxyx()[0]-5,
                  0, screen.getmaxyx()[0]-3,
                  screen.getmaxyx()[1]-5)
        screen.refresh()
        box = Textbox(editwin)
        # Let the user edit until Ctrl-G is struck.
        box.edit()
        # Get resulting contents
        message = box.gather()
        Tache().ajouter_tache(message, datetime.now())
        screen.clear()
        print_main_screen(screen)
        print_taches(screen, Tache().get_tache_undone(), "Taches a faire :")
        deal_with_selected(screen, 33, 45, Tache().get_tache_undone(),
                           window_for_undone_task)
Esempio n. 32
0
    def __call__(self, *args, **kwargs):
        args = self.arguments(*args, **kwargs)
        field_name = args['field']
        menu = kwargs['menu']
        item = menu.active_item.source

        stdscr = kwargs['stdscr']

        my, mx = stdscr.getmaxyx()
        sy = int(my * self.box_size[0])
        sx = int(mx * self.box_size[1])

        starty = (my - sy) // 2
        startx = (mx - sx) // 2

        header = "Edit field `{}`:".format(field_name)

        stdscr.addstr(starty, startx + (sx - len(header)) // 2, header)

        editwin = curses.newwin(sy - 3, sx - 1, starty + 2, startx + 1)
        rectangle(stdscr, starty + 1, startx, starty + sy, startx + sx)
        stdscr.refresh()

        box = MyTextPad(editwin, getattr(item, field_name))

        # Let the user edit until Ctrl-G is struck.
        box.edit()

        # Get resulting contents
        message = box.gather()

        setattr(item, field_name, message)

        menu.update_items()
Esempio n. 33
0
def print_help_screen(stdscr):
    screen_height, screen_width = stdscr.getmaxyx()
    border_offset = 3
    box = [[border_offset, border_offset],
           [screen_height - border_offset, screen_width - border_offset]]
    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])

    help_entries = [
        'Down    -> Go Down',
        'Up      -> Go Up',
        'G       -> Go To',
        '.       -> Toggle Status Bar',
        'ESC     -> Closes the program/Dialogs',
        'S       -> Save Progress',
        'H       -> Show the Help Dialog',
        'P       -> Show Percentage Points',
        'N       -> Open Notes file',
        'O       -> Opens RAE Web site with search from the clipboard.',
        'R       -> Opens GoodReads Web site with search from the clipboard.',
        'W       -> Open Word Building Mode with current sentence',
        'V       -> View Words added to the Word Building Database',
        'T       -> View Stats',
        'ESPACE  -> Toggle Navigation Mode',
    ]

    for idx, help_entry in enumerate(help_entries):
        stdscr.addstr(border_offset + idx + 1, border_offset + 1, help_entry)
Esempio n. 34
0
    def __edit_box(self,
                   title,
                   input_msg,
                   placeholder="",
                   size=5,
                   is_attachment=False):
        '''Function to show edit text box on screen'''

        curses.curs_set(1)
        self.__set_default_screen(title)
        # self.__stdscr.addstr(0, 0, input_msg)
        _, w = self.__stdscr.getmaxyx()

        number_of_lines = size
        number_of_columns = w - 3

        # create a new window
        editwin = curses.newwin(number_of_lines, number_of_columns, 2, 1)
        rectangle(self.__stdscr, 1, 0, 2 + number_of_lines,
                  2 + number_of_columns)
        if is_attachment:
            self.__stdscr.addstr(number_of_lines + 3, 1,
                                 "* Use ; to separate multiple filepaths")
        self.__stdscr.refresh()

        editwin.insstr(placeholder)

        # Make this new window a textbox to edit
        box = Textbox(editwin)
        # box.stripspaces = True
        box.edit()

        self.__set_default_screen(self.__title, isMain=True)
        curses.curs_set(0)
        return box.gather()
def test_textpad(stdscr, insert_mode=False):
    ncols, nlines = 8, 3
    uly, ulx = 3, 2
    if insert_mode:
        mode = 'insert mode'
    else:
        mode = 'overwrite mode'

    stdscr.addstr(uly-3, ulx, "Use Ctrl-G to end editing (%s)." % mode)
    stdscr.addstr(uly-2, ulx, "Be sure to try typing in the lower-right corner.")
    win = curses.newwin(nlines, ncols, uly, ulx)
    textpad.rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols)
    stdscr.refresh()

    box = textpad.Textbox(win, insert_mode)
    contents = box.edit()
    stdscr.addstr(uly+ncols+2, 0, "Text entered in the box\n")
    stdscr.addstr(repr(contents))
    stdscr.addstr('\n')
    stdscr.addstr('Press any key')
    stdscr.getch()

    for i in range(3):
        stdscr.move(uly+ncols+2 + i, 0)
        stdscr.clrtoeol()
Esempio n. 36
0
    def print_grid(self, numbers):
        self.screen.clear()
        sh, sw = self.screen.getmaxyx()
        y_offset = sh // 2 - len(numbers) * self.box_height // 2
        x_offset = sw // 2 - len(numbers) * self.box_width // 2

        for i, row in enumerate(numbers):
            for j, number in enumerate(row):
                # Rectangle border
                y_pos = y_offset + i * self.box_height
                x_pos = x_offset + j * self.box_width
                textpad.rectangle(self.screen, y_pos, x_pos,
                                  y_pos + self.box_height,
                                  x_pos + self.box_width)

                if number:
                    # Color box
                    color = int(math.log(number, 2))
                    for row in range(self.box_height - 1):
                        filler = ' ' * (self.box_width - 2)
                        self.screen.addstr(y_pos + row + 1, x_pos + 1, filler,
                                           curses.color_pair(color))
                        self.screen.refresh()

                    # Number text
                    num_text = str(number)
                    y_pos += self.box_height // 2
                    x_pos += self.box_width // 2 - len(num_text)
                    self.screen.addstr(y_pos, x_pos, num_text,
                                       curses.color_pair(color))

        self.screen.refresh()
Esempio n. 37
0
File: Main.py Progetto: huyna/sftc
 def drawchat(self):
     #self.screen.clear()
     self.screen.border(0)
     self.addtext("Nibble's Chat Client - Connected", 1, 2, 2)
     self.size = self.screen.getmaxyx()
     rectangle(self.screen, 2,1, self.size[0] - 3,self.size[1]-2)
     self.addtext(" "*(self.size[1]-3),    self.size[0] - 2,2, self.usertext) #Clear the buffer
     self.addtext(self.username + " $> ",self.size[0] - 2,2, self.usertext)
Esempio n. 38
0
    def draw(self):
        height, width = self.size
        win    = self.win
        height -= 1

        count  = len(self.entries)

        # hmm...
        #rectangle(win, 0, 0, height-1, width)
        #win.addstr(0, 3, '[Keyboard Layout Selection]')

        rectangle(win, 0, 0, height, width)
        win.addstr(0, 3, '[%s]' % L('Keyboard Layout Selection'))

        # borders
        height -= 1

        # list line
        button_line = height
        height -= 1
        win.hline(height,     1, curses.ACS_HLINE, width-1)
        win.addch(height,     0, curses.ACS_LTEE)
        win.addch(height, width, curses.ACS_RTEE)

        # scroll clamp
        if self.kbd_pos < self.scroll:
            self.scroll = self.kbd_pos
        elif self.scroll < self.kbd_pos - height + 2:
            self.scroll =  self.kbd_pos - height + 2

        # scrollability indicator
        if self.scroll > 0:
            win.addstr(0,      width - 16, utils.MORE_UP)
        if self.scroll + height < count:
            win.addstr(height, width - 16, utils.MORE_DOWN)

        # -1 for the list line border
        height -= 1

        # pylint: disable=invalid-name
        x = 2
        y = 1
        eindex   = 0
        selected = self.kbd_pos - self.scroll
        for i in range(self.scroll, count):
            if y > height:
                break
            _, name = self.entries[i]
            win.hline(y, x, ' ', width-x)
            win.addstr(y, x, name, utils.highlight_if(eindex == selected))
            eindex += 1
            y      += 1

        y = button_line
        win.hline(y, x, ' ', width-x)
        win.addstr(y, x, L('[ OK ]'),   utils.highlight_if(self.current == 0))
        x += len(L('[ OK ]')) + 2
        win.addstr(y, x, L('[ Skip ]'), utils.highlight_if(self.current == 1))
Esempio n. 39
0
def textbox(nrow, ncol, x, y):
	editwin = curses.newwin(nrow,ncol,x,y)
	# upleft point x, upleft point y, downright x, downright y
	rectangle(scr, x-1, y-1, x + nrow, y + ncol)
	scr.refresh()
	box = Textbox(editwin)
	box.edit()
	message = box.gather()
	return message
Esempio n. 40
0
def main(stdscr):

  curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
  curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLUE )

  #curses.noecho()
  #curses.curs_set(0)
  #stdscr.clear()
  #stdscr.resize(50, 50)
  #stdscr.border(0)
  #x=input("...waiting..")
  #curses.endwin()

  stdscr.border(0)
  stdscr.refresh()

  stdscr_y = curses.LINES - 1
  stdscr_x = curses.COLS - 1

  drawCoor(stdscr)

  pad = curses.newpad(20, 20)
  pad2 = curses.newpad(20, 20)


  for y in range(0, 19):
    for x in range(0, 19):
      pad.addch(y,x, ord('a') + (x*x+y*y) % 26)

  for y in range(0, 19):
    for x in range(0, 19):
      pad2.addch(y,x, ord('-'))

  pad.border(0)
  pad2.border(0)

  pad2.refresh(0,0, 15,5, 65,30)
  pad.refresh(0,0, 5,15, 30,40)
  stdscr.refresh()

  stdscr.addstr(15, 50,"Pretty text", curses.color_pair(2))
  stdscr.addstr(10, 50, "Current mode: Typing mode", curses.A_REVERSE)
  stdscr.addstr(10, 50, "HELLO")
  stdscr.refresh()


  stdscr.addstr(50, 50, "Enter IM message: (hit Ctrl-G to send)")


  rectangle(stdscr, 40,80, 60, 100)
  stdscr.refresh()

  ## Let the user edit until Ctrl-G is struck.
  editwin = curses.newwin(10,10, 50,90) # height, width, begin_y, begin_x
  stdscr.refresh()
  box = Textbox(editwin)
  box.edit()
Esempio n. 41
0
def textbox(screen):
    screen.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)", curses.A_REVERSE)
    editwin = curses.newwin(5, 30, 2, 1)
    rectangle(screen, 1, 0, 1+5+1, 1+30+1)
    screen.refresh()

    box = Textbox(editwin)
    box.edit()

    message = box.gather()
Esempio n. 42
0
def drawOrderbookDefaults(window):

    rectangle(window.cursesObj, 3, 3, 12, 72)
    rectangle(window.cursesObj, 14, 3, 23, 72)
    window.cursesObj.addstr(12, 34, " Asks ")
    window.cursesObj.addstr(14, 34, " Bids ")
    window.cursesObj.addstr(13, 5, "{0:20}{1:20}{2:20}{3}".format("Price", "Amount", "Seller", "Exchang-"))
    window.cursesObj.refresh()
    window.children["windows"]["placeOrderWindow"].initTitle([[1, 1], [1, 22]], "Market Info")
    window.children["windows"]["placeOrderWindow"].cursesObj.border()
    window.children["windows"]["orderbookBar"].cursesObj.hline(1, 0, "-", curses.COLS - 1)
    childLoop(window.childrenList)
Esempio n. 43
0
def init_term(stdscr, data=None):
	'''Initialize the terminal UI for NanoPy'''
	if data:
		add_head(stdscr, data)
	else:
		add_head(stdscr)
	write_keys(stdscr)
	editwin = curses.newwin(curses.LINES - 6, curses.COLS - 3, 2, 1)
	rectangle(stdscr, 1, 0, (curses.LINES - 4), (curses.COLS - 1))
	stdscr.scrollok(True)
	stdscr.refresh()
	return editwin
Esempio n. 44
0
	def __init__(self,screen):
		self.mode = 'move'
		self.screen = screen
		self.textwin = curses.newwin(1,78,21,1)
#		self.outputwin = curses.newwin(3,80,23,0)
		textpad.rectangle(self.screen,0,0,20,80)
		textpad.rectangle(self.screen,20,0,22,80)
		self.pad = curses.newpad(20,80)
		self.textpad = textpad.Textbox(self.textwin)
		self.game = Game()
		self.output = ''
		self.redraw()
Esempio n. 45
0
def main(stdscr):
	stdscr = curses.initscr()
	stdscr.clear()
	stdscr.addstr(0, 0, "JukeBox - v.0.1 'dancing Saci'")
	editwin = curses.newwin(5,30, 2,1)
	rectangle(stdscr, 1,0,1+5+1, 1+30+1)
	stdscr.refresh()
	
	box = Textbox(editwin)

	box.edit()
	message = box.gather()
Esempio n. 46
0
 def print_rectangle(self, tlX, tlY, drX, drY):
     logging.info("print_rectangle :" +
                  " Top x " + str(tlX) +
                  " Top Y" + str(tlY) +
                  " Down X" + str(drX) +
                  " Down Y" + str(drY) +
                  " Max Y"+str(self.getMaxXY()["y"]) +
                  " Max X"+str(self.getMaxXY()["x"])
                  )
     try:
         rectangle(self.screen, tlY, tlX, drY, drX)
     except Exception as e:
         logging.info(e)
     self.screen.refresh()
Esempio n. 47
0
def main(stdscr):
    stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")

    editwin = curses.newwin(30,30, 30, 30)
    rectangle(stdscr, 20, 20, 1+5+1, 1+30+1)
    stdscr.refresh()

    box = Textbox(editwin)

    # Let the user edit until Ctrl-G is struck.
    box.edit()

    # Get resulting contents
    message = box.gather()
Esempio n. 48
0
    def draw(self):
        width  = self.width
        height = self.height
        win    = self.win

        # pylint: disable=invalid-name
        y = 1
        x = 2
        for i in range(self.tabcount):
            text, _ = self.entries[i]
            win.addstr(y, x, text, utils.highlight_if(i == self.current))
            y += 1

        rectangle(win, 0, 0, height-1, width)
        win.addstr(0, 3, '[%s]' % self.title)
Esempio n. 49
0
def main():
    stdscr = curses.initscr()
    begin_x =  2
    begin_y = 2
    height = 8
    width = 54

    window = curses.newwin(height, width, begin_y, begin_x)
    window.addstr(0, 0, "Please type what you heard:")
    rectangle(window, 1, 0, 7, 50)
    text_box = Textbox(window)

    text_box.edit(on_key)
    message = text_box.gather()
    window.addstr(0, 40, message)
Esempio n. 50
0
def main(stdscr):
	lines, cols = curses.getmaxyx()
	stdscr.addstr(1, 1, "Enter IM message: (hit Ctrl-G to send)")
	stdscr.border()

	editwin = curses.newwin(5,30, 3,2)
	rectangle(stdscr, 2,1, 1+5+1, 1+30+1)
	stdscr.refresh()

	box = Textbox(editwin)

	# Let the user edit until Ctrl-G is struck.
	box.edit()

	# Get resulting contents
	message = box.gather()
Esempio n. 51
0
 def print_ajouter_tache(self):
     self.screen.addstr(self.max["y"]-6, 1, "Ajouter une tache :")
     editwin = curses.newwin(1,
                             self.max["x"]-6,
                             self.max["y"]-4,
                             1
                             )
     rectangle(self.screen,
               self.screen.getmaxyx()[0]-5,
               0, self.max["y"]-3,
               self.max["x"]-5)
     self.screen.refresh()
     box = Textbox(editwin)
     # Let the user edit until Ctrl-G is struck.
     box.edit()
     # Get resulting contents
     message = box.gather()
     return(message)
Esempio n. 52
0
def text_edit(text_to_display):
   stdscr = curses.initscr()
   curses.noecho()
   stdscr.addstr(0, 0, "%s: (hit Ctrl-G when finished)" % text_to_display)

   editwin = curses.newwin(20, 100, 2,1)
   rectangle(stdscr, 1,0, 1+20+1, 1+100+1)
   stdscr.refresh()

   box = Textbox(editwin)

   # Let the user edit until Ctrl-G is struck.
   box.edit()

   # Get resulting contents
   data =  box.gather()
   curses.endwin()
   return data   
def foo(stdscr):
    stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")

    editwin = curses.newwin(5, 30, 2, 1)
    rectangle(stdscr, 1,0, 1+5+1, 1+30+1)
    stdscr.refresh()

    box = Textbox(editwin)

    #pad = curses.newpad(100, 100)
    height = 7; width = 33

    begin_y = 1; begin_x = 33
    win0 = curses.newwin(height, width, begin_y, begin_x)
    win0.border()
    win0.refresh()

    begin_y = 8; begin_x = 0
    win1 = curses.newwin(height, width, begin_y, begin_x)
    win1.border()
    win1.refresh()

    begin_y = 8; begin_x = 33
    win2 = curses.newwin(height, width, begin_y, begin_x)
    win2.border()
    win2.refresh()

    # Let the user edit until Ctrl-G is struck.
    box.edit()

    # Get resulting contents
    message = box.gather()


    win0.addstr(1,1,message)
    win1.addstr(1,1,message)
    win2.addstr(1,1,message)

    win0.refresh()
    win1.refresh()
    win2.refresh()
    
    stdscr.refresh()
    stdscr.getkey()
Esempio n. 54
0
 def inputbox(self,message,title="Message Box"):
     """Displays a modal message box.  Let's try not to use this
     much!"""
     self.scr.clear();
     self.scr.addstr(0,0,
                     "^G to commit.");
     self.scr.addstr(30,0,
                     "----%s----"%title,
                     curses.color_pair(9));
     self.scr.addstr(31,0,message);
     
     editwin = curses.newwin(5,30, 2,1)
     rectangle(self.scr, 1,0, 1+5+1, 1+30+1)
     self.scr.refresh()
     
     box = Textbox(editwin)
     box.edit();
     
     self.scr.clear();
     return box.gather();
Esempio n. 55
0
def inputwnd(stdscr, msg = None, pos_y = None, pos_x = 2, size_y = 1, size_x = 30):
    tempscr = tempfile.TemporaryFile()
    stdscr.putwin(tempscr)

    if pos_y is None:
        pos_y = curses.LINES - 5
    if msg is not None and (len(msg) + 2 > size_x):
        size_x = len(msg) + 2
    inputWnd = curses.newwin(size_y, size_x, pos_y, pos_x)
    rectangle(stdscr, pos_y - 1, pos_x - 1, pos_y + size_y, pos_x + size_x)
    if msg is not None:
        stdscr.addstr(pos_y - 1, pos_x, " %s " % msg)
    stdscr.refresh()
    box = Textbox(inputWnd)
    box.edit()
    boxtext = box.gather()[:len(box.gather()) - 1]

    tempscr.seek(0)
    stdscr = curses.getwin(tempscr)
    stdscr.refresh()

    return boxtext
Esempio n. 56
0
def main(stdscr):
    stdscr.clear()
    columns = split_into_columns(stdscr,3)
    shouldExit = False

    box = Textbox(columns[0])
    rect = rectangle(columns[0],5,5,0,0)

    while not shouldExit:
        box.edit()
        k = stdscr.getkey()

        if k == "q":
            shouldExit = True
Esempio n. 57
0
def drawSuperNETDefaults(window):

    try:
        window.initTitle([[2, curses.COLS / 2], [2, curses.COLS - 1]], "Tests")
    except:
        pass

    # for windowsThatNeedBorders in window.children:
    #    this.drawBorder()

    rectangle(window.cursesObj, 3, 87, 23, 179)
    rectangle(window.cursesObj, 24, 41, 40, 135)
    rectangle(window.cursesObj, 3, 0, 23, 86)

    # window.children["pads"]["menu"].drawRectangle()
    window.cursesObj.refresh()
    # window.children["windows"]["supernetBar"].cursesObj.hline(1,0,'-',curses.COLS-1)
    window.children["windows"]["testsWin"].cursesObj.hline(1, 0, "-", 85)
    childLoop(window.childrenList)
Esempio n. 58
0
    def display(self, backends):
        s = curses.initscr()
        curses.start_color()
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.noecho()
        curses.curs_set(0)
        s.timeout(1000)
        s.border(0)

        h,w = s.getmaxyx()
        s.clear()
       
        #first line
        s.addstr(1, 2, 'haproxytop -')
        s.addstr(1, 15, datetime.now().strftime('%H:%M:%S'))
        s.addstr(1, 26, self._get_counter_msg())
        if self.filter:
            s.addstr(1, 65, ('filter: %s' % self.filter))

        columns = views[self.active_view]

        #second line, column headers
        x_pos = _startcol
        for c in columns:
            s.addstr(3, x_pos, c[0], curses.A_BOLD)
            x_pos += c[1]

        #remainder of lines
        y_pos = 5
        maxlines = h - 2

        for b in backends:
            x_pos = _startcol
            for c in columns:
                width = c[1]
                if isinstance(c[2], tuple):
                    if c[0] == 'NET I/O':
                        values = [ format_bytes(b.__getattribute__(i)) for i in c[2] ]
                    else:
                        values = [ str(b.__getattribute__(i)) for i in c[2] ]
                    value = ' / '.join([ v if v else '-' for v in values ])
                else:
                    value = str(b.__getattribute__(c[2]))


                if len(value) >= width:
                    value = self._truncate(value, width)

                if c[0] == 'NAME':
                    if not self.tree:
                        value = '%s (%d listeners)' % (value, len(b.listeners))
                    s.addstr(y_pos, x_pos, value, curses.color_pair(6))
                elif c[0] == 'STATUS':
                    if value == 'UP':
                        s.addstr(y_pos, x_pos, value, curses.color_pair(3))
                    else:
                        s.addstr(y_pos, x_pos, value, curses.color_pair(1))
                else:
                    s.addstr(y_pos, x_pos, value)

                x_pos += width
            if y_pos >= maxlines:
                break
            else:
                y_pos += 1
            
            if self.tree:
                for l in b.listeners:
                    x_pos = _startcol
                    for c in columns:
                        width = c[1]
                        if isinstance(c[2], tuple):
                            if c[0] == 'NET I/O':
                                values = [ format_bytes(l.__getattribute__(i)) for i in c[2] ]
                            else:
                                values = [ str(l.__getattribute__(i)) for i in c[2] ]
                            value = ' / '.join([ v if v else '-' for v in values ])
                        else:
                            value = str(l.__getattribute__(c[2]))
                        
                        if c[0] == 'NAME':
                            value = '├ ' + value

                        if len(value) >= width:
                            value = self._truncate(value, width)
                        
                        if c[0] == 'STATUS':
                            if value == 'UP':
                                s.addstr(y_pos, x_pos, value, curses.color_pair(3))
                            else:
                                s.addstr(y_pos, x_pos, value, curses.color_pair(1))
                        else:
                            s.addstr(y_pos, x_pos, value)

                        x_pos += width

                    if y_pos >= maxlines:
                        break
                    else:
                        y_pos += 1

        s.refresh()

        x = s.getch()
        if x == ord('q'):
            self._exit()

        if x == ord('h') or x == ord('?'):
            s.clear()
            startx = int(w / 2 - 20) # I have no idea why this offset of 20 is needed

            s.addstr(6, startx+1, 'haproxy-top version %s' % version)
            s.addstr(8, startx+1, 't - tree')
            s.addstr(9, startx+1, 's - select sort field')
            s.addstr(10, startx+1, 'r - reverse sort order')
            s.addstr(11, startx+1, 'f - filter by name')
            s.addstr(12, startx+1, 'h - show this help dialog')
            s.addstr(13, startx+1, 'q - quit')

            rectangle(s, 7,startx, 14,(startx+48))
            s.refresh()
            s.nodelay(0)
            s.getch()
            s.nodelay(1)
            
        if x == ord('t'):
            self.tree = not self.tree

        if x == ord('r'):
            self.sort['reversed'] = not self.sort['reversed']

        if x == ord('s'):
            startx = int(w / 2 - 20) # I have no idea why this offset of 20 is needed

            opts = [ i[0] for i in views[self.active_view] if i[3] ]
            selected = run_menu(tuple(opts), x=int(startx), y=6, name="sort")
            self.sort['func'] = views[self.active_view][selected][3]

        if x == ord('f'):
            s.clear()
            startx = int(w / 2 - 20) # I have no idea why this offset of 20 is needed

            s.addstr(6, startx, 'String to filter for:')

            editwin = curses.newwin(1, 30, 9, (startx+1))
            rectangle(s, 8, startx, 10, (startx+31))
            curses.curs_set(1) #make cursor visible in this box
            s.refresh()

            box = Textbox(editwin)
            box.edit()

            self.filter = str(box.gather()).strip(' ')
            curses.curs_set(0)
Esempio n. 59
0
 def drawRectangle(self, cursesObj=None, pos=None):
     if pos == None:
         pos = self.windowPos
     rectangle(self.parent.cursesObj, pos[0][0], pos[0][1], pos[1][0], pos[1][1])
     self.parent.cursesObj.refresh()
Esempio n. 60
0
contacts = curses.newwin(curses.LINES, len_contact, 0, 0)
messages = curses.newwin(curses.LINES, curses.COLS - len_contact, 0, len_contact)


attrs = {'curses.A_BLINK': curses.A_BLINK,
         'curses.A_BOLD': curses.A_BOLD,
         'curses.A_DIM': curses.A_DIM,
         'curses.A_REVERSE': curses.A_REVERSE,
         'curses.A_STANDOUT': curses.A_STANDOUT,
         'curses.A_UNDERLINE': curses.A_UNDERLINE, }
for i, attr in enumerate(attrs):
    contacts.addstr(i+2, 1, attr, attrs[attr])
contacts.addstr(1, 1, '测试')
contacts.border()
messages.border()
textpad.rectangle(messages, curses.LINES-4, 1, curses.LINES-2, curses.COLS-len_contact-2)
stdscr.refresh()
contacts.refresh()
messages.refresh()
try:
    for index in range(100):
        msglen = curses.COLS-len_contact-4
        msgheight = curses.LINES - 5
        data = messages.getstr(curses.LINES - 3, 2, msglen).decode('utf-8')
        data = [['> ', '  '][i != 0] + data[msglen * i:msglen*(i+1)] for i in range(ceil(len(data)/msglen))]
        msgs.extend(data)

        for j, info in zip(range(msgheight), msgs[-(msgheight):]):
            messages.addstr(j+1, 1, ' ' * (curses.COLS - len_contact - 2))
            messages.addstr(j+1, 1, info)