예제 #1
0
    def deleteTask(self,results):
        validids = []
        self.stdscr.clear()
        self.stdscr.addstr(0,6,"Select an ID to Delete", curses.color_pair(2))
        i = 1
        for elem in results:
            # Task ID
            self.stdscr.addstr(i,1,"Task ID: ",curses.color_pair(2))
            self.stdscr.refresh()
            y,x = curses.getsyx() # Colorize label only
            self.stdscr.addstr(i,x,"{}".format(elem[0]))
            validids.append(elem[0])
            # Task Body
            body = elem[5].replace('\n', '').replace('\r', '')

            self.stdscr.addstr(i+1,1,"Task: ",curses.color_pair(2))
            self.stdscr.refresh()
            y,x = curses.getsyx()
            self.stdscr.addstr(i+1,x,"{}".format(body))

            self.stdscr.refresh()
            y,x = curses.getsyx()
            i = y + 2

        self.stdscr.addstr(y+2,2,"Enter the ID of the task you wish to delete")
        self.stdscr.refresh()
        userval = self.stdscr.getstr(y+3,2,4)
        self.validID(validids, userval)
예제 #2
0
파일: iptap.py 프로젝트: CatN/usertap
def get_input(screen, title, numeric = False):
	
	position = curses.getsyx()
	screen.addstr(position[0] + 1, 0, "{0}: ".format(title));
	chars = ""
		
	while 1:
		
		try:
			x = screen.getch()
		except KeyboardInterrupt:
			break
			
		if x >= 46 and x <= 57:
			add = curses.getsyx()
			screen.addstr(add[0], add[1], "{0}".format(chr(x)))
			chars += chr(x)
			
		if x == 127:
			if len(chars) > 0:
				remove = curses.getsyx()
				screen.delch(remove[0], (remove[1] - 1))
				chars = chars[:-1]
		
		if x == 10:
			break
	
	if numeric:
		try:
			return int(chars)
		except:
			return 0
	else:
		return chars
예제 #3
0
def main():
    global stdscr
    try:
        global filelist
        # get the file list before initCurses, because opening a pipe
        # after curses is initialized causes Cygwin to hang
        filelist = getFileList()
        initCurses()

        redraw()

        y,x = curses.getsyx()
        stdscr.move(0,1)
        while 1:
            c = stdscr.getch()
            logging.debug(c)
            if c == ord('q'): break  # Exit the while()
            elif c == curses.KEY_UP: 
                logging.debug("KEYUP!")
                move(-1)
            elif c == curses.KEY_DOWN : 
                logging.debug("KEYDOWN")
                move(1)
            elif c == ord(' '):
                logging.debug("SPACE")
                toggleChecked(currentLine)
                move(1)
            elif c == ord('a'):
                y,x = curses.getsyx()
                checkall()
                redraw()
                stdscr.move(y,x)
            elif c == ord('u'):
                y,x = curses.getsyx()
                checkall(False)
                redraw()
                stdscr.move(y,x)
            elif c == curses.KEY_RIGHT: 
                logging.debug("KEY_RIGHT")
                move(getMaxLines())
            elif c == curses.KEY_LEFT: 
                logging.debug("KEY_LEFT")
                move(-getMaxLines())
            elif c == curses.KEY_ENTER or c == 10:
                logging.debug("KEY_ENTER")
                curses.def_prog_mode()
                curses.endwin()
                os.system('clear && svn diff "' + filelist[currentLine]["file"] + '" --diff-cmd=colordiff | less -r')
                stdscr.refresh()
            elif 0 <= c <= 256 and chr(c).isdigit():
                destination = 10
                if chr(c) != 0:
                    destination = int(chr(c)) - 1
                gotoPage(destination)

    except Exception as err:
        logging.error(err)
    cleanupCurses()
    print(' '.join(f["file"] for f in filelist if f["checked"]))
예제 #4
0
        def putline(self, message, color = "NORM", scroll = True):
            """Scroll the window and write the message on the bottom line.

            Positional parameters:
            message -- The message (a string)
            color   -- The color of the message("NORM", "ALERT", "WARN", "GREEN")
            scroll  -- Scroll window before writing
            """
            self.__logger.debug("subwin %s: writing \"%s\"", self.name, message)
            cy, cx = curses.getsyx()
            target = self.window
            if scroll:
                target.scroll()
            try:
                target.addnstr(
                    self.bottomline,
                    self.firstcol,
                    message,
                    self.winwidth,
                    curses.color_pair(self.colors[color]))
            except:
                self.__logger.error(
                    "subwin %s: addnstr(%s, %s, %s, %s, %s) failed",
                    self.name,
                    self.bottomline,
                    self.firstcol,
                    message,
                    self.winwidth,
                    curses.color_pair(self.colors[color]))
                sys.exit(1)
            target.noutrefresh()
            curses.setsyx(cy, cx)
            curses.doupdate()
예제 #5
0
def move(window, display_function, smaxrow, offset, operation_string):
    """Select previous or next item in list.
    
    :param window: Curses pad object where movement will occur.
    :param display_function: Function to display the list.
    :param smaxrow: Last row of pad being displayed.
    :param offset: Current offset of this pad.
    :param operation_string: 'add' or 'sub', for moving down or up, 
                             respectively

    Calculate the next item index and display list, with that item selected. 
    Return the new offset.
    """
    if len(items) < 2:
        return offset
    # operation_string is either 'add' or 'sub'
    operation = getattr(operator, operation_string)
    # Locate current item
    sminrow, smincol = window.getbegyx()
    y, x = curses.getsyx()
    old_index = offset + y - sminrow
    # Tentatively select next index
    new_index = offset + operation(y, 1) - sminrow
    # Check new index validity
    if not 0 <= new_index < len(items):
        offset = len(items) - smaxrow + sminrow - 1 if new_index < 0 else 0
        # offset is negative if number of tasks is lower than task pad height
        offset = max(offset, 0)
        new_index = new_index % len(items)
    # If next item is not in visible part of the pad, adjust offset
    elif not sminrow <= operation(y, 1) <= smaxrow:
        offset = operation(offset, 1)
    display_function(offset=offset, selected=new_index)
    return offset
예제 #6
0
def show_details(task):
    """Show details of selected task.

    :param task: :class:`Task` object corresponding to the selected item 

    Write details of selected task to the details window.

    """
    details_win.clear()
    if not task:
        details_win.refresh()
        return 0
    # Locate cursor so it can be returned to this position later
    y, x = curses.getsyx()
    # Write task variables to details window
    date = date_parser.parse(task.date)
    details_win.addstr(0, 0, date.strftime("%d/%m/%Y"))
    details_win.addstr(1, 0, task.summary, curses.A_BOLD)
    details_win.addstr(2, 0, task.description)
    details_win.addstr(3, 0, task.status)
    details_win.addstr(4, 0, format_seconds(task.logged_time))
    details_win.refresh()
    # Move cursor to previous position
    stdscr.move(y, x)
    stdscr.refresh()
예제 #7
0
def done_task(offset):
    """Mark task done.

    Change selected task's status to 'completed', remove it from the task list
    and synchronize the items dictionary.
    """
    global items
    # Locate the done task
    y, x = curses.getsyx()
    sminrow, smincol = task_pad.getbegyx()
    item = offset + y - sminrow
    # Remove the task from the task list and mark it completed
    try:
        task = items.pop(item)
    except KeyError:
        return 0
    task.status = 'completed'
    task_list.write_tasks()
    # Select the next item in the list, if there is one
    if item < len(items):
        selected = item
    # Otherwise, select previous item, if there is one
    else:
        selected = item - 1 if item > 0 else 0
        # Adjust offset if y is in the first row of the visible pad
        if y == sminrow:
            offset -= 1
    tasks = items.values()
    items = sync_items(tasks)
    draw_tasks(offset=offset, selected=selected)
    write_status("Done task: %s" % task)
    return offset
