Example #1
0
def user_submit(auth, assignment, stdscr, contents=''):
    stdscr.clear()
    stdscr.addstr(0, 0, "Which file to submit: (hit ctrl-g to finish)")

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

    box = Textbox(editwin)

    box.edit()
    message = box.gather().rstrip()
    if message.startswith("!ls"):
        try:
            contents = repr(os.listdir(message[4:]))
        except:
            contents = ''
    try:
        open(message, 'rb').close()
    except:
        return user_submit(auth, assignment, stdscr, contents)

    stdscr.clear()
    stdscr.addstr(
        0, 0, "What should the submission be titled? (hit ctrl-g to finish)")
    editwin = curses.newwin(5, 30, 2, 1)
    rectangle(stdscr, 1, 0, 1 + 5 + 1, 1 + 30 + 1)
    stdscr.refresh()

    box = Textbox(editwin)
    box.edit()

    submit(auth, assignment, message, box.gather().rstrip())
Example #2
0
 def do_command(self, ch):
     if ch == 127:  # backspace
         Textbox.do_command(self, curses.KEY_BACKSPACE)
         self.win.refresh()
         return 1
     if ch == 27:
         Textbox.gather(self)
         return -1
     return Textbox.do_command(self, ch)
Example #3
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
Example #4
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)
Example #5
0
def main(stdscr):
        
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(1)

    rT = threading.Thread(target=receiving, args=("RecvThread", s))
    rT.start()

    put = curses.newwin(4, 66, 20, 0)
    put.border(0)
    put.addstr(1, 1, nick+' >> ')
    put.addstr(3, 1, 'Enter to send------------------------------------------q to exit')
    put.refresh()

    boxbox = curses.newwin(1, 51, 21, 14)
    boxbox.refresh()
    box = Textbox(boxbox)
    message = ''
    while message != 'q ':
        box.edit()
        message = str(box.gather())
        if message != '':
            s.sendto(nick + " >> " + message, server)
            boxbox.clear()
        time.sleep(0.2)
    s.sendto('3 '+nick, server)
Example #6
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)
def input():
    editwin = curses.newwin(1, 60, 7, 3)
    rectangle(screen, 6, 2, 6 + 1 + 1, 2 + 60 + 1)
    screen.refresh()
    box = Textbox(editwin)
    box.edit()
    return box.gather()
Example #8
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
Example #9
0
File: cli.py Project: kondziu/6p
    def _display(self, text=None, edit=True):
        self._window.refresh()
        self._window.border()

        text_width = self._width - 2
        text_height = self._height - 2

        self._window.addstr(0, 1, "[%s]" % "Your answer"[0:text_width - 2])
        self._window.addstr(self._height - 1, text_width - 8, "[Ctrl+G]")
        #self._window.move(1,1)
        self._window.refresh()

        if edit:
            temporary_edit_window = curses.newwin(text_height, text_width,
                                                  self._y + 1, self._x + 1)
            curses.curs_set(True)

            edit_box = Textbox(temporary_edit_window)
            edit_box.edit()
            curses.curs_set(False)
            content = edit_box.gather().strip()
            del temporary_edit_window

            return content

        else:
            return None
Example #10
0
File: cli.py Project: kondziu/6p
    def _display(self, text=None, edit=True):
        self._window.refresh()
        self._window.border()

        text_width = self._width - 2
        text_height = self._height - 2

        self._window.addstr(0, 1, "[%s]" % "Your answer"[0:text_width - 2])
        self._window.addstr(self._height - 1, text_width - 8, "[Ctrl+G]")
        #self._window.move(1,1)
        self._window.refresh()

        if edit:
            temporary_edit_window = curses.newwin(text_height, text_width, self._y + 1, self._x + 1)
            curses.curs_set(True)

            edit_box = Textbox(temporary_edit_window)
            edit_box.edit()
            curses.curs_set(False)
            content = edit_box.gather().strip()
            del temporary_edit_window

            return content

        else:
            return None
Example #11
0
    def _main(self, stdscr):
        try:
            #   stdscr = curses.initscr()
            # Clear screen
            stdscr.clear()
            # remove the cursor
            curses.curs_set(True)
            # remove echo from touched keys
            # curses.noecho()
            self._initPanels(stdscr)

            box = Textbox(self.commandInput)
            #     stdscr.refresh()
            th = Thread(target = self.refreshProbes, name = "Probe-Refresh", daemon = True)
            th.start()
            stdscr.refresh()

            while self.isRunning:
                stdscr.refresh()
                box.edit()
                self.doCommand(box.gather())
                #         commandInput.refresh()

                # listen without entering enter
                # curses.cbreak())
        finally:
            self.isRunning = False
            th.join()
            # let curses handle special keys
            stdscr.keypad(True)
            stdscr.refresh()
            stdscr.getkey()