예제 #8
0
 def refresh_thread(self):
     while True:
         time.sleep(1.0)
         cur_pos = curses.getsyx()
         self.feedback.draw()
         curses.setsyx(*cur_pos)
         curses.doupdate()
예제 #9
0
def makeGuess(x, y):
	# This part is a test just for the first guess, could probably all be reworked later
	if (x != -1 and y != -1):
		screen.move(y, x)
	else:
		coord = curses.getsyx()
		y = coord[0]
		x = coord[1]

	# Simple boundary checking
	while True: 
		event = screen.getch() 
		if event == ord('w') or event == ord('W'): 
			if y > 7:
				y = y - 1
			screen.move(y,x)
		elif event == ord('a') or event == ord('A'): 
			if x > 4:
				x = x - 2
			screen.move(y,x)
		elif event == ord('s') or event == ord('S'): 
			if y < 16:
				y = y + 1
			screen.move(y,x)
		elif event == ord('d') or event == ord('D'): 
			if x < 22:
				x = x + 2
			screen.move(y,x)
		elif event == ord('e') or event == ord('E'):
			return (x, y, False)
		elif event == ord('f') or event == ord('F'):
			return (x, y, True)
		elif event == ord('q') or event == ord('Q'):
			curses.endwin()
			quit(1)
예제 #10
0
파일: main.py 프로젝트: tubesandlube/pareto
def initialize():
    curses.initscr()
    win = curses.newwin(24, 80, 0, 0)
    win.keypad(1)
    curses.noecho()
    curses.curs_set(0)
    win.border(0)
    win.nodelay(1)

    key = KEY_RIGHT
    git_handle = []

    win.addstr(0, 2, ' Login ')
    win.addstr(0, 36, ' PARETO ')
    win.addstr(12, 31, ' GitHub Username: '******'\n'):
        y,x=curses.getsyx()
        #win.addstr(12, 48+len(git_handle), curses.A_REVERSE)
        event = win.getch()
        if event != -1:
            prevKey = key
            try:
                git_handle.append(chr(prevKey))
            except:
                # not a printable ascii character
                pass
            key = event
            curses.setsyx(y,x+1)
            curses.doupdate()

    #if key == 27:
    #    curses.endwin()
    curses.endwin()
    print "git handle:", "".join(git_handle)
예제 #11
0
	def put_message(self, msg):
		y, x = curses.getsyx()
		self._erase_messages()
		self.messages.insert(0, msg)
		self._draw_messages()
		self.scr.move(y,x)
		self.scr.refresh()
예제 #12
0
 def RenderStatus(self, inWindow, inText):
     (cursY, cursX) = curses.getsyx() # Store cursor position
     inWindow.Win().erase()
     inWindow.AddText(inText, 0, 0)
     inWindow.Refresh()
     if cursX != -1 and cursY != -1:
         curses.setsyx(cursY, cursX) # Restore cursor position
예제 #13
0
def main(stdscr):
    
    stdscr.clear()
    while True:
        ch = stdscr.getch()
        csr_pos = curses.getsyx() #cursor position
        if ch == ord('`'):
            stdscr.addstr(curses.LINES-1, 0, chr(ch))
            menu(stdscr)
예제 #14
0
def noise(window):
    mid, mx, my, mz, mbstate = 0, 0, 0, 0, 0
    ymax, xmax = window.getmaxyx()
    window.timeout(0)  # Nonblocking gets, 0 in ms
    t0 = time()
    tot = 0
    window.addch(ymax-7, 24, curses.ACS_LARROW)
    window.hline(ymax-7, 25, curses.ACS_HLINE, 10)
    window.addstr(ymax-7, 36, "click this box, or press h, or q")
    win2 = curses.newwin(12, 21, ymax-13, 1)
    win2.box()
    win2.keypad(1)
    win2.nodelay(1)
    win2.border()
    win2.leaveok(0)
    win2.scrollok(0)
    win2.bkgd(' ', 0)
    win2_inv = False
    while True:
        t1 = time()
        tot += 1
        ups = tot/(t1-t0)
        x = randint(1, randint(1, xmax - 2))
        y = randint(1, randint(1, ymax - 2 - 12))
        c = ord('#')
        getch = window.getch() 
        if getch == curses.KEY_MOUSE or getch == ord('h'):
            tmid, tmx, tmy, tmz, tmbstate = curses.getmouse()
            if getch == ord('h') or tmbstate == 2 and win2.enclose(tmy, tmx):
                mid, mx, my, mz, mbstate = tmid, tmx, tmy, tmz, tmbstate
                if win2_inv:
                    win2.attroff(curses.A_REVERSE)
                else:
                    win2.attron(curses.A_REVERSE)
                win2_inv = not win2_inv
        elif getch == ord('q'):
            raise SystemExit(None)
        window.addch(y, x, c)
        window.noutrefresh()  # Mark for update

        ylst, xlst = curses.getsyx()
        win2.addstr(12-11, 1, "tot   :%12i" % tot)
        win2.addstr(12-10, 1, "#/s   :%12.3f" % ups)
        win2.addstr(12-9,  1,  "t tot :%12.3f" % (t1-t0))
        win2.addstr(12-8,  1,  "y lst :%12i" % ylst)
        win2.addstr(12-7,  1,  "x lst :%12i" % xlst)
        win2.addstr(12-6,  1,  "m id  :%12i" % mid)
        win2.addstr(12-5,  1,  "m x   :%12i" % mx)
        win2.addstr(12-4,  1,  "m y   :%12i" % my)
        win2.addstr(12-3,  1,  "m z   :%12i" % mz)
        win2.addstr(12-2,  1,  "m st  :%12i" % mbstate)
        win2.noutrefresh()

        #sleep(1/100000.)
        curses.doupdate()  # Perform refreshes
        continue
    def set_screen(self, scr):
        height, width = self.screen_size = YX(*scr.getmaxyx())
        self.pad = curses.newpad(height, width * 2)
        self.pad_size = YX(*self.pad.getmaxyx())

        self.body_height = max(0, height - self.footer_height)
        self.margin_height = self.body_height // 5

        self.screen_csr = Index(height)
        self._screen_csr_set_pos(curses.getsyx()[0])
예제 #16
0
 def move_cursor(self, direction):
     maxx, maxy = self.screen.getmaxyx()
     x, y = curses.getsyx()
     if direction[0] == 1 and x < maxx:
         curses.setsyx(x+1, y)
     elif direction[0] == -1 and x > 0:
         curses.setsyx(x-1, y)
     elif direction[1] == 1 and y < maxy:
         curses.setsyx(x, y+1)
     elif direction[1] == -1 and y > 0:
         curses.setsyx(x, y-1)
예제 #17
0
def get_input(prompt_string):
    """Read input string from user."""
    y, x = curses.getsyx()
    curses.echo()
    curses.curs_set(1)
    write_status(prompt_string)
    input_string = status_bar.getstr(0, len(prompt_string))
    curses.noecho()
    curses.curs_set(0)
    stdscr.move(y, x)
    stdscr.refresh()
    return input_string
예제 #18
0
def current_item(window, offset):
    """Find current item.

    :param offset: Current offset

    Get current y and first row of window; use offset to calculate item.
    
    """
    y, x = curses.getsyx()
    sminrow, smincol = window.getbegyx()
    item = offset + y - sminrow
    return item
예제 #19
0
def printLambdaFinal(Lambda_current):

    stdscr = initialiseDisplay()
    printLambdaFlags(stdscr,Lambda_current)
    y,x = curses.getsyx()
    stdscr.addstr(y+2,0,"Press 'q' to return to the console")
    stdscr.refresh() 
    key = ''
    while key != ord('q'):
        key = stdscr.getch()
    stdscr.clear()
    killDisplay()
 def clear_err(self):
     '''Clear error text and mark this window inactive
     
     Restores cursor location after updating
     '''
     if self.visible:
         cursor_loc = curses.getsyx()
         self.clear()
         self.make_inactive()
         curses.setsyx(cursor_loc[0], cursor_loc[1])
         curses.doupdate()
         self.visible = False
예제 #21
0
def waitToKill(stdscr):

    key = ''
    
    y,x = curses.getsyx()
    stdscr.addstr(y+10,0,"Press 'q' to return to the console")
    stdscr.refresh()

    while key != ord('q'):
        key = stdscr.getch()
    
    stdscr.clear()
    killDisplay()
예제 #22
0
 def _print_msg(self, i, msg, x=None, y=None, color=None):
     num_wigth = 4
     if not color:
         color = curses.color_pair(3)
     if not x or not y:
         y, x = curses.getsyx()
     w = self.max_x - x
     h = len(msg)/(w - num_wigth) + 1
     msg_win = curses.newwin(h, w, y, x)
     msg_win.border(1)
     msg_win.addstr(0, 0, msg, curses.color_pair(3))
     # msg_win.noutrefresh()
     msg_win.refresh()
예제 #23
0
 def update_load_bar(self, actual, maxi):
     import math
     max_len = curses.COLS - 15
     actual_len = int(actual * max_len / maxi)
     percent = str(math.floor(actual_len * 100 / max_len))
     message = sfill(actual_len, '█')
     currenty, currentx = curses.getsyx()
     self.statscr.move(1, 7)
     self.statscr.clrtoeol()
     self.statscr.addstr(1, 8, percent + " %")  # Show percentage
     self.statscr.addstr(1, 14, message)  # Show load bar
     self.statscr.refresh()
     curses.setsyx(currenty, currentx)
예제 #24
0
 def update_status(self, value):
     """Update the status window content"""
     currenty, currentx = curses.getsyx()
     self.statscr.move(1, 1)
     self.statscr.clrtoeol()
     if self.connected:
         self.statscr.addstr("-O-")
     else:
         self.statscr.addstr("-||-")
     self.statscr.addch(0, 6, curses.ACS_TTEE)
     self.statscr.addch(1, 6, curses.ACS_VLINE)
     self.statscr.addstr(1, 8, value)
     self.statscr.refresh()
     curses.setsyx(currenty, currentx)
 def flash(self):
     '''Flash this error window'''
     if self.visible:
         cursor_loc = curses.getsyx()
         flash_color = self.highlight_color ^ curses.A_REVERSE
         self.set_color(flash_color)
         curses.setsyx(cursor_loc[0], cursor_loc[1])
         curses.doupdate()
         gotch = self.window.getch()
         if gotch != -1:
             curses.ungetch(gotch)
         self.set_color(self.highlight_color)
         curses.setsyx(cursor_loc[0], cursor_loc[1])
         curses.doupdate()
예제 #26
0
def write_status(status):
    """Write text in status bar.

    :param status: String of text to be written in the status bar

    After writing the provided text in the status bar, return cursor to its 
    previous location.

    """
    y, x = curses.getsyx()
    status_bar.clear()
    status_bar.addstr(str(status))
    status_bar.refresh()
    stdscr.move(y, x)
    stdscr.refresh()
예제 #27
0
    def refresh(self):
        syx = curses.getsyx()
        self.wname.clear()
        self.wtext.clear()
        
        (my, mx) = self.wtext.getmaxyx()
        my -= 1
        
        y = 0
        for i, s in enumerate(self.timeline[self.offset:]):
            # escape illegal character
            text = ctools.delete_notprintable(s.text)
            
            cnt = ctools.cw_count(text)
            row = int(math.ceil(float(cnt) / float(mx)))
            rem = my - y
            xmod = cnt % mx
            
            if row > rem:
                s = copy.copy(s)
                text = ctools.split_text(text, (rem * mx) - 1)[0]
            
            attr = ctools.attr_select(s, self.twitter.my_name)
            
            if self.selected == i:
                attr |= curses.A_STANDOUT
                if xmod != 0:
                    text += " " * (mx - xmod)
            
            try:
                self.wname.addstr(y, 0, s.user.screen_name[:9], attr)
                self.wtext.addstr(y, 0, text.encode(self.CENCODING), attr)
            except:
                curses.endwin()
                print s.user.screen_name, text
                print ["%x %s" % (ord(c), c)
                       for c in text]

            y += row
            if y >= my: 
                self.last = i
                break
        
        self.wname.refresh()
        self.wtext.refresh(*self.wtext_refp)
        
        curses.setsyx(*syx)
        self.on_refresh()
예제 #28
0
파일: base.py 프로젝트: BitCrane/Tool_Box
 def update(self):
   # save cursor
   cy,cx = curses.getsyx()
   try:
     self.update_log()
     # run updates
     self.update_ui()
   except Exception as ex:
     self.log(str(ex))
   except:
     self.log("Unexpected Error")
   finally:
     self.refresh()
     # return cursor
     curses.setsyx(cy,cx)
     self.winput.refresh()
예제 #29
0
def outputToDash(ypos,xpos,output):

    stdscr = initialiseDisplay()
    stdscr.addstr(ypos,xpos,output) 
    stdscr.refresh()
    
    y,x = curses.getsyx()
    stdscr.addstr(y+10,0,"Press 'q' to return to the console")
    stdscr.refresh()
    
    key = ''

    while key != ord('q'):
        key = stdscr.getch()
    
    stdscr.clear()
    killDisplay()
 def display_err(self, text):
     '''Display error 'text'. Will also flash
     the error text if this box was already visible, to draw
     the user's attention to the new (or existing) error
     
     Restores cursor location after updating
     
     '''
     cursor_loc = curses.getsyx()
     self.clear()
     terminalui.LOGGER.debug("displaying err '%s'", text)
     self.add_text(fit_text_truncate(text, self.area.columns - 1),
                   centered=self.centered)
     self.make_active()
     curses.setsyx(cursor_loc[0], cursor_loc[1])
     curses.doupdate()
     if self.visible:
         self.flash()
     self.visible = True
예제 #31
0
def transferFile(file, presentUSB, choice):
    refresh()
    if choice == presentUSB[0]:
        destination = presentUSB[1]
    else:
        destination = presentUSB[0]
    astdprnt('Do you want to send ' + file + '?', curses.A_BOLD)
    stdprnt(' ')
    tbprnt('1) YES')
    tbprnt('0) NO')
    top = curses.getsyx()[0] - 2
    bottom = curses.getsyx()[0] - 1
    stdscr.move(top, 4)
    confirm = 0
    while True:
        confirm = stdscr.getch()
        if confirm != 10:
            if confirm == 259:
                if curses.getsyx()[0] > top:
                    stdscr.move(curses.getsyx()[0] - 1, 4)
            elif confirm == 258:
                if curses.getsyx()[0] < bottom:
                    stdscr.move(curses.getsyx()[0] + 1, 4)
            elif confirm == 260:
                escapeProg(findUSB())
            else:
                finalize(findUSB())
        elif curses.getsyx()[0] == bottom:
            return transferFile(
                chooseFile(
                    file[:len(file) - file[::-1].index('/') - 1],
                    listFile(file[:len(file) - file[::-1].index('/') - 1],
                             True)),
                findUSB()[1], choice)
        elif curses.getsyx()[0] == top:
            confirm = 1
            break
    if confirm == 1:
        stdprnt(' ')
        astdprnt('Do you want to Move or Copy?', curses.A_BOLD)
        stdprnt(' ')
        tbprnt('0) MOVE')
        tbprnt('1) COPY')
        copyMove = 0
        top = curses.getsyx()[0] - 2
        bottom = curses.getsyx()[0] - 1
        stdscr.move(top, 4)
        while True:
            copyMove = stdscr.getch()
            if copyMove != 10:
                if copyMove == 259:
                    if curses.getsyx()[0] > top:
                        stdscr.move(curses.getsyx()[0] - 1, 4)
                elif copyMove == 258:
                    if curses.getsyx()[0] < bottom:
                        stdscr.move(curses.getsyx()[0] + 1, 4)
                else:
                    finalize(findUSB())
            elif curses.getsyx()[0] == top:
                refresh()
                ctrprnt('Loading...', curses.A_BOLD)
                system("sudo mv '" + file + "' '" + destination + "'")
                finalize(findUSB())
            elif curses.getsyx()[0] == bottom:
                refresh()
                ctrprnt('Loading...', curses.A_BOLD)
                if path.isdir(file):
                    system("sudo cp -r '" + file + "' '" + destination + "'")
                else:
                    system("sudo cp '" + file + "' '" + destination + "'")
                finalize(findUSB())