Example #12
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)
Example #13
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)
Example #14
0
def draw_menu(stdscr):
    k = 0
    # Clear and refresh the screen for a blank canvas
    stdscr.clear()
    stdscr.refresh()
    height, width = stdscr.getmaxyx()

    # Start colors in curses
    curses.start_color()
    curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)

    summoner_name_str = 'Summoner name:'
    start_x_title = int((width // 2) - (len(summoner_name_str)))
    stdscr.addstr(0, start_x_title, summoner_name_str, curses.color_pair(3))
    stdscr.refresh()

    editwin = curses.newwin(1, 17, 0, int((width // 2) + 1))
    box = Textbox(editwin)
    # Let the user edit until Ctrl-G is struck.
    box.edit()
    # Get resulting contents
    message = box.gather()

    while k != ord('q'):
        stdscr.clear()
        stdscr.refresh()
        stdscr.addstr(0, 0, message)
        # Refresh the screen

        # Wait for next input
        k = stdscr.getch()
Example #15
0
def draw_edit_box(menu_man, win_man, build_opts):
    ## BUGGY (resize + too small windows not handled properly)
    win_man.resize_wins("edit_mode")
    win_man.refresh_all()
    curses.curs_set(1)
    # Add title of the box
    win_man._field_win.bkgd(" ", curses.color_pair(5))
    win_man._field_win.addstr(0, 0, menu_man.get_verbose_cur_field(), curses.color_pair(5))
    win_man._field_win.chgat(0, 0, -1, curses.color_pair(1))
    # Create the window that will holds the text
    (YMAX, XMAX) = win_man._field_win.getmaxyx()
    (YBEG, XBEG) = win_man._field_win.getparyx()
    text_win = curses.newwin(YMAX, XMAX, YBEG + 6, XBEG + 5)
    text_win.bkgd(" ", curses.color_pair(5))
    text_win.addstr(0, 0, build_opts[menu_man._cur_field], curses.color_pair(5))
    # Refresh both windows
    win_man._field_win.noutrefresh()
    text_win.noutrefresh()
    curses.doupdate()
    # Create a textbox
    box = Textbox(text_win)
    box.edit()
    build_opts[menu_man._cur_field] = box.gather()[:-2]
    del text_win
    curses.curs_set(0)
    menu_man._cur_field = ""
    win_man.resize_wins("menu_mode")
Example #16
0
def edited_text(scr,
                text,
                y,
                x,
                w=50,
                prompt="Edit the text then Ctrl-G to exit"):
    """
    Provides the editing capability:
    Returns the edited (or not) version of text.
    Editing window begins at (y,x) of the <scr>een,
    consists of 3 rows and is w+2 characters wide.
    Text to be edited appears on line y+1 beginning in column x+1
    within a 'bordered' window with room for w characters or as many
    as are in text, which ever is the greater.
    The <prompt> overwrites the box border in bold.
    """
    #   scr.
    #   scr.refresh()
    if l := len(text) > w: w = l
    # create the text box with border around the outside
    tb_border = cur.newwin(3, w + 2, y, x)
    tb_border.box()
    # place promt on line above the box
    tb_border.refresh()
    scr.addstr(y, x + 2, prompt, cur.A_BOLD)
    scr.refresh()
    tb_body = cur.newwin(1, w, y + 1, x + 1)
    tb = Textbox(tb_body)
    for ch in text:  # insert starting text
        tb.do_command(ch)
    tb.edit()  # start the editor running, Ctrl-G ends
    s2 = tb.gather()  # fetch the contents
    scr.clear()  # clear the screen
    #   return s2
    return s2.strip()
Example #17
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()
Example #18
0
def command(stdscr, repl_y, repl_x):
    stdscr.addstr(repl_y, 0, ":")
    editwin = curses.newwin(1, repl_x - 1, repl_y, repl_x + 2)
    editwin.refresh()
    stdscr.refresh()
    box = Textbox(editwin)
    box.edit()
    return box.gather()
Example #19
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
Example #20
0
	def getText(self, dflt=""):
		offset = 40
		width  = 30
		self.showGetRectangle()
		self.textWin.addstr(0,0,dflt)
		box = Textbox(self.textWin)
		box.edit()
		message = box.gather()
		self.textWin.clear()
		return message.strip()
Example #21
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()
Example #22
0
File: GUI.py Project: W4ld3n/b-CD
    def inputCommand(self):
        box = Textbox(self.commandWin)

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

        # Get resulting contents
        message = box.gather()
        self.commandWin.clear()
        return message
Example #23
0
def show_search_screen(stdscr):
     curses.curs_set(1)
     stdscr.addstr(1, 2, "Artist name: (Ctrl-G to search)")
     editwin = curses.newwin(1, 40, 3, 3)
     rectangle(stdscr, 2, 2, 4, 44)
     stdscr.refresh()
     box = Textbox(editwin)
     box.edit()
     criteria = box.gather()
     return criteria
Example #24
0
def main(stdscr):
    stdscr.addstr(0, 0, "Introduzca mensaje: (Ctrl-G para terminar)")

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

    box = Textbox(editwin)
    box.edit()  # Let the user edit until Ctrl-G is struck
    message = box.gather()  # Get resulting contents
Example #25
0
    def get_filename(self):
        editwin = curses.newwin(1, 30, 10, 1)
        rectangle(stdscr, 9, 0, 11, 42)
        stdscr.refresh()

        box = Textbox(editwin)

        # Let the user edit until Ctrl-G is struck.
        box.edit()
        return box.gather()
Example #26
0
File: ui.py Project: foopub/Toys
async def textbox(handler):
    """
    Handles user input to the textbox.
    """
    while True:
        win['t'].erase()
        box = Textbox(win['t'])
        box.edit()
        message = box.gather()
        await handler(message)
Example #27
0
def drawLoginInput(screen, height, width):
    dramaticOutput(screen, height//2, width//2, 'Enter your handle:', 0.05)
    handleWindow = curses.newwin(1, 30, height//2+1, width//2 - 16) 
    handleBox = Textbox(handleWindow)
    handleBox.edit()
    handle = handleBox.gather()
    screen.clear()
    dramaticOutput(screen, height//2, width//2, 'Logging you in as ' + handle + '...', 0.05)
    time.sleep(1)
    return handle
Example #28
0
def new_game_get_seed(win):
    # Ask for a random seed to start the game

    win.clear()
    win.addstr(0, 0, SEED_STRING)

    # create a text box for the user to type in
    editwin = curses.newpad(1, 32)
    rectangle(win, 5, 0, 1 + 5 + 1, 1 + 32 + 1)

    win_height = curses.LINES - 2
    win_width = curses.COLS - 4
    win.refresh(0, 0, 1, 2, win_height, win_width)

    box = Textbox(editwin)

    while True:
        # wait for user input
        win.refresh(0, 0, 1, 2, win_height, win_width)
        editwin.refresh(0, 0, 7, 4, 7 + 1, 4 + 32)
        c = editwin.getch()

        # handle special cases:
        if c == 10:  # [enter]
            break
        elif c == curses.KEY_RESIZE:  # window resizing

            stdscr.clear()
            stdscr.border('|', '|', '-', '-', '+', '+', '+', '+')
            stdscr.refresh()
            rectangle(win, 5, 0, 1 + 5 + 1, 1 + 32 + 1)

            h, w = stdscr.getmaxyx()
            assert h > 2 and w > 10
            win_height = h - 2
            win_width = w - 4

            win.resize(100, win_width - 1)
            win.refresh(0, 0, 1, 2, win_height, win_width)

        # draw the user input in the text box
        box.do_command(c)

    # Get resulting contents
    message = box.gather()

    win.clear()

    if message:
        logger.info(f"Seed by user: {message}")
        return message
    else:
        seed = random.randint(1, sys.maxsize)
        logger.info(f"Seed generated: {seed}")
        return seed
Example #29
0
def main(stdscr, Numero_Linhas):
    stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")
    editwin = curses.newwin(Numero_Linhas, 30, 2, 1)
    rectangle(stdscr, 1, 0, 1 + Numero_Linhas + 1, 1 + 30 + 1)
    stdscr.refresh()
    box = Textbox(editwin)
    # Let the user edit until Ctrl-G is struck.
    box.edit([Control - A, Control - B])
    # Get resulting contents
    message = box.gather()
    return message
Example #30
0
def name_screen(w, h):
    print_centered(w, 2, "Enter NAME: (hit ENTER to send)", "top")
    print_centered(w, h, "To play the game use your arrow keys:", "mid")
    print_centered(w, h + 2, "<- left | right ->", "mid")

    editwin = curses.newwin(1, 12, 5, (w // 2) - 6)
    rectangle(stdscr, 4, w // 2 - 8, 6, w // 2 + 8)
    stdscr.refresh()

    box = Textbox(editwin)
    box.edit()
    return box.gather()
Example #31
0
 def downloadMp4ByURL(self, stdscr, format):
     stdscr.addstr(0, 0, "Enter YouTube URL: (hit Ctrl-G to download)")
     editwin = curses.newwin(1,80, 2,1)
     rectangle(stdscr, 1,0, 1+1+1, 1+80+1)
     stdscr.refresh()
     box = Textbox(editwin)
     box.edit()
     url = box.gather()
     if format == "MP3 DOWNLOAD":
         Download.mp3Download(url, "test")
     elif format == "MP4 DOWNLOAD":
         Download.mp4Download(url, "test")
Example #32
0
 def _textbox(self, prompt):
     self.foot.erase()
     self.foot.addstr(0, 0, prompt, curses.A_BOLD)
     curses.curs_set(1)
     self.foot.refresh()
     tb = self.foot.subwin(self.maxy - 1, len(prompt))
     box = Textbox(tb)
     box.edit()
     curses.curs_set(0)
     result = box.gather()
     self.foot.erase()
     return result
Example #33
0
File: main.py Project: enzo-bc/abbr
def search_box(stdscr):
    scr_height, scr_width = stdscr.getmaxyx()
    boxwin = newwin(4, 46, int(scr_height / 2 - 2), int(scr_width / 2 - 23))
    editwin = newwin(1, 44, int(scr_height / 2), int(scr_width / 2 - 22))
    boxwin.border(1)
    boxwin.addstr(1, 1, "Search for definition")
    boxwin.refresh()
    editwin.refresh()
    box = Textbox(editwin)
    box.edit()

    return box.gather()
Example #34
0
def main(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)

    box.edit()

    message = box.gather()
Example #35
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()
Example #36
0
File: main.py Project: ymizushi/dtt
def docker_mode(stdscr):
    client = docker.from_env()
    curses.cbreak()
    containers = Containers(client.containers.list())
    line_num = 1 if len(containers.list) == 0 else len(containers.list)
    pad = curses.newpad(line_num,curses.COLS)
    pad.keypad(True)
    Color.init()
    while True:
        if len(containers.list) == 0:
            pad.addstr(0, 0, "empty runnning container.", Color.get("RED_WHITE"))
        for i, l in enumerate(containers.list):
            pad.addstr(i, 0, "{}".format(l.id)[:10], Color.get("BLUE"))
            pad.addstr(i, 15, "{}".format(l.name), Color.get("CYAN"))
        pad.move(containers.index, 0);
        pad.refresh(containers.index-(curses.LINES-1), 0, 0, 0, curses.LINES-1, curses.COLS-1)
        c = pad.getch()
        if c in [curses.KEY_ENTER, KeyPad.ENTER]:
            curses.nocbreak() 
            pad.keypad(False)
            pad.clear()
            subprocess.call(["clear"])
            subprocess.call(get_command(containers.current_container.id, "/bin/sh"))
            curses.cbreak() 
            pad.keypad(True) 
        elif c in [ord('j'), curses.KEY_DOWN]:
            containers.add_index()
        elif c in [ord('k'), curses.KEY_UP]:
            containers.sub_index()
        elif c == ord('X'):
            win = curses.newwin(1, curses.COLS-1, curses.LINES-1, 0)
            box = Textbox(win)
            box.edit()
            command = box.gather().rstrip()

            curses.nocbreak() 
            pad.keypad(False)
            pad.clear()
            subprocess.call(["clear"])
            subprocess.call(get_command(containers.current_container.id, command))
            curses.cbreak() 
            pad.keypad(True) 
        elif c in [ord('h')]:
            pad.clear()
            wrapper(help_mode)
            curses.cbreak()
        elif c == ord('q'):
            break
    curses.nocbreak()
    pad.keypad(False)
    curses.echo()
    curses.endwin()
Example #37
0
File: Pad.py Project: yottu/yottu
	def query_userinput(self, label="Input: ", input_type="all", input_size=20):
		# Display query for pass pin and switch to command mode

		def valid_number(userchar):
			if 47 < userchar < 58: # 0 - 9
				return userchar
			elif userchar == 263: # Backspace
				return userchar
			elif userchar == 10: # Enter
				return 7 # Ctrl+G (Terminate)
			else:
				self.dlog.msg("Invalid user input: " +  (str(userchar)))
				return False

		def valid_text(userchar):
			if 47 < userchar < 58: # 0 - 9
				return userchar
			if 64 < userchar < 90: # A - Z
				return userchar
			if 96 < userchar < 123: # a - z
				return userchar
			elif userchar == 263: # Backspace
				return userchar
			elif userchar == 10: # Enter
				return 7 # Ctrl+G (Terminate)
			else:
				self.dlog.msg("Invalid user input: " +  (str(userchar)))
				return False
		
		try:
			total_size = len(label)+int(input_size)
	
			self.stdscr.addstr(2, 1, label)
			editwin = curses.newwin(1, int(input_size), 2, 1+len(label)) # window size(y,x) cursor postion(y,x)
			rectangle(self.stdscr, 1, 0, 3, 1+total_size+1) # y,x, height, width
			self.stdscr.refresh()

			box = Textbox(editwin)

			if input_type == "number":
				box.edit(valid_number)
			elif input_type == "text":
				box.edit(valid_text)
			else:
				box.edit()

			userinput = box.gather()
			
			return userinput[:-1] # strip ctrl+g
			
		except Exception as err:
			self.dlog.excpt(err, msg=">>>in Pad.query_userinput()", cn=self.__class__.__name__)	
Example #38
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
def cargar(window):
    window.clear()
    curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK) 
    titulo(window, "Ingrese nombre archivo csv: (Ctrl-G para cargar)")
    window.attron(curses.color_pair(4)) 
    editwin = curses.newwin(3,15, 9,25) 
    rectangle(window, 7,11, 1+11+1, 1+45+1)
    window.attron(curses.color_pair(4))
    window.refresh()
    box = Textbox(editwin)
    box.edit()
    nombreA = box.gather()
    return nombreA   
Example #40
0
def textbox(win, page_num):
    win.clear()
    prompt = "page number (hit Ctrl-G after typing number):"
    win.addstr(4, 4, prompt)
    tbox = Textbox(win)
    tbox.edit()
    raw_res = tbox.gather()
    res = raw_res.replace(prompt, "").strip()
    new_page = convert_str_to_page_num(res)
    if new_page is not None:
        old = page_num
        page_num = new_page
    return page_num
Example #41
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()
Example #42
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)
Example #43
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()
def client(address, send_win):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(address)
    payload = (sock,)
    Thread(target=listen_for_updates, args=payload).start()
    title_buffer_win.addstr(0, 0, STATUS_CONSTANTS[1] + address[0], curses.A_STANDOUT)
    while True:
        box = Textbox(send_win)
        box.edit()
        message = box.gather()
        message = bytes(message.encode('utf-8'))
        sock.sendall(message)
        send_win = curses.newwin(1, TERMINAL_SIZE.columns, TERMINAL_SIZE.lines - 1, 0)

    update_status(STATUS_CONSTANTS[0])
    sock.shutdown(socket.SHUT_RD)
    sock.close()
Example #45
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   
Example #46
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)
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()
Example #48
0
 def print_ajouter_tag(self, tagMenu):
     tagMenu.getLastItemY()
     newTagStr = "New TAG >"
     self.screen.addstr(tagMenu.getLastItemY(),
                        tagMenu.getFirstItemX()+len(tagMenu.getSelector())-len(newTagStr),
                        newTagStr)
     editwin = curses.newwin(
                             1,
                             self.max["x"]-tagMenu.getFirstItemX()+len(tagMenu.getSelector()),
                             tagMenu.getLastItemY(),
                             tagMenu.getFirstItemX()+len(tagMenu.getSelector()),
                             )
     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)
Example #49
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();
Example #50
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)
Example #51
0
def main(stdscr):
	curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
	curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
	curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK)

	rfs_screen(stdscr)

	while True:
                ch = stdscr.getch()
		line = get_fcsline()
		fn = ""
		if line != {}:
			fn = os.path.join(line['phn'], line['fln'])
                if ch == ord('q'):
                        break
                elif ch == curses.KEY_UP:
                        scrolllines(stdscr, 1)
                elif ch == curses.KEY_DOWN:
                        scrolllines(stdscr, -1)
                elif ch == ord('u'):
                        mvfcs(-1)
                        scrolllines(stdscr, 0)
			shw_status(stdscr, "file")
                elif ch == ord('j'):
                        mvfcs(1)
                        scrolllines(stdscr, 0)
			shw_status(stdscr, "file")
		elif ch == ord('d'):
			if not fn:
				continue
			mva_bottom(stdscr, "delete it, y/n?", curses.A_REVERSE)
			while True:
				d_ch = stdscr.getch()
				if d_ch == ord('y'):
					if os.path.isdir(fn):
						shutil.rmtree(fn)
					else:
						os.remove(fn)
					del_fcsline()
					stdscr.clear()
					scrolllines(stdscr, 0)
					shw_status(stdscr, "file")
					break
				elif d_ch == ord('n'):
					shw_status(stdscr, "file")
					break
				else:
					mva_bottom(stdscr, "please enter y to make sure, or n to cancel it.", curses.A_REVERSE)
		elif ch == ord('m'):
			if not fn:
				continue
			m_tips = "please hit the char(in pn col) of the path or UP to move into, or 'c' to cancel out."
			mva_bottom(stdscr, m_tips, curses.A_REVERSE)
			m_phn = ""
			while True:
				m_ch = stdscr.getch()
				m_line = get_pthline(m_ch)
				if m_line != {}:
					m_phn = os.path.join(m_line["phn"], m_line["fln"])
					mva_bottom(stdscr, "move into \"{}\", y/n?".format(m_phn), curses.A_REVERSE)
				elif m_ch == ord('y') and m_phn != "":
					shutil.move(fn, m_phn) 
					rfs_screen(stdscr)
					break
				elif m_ch == ord('n'):
					m_phn = ""
					mva_bottom(stdscr, m_tips, curses.A_REVERSE)
				elif m_ch == ord('c'):
					shw_status(stdscr, "file")
					break
		elif ch == ord('r'):
			if not fn:
				continue
			mva_bottom(stdscr, "rename it, y/n?(if yes, then edit the new name and fire it with ctrl+g when it's done.)", curses.A_REVERSE)
			while True:
				r_ch = stdscr.getch()
				if r_ch == ord('y'):
					r_title = "new name:"
					yx = stdscr.getmaxyx()
					mva_bottom(stdscr, r_title, curses.A_REVERSE)
					editwin = curses.newwin(1, yx[1] - len(r_title) - 1, yx[0] - 1, len(r_title) + 1)
					stdscr.refresh()
					box = Textbox(editwin)
					# Let the user edit until Ctrl-G is struck.
					box.edit()
					# Get resulting contents
					newname = box.gather().strip()
					if newname == line['fln']:
						mva_bottom(stdscr, "no change.", curses.A_REVERSE)
					else:
						old_name = os.path.join(line['phn'], line['fln'])
						new_name = os.path.join(line['phn'], newname)
						os.rename(old_name, new_name)
						rfs_screen(stdscr)
					break
				elif r_ch == ord('n'):
					shw_status(stdscr, "file")
					break
		elif ch == curses.KEY_F5:
			stdscr.clear()
			scrolllines(stdscr, 0)
		elif ch == ord('?'):
			mva_bottom(stdscr, "u/j to select,d to remove,m to move,ENTER into a folder,UP/DW to scroll,F5 to refresh,? to help,q to quit.", curses.A_REVERSE)
		elif ch in (curses.KEY_ENTER, 10):
			if not fn:
				continue
			if line['pnu'] != -1:
				vpath = os.path.join(line['phn'], line['fln'])
				psh_vpath(vpath, -1)
				rfs_screen(stdscr)
		elif ch == curses.KEY_BACKSPACE:
			pop_vpath()
			rfs_screen(stdscr)
		else:
                        continue
Example #52
0
class EditPad():
    def __init__(self):
        y, x = scr.getmaxyx()
        self.edit = curses.newwin(1, x, y - 2, 0)
        self.status = curses.newwin(1, x, y - 3, 0)
        self.pad = Textbox(self.edit, insert_mode=True)
        self.lastcmd = []

    def update_cmd_status(self, message, color=None):
        if not color:
            color = curses.color_pair(1)
        self.status.clear()
        try:
            self.status.addstr(0, 0, message, color)
            self.status.refresh()
        except:
            pass

    def focus(self):
        modeline.update_activeWindow("Command Entry")
        self.edit.erase()
        entercommandstr = "Enter command. TAB for auto complete. (command-list for command help or ? for general help)"
        pad.update_cmd_status(entercommandstr)

        curses.curs_set(1)
        while True:
            message = self.pad.edit(validate=self.handle_key_event).strip()
            try:
                cmd = commands[message]
            except KeyError:
                self.update_cmd_status("Unknown command: {}".format(message), colors['red'])
                continue

            if message not in self.lastcmd:
                self.lastcmd.append(message)

            func = cmd()
            if not func:
                self.update_cmd_status(entercommandstr)
                self.edit.clear()
                self.edit.refresh()
                continue

            try:
                qanda = func.send(None)
                while True:
                    self.edit.clear()
                    self.update_cmd_status(qanda.question, color=curses.color_pair(qanda.type))
                    message = self.pad.edit(validate=self.handle_key_event).strip()
                    qanda = func.send(message)
            except StopIteration:
                pass

            self.update_cmd_status(entercommandstr)
            self.edit.erase()

    def clear(self):
        self.edit.erase()

    def handle_key_event(self, event):
        """
        Handle edit pad key events
        :param event:
        :return:
        """
        logging.info("Key Event:{}".format(event))
        if event == curses.KEY_UP:
            try:
                cmd = self.lastcmd[0]
            except IndexError:
                return event

            self.edit.clear()
            self.edit.addstr(0, 0, cmd)
            self.edit.refresh()

        try_handle_global_event(event)

        if event == 9:
            logging.info("Calling auto complete on TAB key")
            data = self.pad.gather().strip()
            cmds = {key[:len(data)]: key for key in commands.keys()}
            logging.info("Options are")
            for cmd, fullname in cmds.iteritems():
                if cmd == data:
                    logging.info("Grabbed the first match which was {}".format(fullname))
                    self.edit.clear()
                    self.edit.addstr(0, 0, fullname)
                    self.edit.refresh()
                    break
        return event
Example #53
0
def main(stdscr):
	startAnim = True
	stdscr = curses.initscr()	# init curses, return a window obj
	curses.start_color()		# init default colour set, wrapper should have done this
	stdscr.clearok(1)		# makes next call to refresh clear the window as well
	hudXPos = curses.COLS - 40	# x pos of HUDs to draw

	newGame = gameInfo(False, curses.COLS - 40)	# false; goto title screen, num levels to pass
	newPlayer = player( int(curses.COLS/2), curses.LINES - 2, 100, "New Player")

	# setup main window where stuff coming at player is drawn, fire into mid of screen
	mainWin = gameWindow( 0, 0, curses.LINES, hudXPos)
	mainWin.makeWin( curses.newwin( mainWin.height, mainWin.width, mainWin.yTop, mainWin.xTop))

	titleScreen = gameWindow( 0, 0, curses.LINES, curses.COLS)
	titleScreen.makeWin( curses.newwin( titleScreen.height, titleScreen.width, titleScreen.yTop, titleScreen.xTop))

	editwin = curses.newwin( 3, 12, int(titleScreen.height/2), int(titleScreen.width/2))	# edit box with height 3, w 12, mid screen
	box = Textbox(editwin)

	# set HUD windows
	statsWin = gameWindow( hudXPos, 0, int(curses.LINES/3), 40)
	statsWin.makeWin( curses.newwin( statsWin.height, statsWin.width, statsWin.yTop, statsWin.xTop))

	mapWin = gameWindow( hudXPos, int(curses.LINES/3), int(curses.LINES/3), 40)
	mapWin.makeWin( curses.newwin( mapWin.height, mapWin.width, mapWin.yTop, mapWin.xTop))


	# Set some properties
	curses.noecho()			# do not output inputted char to screen
	curses.cbreak()			# dont wait for 'enter' pressed to respond to input
	curses.curs_set(False)		# no blinking cursor
	stdscr.keypad(True)		# allows recog of LEY_LEFT, PAGE_UP
	stdscr.nodelay(True)		# make getch(), and getKey non block

# 	Define colours; for some reason, they arent defined already, access to 0 - 7
	curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)	# colorID to change, forground, background
	curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)	# colorID to change, forground, background
	curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)	# colorID to change, forground, background
	curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)	# colorID to change, forground, background
	curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)	# colorID to change, forground, background
	curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)	# colorID to change, forground, background
	curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)	# colorID to change, forground, background

#	Set bkg to black
	mainWin.winObj.bkgd(' ', curses.color_pair(0))

	var = 1
	x = 1
	y = 1
	rows = 20
	toadd = 0.1

	while( (stdscr.getch() != ord('q')) and (stdscr.getch != curses.KEY_EXIT) ):
		if(newGame.gameState):
			if startAnim:
				titleScreen.winObj.erase()
				if rows < 120:
					rows += 2
				else:
					rows = 20
				for r in range(1, rows):
					for ang in range(0, 360):
						x = int(titleScreen.width/2 + r*cos(radians(ang)))
						y = int(titleScreen.height/2 + r*sin(radians(ang)))
						if titleScreen.winObj.enclose(y, x):	# check that provided coords are in window, so no error`
							try:
								titleScreen.winObj.addch(y, x, ord('@'), curses.color_pair(var))
							except:
								pass
		

					if var < 7:
						var += 1
					else:
						var = 1

				titleScreen.winObj.addnstr(int(titleScreen.height/2), int(titleScreen.width/2), "Get ready for Fun game!!!", 40, curses.color_pair(4))
				titleScreen.winObj.addnstr(int(titleScreen.height/2)+1, int(titleScreen.width/2), "Press t to start!", 40, curses.color_pair(4))

				if stdscr.getch() == ord('t'):
					startAnim = not startAnim


				titleScreen.winObj.border()	# use default lines, and corners	
				titleScreen.winObj.refresh()
				stdscr.refresh()


			else:
	#			Clear screen so to draw next frame; future performance; draw only whats req
				mainWin.winObj.erase()