예제 #32
0
 def fn(*args, **kwargs):
     curs_y, curs_x = curses.getsyx()
     results = f(screen, *args, **kwargs)
     screen.move(curs_y, curs_x)
     return results
예제 #33
0
 def fn(*args, **kwargs):
     curs_y, curs_x = curses.getsyx()
     f(*args, **kwargs)
     screen.move(curs_y, curs_x)
예제 #34
0
    def pop_up(self,
               header,
               question,
               left_btn_txt,
               right_btn_txt,
               color=None):
        '''Suspend the current screen, setting the header
        to 'header', presenting the 'question,' and providing two 'buttons'.
        Returns True if the RIGHT button is selected, False if the LEFT is
        selected. The LEFT button is initially selected.
        
        '''

        # Hide the cursor, storing its previous state (visibility) so
        # it can be restored when finished. Then, move the cursor
        # to the default position (in case this terminal type does not support
        # hiding the cursor entirely)
        try:
            old_cursor_state = curses.curs_set(0)
        except curses.error:
            old_cursor_state = 2
        cursor_loc = curses.getsyx()
        curses.setsyx(self.cursor_pos[0], self.cursor_pos[1])

        # Add the header, a border, and the question to the window
        self.popup_win.window.border()
        header_x = int((self.popup_win.area.columns - textwidth(header)) / 2)
        self.popup_win.add_text(header, 0, header_x)
        y_loc = 2
        y_loc += self.popup_win.add_paragraph(question, y_loc, 2)
        y_loc += 2

        # Set the background color based on the parameter given, or choose
        # a default based on the theme. Set the highlight_color by flipping
        # the A_REVERSE bit of the color
        if color is None:
            color = self.popup_win.color
        self.popup_win.set_color(color)
        highlight_color = color ^ curses.A_REVERSE

        # Create two "buttons" of equal size by finding the larger of the
        # two, and centering them
        max_len = max(textwidth(left_btn_txt), textwidth(right_btn_txt))
        left_btn_txt = " [ %s ]" % left_btn_txt.center(max_len)
        right_btn_txt = " [ %s ]" % right_btn_txt.center(max_len)
        button_len = textwidth(left_btn_txt) + 1
        win_size = self.popup_win.window.getmaxyx()
        left_area = WindowArea(1, button_len, y_loc,
                               int(win_size[1] / 2) - (button_len + 2))
        left_button = ListItem(left_area,
                               window=self.popup_win,
                               text=left_btn_txt,
                               color=color,
                               highlight_color=highlight_color)
        right_area = WindowArea(1, button_len, y_loc, int(win_size[1] / 2) + 2)
        right_button = ListItem(right_area,
                                window=self.popup_win,
                                text=right_btn_txt,
                                color=color,
                                highlight_color=highlight_color)

        # Highlight the left button, clear any errors on the screen,
        # and display the pop up
        self.popup_win.activate_object(left_button)
        self.popup_win.no_ut_refresh()
        self.error_line.clear_err()
        self.do_update()

        self._active_win = self.popup_win
        # Loop until the user selects an option.
        input_key = None
        while input_key != curses.KEY_ENTER:
            input_key = self.getch()
            input_key = self.popup_win.process(input_key)
            if input_key == curses.KEY_LEFT:
                self.popup_win.activate_object(left_button)
            elif input_key == curses.KEY_RIGHT:
                self.popup_win.activate_object(right_button)
            self.do_update()
        self._active_win = self.central_area
        user_selected = (self.popup_win.get_active_object() is right_button)

        # Clear the pop up and restore the previous screen, including the
        # cursor position and visibility
        self.popup_win.clear()
        self.central_area.redrawwin()
        curses.setsyx(cursor_loc[0], cursor_loc[1])
        try:
            curses.curs_set(old_cursor_state)
        except curses.error:
            pass
        self.do_update()

        return user_selected
예제 #35
0
def main(stdscr):
    key = 0
    cursor_x = 0
    cursor_y = 0

    stdscr.clear()
    stdscr.refresh()

    curses.initscr()
    curses.curs_set(0)
    curses.start_color()

    inter = interpreter.Interpreter()

    running = True
    lines = [Line(0)]
    current = 0

    while running:
        stdscr.clear()
        l = lines[current]
        w = l.current()
        height, width = stdscr.getmaxyx()

        if key == curses.KEY_LEFT:
            if l.c == 0:  # at start of line
                if current != 0:  # not at first line
                    current -= 1  # move up a line
            else:  # move back a word
                l.c -= 1

        elif key == curses.KEY_RIGHT:
            if l.c == len(l.words) - 1:
                if current != len(lines) - 1:
                    current += 1
            else:
                l.c += 1

        if key == curses.KEY_BACKSPACE:
            if w.text == "":
                if l.c != 0:
                    del w
                    w.c -= 1
                    l = lines[current]
            else:
                w.text = w.text[:-1]

        elif chr(key) == " ":
            pos = curses.getsyx()
            newpos = pos[0], pos[1] + 1
            l.words.append(Word(newpos))
            l.c += 1
            w = l.current()

        elif chr(key) in string.printable:
            w.text += chr(key)
        x = -1
        for t in l.words:
            if t == l:
                t.update(x)
                stdscr.attron(curses.A_REVERSE)
                t.render(stdscr)
                stdscr.attroff(curses.A_REVERSE)
                x = t.end
            else:
                t.update(x)
                t.render(stdscr)
                x = t.end

        stdscr.refresh()
        key = stdscr.getch()