#				Draw player:
				if mainWin.winObj.enclose(newPlayer.yPos, newPlayer.xPos):	# check that provided coords are in window, so no error`
					mainWin.winObj.addch(newPlayer.yPos, newPlayer.xPos, ord('@'), curses.A_STANDOUT)
#				Draw Enemies:
				for i in range(1, 20, 2): 
					if mainWin.winObj.enclose( newGame.enemies[i], newGame.enemies[i-1]):
						mainWin.winObj.addch(newGame.enemies[i], newGame.enemies[i-1], ord('e'))
				for i in range(1, 20, 2): 
					if(newGame.enemies[i] + 2 < curses.LINES - 1):
						toadd += 0.0001
						newGame.enemies[i] += int(toadd)
					else:
						startAnim = not startAnim
#				statsWin.winObj.addnstr(y, x, str, n[, attr])
				statsWin.winObj.addnstr(1, 1, newPlayer.playerName, 10, curses.color_pair(4))
				statsWin.winObj.addnstr(2, 1, "Health:"+str(newPlayer.hitPoints), 20, curses.color_pair(4))
				statsWin.winObj.addnstr(3, 1, "Damage:", 10, curses.color_pair(4))

						
				mapWin.winObj.addnstr(1, 1, "Map", 10, curses.color_pair(5))
				mapWin.winObj.vline(1, int(mapWin.width/2), '=', int(mapWin.height - 2))


		#		mainWin.winObj.border('x','x','x','x','*','*','*','*')	# ls, rs, ts, bs, tl, tr, bl, br	
				mainWin.winObj.border()	# use default lines, and corners	
#				mainWin.winObj.box(1, 160)
				statsWin.winObj.border('x','x','x','x','*','*','*','*')	# ls, rs, ts, bs, tl, tr, bl, br	
				mapWin.winObj.border('x','x','x','x','*','*','*','*')	# ls, rs, ts, bs, tl, tr, bl, br	
#				ammoStatusWin.winObj.border('x','x','x','x','*','*','*','*')	# ls, rs, ts, bs, tl, tr, bl, br	

# 				Key input needs to be in another thread, bcs waiting for prog to get out of nap
				if stdscr.getch() == ord('a'):
					if newPlayer.xPos > 0:
						newPlayer.xPos -= 10
				if stdscr.getch() == ord('d'):
					if newPlayer.xPos < hudXPos:
						newPlayer.xPos += 10
				if stdscr.getch() == ord('w'):
					if newPlayer.yPos > 0:
						newPlayer.yPos -= 10
					else:
						newGame.advLvl()
				if stdscr.getch() == ord('s'):
					if newPlayer.yPos < curses.LINES - 1:
						newPlayer.yPos += 10
				if stdscr.getch() == ord('t'):
					startAnim = not startAnim

				# Collision detect, if x = x, y = y

				mainWin.winObj.refresh()
				statsWin.winObj.refresh()
				mapWin.winObj.refresh()
				stdscr.refresh()
				curses.napms(100);		# draw every second
				
		else:	# Draw title screen
			titleScreen.winObj.addnstr(1, 1, "Enter your name: ", 30, curses.color_pair(5))
			titleScreen.winObj.addnstr(2, 1, "Press Ctrl-G when done.", 30, curses.color_pair(5))
			titleScreen.winObj.border()	# use default lines, and corners	
			titleScreen.winObj.refresh()