예제 #36
0
def chooseFile(folder, fileList):
    global prints
    bottom = curses.getsyx()[0] - 2
    try:
        curses.setsyx(bottom, 0)
        curses.doupdate()
    except:
        pass
    pages = int(math.ceil(prints / height))
    topcornerY = (height * pages)
    filePos = len(fileList)
    while True:
        pos = pad.getyx()[0]
        time.sleep(0.2)
        if GPIO.input(enter) != False:
            if GPIO.input(up) == False:
                if filePos > 1:
                    if curses.getsyx()[0] == 0:
                        topcornerY -= height
                        curses.setsyx(height, 0)
                        pad.refresh(topcornerY, 0, 0, 0, height, width)
                    else:
                        curses.setsyx(curses.getsyx()[0] - 1, 0)
                        curses.doupdate()
                        filePos -= 1
            elif GPIO.input(down) == False:
                if filePos < len(fileList):
                    if curses.getsyx()[0] == height:
                        topcornerY += height
                        curses.setsyx(0, 0)
                        pad.refresh(topcornerY, 0, 0, 0, height, width)

                    else:
                        curses.setsyx(curses.getsyx()[0] + 1, 0)
                        curses.doupdate()
                        filePos += 1
            elif GPIO.input(back) == False:
                escapeProg(folder, fileList)
        else:
            break
    if path.isdir(folder + '/' + fileList[filePos - 1]):
        refresh()
        astdprnt('Open folder ' + fileList[filePos - 1] + '?', curses.A_BOLD)
        stdprnt(' ')
        tbprnt('1) YES')
        tbprnt('0) NO')
        top = curses.getsyx()[0] - 2
        bottom = curses.getsyx()[0] - 1
        stdprnt(' ')
        curses.setsyx(top, 4)
        curses.doupdate()
        while True:
            time.sleep(0.2)
            if GPIO.input(enter) != False:
                if GPIO.input(up) == False:
                    if curses.getsyx()[0] > top:
                        curses.setsyx(curses.getsyx()[0] - 1, 4)
                        curses.doupdate()
                elif GPIO.input(down) == False:
                    if curses.getsyx()[0] < bottom:
                        curses.setsyx(curses.getsyx()[0] + 1, 4)
                        curses.doupdate()
                elif GPIO.input(back) == False:
                    escapeProg(folder, fileList)
            elif curses.getsyx()[0] == top:
                return chooseFile(
                    folder + "/" + fileList[filePos - 1],
                    listFile(folder + "/" + fileList[filePos - 1], True))
            elif curses.getsyx()[0] == bottom:
                return folder + "/" + fileList[filePos - 1]
    else:
        return folder + "/" + fileList[filePos - 1]
예제 #37
0
파일: gui.py 프로젝트: pianomanx/arsenal
    def draw(self, stdscr):
        """
        Draw the arguments menu to ask them
        :param stdscr: screen
        """
        # init vars and set margins values
        self.height, self.width = stdscr.getmaxyx()
        self.AB_SIDE = 5
        padding_text_border = 3
        self.max_preview_size = self.width - (2 * self.AB_SIDE) - (
            2 * padding_text_border)

        # draw background cheatslist menu (clean resize)
        self.previous_menu.draw(stdscr)

        # draw argslist menu popup
        self.prev_lastline_len = 0
        nbpreviewnewlines = self.get_nb_preview_new_lines()
        # if Gui.cmd.nb_args != 0:
        #     nbpreviewnewlines = self.get_nb_preview_new_lines()
        # else:
        #     nbpreviewnewlines = 0

        # -------------- border
        # cmd
        # nbpreviewnewlines
        # .............. args margin top
        # args
        # ------
        # description
        # .............  description margin
        # ---------- border

        # width - preview
        ncols = self.width - 2 * self.AB_SIDE

        # prepare showed description
        description_lines = Gui.cmd.get_description_cut_by_size(
            ncols - (padding_text_border * 2))

        border_height = 1
        cmd_height = 1 + nbpreviewnewlines
        args_height = (2 + Gui.cmd.nb_args) if (Gui.cmd.nb_args > 0) else 0
        desc_height = (len(description_lines) + 1 +
                       1) if (len(description_lines) > 0) else 0

        cmd_pos = 1
        args_pos = border_height + cmd_height + 1
        desc_pos = args_pos + args_height - 1

        nlines = border_height * 2 + cmd_height + args_height + desc_height
        if nlines > self.height:
            nlines = self.height

        self.AB_TOP = (self.height - nlines) // 2
        y, x = self.AB_TOP, self.AB_SIDE

        try:
            argprev = curses.newwin(nlines, ncols, y, x)

            # draw command
            self.draw_cmd_preview(argprev, padding_text_border, cmd_pos)

            # draw description
            self.draw_desc_preview(argprev, padding_text_border, desc_pos,
                                   description_lines)

            if len(Gui.cmd.args) > 0:
                self.draw_args_list(args_pos)
                self.draw_selected_arg(args_pos)
                # init cursor position (if first draw)
                if self.x_init is None or self.y_init is None or self.xcursor is None:
                    self.y_init, self.x_init = curses.getsyx()
                    # prefill compatibility
                    self.x_init -= len(Gui.cmd.args[self.current_arg][1])
                    self.xcursor = self.x_init + len(
                        Gui.cmd.args[self.current_arg][1])
                # set cursor position
                curses.setsyx(self.y_init, self.xcursor)
                curses.doupdate()
        except curses.error:
            # catch all curses error to not end with an exception in case of size error
            pass
예제 #38
0
 def move_down(self):
     if self.actual_y < len(self.lines) - 1:
         self.move_cursor(1)
         cursor_pos = curses.getsyx()
         if cursor_pos[0] > self.pad_height - 4:
             self.scroll(1)
예제 #39
0
     if x == 0:
         if y != 0:
             y -= 1
             try:
                 x = xy[len(xy) - 1][1]
                 xy.pop(len(xy) - 1)
             except IndexError:
                 x = dimensions[1] - 1
             screen.delch(y, x)
         else:
             pass
     else:
         screen.delch(y, x - 1)
         x -= 1
 elif q == 10:
     xy.append(curses.getsyx())
     screen.addstr(y, x, chr(10), curses.color_pair(1))
     y += 1
     x = 0
 elif q == 261:
     if dimensions[1] - x == 1:
         y += 1
         x = 0
     else:
         x += 1
         screen.addstr(y, x, "", curses.color_pair(1))
 elif q == 260:
     if x == 0:
         if y != 0:
             y -= 1
             x = 78
예제 #40
0
# Return what a choice wins against
def win_against(num):
    if num == 1:
        return 4
    elif num == 2:
        return 1
    elif num == 3:
        return 2
    elif num == 4:
        return 3



try:
    while True:
        (y, x) = c.getsyx()
        stdscr.addstr(0, 0,
        """+--+--+
|01|02|
+--+--+
|03|04|
+--+--+""")
        y = 2
        x = 1
        stdscr.addstr(8, 0, f"AI HP: {aihp} Your HP: {playerhp}")

        stdscr.move(boxy * 2 + 1, boxx * 3 + 1)
        if (aihp == 0) or (playerhp == 0):
            if aihp == 0:
                exitcode = 2
            elif playerhp == 0:
예제 #41
0
def drawscreen(scr,doc):
	#To be clear, curses supports some very good mechanisms for subdividing the terminal screen
	#	e.g. 'windows', 'pads', 'TextBox'es, etc.
	#However, they do add a couple (very minor) complications that wouldn't have been ideal for this first look.
	#It's up to you whether you'storyBook prefer to employ them for your final product, or if you'storyBook like to stick with this
	#duct-tape-y approach.
	height,width = scr.getmaxyx()
	if height < 24 or width < 80:
		scr.move(0,0)
		scr.erase()
		curses.doupdate()
		return
	pos_r,pos_c = curses.getsyx()
	scr.hline(20,0,'~',width)
	pos_p = str(doc.current+1)+'/'+str(len(doc.pages)) #Not displaying zero-based indexing
	scr.addstr(20,width-len(pos_p),pos_p)
	
	commands = [["^C: Quit", "^L: Binary load", "^K: Restart"],
		[outLog]]
	#Could've used A_UNDERLINE for this, but the other decorations aren't as widely-supported across terminals
	#There's a decent chance A_BOLD will work, too
	for r in range(2):
		ct = 0
		for cmd in commands[r]:
			scr.addstr(21+r,ct*20+5,cmd,curses.A_BOLD)
			ct += 1
	if width > 80: #if we need to fill in the excess space to the right of the document...
		for row in range(height-4):
			scr.addstr(row,80," "*(width-80),curses.A_REVERSE)
	scr.move(0,0)
	lines = str(doc).split('\n')
	choiceCounter = 0
	for lineNumber in range(len(lines)):
		line = lines[lineNumber]

		#Format room title
		#All text after a '$' is ommited from the jubjub viewer, allowing multiple rooms to share the 'same' room name

		if (line[0] == '#'):
			dollarIndex = line.find('$') if '$' in line else line.rfind('#')	
			line =  line[1 : dollarIndex]
			lastAction = doc.getLastAction()
			line = ("(" + lastAction.rstrip() + ") -> " + line) if len(lastAction) > 0 else line
			line += " " * (80 - len(line))
			scr.addstr(lineNumber, 0, line, curses.A_STANDOUT )
		#Format choices 
		elif (line[0] == '*'):
			pageID = line[line.find('*') + 1 : line.rfind('*')]
			if len(pageID) > 1 and doc.GetPageFromID(pageID) >= 0: #valid pageID and pageID found 
				choiceCounter += 1
				regexLine = regex.sub('\*.+?\*', '', line)
				scr.addstr(lineNumber,0,"[" + str(choiceCounter) + "]" + regexLine)
			else:
				scr.addstr(lineNumber, 0, " " * 80)
		elif (line[0] == "&"):
			regexLine = regex.sub('\&.+?\&', '', line)
			scr.addstr(lineNumber,0,"[ENTER]" + regexLine)
		else:
			scr.addstr(lineNumber, 0, line)

	scr.move(pos_r,pos_c)
예제 #42
0
# Don't echo keys to screen when pressed
curses.noecho()  # curses.echo() to set it back

# Hide the cursor
curses.curs_set(0)

# Get the window size. In this case the window is whole screen
size = screen.getmaxyx()
screen.addstr(0, 0, "Terminal size" + repr(size))
screen.refresh()
time.sleep(2)

screen.addstr(3, 10, 'Text on line 3 char 10')

# Get cursor positions
yx = curses.getsyx()
screen.addstr(4, 10, 'Cursor position:' + repr(yx))

screen.refresh()

time.sleep(2)
screen.clear()

# Color text
curses.start_color()
screen.addstr("Pretty text", curses.color_pair(1))
screen.refresh()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
screen.addstr(0, 0, "RED ALERT!", curses.color_pair(1))
screen.refresh()
예제 #43
0
def chooseFile(folder, fileList):
    global prints
    bottom = curses.getsyx()[0] - 2
    try:
        stdscr.move(bottom, 0)
    except:
        pass
    pages = int(math.ceil(prints / height))
    topcornerY = (height * pages)
    filePos = len(fileList)
    while True:
        choice = stdscr.getch()
        pos = pad.getyx()[0]
        if choice != 10:
            if choice == 259:
                if filePos > 1:
                    if curses.getsyx()[0] == 0:
                        topcornerY -= height
                        stdscr.move(height, 0)
                        pad.refresh(topcornerY, 0, 0, 0, height, width)
                    else:
                        stdscr.move(curses.getsyx()[0] - 1, 0)
                        filePos -= 1
            elif choice == 258:
                if filePos < len(fileList):
                    if curses.getsyx()[0] == height:
                        topcornerY += height
                        stdscr.move(0, 0)
                        pad.refresh(topcornerY, 0, 0, 0, height, width)

                    else:
                        stdscr.move(curses.getsyx()[0] + 1, 0)
                        filePos += 1
            elif choice == 260:
                escapeProg(folder, fileList)
            else:
                finalize(findUSB())
        else:
            break
    if path.isdir(folder + '/' + fileList[filePos - 1]):
        refresh()
        astdprnt('Open folder ' + fileList[filePos - 1] + '?', curses.A_BOLD)
        stdprnt(' ')
        tbprnt('1) YES')
        tbprnt('0) NO')
        top = curses.getsyx()[0] - 2
        bottom = curses.getsyx()[0] - 1
        stdprnt(' ')
        stdscr.move(top, 4)
        while True:
            chooseSource = stdscr.getch()
            if chooseSource != 10:
                if chooseSource == 259:
                    if curses.getsyx()[0] > top:
                        stdscr.move(curses.getsyx()[0] - 1, 4)
                elif chooseSource == 258:
                    if curses.getsyx()[0] < bottom:
                        stdscr.move(curses.getsyx()[0] + 1, 4)
                elif chooseSource == 260:
                    escapeProg(findUSB())
                else:
                    finalize(findUSB())
            elif curses.getsyx()[0] == top:
                return chooseFile(
                    folder + "/" + fileList[filePos - 1],
                    listFile(folder + "/" + fileList[filePos - 1], True))
            elif curses.getsyx()[0] == bottom:
                return folder + "/" + fileList[filePos - 1]
    else:
        return folder + "/" + fileList[filePos - 1]
예제 #44
0
                    # Step 3: adding strings to the second column
                    strings = []
                    slicing(result[item], 20)
                    current_line_number = 0
                    for resulting_item in strings:
                        second_win.addstr(
                            current_cursor_position_y + current_line_number, 0,
                            resulting_item)
                        current_line_number += 1
                    # Step 3.0: adding empty strings if
                    #           number of added lines is smaller
                    #           than the maximum lines number
                    while current_line_number < lines_counter:
                        second_win.addstr(' ' * 20)
                        current_line_number += 1
                    # Step 4: updating counter of initial position y
                    #         for the next value not to override current
                    current_cursor_position_y += lines_counter
                first_win.refresh()
                second_win.refresh()
                curses.curs_set(0)
                stdscr.refresh()
                stdscr.getkey()

            else:
                pass  # TODO the place for future list-of-the-lists code
        else:
            current_cursor_position = curses.getsyx()
            stdscr.addstr(current_cursor_position[0] + 1, 0, 'gogakal')
            stdscr.refresh()
예제 #45
0
 def _render_content(self, window):
     yx = curses.getsyx()
     window.addstr(self.border_lines_, 0, self.lines_manager.to_formatted())
예제 #46
0
 def refresh(self):
     self.pad.refresh(self.actual_offset, 0, 0, self.start_x,
                      self.pad_height, self.width + self.start_x - 2)
     cursor_pos = curses.getsyx()
     curses.setsyx(cursor_pos[0], cursor_pos[1] - self.start_x)