#			User edits until press ctrl-g:
			box.edit()
			newPlayer.setName(box.gather())
			newGame.startNewGame()
	
#			done enter name, set max level
			titleScreen.winObj.border()	# use default lines, and corners	
			titleScreen.winObj.refresh()
			stdscr.refresh()

		curses.napms(100);		# draw every second
	curses.endwin()			# deinit curses,& return terminal to previous state;echo,cbreak,keypad
Example #54
0
def processWindow(window):

    global windowStack
    global allWindows
    global assetInfo

    mainWindow.refresh()

    if window.typeWin == "menu":

        window.cursesObj.border()
        fourArrowUI(window)
        ignore = window.menu.data[window.userPos[1]]
        if ignore == "Settings" or ignore == "Find Orderbook":
            processWindow(window)
        windowStack.append(allWindows[window.menu.dataHref[window.userPos[1]]])
        processWindow(windowStack[len(windowStack) - 1])

    elif window.typeWin == "allOrderbooks":

        # allOrderbooksBar.userPos=[-1,0]
        # allOrderbooksBar.menu.updateMenu()

        popupSelection = None
        pad = window.children["pads"]["menu"]
        pad.menu = padMenu(pad, [[22, 95], [0, 1]], [22, 0], [1, 48], assetInfo, None, ["name", "asset"])
        pad.menu.initDataFormat()

        while popupSelection != "Confirm":  # get rid of this

            drawAllOrderbooksDefaults(window)
            baseRel = []
            assetCounter = 0
            counter = 0
            while len(baseRel) < 2:  # get rid of
                currentChild = window.childrenList[counter]
                currentChild.userPos = currentChild.prevUserPos
                if fourArrowUI(currentChild) == -2:  # handle this somewhere else
                    currentChild.prevUserPos = currentChild.userPos
                    currentChild.userPos = [-1, 0]
                    currentChild.menu.updateMenu()
                    counter = counter + 1 if counter < len(window.childrenList) - 1 else 0
                elif currentChild.typeWin == "allOrderbooksBar":
                    barSelection = currentChild.menu.data[currentChild.userPos[1]]
                    if barSelection == "Add":
                        popup = cPopup()  # merge popup calls
                        popup.popupAddAsset()
                        popup.showPanel()
                        assetIDBox = Textbox(popup.assetIDInputWin)
                        assetNameBox = Textbox(popup.assetNameInputWin)
                        while True:
                            curses.curs_set(0)  # merge
                            fourArrowUI(popup)
                            curses.curs_set(1)
                            popupSelection = popup.menu.data[popup.userPos[0]]
                            if popupSelection == "Asset ID:":
                                assetIDBox.edit()
                            elif popupSelection == "Asset Name:":
                                assetNameBox.edit()
                            else:
                                assetID = assetIDBox.gather()
                                assetName = assetNameBox.gather()
                                popup.popStack()
                                curses.curs_set(0)
                                if len(assetID) and len(assetName):
                                    assetInfo.append({"name": assetName, "asset": assetID})
                                    tempList = sorted(assetInfo, key=operator.itemgetter("name"))
                                    assetInfo = tempList
                                    with io.open("assetInfo2.txt", "w", encoding="utf-8") as f:
                                        f.write(
                                            unicode(json.dumps(assetInfo, sort_keys=True, indent=4, ensure_ascii=False))
                                        )
                                    curses.flash()
                                processWindow(window)

                elif currentChild.typeWin == "allOrderbooksList":
                    baseRel.append(
                        currentChild.menu.data[
                            currentChild.userPos[1] * currentChild.menu.maxRows + currentChild.userPos[0]
                        ]
                    )

            if baseRel[0] == baseRel[1]:
                popup = cPopup()
                popup.popupErrorMessage("Base Asset and Rel Asset must be different!")
            else:
                popup = cPopup()
                popup.popupViewOrderbook(baseRel[0], baseRel[1])

            popup.showPanel()
            fourArrowUI(popup)
            popupSelection = popup.menu.data[popup.userPos[1]]
            popup.popStack()

        window.cursesObj.clear()
        window.cursesObj.refresh()
        windowStack.pop()
        orderbook = allWindows["orderbook"]
        orderbook.initBook(baseRel[0], baseRel[1])
        windowStack.append(orderbook)
        processWindow(windowStack[len(windowStack) - 1])

    elif window.typeWin == "activeOrderbooks":

        popupSelection = None
        pad = window.children["pads"]["activeOrderbooksPad"]

        retdata = getAllOrderbooks(bit)
        if not "orderbooks" in retdata or not len(retdata["orderbooks"]):
            pad.menu = padMenu(pad, [[20, 98], [0, 1]], [1, 1], [1, 25], ["No active orderbooks"])
        else:
            allObooks = retdata["orderbooks"]
            tempSort = sorted(allObooks, key=operator.itemgetter("exchange"))
            allObooks = tempSort
            pad.menu = padMenu(
                pad,
                [[21, 98], [0, 1]],
                [len(allObooks), 1],
                [1, 25],
                allObooks,
                None,
                ["base", "rel", "numquotes", "exchange"],
            )
        pad.menu.initDataFormat()

        drawActiveOrderbooksDefaults(window)
        counter = 0
        while True:
            currentChild = window.childrenList[counter]
            currentChild.userPos = currentChild.prevUserPos
            if fourArrowUI(currentChild) == -2:
                currentChild.prevUserPos = currentChild.userPos
                currentChild.userPos = [-1, 0]
                currentChild.menu.updateMenu()
                counter = counter + 1 if counter < len(window.childrenList) - 1 else 0
            elif currentChild.typeWin == "activeOrderbooksBar":
                continue
            elif currentChild.typeWin == "activeOrderbooksPad":
                menuData = currentChild.menu.data[currentChild.userPos[0]]
                baseAsset = {"name": menuData["base"], "asset": menuData["baseid"]}
                relAsset = {"name": menuData["rel"], "asset": menuData["relid"]}
                popup = cPopup()  # merge
                popup.popupViewOrderbook(baseAsset, relAsset)
                popup.showPanel()
                fourArrowUI(popup)
                popupSelection = popup.menu.data[popup.userPos[1]]
                popup.popStack()
                if popupSelection == "Confirm":
                    window.cursesObj.clear()
                    window.cursesObj.refresh()
                    windowStack.pop()
                    orderbook = allWindows["orderbook"]
                    orderbook.initBook(baseAsset, relAsset)
                    windowStack.append(orderbook)
                    processWindow(windowStack[len(windowStack) - 1])
                else:
                    processWindow(window)

    elif window.typeWin == "orderbook":

        drawOrderbookDefaults(window)

        counter = 0
        while True:
            currentChild = window.childrenList[counter]
            currentChild.userPos = currentChild.prevUserPos
            if fourArrowUI(currentChild) == -2:  # merge
                currentChild.prevUserPos = currentChild.userPos
                currentChild.userPos = [-1, 0]
                currentChild.menu.updateMenu()
                counter = counter + 1 if counter < len(window.childrenList) - 1 else 0
            elif currentChild.typeWin == "orderbookBar":
                barSelection = currentChild.menu.data[currentChild.userPos[1]]
                if barSelection == "Refresh":
                    window.initBook(window.baseAsset, window.relAsset)
                    curses.flash()
                    processWindow(window)
                elif barSelection == "Flip":
                    window.initBook(window.relAsset, window.baseAsset)
                    curses.flash()
                    processWindow(window)
            elif currentChild.typeWin == "placeOrderWindow":
                placeOrderType = currentChild.menu.data[currentChild.userPos[0]]
                popup = cPopup()  # merge popup calls
                popup.popupPlaceOrder(placeOrderType)
                popup.showPanel()
                priceBox = Textbox(popup.priceInputWin)
                amountBox = Textbox(popup.amountInputWin)
                while True:
                    curses.curs_set(0)  # merge
                    fourArrowUI(popup)
                    curses.curs_set(1)
                    popupSelection = popup.menu.data[popup.userPos[0]]
                    successFlash = False
                    if popupSelection == "Price":
                        priceBox.edit()
                    elif popupSelection == "Amount":
                        amountBox.edit()
                    else:
                        price = priceBox.gather()
                        amount = amountBox.gather()
                        curses.curs_set(0)
                        if len(price) and len(amount):
                            retdata = placeOrder(
                                bit, window.baseAsset["asset"], window.relAsset["asset"], price, amount, placeOrderType
                            )
                            if "result" in retdata and retdata["result"] is not None:
                                successFlash = True  # success?
                            else:
                                pass  # error?
                        window.initBook(window.baseAsset, window.relAsset)
                        popup.popStack()
                        if successFlash:
                            curses.flash()
                        processWindow(window)
            elif currentChild.typeWin == "bidPad":
                continue
            elif currentChild.typeWin == "askPad":
                continue

    elif window.typeWin == "openOrders":

        pad = window.children["pads"]["openOrdersPad"]
        pad.menu = openOrdersMenu(pad, [[24, 95], [0, 1]], [10, 10], [7, 70], assetInfo, None, ["name", "asset"])
        pad.menu.initDataFormat()

        # rectangle(window.cursesObj, 3,3,12,72)
        # rectangle(window.cursesObj, 14,3,23,72)

        drawOpenOrdersDefaults(window)

        while True:
            fourArrowUI(pad)
Example #55
0
    def display(self):
        s = curses.initscr()
        curses.noecho()
        curses.curs_set(0)
        s.timeout(1000)
        s.border(0)

        h,w = s.getmaxyx()
        signal.signal(signal.SIGINT, self.sig_handler)
        s.clear()
       
        #first line
        s.addstr(1, 2, 'statsquid top -')
        s.addstr(1, 18, datetime.now().strftime('%H:%M:%S'))
        s.addstr(1, 28, ('%s containers' % len(self.display_stats)))
        if self.filter:
            s.addstr(1, 42, ('filter: %s' % self.filter))

        #second line
        s.addstr(3, 2, "NAME", curses.A_BOLD)
        s.addstr(3, 25, "ID", curses.A_BOLD)
        s.addstr(3, 41, "CPU", curses.A_BOLD)
        s.addstr(3, 48, "MEM", curses.A_BOLD)
        s.addstr(3, 58, "NET TX", curses.A_BOLD)
        s.addstr(3, 68, "NET RX", curses.A_BOLD)
        s.addstr(3, 78, "READ IO", curses.A_BOLD)
        s.addstr(3, 88, "WRITE IO", curses.A_BOLD)
        s.addstr(3, 98, "SOURCE", curses.A_BOLD)

        #remainder of lines
        line = 5
        maxlines = h - 2
        for stat in self.display_stats:
            s.addstr(line, 2,  stat['name'][:20])
            s.addstr(line, 25, stat['id'][:12])
            s.addstr(line, 41, str(stat['cpu']))
            s.addstr(line, 48, format_bytes(stat['mem']))
            s.addstr(line, 58, format_bytes(stat['net_tx_bytes_total']))
            s.addstr(line, 68, format_bytes(stat['net_rx_bytes_total']))
            s.addstr(line, 78, format_bytes(stat['io_read_bytes_total']))
            s.addstr(line, 88, format_bytes(stat['io_write_bytes_total']))
            s.addstr(line, 98, stat['source'])
            if line >= maxlines:
                break
            line += 1
        s.refresh()

        x = s.getch()
        if x == ord('q'):
            curses.endwin()
            sys.exit(0)

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

            s.addstr(6, startx+1, 'statsquid top version %s' % version)
            s.addstr(8, startx+1, 'c - toggle between cumulative and current view')
            s.addstr(9, startx+1, 's - select sort field')
            s.addstr(9, startx+1, 'r - reverse sort order')
            s.addstr(10, startx+1, 'f - filter by container name')
            s.addstr(11, startx+5, '(e.g. source:localhost)')
            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('c'):
            self.sums = not self.sums

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

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

            #format field names for readable output
            opts = list(self.keys.keys())
            fmt_opts = [k.replace('_',' ').replace('total','') for k in opts]

            selected = run_menu(tuple(fmt_opts),x=startx,y=6,name="sort")
            self.sort['key'] = opts[selected]

        if x == ord('f'):
            startx = 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, 12,(startx+1))
            rectangle(s, 11,startx, 13,(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)
            
            #check if valid filter
            if not self._validate_filter():
                self.filter = None
                s.clear()
                s.addstr(6, startx+5, 'Invalid filter')
                s.refresh()
                curses.napms(800)