예제 #47
0
def main(stdscr):
	global storyBook #We need to bother with this, because storyBook will be reassigned during loading (which would otherwise make it local)
	global outLog 
	curses.curs_set(0)
	outLog = "Welcome to JubJub. Load a game already"

	stdscr.clear()
	drawscreen(stdscr,storyBook)
	stdscr.move(0,0)
	s_height,s_width,enabled = sizecheck(stdscr)
	
	while True:
		charInput = stdscr.getch()
		if enabled:
			#Why are these in a tonberry of if/elif's? Because... I can?					
			if charInput == curses.KEY_PPAGE: #PGUP (previous page)
				#storyBook.prevPage()
				#drawscreen(stdscr,storyBook)
				pos_r,pos_c = 0,0
				stdscr.move(pos_r,pos_c)
			elif charInput == curses.KEY_NPAGE: #PGDN (next page)
				#storyBook.nextPage()
				#drawscreen(stdscr,storyBook)
				pos_r,pos_c = 0,0
				stdscr.move(pos_r,pos_c)
			elif charInput == curses.KEY_BACKSPACE or curses.keyname(charInput ) == '^H': #^H is weirdness for some terminals
				pos_r,pos_c = curses.getsyx()
				pos_c -= 1
				if pos_c < 0:
					pos_c = s_width-1
					pos_r -= 1
					if pos_r < 0:
						pos_r = 0
						pos_c = 0
				stdscr.addch(pos_r,pos_c,32)
				storyBook.setChr(pos_r,pos_c,' ')
				stdscr.move(pos_r,pos_c)
			elif curses.keyname(charInput) == '1':
				storyBook.TakePath(1)
			elif curses.keyname(charInput) == '2':
				storyBook.TakePath(2)
			elif curses.keyname(charInput) == '3':
				storyBook.TakePath(3)
			elif charInput == 10: #enter
				storyBook.ContinuePage()

			elif curses.keyname(charInput) == '^K': #Restart
				try:
					f = open(storyBook.filename,'r') #open in 'read' mode
					storyBook = pickle.load(f)
					f.close()
					storyBook.current = 0
					storyBook.pageHistory = [0]
					storyBook.posInHistory = 0
					outLog = PadString("Currently Playing: " + storyBook.filename)
				except IOError: #e.g. if the file doesn't exist yet
					outLog = PadString("Could not open: " + filename)
					pass
				drawscreen(stdscr,storyBook)				

			elif curses.keyname(charInput ) == '^L': #ctrl+l - Binary restore
				outLog = PadString("LoadFile Name: ")
				drawscreen(stdscr,storyBook)
				curses.echo()				
				curses.curs_set(1)
				stdscr.move(22,20)
				filename = stdscr.getstr(22,20)
				filename = filename if len(filename) > 0 else "binary.bindoc"
				curses.curs_set(0)
				curses.noecho()
				try:
					f = open(filename,'r') #open in 'read' mode
					storyBook = pickle.load(f)				
					f.close()
					storyBook.filename = filename
					storyBook.current = 0
					storyBook.pageHistory = [0]
					storyBook.posInHistory = 0
					outLog = PadString("Currently Playing: " + storyBook.filename)
				except IOError: #e.g. if the file doesn't exist yet
					outLog = PadString("Could not open: " + filename)
					pass
				drawscreen(stdscr,storyBook)
				stdscr.move(0,0)		
			elif charInput == curses.KEY_RESIZE: #As odd as it sounds, resizing the terminal is treated like any other character
				s_height,s_width,enabled = sizecheck(stdscr)
				#drawscreen(stdscr,storyBook)
			#else: #eventually delete this
			#	stdscr.addstr(0,0,curses.keyname(charInput ))
		else: #We want to keep everything disabled until the window is back to a legal size
			if charInput == curses.KEY_RESIZE: #We still need to listen for this one, so we'll know it's safe again
				s_height,s_width,enabled = sizecheck(stdscr)
		drawscreen(stdscr,storyBook)		
		curses.doupdate()
예제 #48
0
def main(screen):
    # parse args
    parser = argparse.ArgumentParser(
        description='Verbose QuakeLive server statistics')
    parser.add_argument('--host',
                        default=HOST,
                        help='ZMQ URI to connect to. Defaults to %s' % HOST)
    parser.add_argument('--password', required=False)
    parser.add_argument(
        '--identity',
        default=uuid.uuid1().hex,
        help='Specify the socket identity. Random UUID used by default')
    args = parser.parse_args()

    # set up curses, logging, etc
    input_window, output_window = InitWindows(screen, args)

    # ready to go!
    logger.info('zmq python bindings %s, libzmq version %s' %
                (repr(zmq.__version__), zmq.zmq_version()))

    q = setupInputQueue(input_window)
    try:
        ctx = zmq.Context()
        socket = ctx.socket(zmq.DEALER)
        monitor = socket.get_monitor_socket(zmq.EVENT_ALL)
        if (args.password is not None):
            logger.info('setting password for access')
            socket.plain_username = '******'
            socket.plain_password = args.password
            socket.zap_domain = 'rcon'
        socket.setsockopt(zmq.IDENTITY, args.identity)
        socket.connect(args.host)
        logger.info('Connecting to %s' % args.host)
        while (True):
            event = socket.poll(POLL_TIMEOUT)
            event_monitor = _checkMonitor(monitor)
            if (event_monitor is not None
                    and event_monitor[0] == zmq.EVENT_CONNECTED):
                # application layer protocol - notify the server of our presence
                logger.info('Registering with the server.')
                socket.send('register')

            while (not q.empty()):
                l = q.get()
                # logger.info( 'sending command: %s' % repr( l ) )
                socket.send(l)

            if (event == 0):
                continue

            while (True):
                try:
                    msg = socket.recv(zmq.NOBLOCK)
                except zmq.error.Again:
                    break
                except Exception as e:
                    logger.info(e)
                    break
                else:
                    if len(msg) > 0:
                        # store/return cursor position so that it stays over the input box as we print output
                        y, x = curses.getsyx()
                        PrintMessageFormatted(output_window, msg)
                        curses.setsyx(y, x)
                        curses.doupdate()

    except Exception as e:
        logger.info(e)
예제 #49
0
def transferFile(file, presentUSB, choice):
    refresh()
    if choice == presentUSB[0]:
        destination = presentUSB[1]
    else:
        destination = presentUSB[0]
    astdprnt('Do you want to send ' + file + '?', curses.A_BOLD)
    stdprnt(' ')
    tbprnt('1) YES')
    tbprnt('0) NO')
    top = curses.getsyx()[0] - 2
    bottom = curses.getsyx()[0] - 1
    curses.setsyx(top, 4)
    curses.doupdate()
    confirm = 0
    while True:
        time.sleep(0.2)
        if GPIO.input(enter) != False:
            if GPIO.input(up) == False:
                if curses.getsyx()[0] > top:
                    curses.setsyx(curses.getsyx()[0] - 1, 4)
                    curses.doupdate()
            elif GPIO.input(down) == False:
                if curses.getsyx()[0] < bottom:
                    curses.setsyx(curses.getsyx()[0] + 1, 4)
                    curses.doupdate()
            elif GPIO.input(back) == False:
                escapeProg(choice, listFile(choice, False))
        elif curses.getsyx()[0] == bottom:
            return transferFile(
                chooseFile(
                    file[:len(file) - file[::-1].index('/') - 1],
                    listFile(file[:len(file) - file[::-1].index('/') - 1],
                             True)),
                findUSB()[1], choice)
        elif curses.getsyx()[0] == top:
            confirm = 1
            break
    if confirm == 1:
        stdprnt(' ')
        astdprnt('Do you want to Move or Copy?', curses.A_BOLD)
        stdprnt(' ')
        tbprnt('0) MOVE')
        tbprnt('1) COPY')
        copyMove = 0
        top = curses.getsyx()[0] - 2
        bottom = curses.getsyx()[0] - 1
        curses.setsyx(top, 4)
        curses.doupdate()
        while True:
            time.sleep(0.2)
            if GPIO.input(enter) != False:
                if GPIO.input(up) == False:
                    if curses.getsyx()[0] > top:
                        curses.setsyx(curses.getsyx()[0] - 1, 4)
                        curses.doupdate()
                elif GPIO.input(down) == False:
                    if curses.getsyx()[0] < bottom:
                        curses.setsyx(curses.getsyx()[0] + 1, 4)
                        curses.doupdate()
                elif GPIO.input(back) == False:
                    finalize(findUSB())
            elif curses.getsyx()[0] == top:
                refresh()
                ctrprnt('Loading...', curses.A_BOLD)
                system("sudo mv '" + file + "' '" + destination + "'")
                finalize(findUSB())
            elif curses.getsyx()[0] == bottom:
                refresh()
                ctrprnt('Loading...', curses.A_BOLD)
                if path.isdir(file):
                    system("sudo cp -r '" + file + "' '" + destination + "'")
                else:
                    system("sudo cp '" + file + "' '" + destination + "'")
                finalize(findUSB())
예제 #50
0
 def cursor_pos(Shell):
     pos = curses.getsyx()
     return pos[0], pos[1]
def main(stdscr):
    global storyBook  #We need to bother with this, because storyBook will be reassigned during loading (which would otherwise make it local)
    global outLog

    outLog = PadString("Please make new file or load existing")

    stdscr.clear()
    drawscreen(stdscr, storyBook)
    stdscr.move(0, 0)
    s_height, s_width, enabled = sizecheck(stdscr)

    while True:
        charInput = stdscr.getch()
        if enabled:
            if charInput == curses.KEY_UP:
                curRow, curColumn = curses.getsyx(
                )  #There's honestly no need to have both the curses cursor position and separate variables
                curRow = max(curRow - 1, 0)
                stdscr.move(curRow, curColumn)
            elif charInput == curses.KEY_DOWN:
                curRow, curColumn = curses.getsyx()
                curRow = min(curRow + 1, 19)
                stdscr.move(curRow, curColumn)
            elif charInput == curses.KEY_LEFT:
                curRow, curColumn = curses.getsyx()
                curColumn = max(curColumn - 1, 0)
                stdscr.move(curRow, curColumn)
            elif charInput == curses.KEY_RIGHT:
                curRow, curColumn = curses.getsyx()
                curColumn = min(curColumn + 1, 79)
                stdscr.move(curRow, curColumn)

            elif curses.keyname(
                    charInput
            ) == '1':  #Guess you guys arnt allowed to have numbers
                pathName = storyBook.TakePath(1)
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 1, 0
                stdscr.move(curRow, curColumn)
            elif curses.keyname(
                    charInput
            ) == '2':  #Guess you guys arnt allowed to have numbers
                storyBook.TakePath(2)
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 1, 0
                stdscr.move(curRow, curColumn)
            elif curses.keyname(
                    charInput
            ) == '3':  #Guess you guys arnt allowed to have numbers
                storyBook.TakePath(3)
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 1, 0
                stdscr.move(curRow, curColumn)
            elif curses.keyname(charInput) == '4':
                storyBook.ContinuePage()
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 1, 0
                stdscr.move(curRow, curColumn)

            elif charInput >= 32 and charInput <= 126:  #Matches on any of teh 'standard' printable characters.
                curRow, curColumn = curses.getsyx()
                stdscr.addstr(curRow, curColumn, chr(charInput))
                storyBook.setChr(curRow, curColumn, chr(charInput))
                drawscreen(stdscr, storyBook)
                #stdscr.move(curRow,curColumn + 1)
                #outLog = PadString("(" + str(curRow) + " " + str(curColumn) + ")")
                if (curColumn < 79):
                    stdscr.move(curRow, curColumn + 1)
                else:
                    if curRow < 19:
                        stdscr.move(curRow + 1, 0)

            elif charInput == curses.KEY_HOME:  #Jump to start of the current lineNumber
                curColumn = 0
                stdscr.move(curRow, curColumn)
            elif charInput == curses.KEY_END:  #Jump to end of the current lineNumber
                curColumn = 79
                stdscr.move(curRow, curColumn)

            elif charInput == curses.KEY_PPAGE:  #PGUP (previous page)
                storyBook.prevPage()
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 0, 0
                stdscr.move(curRow, curColumn)
            elif charInput == curses.KEY_NPAGE:  #PGDN (next page)
                storyBook.nextPage()
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 0, 0
                stdscr.move(curRow, curColumn)

            elif charInput == curses.KEY_IC:  #Insert (add page)
                storyBook.addPage()
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 0, 0
                stdscr.move(curRow, curColumn)
            elif charInput == curses.KEY_DC:  #Delete (remove page)
                storyBook.delPage(storyBook.current)
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 0, 0
                stdscr.move(curRow, curColumn)

            elif charInput == curses.KEY_BACKSPACE or curses.keyname(
                    charInput) == '^H':  #^H is weirdness for some terminals
                curRow, curColumn = curses.getsyx()
                curColumn -= 1
                if curColumn < 0:
                    curColumn = s_width - 1
                    curRow -= 1
                    if curRow < 0:
                        curRow = 0
                        curColumn = 0
                stdscr.addch(curRow, curColumn, 32)
                storyBook.setChr(curRow, curColumn, ' ')
                drawscreen(stdscr, storyBook)
                stdscr.move(curRow, curColumn)

            elif charInput == 10:  #linefeed
                curRow, curColumn = curses.getsyx()
                curColumn = 0
                curRow = min(curRow + 1, 19)
                stdscr.move(curRow, curColumn)

            elif curses.keyname(charInput) == '^K':  #show page history path
                drawscreen(stdscr, storyBook)
                outLog = PadString(storyBook.GetPageHistory())
                drawOutlog(stdscr, storyBook)

            elif curses.keyname(charInput) == '^R':  #Redraw screen
                drawscreen(stdscr, storyBook)

            elif curses.keyname(charInput) == '^X':  #testing
                val = storyBook.GetPageFromID("Boss")
                storyBook.Jump(val)
                drawscreen(stdscr, storyBook)
                curRow, curColumn = 0, 0
                stdscr.move(curRow, curColumn)

            elif curses.keyname(charInput) == '^N':  #ctrl+n - new story
                outLog = PadString("NewFile Name: ")
                drawOutlog(stdscr, storyBook)
                curses.echo()
                stdscr.move(22, 20)
                storyBook.filename = stdscr.getstr(22, 20)
                curses.noecho()
                outLog = PadString("Currently editing: " + storyBook.filename)
                drawscreen(stdscr, storyBook)
                stdscr.move(0, 0)
            elif curses.keyname(charInput) == '^L':  #ctrl+l - Binary restore
                outLog = PadString("LoadFile Name: ")
                drawOutlog(stdscr, storyBook)
                curses.echo()
                stdscr.move(22, 20)
                filename = stdscr.getstr(22, 20)
                filename = filename if len(filename) > 0 else "binary.bindoc"
                curses.noecho()
                try:
                    f = open(filename, 'r')  #open in 'read' mode
                    storyBook = pickle.load(f)
                    f.close()
                    storyBook.filename = filename
                    storyBook.current = 0
                    storyBook.pageHistory = [0]
                    storyBook.posInHistory = 0
                    outLog = PadString("Currently editing: " +
                                       storyBook.filename)
                except IOError:  #e.g. if the file doesn't exist yet
                    outLog = PadString("Could not open: " + filename)
                    pass
                drawscreen(stdscr, storyBook)
                stdscr.move(0, 0)
            elif curses.keyname(charInput) == '^O':  #ctrl+o - Binary save

                problemPage = storyBook.VerifyPages()

                if (problemPage < 0):
                    f = open(storyBook.filename, 'w')  #open in 'write' mode
                    pickle.dump(
                        storyBook,
                        f)  #pickling is much simpler than Java serialization
                    f.close()
                    outLog = PadString("Save successful")
                else:
                    outLog = PadString("Can not save because page " +
                                       str(problemPage + 1) + " is not named")

                drawscreen(stdscr, storyBook)

            elif charInput == curses.KEY_RESIZE:  #As odd as it sounds, resizing the terminal is treated like any other character
                s_height, s_width, enabled = sizecheck(stdscr)
                drawscreen(stdscr, storyBook)
        else:  #We want to keep everything disabled until the window is back to a legal size
            if charInput == curses.KEY_RESIZE:  #We still need to listen for this one, so we'll know it's safe again
                s_height, s_width, enabled = sizecheck(stdscr)
                drawscreen(stdscr, storyBook)
        curses.doupdate()
예제 #52
0
def pos():
    """Get the current x, y position of the cursor."""
    y, x = curses.getsyx()
    return x, y