Ejemplo n.º 1
0
def uploadAll(folderSrc, folderDst):
   global FILESTOUP

   stdscr = curses.initscr()
   curses.noecho()
   curses.cbreak()
   
   FILESTOUP = []
   
   dirs = []
   
   createFolder(os.path.dirname(os.path.join(folderDst, folderSrc)), os.path.basename(folderSrc), True)
   
   for (dirpath, dirnames, filenames) in os.walk(folderSrc):
      for dirname in dirnames:
         dirs.append(os.path.join(dirpath, dirname))
      
      for filename in filenames:
         FILESTOUP.append(os.path.join(dirpath, filename))
   
   for d in dirs:
      createFolder(os.path.join(folderDst, os.path.dirname(d)), os.path.basename(d), True)
   
   uploadBunch(folderDst, FILESTOUP)
   
   return
Ejemplo n.º 2
0
    def __init__ (self):
        self.board = puzzle_2048()
        
        self.screen = curses.initscr()
        self.screen.keypad(1)
        self.screen.leaveok(0)
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.noecho()
        curses.curs_set(0)
        
        self.screen.addstr(0,0,"To play: combine the tiles that match using the arrow keys, and press esc to exit")
        
        #Drawing the lines for the board
        self.screen.hline(5,10,"-", 29, curses.color_pair(1))
        self.screen.hline(9,10,"-", 29, curses.color_pair(1))
        self.screen.hline(13,10,"-", 29, curses.color_pair(1))
        self.screen.hline(17,10,"-", 29, curses.color_pair(1))
        self.screen.hline(21,10,"-", 29, curses.color_pair(1))
        self.screen.vline(5,10,"|", 17, curses.color_pair(1))
        self.screen.vline(5,17,"|", 17, curses.color_pair(1))
        self.screen.vline(5,24,"|", 17, curses.color_pair(1))
        self.screen.vline(5,31,"|", 17, curses.color_pair(1))
        self.screen.vline(5,38,"|", 17, curses.color_pair(1))
        
        self.Update_screen()

        self.run()
Ejemplo n.º 3
0
    def receive_command(self):
        numlines, numcols = self.get_termsize()

        # clear command line
        cl = ""
        for i in range(numcols-1):
            cl += " "

        self.screen.addstr(numlines-1, 0, cl)

        # get command w/ visual response
        self.dontupdate.acquire()
        curses.echo()
        curses.curs_set(1)
        self.screen.addstr(numlines-1, 0, ":")
        command = self.screen.getstr(numlines-1, 1)
        curses.curs_set(0)
        curses.noecho()
        self.dontupdate.release()

        if command == 'q':
            self.running = False
        else:
            self.screen.addstr(numlines-1,0,"received unknown command:\"%s\"" %
                    (command,))
Ejemplo n.º 4
0
    def __init__(self, wallet, config, app=None):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
        self.stdscr.keypad(1)
        self.stdscr.border(0)
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        curses.curs_set(0)
        self.w = curses.newwin(10, 50, 5, 5)

        self.wallet = wallet
        self.config = config
        set_verbosity(False)
        self.tab = 0
        self.pos = 0
        self.popup_pos = 0

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""
        
        self.wallet.interface.register_callback('updated', self.refresh)
        self.wallet.interface.register_callback('connected', self.refresh)
        self.wallet.interface.register_callback('disconnected', self.refresh)
        self.wallet.interface.register_callback('disconnecting', self.refresh)
        self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")]
        self.num_tabs = len(self.tab_names)
Ejemplo n.º 5
0
 def init_curses(self):
     self.screen = curses.initscr()
     curses.noecho()
     curses.start_color()
     curses.cbreak()
     self.screen.keypad(0)
     curses.curs_set(0)
Ejemplo n.º 6
0
 def run(self):
     curses.cbreak()
     curses.noecho()
     output.lastline()
     output.overwriteline()
     self.prompt()
     output.scr.refresh()
     last = None
     for item in self.data:
         if item[0] != None:
             if not self.inahurry:
                 if last != None:
                     curses.napms(600 + len(last)*30)
                 else:
                     curses.napms(1000)
             self.receive(item[0], item[1])
             output.scr.refresh()
             last = item[1]
         else:
             self.send(item[1])
             output.openline()
             self.prompt()
             output.scr.refresh()
             last = None
     output.removelastline()
Ejemplo n.º 7
0
 def init(self):
     self.window = curses.initscr()
     self.initted = True
     self.ymax, self.xmax = self.window.getmaxyx()
     terminfo = curses.longname()
     assert '256' in terminfo  # your env TERM must be xterm-256color!
     assert curses.has_colors()
     curses.start_color()
     curses.use_default_colors()
     ctr = 1
     for fg in CLRS:
         for bg in CLRS:
             if ctr <= curses.COLORS-1 and fg != bg:
                 curses.init_pair(ctr, CLRS[fg], CLRS[bg])
                 pairs[(fg,bg)] = curses.color_pair(ctr)
                 ctr += 1
     curses.meta(1)
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     curses.delay_output(0)
     curses.mouseinterval(150)
     availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS)
     assert availmask != 0  # mouse must be available!
     self.window.leaveok(1)
     self.window.scrollok(0)
     self.window.keypad(1)
     if NONBLOCKING:
         self.window.nodelay(1)
         self.window.timeout(NONBLOCKING_TIMEOUT)
     else:
         self.window.nodelay(0)
         self.window.timeout(-1)
     self.window.refresh()
Ejemplo n.º 8
0
def main(argv):
    global mines, board

    args = map(int, argv[1:])
    xw = int(args[0]) if args else 20
    yw = int(args[1]) if len(args) > 1 else xw / 2
    mines = int(args[2]) if len(args) > 2 else int(xw * yw / 20)

    board = [' ' * xw for i in range(yw)]
    mines = {(randint(0, xw), randint(0, yw)) : True for i in range(mines)}

    scr = curses.initscr()
    scr.keypad(1)
    curses.curs_set(0)
    curses.noecho()
    curses.mousemask(curses.ALL_MOUSE_EVENTS)

    while True:
        scr.clear()

        k = scr.getch()
        scr.addstr(yw + 2, 0, ': ' + str(k))
        if k == 27:
            break
        elif k == curses.KEY_MOUSE:
            _, x, y, z, bstate = curses.getmouse()
            scr.addstr(y, x, ' '.join(str(v) for v in (z, bstate)))
        elif k == curses.KEY_DC:
            boom(scr)

    scr.clear()
    curses.endwin()
Ejemplo n.º 9
0
    def obtainInput( self, option, cnc ):
        """
            Create a new window to obtain user input.

            @param String            option   - Selected option
            @param CommandAndControl cnc      - Command And Control Object

            @return tuple ( 
                    STRING selectedOption,
                    STRING userInput,
            )
        """
        screen = curses.newwin( 3, 65, 4, 6 )
        screen.box()

        screen.addstr( 1, 2, " "*59, curses.A_UNDERLINE )
        screen.refresh()

        # Tell curses to allow feedback
        curses.echo()
        curses.nocbreak()

        # Obtain data and assign it for processing
        data_in = screen.getstr( 1, 2 )
        self.process = data_in

        for optIdentifier, call in self.obj[ 'calls' ].iteritems(): 
            if option == optIdentifier:
                self.cnc.pushTargets( call )

        # Reset curses
        curses.noecho()
        curses.cbreak()

        return ( option, data_in )
Ejemplo n.º 10
0
	def __init__(self, tFile):
		self.tFile = tFile		

		#window setup
		self.screen = curses.initscr()
		curses.noecho()
		curses.cbreak()
Ejemplo n.º 11
0
    def __init__(self, evm):
        self.evm = evm
        evm.RegisterListener(self)
        # first we must create a window object; it will fill the whole screen
        self.scrn = curses.initscr()
        # turn off keystroke echo
        curses.noecho()
        # keystrokes are honored immediately, rather than waiting for the
        # user to hit Enter
        curses.cbreak()

        self.scrn.keypad(1)

        self.scrn.nodelay(1)
        # start color display (if it exists; could check with has_colors())
        curses.start_color()

        curses.mousemask(curses.BUTTON1_PRESSED)

        curses.curs_set(0)

        # clear screen
        self.scrn.clear()

        i = 1
        for color_background in self.list_of_colors:
            for color_foreground in self.list_of_colors:
                curses.init_pair(i, color_foreground, color_background)
                self.mapping[color_foreground, color_background] = i
                i += 1

        # implement the actions done so far (just the clear())
        self.scrn.refresh()
    def doRead(self):
        """ Input is ready! """
        curses.noecho()
        self.timer = self.timer + 1
        c = self.stdscr.getch()  # read a character

        if c == curses.KEY_BACKSPACE:
            self.searchText = self.searchText[:-1]

        elif c == curses.KEY_ENTER or c == 10:
            self.addLine(self.searchText)
            # for testing too
            try:
                self.irc.sendLine(self.searchText)
            except:
                pass
            self.stdscr.refresh()
            self.searchText = ""

        else:
            if len(self.searchText) == self.cols - 2:
                return
            self.searchText = self.searchText + chr(c)

        self.stdscr.addstr(self.rows - 1, 0, self.searchText + (" " * (self.cols - len(self.searchText) - 2)))
        self.stdscr.move(self.rows - 1, len(self.searchText))
        self.paintStatus(self.statusText + " %d" % len(self.searchText))
        self.stdscr.refresh()
Ejemplo n.º 13
0
	def prompt_screen(self, should_prompt):
		if should_prompt:
			curses.nocbreak()
			curses.echo()
		else:
			curses.cbreak()
			curses.noecho()
Ejemplo n.º 14
0
    def show_menu(self, title, items):
        """ Show a menu """

        done = False

        while not done:
            self.newpage(title)

            self.nextrow()
            options = []
            for item in items:
                self.stdscr.addstr(self.row, 0, "  {0}) {1}".format(*item))
                options.append(item[0])
                self.nextrow()

            self.nextrow()
            self.stdscr.addstr(self.row, 0, "Select an option (" + ", ".join(options) + "): ")

            curses.echo()
            answer = self.stdscr.getstr()
            curses.noecho()

            for item in items:
                if answer == item[0]:
                    if item[2] == None:
                        done = True
                    else:
                        item[2](self)
Ejemplo n.º 15
0
 def initializeScreen (self):
     self.screen = curses.initscr ()
     curses.start_color ()
     curses.noecho ()
     curses.cbreak ()
     (self.screenHeight, self.screenWidth) = self.screen.getmaxyx ()
     pass
Ejemplo n.º 16
0
    def __init__(self, player_sub):
        self.player_sub = player_sub
        # self.sea = sea
        self.display_screen = ''

        # setlocale enables UTF chars
        # see: https://docs.python.org/2/library/curses.html
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
        self.strcode = locale.getpreferredencoding()
        # print(self.strcode)
        screen = curses.initscr()

        self.screen = screen

        # Applications will also commonly need to react to keys instantly, without requiring the Enter key
        # to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode.
        curses.cbreak()

        # Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read
        #  keys and only display them under certain circumstances. This requires calling the noecho() function.
        curses.noecho()


        screen.nodelay(1)

        curses.curs_set(0)
        screen.keypad(True)

        curses.start_color()
        curses.use_default_colors()
Ejemplo n.º 17
0
def setup():
    """
     sets environment up and creates main window
     :returns: the main window object
    """
    # setup the console
    mmask = curses.ALL_MOUSE_EVENTS # for now accept all mouse events
    main = curses.initscr()         # get a window object
    y,x = main.getmaxyx()           # get size
    if y < 24 or x < 80:            # verify minimum size rqmts
        raise RuntimeError("Terminal must be at least 80 x 24")
    curses.noecho()                 # turn off key echoing
    curses.cbreak()                 # turn off key buffering
    curses.mousemask(mmask)         # accept mouse events
    initcolors()                    # turn on and set color pallet
    main.keypad(1)                  # let curses handle multibyte special keys
    main.clear()                    # erase everything
    banner(main)                    # write the banner
    mainmenu(main)                  # then the min and menu
    main.attron(CPS[RED])           # make the border red
    main.border(0)                  # place the border
    main.attroff(CPS[RED])          # turn off the red
    curses.curs_set(0)              # hide the cursor
    main.refresh()                  # and show everything
    return main
Ejemplo n.º 18
0
def main():
    """
    Main entry point for gunicorn_console.
    """
    # Set up curses.
    stdscr = curses.initscr()
    curses.start_color()
    curses.init_pair(1, foreground_colour, background_colour)
    curses.noecho()
    stdscr.keypad(True)
    stdscr.nodelay(True)
    try:
        curses.curs_set(False)
    except:
        pass
    try:
        # Run main event loop until quit.
        while True:
            try:
                update_gunicorns()
                handle_keypress(stdscr)
                display_output(stdscr)
                curses.napms(int(screen_delay * 1000))
            except KeyboardInterrupt:
                break
    finally:
        # Tear down curses.
        curses.nocbreak()
        stdscr.keypad(False)
        curses.echo()
        curses.endwin()
Ejemplo n.º 19
0
 def __init__(self):
   import curses
   self.key = curses.initscr()
   curses.cbreak()
   curses.noecho()
   self.key.keypad(1)
   self.key.nodelay(1)
Ejemplo n.º 20
0
	def start_interface(self): # {{{
		self.stdscr = curses.initscr()
		curses.noecho()
		curses.cbreak()
		self.stdscr.keypad(1)
		curses.curs_set(0)
		self.mainloop()
Ejemplo n.º 21
0
Archivo: yottu.py Proyecto: yottu/yottu
def main(argv):
	def __call__(self):
		pass

	dlog = DebugLog("debug.log")
	dlog.msg("Logging started\n")
	
	stdscr = curses.initscr()
	curses.noecho()
	curses.cbreak()
	stdscr.keypad(1)
	curses.start_color()
	
	try:
		wl = WindowLogic(stdscr)
		wl.start()

		ci = CommandInterpreter(stdscr, wl)
		ci.start()
	except Exception as e:
		dlog.excpt(e)
		raise

	ci.join()
	dlog.msg("Command Interpreter joined.\n")
	wl.stop()
	wl.join()
	dlog.msg("Thread Fetcher joined.\n")

	curses.nocbreak()
	stdscr.keypad(0)
	curses.echo()
	curses.endwin()
	curses.resetty()
	dlog.msg("Terminal restored.\n")
Ejemplo n.º 22
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

        curses.cbreak()
        curses.noecho()
        curses.halfdelay(20)
        try:
            curses.curs_set(int(bool(self.settings.show_cursor)))
        except:
            pass
        curses.start_color()
        curses.use_default_colors()

        self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse)
        _setup_mouse(dict(value=self.settings.mouse_enabled))

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
            self._draw_title = curses.tigetflag('hs') # has_status_line
        self.update_size()
        self.is_on = True

        if self.settings.update_tmux_title:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()
Ejemplo n.º 23
0
    def refresh(self, txt):
        # Compute row and scrolling information
        currRow = 0
        nTxtRows = (len( txt ) // self.width) + 3 # + 1 due to array indexing and + 2 for the documentation and newline
        maxRow = 0
        if nTxtRows > self.height:
            maxRow = nTxtRows - self.height

        curses.noecho()
        self.inner_window.clear()
        self.inner_window.addstr(0, 0, "j/k -- scroll down/up | y/n -- yes/no, q -- quit") # Documentation line
        self.inner_window.addstr(2, 0, txt)

     
        # Enter loop with simple interactivity
        while True:
            self.outer_window.box()
            self.outer_window.noutrefresh()
            self.inner_window.refresh(currRow, 0, self.yOffset, self.xOffset, self.yOffset + self.height, self.xOffset + self.width)
            c = self.inner_window.getch()
            if c == 106 and currRow < maxRow: # j scroll down
                currRow += 1
            if c == 107 and currRow > 0: # k scroll up
                currRow -= 1
            if c == 113: # q quit dialog
                break

        self.outer_window.clear()
        self.outer_window.noutrefresh()
        self.inner_window.clear()
        self.inner_window.refresh(currRow, 0, 1, self.xOffset, 11, self.xOffset + self.width)
        curses.echo()
Ejemplo n.º 24
0
	def __init__(self):
		curses.curs_set(0)
		curses.noecho()
		self.win=curses.newwin(LINES-4,COLS-4,2,2)
		self.win.clear()
		self.win.refresh()
		self.win.keypad(1)
Ejemplo n.º 25
0
  def __init__(self):
    self.myscreen = curses.initscr()
    self.thread = None
    self.threadName = 'CLI'

    curses.noecho()
    curses.cbreak()
    curses.start_color()
    self.myscreen.keypad(1)

    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
    self.myscreen_highlighted = curses.color_pair(1)
    self.myscreen_normal = curses.A_NORMAL

    self.menus = {
      'title': "Main Menu", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option...", 'options': [
        { 'title': "Status", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option..", 'options': [
          { 'title': "Media Information", 'type': MENU_TYPES.COMMAND, 'command': 'printMediaInfo' },
          { 'title': "Thread Information", 'type': MENU_TYPES.COMMAND, 'command': 'printThreadInfo' }
          ]
        }
      ]
    }

    self.commands = {
      'printMediaInfo': _printMediaInfo(),
      'printThreadInfo': _printThreadInfo()
    }

    self.initThread()
Ejemplo n.º 26
0
def main():
    stdscr = curses.initscr()
    curses.nocbreak()
    mode = NORMAL
    max_y, max_x = stdscr.getmaxyx()
    print_before, z = covert("输入一个文件地址:")
    stdscr.addstr((max_y-1)/2-1, (max_x-1-z)/2-1, print_before)
    stdscr.move((max_y-1)/2, (max_x-1-z)/2-1)
    path = ""
    while True:
        ch = stdscr.getch()
        if ch == curses.KEY_ENTER or ch == 10:
            break
        else:
            path += chr(ch)
            stdscr.addstr(chr(ch))
    stdscr.move(0,0)
    stdscr.clear()
    stdscr.refresh()
    with open(path,'r') as f:
        lines = list(line_resize(f.readlines(), 5))
        for line in lines[-20:]:
            stdscr.addstr(line)
    curses.cbreak()
    curses.noecho()
    while True:
        ch = stdscr.getch()
        if ch == 27:
            break
        else:
            string = parse(ch)
            stdscr.addstr(string)
Ejemplo n.º 27
0
    def start(self):
        """Initialize curses. Mostly copied from curses/wrapper.py"""

        # This might do some good
        locale.setlocale(locale.LC_ALL, "")

        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
            curses.use_default_colors()
            for i in range(1, curses.COLORS):
                curses.init_pair(i, i, -1)
        except:
            LOG.exception("Exception in curses color init")

        self.stdscr = stdscr
Ejemplo n.º 28
0
def main():
   open_message = 'SecLab is open :)'
   closed_message = 'SecLab is closed :('
   authenticate()
   try:
      is_open = True
      stdscr = curses.initscr()
      curses.cbreak()
      curses.noecho()
      stdscr.keypad(1)
      key = ''

      stdscr.addstr(5,33,please_wait, curses.A_BLINK)
      stdscr.refresh()
      stdscr.addstr(5,33,opened, curses.A_NORMAL)
      post_status(authenticate(), open_message)

      while 1:
         key = stdscr.getch()
         stdscr.clear()
         if is_open:
            stdscr.addstr(5, 33, please_wait, curses.A_BLINK)
            stdscr.refresh()
            stdscr.addstr(5, 33, closed, curses.A_NORMAL)
            post_status(authenticate(), closed_message)
         else:
            stdscr.addstr(5,33,please_wait, curses.A_BLINK)
            stdscr.refresh()
            stdscr.addstr(5,33,opened, curses.A_NORMAL)
            post_status(authenticate(), open_message)
         is_open = not is_open
   finally:
      curses.endwin()
      authenticate().destroy_status(id=LAST_POST_ID)
Ejemplo n.º 29
0
    def build_playinfo(self,
                       song_name,
                       artist,
                       album_name,
                       quality,
                       start,
                       pause=False):
        curses.noecho()
        # refresh top 2 line
        self.screen.move(1, 1)
        self.screen.clrtoeol()
        self.screen.move(2, 1)
        self.screen.clrtoeol()
        if pause:
            self.screen.addstr(1, self.indented_startcol,
                               '_ _ z Z Z ' + quality, curses.color_pair(3))
        else:
            self.screen.addstr(1, self.indented_startcol,
                               '♫  ♪ ♫  ♪ ' + quality, curses.color_pair(3))

        self.screen.addstr(
            1, min(self.indented_startcol + 18, self.x - 1),
            song_name + self.space + artist + '  < ' + album_name + ' >',
            curses.color_pair(4))

        self.screen.refresh()
Ejemplo n.º 30
0
    def __enter__(self):
        # init curses and it's wrapper
        self.screen  = curses.initscr()
        self.display = Display(self.screen, self.encoding)

        # create keyhandler
        self.keyhandler = key.KeyHandler(self.screen)

        # create view
        self.view = SelectorView(percol = self)

        # create command
        self.command_candidate = SelectorCommand(self.model_candidate, self.view)
        self.command_action = SelectorCommand(self.model_action, self.view)

        # suppress SIGINT termination
        signal.signal(signal.SIGINT, lambda signum, frame: None)

        # handle special keys like <f1>, <down>, ...
        self.screen.keypad(True)

        curses.raw()
        curses.noecho()
        curses.cbreak()
        # Leave newline mode. Make percol distinguish between "C-m" and "C-j".
        curses.nonl()

        return self
def update_loop(stdscr, ev_stop, client_dict):
    curses.curs_set(0)
    curses.start_color()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(True)
    stdscr.nodelay(1)

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

    status_color_map = {'alive': 2,
                        'delay': 3,
                        'lost': 4,
                        'fault': 5}

    columns = [('hostname', 'Hostname', 17),
               ('src_ip', 'Source IP', 18),
               # ('mac', 'MAC', 19),
               ('tzdelta', 'Delta', 9),
               ('last_seen', 'Seen', 7),
               ('status', 'Status', 10)]

    frame_top = ' ┌' + '┬'.join(['─' * c[2] for c in columns]) + '┐\n'
    header_template = ' │' + '│'.join(['{: ^'+str(c[2])+'s}' for c in columns]) + '│\n'
    table_header = header_template.format(*[c[1] for c in columns])

    frame_top_lower = ' ├' + '┼'.join(['─' * c[2] for c in columns]) + '┤\n'
    frame_bottom = ' └' + '┴'.join(['─' * c[2] for c in columns]) + '┘\n'

    while not ev_stop.is_set():
        # Process user input
        try:
            c = stdscr.getkey()
            if c == 'q':
                ev_stop.set()
                break
            if c == 'r':
                client_dict.clear()

        except curses.error:
            pass

        # Show current clients
        if stdscr is not None:
            stdscr.clear()
            stdscr.addstr(frame_top, curses.color_pair(1))
            stdscr.addstr(table_header, curses.color_pair(1))
            stdscr.addstr(frame_top_lower, curses.color_pair(1))

            for src_ip in sorted(client_dict):
                host = client_dict[src_ip]

                delta = (time.time() - host['arrival'])
                if host['data'] == 'invalid':
                    hostname = ''
                    status = 'FAULT'
                else:
                    hostname = host['hostname']
                    status = 'LOST'
                    if delta < LIFESIGN_TIMEOUT:
                        status = 'DELAY'
                    if delta < LIFESIGN_LAG:
                        status = 'ALIVE'

                stdscr.addstr(' ', curses.color_pair(1))
                for col in columns:
                    if col[0] == 'status':
                        stdscr.addstr('│ ', curses.color_pair(1))
                        status_color = status_color_map[status.lower()]
                        al_str = '{: <5s}'.format(status)
                        stdscr.addstr(al_str, curses.color_pair(status_color))
                        stdscr.addstr(' ' * (col[2] - 1 - len(al_str)) + '│\n', curses.color_pair(1))
                    else:
                        value = ''
                        cp = 1
                        if col[0] == 'mac' and col[0] in host:
                            value = host['mac']
                        elif col[0] == 'hostname':
                            value = hostname
                        elif col[0] == 'src_ip':
                            value = src_ip
                        elif col[0] == 'tzdelta':
                            if 'localtime' in host:
                                t_diff = host['arrival'] - host['localtime']
                                if status != 'LOST':
                                    if fabs(t_diff) < TIMEDELTA_OK:
                                        cp = 2
                                    elif fabs(t_diff) < TIMEDELTA_LAG:
                                        cp = 3
                                    else:
                                        cp = 4
                                    value = t_str(t_diff, ms=True)

                        elif col[0] == 'last_seen':
                            value = t_str(delta)

                        stdscr.addstr('│ ', curses.color_pair(1))
                        cell = '{: <' + str(col[2] - 1) + 's}'
                        stdscr.addstr(cell.format(str(value)), curses.color_pair(cp))

            stdscr.addstr(frame_bottom, curses.color_pair(1))
            stdscr.refresh()

        time.sleep(.5)
Ejemplo n.º 32
0
import curses
from random import randint

# set up the window
curses.initscr()  # initializing
y = 20
x = 80
window = curses.newwin(y, x, 0, 0)  # creates the window
window.keypad(True)  # to accept keyboard input
curses.noecho()
curses.curs_set(0)
window.border()  # adds a border to the window
window.nodelay(True)

# snake and food
snake = [(6, 10), (6, 9), (6, 8)]
food = (13, 28)

window.addch(food[0], food[1],
             "#")  # add the food at the beginning of the game

score = 0

ESC = 27  # Escape key
key = curses.KEY_RIGHT  # right arrow key

# logic of the game
while key != ESC:

    window.addstr(0, 2, 'Score : %s ' % score)  # adds the score in the window
    window.timeout(150 - (len(snake)) // 5 + len(snake) // 10 %
Ejemplo n.º 33
0
 def __init__(self):
     self.screen = curses.initscr()
     self.sys = System()
     self.sys.update()
     curses.noecho()
     curses.cbreak()
Ejemplo n.º 34
0
def init_screen():
    screen = curses.initscr()
    curses.noecho()
    curses.cbreak()
    screen.clear()
Ejemplo n.º 35
0
def init_screen():
    curses.noecho()

    make_greet_window()
    make_ip_window()
    make_hint_window()
Ejemplo n.º 36
0
def pong():
    HEIGHT = 20
    WIDTH = 60
    TIMEOUT = 50

    class player(object):
        def __init__(self, name, body, keyup, keydown, side):
            self.name = name
            self.hit_score = 0
            self.keyup = keyup
            self.keydown = keydown
            self.body = body
            self.side = side
            if side == 'left':
                self.bounce = [[coord[0], coord[1] + 1] for coord in self.body]
            if side == 'right':
                self.bounce = [[coord[0], coord[1] - 1] for coord in self.body]
            for part in self.body:
                win.addch(part[0], part[1], '|')

        @property
        def score(self):
            return ' {}: {} '.format(self.name, self.hit_score)

        def make_a_point(self):
            self.hit_score += 1

        def update_bounce(self):
            if self.side == 'left':
                self.bounce = [[coord[0], coord[1] + 1] for coord in self.body]
            if self.side == 'right':
                self.bounce = [[coord[0], coord[1] - 1] for coord in self.body]
            for part in self.body:
                win.addch(part[0], part[1], '|')

        def go_up(self):
            win.addch(self.body[-1][0], self.body[-1][1], ' ')
            del self.body[-1]
            if self.body[0][0] == 1:
                self.body.insert(0, [HEIGHT - 2, self.body[-1][1]])
            else:
                self.body.insert(0, [self.body[0][0] - 1, self.body[-1][1]])
            self.update_bounce()
            win.addch(self.body[0][0], self.body[0][1], '|')

        def go_down(self):
            win.addch(self.body[0][0], self.body[0][1], ' ')
            del self.body[0]
            if self.body[-1][0] == HEIGHT - 2:
                self.body.insert(len(self.body), [1, self.body[-1][1]])
            else:
                self.body.insert(len(self.body),
                                 [self.body[-1][0] + 1, self.body[-1][1]])
            self.update_bounce()
            #win.addch(self.body[-1][0], self.body[-1][1], '|')

    class ball(object):
        def __init__(self, dir=-1, coef=0):
            self.position = [HEIGHT / 2, WIDTH / 2]
            self.dir = dir
            self.coef = coef
            win.addch(self.position[0], self.position[1], 'o')

        def bounce(self, where):
            #control if len(player)%2 = 0 or 1
            if where == 0:
                self.coef -= 1
            elif where == 2:
                self.coef += 1
            self.dir *= -1

        def bounce_segment(self):
            self.coef *= -1

        def reset(self, position=[HEIGHT / 2, WIDTH / 2], dir=-1, coef=0):
            self.position = position
            self.dir = dir
            self.coef = coef

    def input_key(name, direction):
        k = raw_input("{}'s key {}: ".format(name, direction))
        if k == 'up':
            key = curses.KEY_UP
        elif k == 'down':
            key = curses.KEY_DOWN
        else:
            key = ord(k)
        return (key)

    print('---------------------------')
    print('Welcome to PONG multiplayer')
    print('---------------------------')
    choice = raw_input('Change timeout ? (default=50) ')
    if 'y' in choice:
        TIMEOUT = raw_input('timeout = ')

    name1 = raw_input("left player's name: ")
    print('Do not use the following keys: ESC, SPACE, p, n')
    print('write "up" or "down" to use the arrows')
    keyup1 = input_key(name1, 'up')
    keydown1 = input_key(name1, 'down')

    name2 = raw_input("right player's name: ")
    print('Do not use the following keys: ESC, SPACE, p, n')
    print('write "up" or "down" to use the arrows')
    keyup2 = input_key(name2, 'up')
    keydown2 = input_key(name2, 'down')

    curses.initscr()
    win = curses.newwin(HEIGHT, WIDTH, 0, 0)  #y,x coordinates
    win.keypad(1)
    curses.noecho()
    curses.curs_set(0)
    win.border(0)
    win.nodelay(1)
    try:
        win.timeout(int(TIMEOUT))
    except TypeError:
        win.timeout(50)

    #name1 = 'player1'
    score1 = 0
    body1 = [[HEIGHT / 2 - 1, 1], [HEIGHT / 2, 1], [HEIGHT / 2 + 1, 1]]
    player1 = player(name1, body1, keyup1, keydown1, 'left')

    score2 = 0
    body2 = [[HEIGHT / 2 - 1, WIDTH - 2], [HEIGHT / 2, WIDTH - 2],
             [HEIGHT / 2 + 1, WIDTH - 2]]
    player2 = player(name2, body2, keyup2, keydown2, 'right')

    ball = ball()

    score_max = 3
    new_round_message = 'press SPACE bar for another round'
    new_round_message_erase = '                                 '
    end_message = '  THE END\n  - ESC to quit\n  - n bar for another game'
    key = 0
    point = False

    while key != 27:  # While Esc key is not pressed
        win.border(0)
        win.addstr(0, 3, ' {}'.format(player1.score))
        win.addstr(0, WIDTH / 2 - 4, ' PONG ')
        win.addstr(0, WIDTH - 15, '{}'.format(player2.score))
        win.addstr(HEIGHT - 1, WIDTH / 2 - 12, ' ESC (quit), p (pause) ')

        event = win.getch()
        key = event

        # pause mode
        prevKey = key
        event = win.getch()
        key = key if event == -1 else event

        if key == ord('p'):
            key = -1
            while key != ord('p'):
                key = win.getch()
            key = prevKey
            continue

    # move the players
        if key == player1.keyup:
            player1.go_up()
        if key == player1.keydown:
            player1.go_down()
        if key == player2.keyup:
            player2.go_up()
        if key == player2.keydown:
            player2.go_down()

    # move the ball
        if ball.position in player1.bounce:
            ball.bounce(player1.bounce.index(ball.position))
        elif ball.position in player2.bounce:
            ball.bounce(player2.bounce.index(ball.position))
        elif ball.position[0] == 1 or ball.position[0] == HEIGHT - 2:
            ball.bounce_segment()

        if ball.position[
                1] == WIDTH - 2:  #and ball.position not in player2.body:
            if player1.hit_score < score_max - 1:
                win.addstr(3, 10, new_round_message)
            else:
                win.addstr(3, 10, end_message)
                win.addstr(7, 3, winer_message)

            player1.make_a_point()
            old = [ball.position[0], ball.position[1]]
            ball.reset(dir=1)
            point = True

        elif ball.position[1] == 1:  #and ball.position not in player1.body:
            if player2.hit_score < score_max - 1:
                win.addstr(3, 10, new_round_message)
            else:
                win.addstr(3, 10, end_message)
                win.addstr(7, 3, winer_message)

            player2.make_a_point()
            old = [ball.position[0], ball.position[1]]
            ball.reset(dir=-1)
            point = True

        if point:
            if key == ord(' '):
                win.addch(old[0], old[1], ' ')
                win.addstr(3, 10, new_round_message_erase)
                point = False
            elif key == ord('n'):
                win.addch(old[0], old[1], ' ')
                win.addstr(3, 2, '                       ')
                win.addstr(4, 2, '                       ')
                win.addstr(5, 2, '                         ')
                win.addstr(7, 2, '                                         ')
                player1.hit_score = 0
                player2.hit_score = 0
                point = False
            else:
                continue
        else:
            win.addch(ball.position[0], ball.position[1], ' ')
            ball.position = [
                ball.position[0] + ball.coef, ball.position[1] + ball.dir
            ]
            if ball.position[0] < 1:
                ball.position[0] = 1
            elif ball.position[0] > HEIGHT - 2:
                ball.position[0] = HEIGHT - 2
            elif ball.position[1] < 1:
                ball.position[1] = 1
            elif ball.position[1] > WIDTH - 2:
                ball.position[1] = WIDTH - 2
            win.addch(ball.position[0], ball.position[1], 'o')

        if player1.hit_score == score_max - 1:
            winer = player1
            looser = player2
            winer_message = '{} has defeated {} {}-{}'.format(
                winer.name, looser.name, winer.hit_score + 1, looser.hit_score)
        elif player2.hit_score == score_max - 1:
            winer = player2
            looser = player1
            winer_message =\
            '{} has defeated{}{}-{}'.format(winer.name,looser.name,
                                                    winer.hit_score+1,
                                                    looser.hit_score)

    curses.endwin()
    print('---------------------------')
    print('End game')
    try:
        print(winer_message)
    except UnboundLocalError:
        print('No one won the match')
    sys.exit(0)
Ejemplo n.º 37
0
def main(stdscr):
    global screen
    screen = stdscr

    cipher_file = sys.argv[1]
    f = open(cipher_file, 'r')
    cipher = f.readlines()
    f.close()

    f = open('cipher_tools/dictionary.db', 'rb')
    dictionary = pickle.load(f)
    f.close()

    x = 0
    while x != ord('9'):
        # Dont clear on our Dictionary searches
        if x != ord('4') and x != ord('>') and x != ord('<'):
            screen.erase()

        # BUILD MY MENU
        screen.addstr(0, 1, '1: Replace |')
        screen.addstr(0, 14, '2: Undo |')
        screen.addstr(0, 24, '3: Redo |')
        screen.addstr(0, 34, '4: Dictionary |')
        screen.addstr(0, 50, '8: Save |')
        screen.addstr(0, 60, '9: Quit')

        # Print Cipher blob
        count = 4
        for i in cipher:
            screen.addstr(count, 2, i)
            count += 1

        # Draw conntent
        screen.refresh()

        # Get Keyboard input
        x = screen.getch()

        # REPLACE
        if x == ord('1'):
            # Ask question to replace
            curses.echo()
            screen.addstr(count, 2, 'Replace: ')
            screen.refresh()
            replace = chr(screen.getch())

            screen.addstr(count + 1, 2, 'Replace with: ')
            screen.refresh()
            replacewith = chr(screen.getch())
            curses.noecho()

            newcipher = []
            for i in cipher:
                i = i.replace(replace, replacewith)
                newcipher.append(i)

            # Build our undo only if the previous undo
            # doesn't match
            try:
                if cipher != undo:
                    undo = cipher
            except UnboundLocalError:
                undo = cipher

            cipher = newcipher

        # UNDO
        if x == ord('2'):

            # If my undo and current cipher match
            # we are last undo
            if undo == cipher:
                continue

            try:
                redo = cipher
                cipher = undo
            except UnboundLocalError:
                continue

        # REDO
        if x == ord('3'):
            try:
                cipher = redo
            except UnboundLocalError:
                continue

        # DICTIONARY
        if x == ord('4'):
            curses.echo()
            curses.nocbreak()
            # clear line
            screen.addstr(2, 1, ' ' * 200)
            screen.refresh()

            screen.addstr(2, 1, 'Expression: ')
            user_input = screen.getstr()
            curses.noecho()
            curses.cbreak()
            screen.refresh()

            words = cipher_tools.dictionary.expression(user_input, dictionary)
            wordstring = ''

            wordcount = 1
            maxcount = wordcount + 10

            for word in words:
                if wordcount < maxcount:
                    wordstring = wordstring + ' ' + words[word]
                    wordcount += 1

            # Reset word count for Travel portion
            wordcount = 1

            # clear line
            screen.addstr(2, 1, ' ' * 200)
            screen.refresh()

            # If we have more words in the list give the option
            # to travel the list
            if len(words) > maxcount:
                screen.addstr(2, 1, wordstring + ' >')
            else:
                screen.addstr(2, 1, wordstring)

            screen.refresh()

        # TRAVEL THE DICTIONARY
        if x == ord('<'):

            # If newount isn't set we shouldn't run
            try:
                if newcount:
                    pass
            except UnboundLocalError:
                continue

            # Shouldn't shrink the number before 1
            if newcount - 10 < 1:
                continue
            else:
                newcount = newcount - 10

            count = 1

            maxcount = newcount + 10
            wordstring = ''

            for word in words:
                if wordcount < maxcount:
                    if count >= newcount and count <= maxcount:
                        wordstring = wordstring + ' ' + words[word]
                    count += 1

            # clear line
            screen.addstr(2, 1, ' ' * 200)
            screen.refresh()

            if newcount == 1:
                screen.addstr(2, 1, wordstring + ' >')
            else:
                screen.addstr(2, 1, '<' + wordstring + ' >')

            screen.refresh()

        # TRAVEL THE DICTIONARY
        if x == ord('>'):

            # No need to run if our list is smaller than count
            if len(words) < maxcount:
                continue

            count = 1

            # If we increased befiore we need to bump the number
            try:
                newcount = newcount + 10
            except UnboundLocalError:
                newcount = wordcount + 10

            maxcount = newcount + 10
            wordstring = ''

            for word in words:
                if wordcount < maxcount:
                    if count >= newcount and count <= maxcount:
                        wordstring = wordstring + ' ' + words[word]
                    count += 1

            # clear line
            screen.addstr(2, 1, ' ' * 200)
            screen.refresh()

            # If we have more words in the list give the option
            # to travel the list
            if len(words) > maxcount:
                screen.addstr(2, 1, '<' + wordstring + ' >')
            else:
                screen.addstr(2, 1, '<' + wordstring)

            screen.refresh()

        # SAVE
        if x == ord('8'):
            ciphertext = ''
            for i in cipher:
                ciphertext = ciphertext + i
            f = open(cipher_file, 'w+')
            f.write(ciphertext)
            f.close
Ejemplo n.º 38
0
 def new_screen(self):
     self._mainWin = curses.initscr()
     curses.noecho()
     curses.raw()
     curses.curs_set(0)
     self._mainWin.keypad(True)
Ejemplo n.º 39
0
def main(screen, avionics):
    global screenHandle, formatISfullsensor, quit
    global enableVicon, enableJoystick, enablePlot
    global thread_joystick, thread_vicon
    global lock_logfile, lock_avionics_state, lock_vicon_state, lock_js
    global vicon_state, avionics_state, js_flap, js_throttle
    global isLogging, logFilename, logBuffer
    global debug_joy_update_interval_ms

    screenHandle = screen
    curses.curs_set(0)  # Set cursor visibility where 0 = invisible,
    screen.nodelay(True)  # Set getch() to be non-blocking - important!
    curses.noecho()
    curses.use_default_colors(
    )  # Lets your terminal client set the fonts and colors
    global ymax, xmax
    ymax, xmax = screen.getmaxyx()  # Get the screen dimensions
    screen.setscrreg(0, ymax - rolling_offset)
    screen.scrollok(True)

    command = ""
    # ---------- display format ------------
    # --- human readable text ----- (scrollable,non-erasing)
    # line 5: joystick output, throttle, flap, in that order
    # line 4: avionics stream, machine
    # line 3: vicon stream, machine
    # line 2  last command executed
    # line 1: interactive command in buffer (ymax-1)

    # main loop, print,parse arduino output and send command
    start_ts = datetime.datetime.now()
    flag_calibrated = False
    flap_new_plot_data = True
    flag_ping_in_progress = False
    flag_vicon_not_ready = True

    calibration_data = []
    R_12 = None
    scale_12 = None

    epoch = datetime.datetime.now()
    debugdata = []
    serial_buffer = ""
    while not (quit):

        global curve00, curve01, curve10, curve11, ptr, data00, data01, data10
        # show loop freq
        #screen.addstr(ymax-1,xmax-20,"loop freq = "+str(int(1.0/(datetime.datetime.now()-start_ts).total_seconds())))
        screen.addstr(
            ymax - 1, xmax - 20, "ts = " +
            str(int((datetime.datetime.now() - epoch).total_seconds())))
        # read from avionics serial (thru xbee)
        if (avionics.in_waiting > 0):
            line = avionics.readline()
            # machine readable data start with #
            if (chr(line[0]) == '#'):
                # display data, remove trailing \r\n which mess up curser
                screen.move(ymax - 4, 0)
                screen.clrtoeol()
                screen.addstr(ymax - 4, 0,
                              "Avionics Datastream: " + line.decode()[:-2])
                # attempt to parse data
                try:
                    # sample parsing, need more work TODO
                    # remove prefix #, suffix \r\n
                    data = [float(i) for i in line[1:-2].split(b',')]
                    # two protocols, one with 13 fields
                    if (formatISfullsensor):
                        if (len(data) == 13):
                            # TODO complete the parsing
                            avionics_ts = data[0]
                            mx = data[1]
                            my = data[2]
                            mz = data[3]
                            mag = np.matrix(data[1:4]).T

                            acc1_x = data[4]
                            acc1_y = data[5]
                            acc1_z = data[6]
                            acc1 = np.matrix(data[4:7]).T

                            acc2_x = data[7]
                            acc2_y = data[8]
                            acc2_z = data[9]
                            acc2 = np.matrix(data[7:10]).T

                            voltage = data[10]

                            # azimuth (degree) from avionics
                            kf_azimuth = data[11]
                            # omega (rev/s) from avionics
                            kf_omega = data[12]
                            #screen.addstr(ymax-9,0,"acc1 = "+str(acc1))
                            #screen.addstr(ymax-9,int(xmax/2),"acc2 = "+str(acc2))

                    else:  # the other protocol contains seq_no, voltage, flap, throttle, isAutomaticControl
                        if (len(data) == 5):
                            seq_no = int(data[0])
                            voltage = data[1]
                            flapPWM = int(data[2])
                            throttlePWM = int(data[3])
                            isAutomaticControl = data[4] > 0.5

                            lock_avionics_state.acquire()
                            avionics_state = voltage, flapPWM, throttlePWM, isAutomaticControl
                            lock_avionics_state.release()

                except ValueError:
                    pass
            elif (chr(line[0]) == '$'):
                # inquiry response, e.g. ping response
                try:
                    response = line.decode()[1:-2]
                except UnicodeDecodeError:
                    pass

                displayText("[avionics response]:" + response)
                if (response == "ping"):
                    tac = time()
                    flag_ping_in_progress = False
                    if tic is None:
                        displayLineno(2, "Error.. Unsolicited ping response")
                    else:
                        displayText("[avionics]: ping success, dt = " +
                                    str(tac - tic) + "s")
                        tic = 0.0

            else:
                #human readable
                screen.scroll()
                # may throw UnicodeDecodeError, not big deal
                try:
                    text = line.decode()[:-2]
                    screen.addstr(ymax - rolling_offset, 0,
                                  "[avionics]: " + text)
                except UnicodeDecodeError:
                    pass
        # Vicon display
        # NOTE disable vicon does not actually disable the daemon, just display
        if (enableVicon):
            lock_vicon_state.acquire()
            local_vicon_state = vicon_state
            lock_vicon_state.release()
            if (vicon_state is None):
                displayLineno(2, "Vicon unavailable")
                #enableVicon = False
                # flag indicating that "vicon not ready" is currently displayed on line 2
                flag_vicon_not_ready = True
            else:
                if (flag_vicon_not_ready):
                    flag_vicon_not_ready = False
                    displayLineno(2, "Vicon Capture Enabled")
                x, y, z, rx, ry, rz = vicon_state
                text = str(x) + "," + str(y) + "," + str(z) + "," + str(
                    rx) + "," + str(ry) + "," + str(rz)
                text = "%.2f, %.2f, %.2f, %.2f, %.2f, %.2f" % (x, y, z, rx, ry,
                                                               rz)
                displayLineno(3, "Vicon Stream: " + text)
        if (enableJoystick):
            lock_js.acquire()
            local_throttle = js_throttle
            local_flap = js_flap
            lock_js.release()
            displayLineno(
                5, "Joystick: T: %d F: %d ,interval(ms) %d" %
                (local_throttle, local_flap, debug_joy_update_interval_ms))
        screen.refresh()

        # read user input, store in buffer
        user_input = screen.getch()
        while (user_input != -1):
            command += chr(user_input)
            user_input = screen.getch()

        # display user typed command TODO add curser, editing
        # currently no backspace allowed
        screen.addstr(ymax - 1, 0, "Command: " + command)
        #screen.refresh()

        # process command when return is sent
        # command here includes a trailing \n, remove that before parsing
        if (len(command) > 0 and command[-1] == '\n'):
            curses.beep()  #doesn't seem to work
            if (command[:-1] == 'quit') or (command[:-1] == 'q'):
                quit = True
            elif command[:-1] == 'clear':
                screen.clear()
            elif command[:-1] == 'flush':
                avionics.reset_input_buffer()
            elif command[:-1] == 'ping':
                flag_ping_in_progress = True
                tic = time()
                avionics.write("ping\r\n".encode())
                displayLineno(2, "Ping...")
            elif command[:-1] == 'vicon':
                enableVicon = not enableVicon
                if (enableVicon):
                    displayLineno(2, "Vicon Capture Enabled")
                else:
                    displayLineno(2, "Vicon Capture Disabled")
            elif command[:-1] == 'log':
                # toggle logging, start a new file each time
                if (isLogging):
                    # logging was enabled, now stopping logging
                    isLogging = False
                    lock_logfile.acquire()
                    with open(logFilename, 'a') as filehandle:
                        for entry in logBuffer:
                            filehandle.write('%s' % entry)
                    logBuffer = []
                    lock_logfile.release()
                    displayLineno(2, "logfile saved: " + logFilename)
                else:
                    no = 1
                    logBuffer = []
                    while os.path.isfile(logFolder + logPrefix + str(no) +
                                         logSuffix):
                        no += 1
                    logFilename = logFolder + logPrefix + str(no) + logSuffix
                    isLogging = True
                    displayLineno(2, "log started: " + logFilename)
            elif command[:-1] == 'joy':
                # toggle joystick
                if enableJoystick:
                    enableJoystick = False
                    displayLineno(2, "Joystick Disabled")
                    thread_joystick.join()
                else:
                    try:
                        js = pygame.joystick.Joystick(0)
                        js.init()
                        enableJoystick = True
                        thread_joystick = threading.Thread(
                            name="joystickUpdate",
                            target=joystickUpdateDaemon,
                            args=(js, avionics))
                        thread_joystick.start()
                        displayLineno(
                            2, "Joystick Enabled : " + str(js.get_name()))
                    except pygame.error as e:
                        displayLineno(2, "Joystick Not available: " + str(e))

            else:
                # command start with single letter 't': intended for teststand
                # command start with single letter 'a': intended for avionics
                # e.g.  "t sync" -> send "sync" to teststand (with additional trailing \r\n)
                # similarly 'a' for avionics
                # it's ok to send the trailing \n, default behavior or arduino IDE's serial monitor
                if command[0] == 'a':
                    # avionics
                    avionics.write(command[2:].encode())
                    screen.move(ymax - 2, 0)
                    screen.clrtoeol()
                    screen.addstr(ymax - 2, 0,
                                  "Command Sent[avionics]: " + command[2:])
                else:
                    screen.move(ymax - 2, 0)
                    screen.clrtoeol()
                    screen.addstr(ymax - 2, 0,
                                  "Unrecognized command: " + command)

            # clear user input
            screen.move(ymax - 1, 0)
            screen.clrtoeol()
            screen.addstr(ymax - 1, 0, "Command: ")
            screen.refresh()
            command = ""
        screen.refresh()

        # display new data

        if (enablePlot and flap_new_plot_data):
            if (flag_calibrated):
                # update plot (avionics related)

                data00[:-1, :] = data00[
                    1:, :]  # shift data in the temporal mean 1 sample left
                #data01[:-1,:] = data01[1:,:]                          # shift data in the temporal mean 1 sample left
                data10[:-1, :] = data10[
                    1:, :]  # shift data in the temporal mean 1 sample left
                #data11[:-1,:] = data11[1:,:]                      # shift data in the temporal mean 1 sample left

                # x axis
                data00[-1, 0] = avionics_ts / 1000.0  # in second
                # y axis
                #data00[-1,1] = np.linalg.norm(acc1-R_12*acc2)              # vector containing the instantaneous values
                data00[-1, 1] = 0

                # x axis
                data10[-1, 0] = avionics_ts / 1000.0  # in second
                # y axis
                #data00[-1,1] = np.linalg.norm(acc1-R_12*acc2)              # vector containing the instantaneous values
                data10[-1, 1] = 0

                #data10[-1,0] = testStand_ts/1000.0 # in second
                # mag angle dot product
                #data10[-1,1] = np.dot(np.array([0,1,0]),mag/np.linalg.norm(mag))

                # estimated omega from avionics
                #data10[-1,1] = kf_omega

                #data11[-1,0] = testStand_ts/1000.0 # in second
                # angle diff
                #data11[-1,1] = min(abs(int(kf_azimuth) - int(azimuth)),360-abs(int(kf_azimuth) - int(azimuth)))
                #data11[-1,1] = kf_omega - omega

                #screen.addstr(ymax-5,0,str(data01[-1,1]))
                screen.refresh()
                curve00.setData(data00)  # set the curve with this data
                #curve01.setData(data01)                     # set the curve with this data
                curve10.setData(data10)  # set the curve with this data
                #curve11.setData(data11)                     # set the curve with this data
                QtGui.QApplication.processEvents(
                )  # you MUST process the plot now
            flap_new_plot_data = False
def init_screen():
    #Init the terminal interface
    stdscr = curses.initscr()
    screen = stdscr.subwin(23, 79, 0, 0)
    screen.box()
    curses.noecho()
    curses.cbreak()
    #Cursor Invisible
    curses.curs_set(0)
    #screen.keypad(1)
    #Define top menu

    #Output strings
    top_pos = 1
    left_pos = 1
    screen.addstr(top_pos, left_pos, "SMART HOUSE DATA:")

    #Close box
    top_pos = TEMP_POSITION - 1
    left_pos = 1
    screen.addstr(top_pos, left_pos,
                  "-------------------------------------------")

    #Temperature
    top_pos = TEMP_POSITION
    left_pos = 2
    screen.addstr(top_pos, left_pos, "Temperature")
    left_pos = 17
    screen.addstr(top_pos, left_pos, "|")
    left_pos = 20
    screen.addstr(top_pos, left_pos, " ---")
    top_pos = PRES_POSITION
    left_pos = 2
    ######
    top_pos = TEMP_POSITION + 1
    left_pos = 2
    screen.addstr(top_pos, left_pos, "Raspi Temp")
    left_pos = 17
    screen.addstr(top_pos, left_pos, "|")
    left_pos = 20
    screen.addstr(top_pos, left_pos, " ---")
    #Pressure
    top_pos = PRES_POSITION
    left_pos = 2
    screen.addstr(top_pos, left_pos, "Pressure")
    left_pos = 17
    screen.addstr(top_pos, left_pos, "|")
    left_pos = 20
    screen.addstr(top_pos, left_pos, " ---")
    #Altitude
    top_pos = ALT_POSITION
    left_pos = 2
    screen.addstr(top_pos, left_pos, "Altitude")
    left_pos = 17
    screen.addstr(top_pos, left_pos, "|")
    left_pos = 20
    screen.addstr(top_pos, left_pos, " ---")
    #Door
    top_pos = DOOR_POSITION
    left_pos = 2
    screen.addstr(top_pos, left_pos, "Door")
    left_pos = 17
    screen.addstr(top_pos, left_pos, "|")
    left_pos = 20
    screen.addstr(top_pos, left_pos, " ---")
    #Alarm
    top_pos = ALARM_POSITION
    left_pos = 2
    screen.addstr(top_pos, left_pos, "Alarm")
    left_pos = 17
    screen.addstr(top_pos, left_pos, "|")
    left_pos = 20
    screen.addstr(top_pos, left_pos, " ---")
    #Close box
    top_pos = ALARM_POSITION + 1
    left_pos = 1
    screen.addstr(top_pos, left_pos,
                  "-------------------------------------------")

    top_pos = ALARM_POSITION + 2
    left_pos = 1
    screen.addstr(top_pos, left_pos, "Press 'q' to exit")
    screen.refresh()
    return screen
Ejemplo n.º 41
0
    def get_search(self):
        search = self.scr.getstr(0, 13)
        curses.noecho()
        curses.curs_set(0)

        return search
Ejemplo n.º 42
0
def curses_main(args):
    global ready, receiver, sender, current
    try:
        w = curses.initscr()  # initialize
        curses.use_default_colors(
        )  # use the terminal settings for color_pair 0, otherwise it's black and white
        curses.init_pair(1, curses.COLOR_GREEN,
                         curses.COLOR_WHITE)  # define some other color pairs
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
        curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_YELLOW)
        w.bkgd(" ", curses.color_pair(1))  # use a custom for the default
        # curses.echo()                                                 # show what's being typed
        curses.noecho()  # or dont
        while True:

            # draw chat history
            LINES, COLUMNS = w.getmaxyx()
            for i in range(LINES - 1):
                if i < len(messages):
                    message = messages[-1 * (i + 1)]
                    index = messages.index(message)
                    color = 1 if message[0] == 0 else 2
                    w.addstr(LINES - i - 2, 0, "  " + message[1], curses.A_BOLD
                             | curses.color_pair(color))  # draw the line
                else:
                    w.addstr(LINES - i - 2, 0, "")
                w.clrtoeol()  # erase the rest of it

            # take input
            if ready:
                curses.flushinp()
                w.addstr(LINES - 1, 0, "> %s" % "".join(current),
                         curses.color_pair(1))  # display something
                w.clrtoeol()
                curses.curs_set(1)
                ch = w.getch()
                if ch != 10:
                    if ch == 127 or ch == 8:
                        if len(current):
                            current.pop()
                    # elif ch < 128 and len(current) < 30:                    # restrict to ascii. make it 256 if you need latin.
                    elif len(current) < 30 and chr(ch).upper() in CHARACTERS:
                        current.append(chr(ch).upper())
                else:
                    message_s = "".join(current).strip()
                    if message_s == "MARADONA":
                        exit()
                    elif message_s == "UNDO":
                        if len(messages):
                            messages.pop()
                        current = []
                    elif len(message_s):
                        messages.append((0, message_s))
                        sender.messages.put(message_s)
                        current = []
                        flush_messages()
                        ready = False
                # w.addstr(LINES - 1, 0, "> %s" % "".join(current), curses.color_pair(1))          # display something
                w.clrtoeol()  # erase from cursor to end of line
                w.refresh()

            # get a response
            else:
                curses.curs_set(0)
                w.addstr(LINES - 1, 0,
                         "> " + "".join(current) + " " + next(spinner),
                         curses.A_REVERSE | curses.color_pair(2))
                w.clrtoeol()
                w.refresh()
                time.sleep(0.1)
                c = get_message()
                if c is not None:
                    if c == "DONE":
                        messages.append((1, "".join(current)))
                        ready = True
                        current = []
                    elif c == "ERASE":
                        if len(current):
                            current.pop()
                    else:
                        current.append(c)

    except Exception as e:
        log.error(log.exc(e))
Ejemplo n.º 43
0
def run_curses_app():
    stdscr = curses.initscr()
    stdscr.refresh()
    stdscr.keypad(True)
    curses.start_color()
    curses.use_default_colors()
    curses.curs_set(0)
    curses.noecho()

    themes = {s.name: s for s in get_themes(BASE16_SCRIPTS_DIR)}

    scroll_list_cols = 35
    preview_cols = 42

    total_cols = scroll_list_cols + preview_cols

    scroll_list_win = ScrollListWindow(NUM_COLORS, scroll_list_cols)
    preview_win = PreviewWindow(NUM_COLORS, preview_cols, 0, scroll_list_cols)

    preview_win.render()

    scroll_list_win.set_data(sorted(themes.keys()))
    scroll_list_win.render()

    themes[scroll_list_win.value].run_script()

    while True:
        scroll_list_win.render()
        preview_win.render()
        c = stdscr.getch()

        if c == curses.KEY_DOWN:
            scroll_list_win.down()
            themes[scroll_list_win.value].run_script()
        elif c == curses.KEY_UP:
            scroll_list_win.up()
            themes[scroll_list_win.value].run_script()
        elif c == curses.KEY_PPAGE:
            scroll_list_win.up_page()
            themes[scroll_list_win.value].run_script()
        elif c == curses.KEY_NPAGE:
            scroll_list_win.down_page()
            themes[scroll_list_win.value].run_script()
        elif c == curses.KEY_HOME:
            scroll_list_win.top()
            themes[scroll_list_win.value].run_script()
        elif c == curses.KEY_END:
            scroll_list_win.bottom()
            themes[scroll_list_win.value].run_script()
        elif c == ord('q'):
            end_run()
        elif c == ord('\n'):
            theme = themes[scroll_list_win.value]
            theme.run_alias()
            end_run(theme)
        elif c == curses.KEY_RESIZE:
            if curses.LINES < NUM_COLORS:
                raise ValueError('Terminal has less than 22 lines.')
            elif curses.COLS < total_cols:
                raise ValueError(
                    'Terminal has less than {} cols.'.format(total_cols))
Ejemplo n.º 44
0
    def response(self):
        response = self._view.scr.getstr(0, len(self._text) + 1)
        curses.noecho()
        curses.curs_set(0)

        return response
Ejemplo n.º 45
0
import RPi.GPIO as GPIO
import curses

GPIO.setmode(GPIO.BOARD)
list_F = [11, 15, 12, 18]
list_B = [40, 13, 16, 38]
list_L = [11, 15, 16, 38]
list_R = [40, 13, 12, 18]

GPIO.setup(list_F, GPIO.OUT)
GPIO.setup(list_B, GPIO.OUT)
GPIO.setup(list_L, GPIO.OUT)
GPIO.setup(list_R, GPIO.OUT)

stdscr = curses.initscr()  # curses initialization
curses.noecho()  # to turn-off echoing of keybord to screen
curses.cbreak()  # no waiting key response
stdscr.keypad(True)  # spciecial values for cursor keys - keypad mode

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

        if c == ord('q'):
            break

        elif c == ord('s'):
            GPIO.output(list_F, GPIO.LOW)
            GPIO.output(list_B, GPIO.LOW)
            GPIO.output(list_L, GPIO.LOW)
            GPIO.output(list_R, GPIO.LOW)
Ejemplo n.º 46
0
 def log(self, logfile=None):
     r = None
     o = None
     print('Logging...')
     if not args.sim:
         self.mode(EXTERNAL_MODE)
     if logfile:
         self.logfile = logfile
         o = open(self.logfile, 'w')
     if args.raw:
         rawfile = '.'.join([os.path.splitext(self.logfile)[0], 'raw'])
         try:
             r = open(rawfile, 'w')
         except IOError:
             print('Opening raw file {} failed!'.format(rawfile))
             args.raw = False
     line = self.s.readline()
     n = 0
     # set up curses
     screen = curses.initscr()
     curses.noecho()
     curses.cbreak()
     screen.nodelay(1)
     try:
         curses.curs_set(0)
     except:
         pass
     if args.plot:
         fig = plt.figure()
     while True:
         if args.sim:
             time.sleep(self.interval)
         if line.startswith('#d'):
             if args.raw:
                 r.write(line)
             fields = line.split(',')
             if len(fields) > 5:
                 w = float(fields[3]) / 10
                 v = float(fields[4]) / 10
                 a = float(fields[5]) / 1000
                 screen.clear()
                 screen.addstr(2, 4, 'Logging to file %s' % self.logfile)
                 screen.addstr(4, 4, 'Time:     %d s' % n)
                 screen.addstr(5, 4, 'Power:   %3.1f W' % w)
                 screen.addstr(6, 4, 'Voltage: %5.1f V' % v)
                 if a < 1000:
                     screen.addstr(7, 4, 'Current: %d mA' % int(a * 1000))
                 else:
                     screen.addstr(7, 4, 'Current: %3.3f A' % a)
                 screen.addstr(9, 4, 'Press "q" to quit ')
                 # if args.debug:
                 #     screen.addstr(12, 0, line)
                 screen.refresh()
                 c = screen.getch()
                 if c in (ord('q'), ord('Q')):
                     break  # Exit the while()
                 if args.plot:
                     self.t.append(float(n))
                     self.power.append(w)
                     self.potential.append(v)
                     self.current.append(a)
                     fig.clear()
                     plt.plot(
                         np.array(self.t) / 60, np.array(self.power), 'r')
                     ax = plt.gca()
                     ax.set_xlabel('Time (minutes)')
                     ax.set_ylabel('Power (W)')
                     # show the plot
                     fig.canvas.draw()
                 if self.logfile:
                     o.write('%s %d %3.1f %3.1f %5.3f\n' %
                             (datetime.datetime.now(), n, w, v, a))
                 n += self.interval
         line = self.s.readline()
     curses.nocbreak()
     curses.echo()
     curses.endwin()
     try:
         o.close()
     except:
         pass
     if args.raw:
         try:
             r.close()
         except:
             pass
Ejemplo n.º 47
0
    def form_groups(self):
        try:
            # Start curses
            stdscr = curses.initscr()
            curses.noecho()
            curses.cbreak()
            stdscr.keypad(True)
            curses.start_color()
            curses.use_default_colors()
            curses.init_pair(1, curses.COLOR_RED, -1)  #curses.COLOR_BLACK)
            curses.init_pair(2, 14, -1)  #curses.COLOR_BLACK)
            curses.init_pair(3, curses.COLOR_GREEN, -1)  #curses.COLOR_BLACK)

            groups = {}
            ungrouped = list(range(len(self.answers)))

            # Begin loop
            text = ""
            g_tmp = {}
            g_off = 0
            while True:
                valid = False
                if "quit".startswith(text) or "exit".startswith(text):
                    valid = True
                g_tmp = self.validate_command(text, groups, ungrouped)
                if g_tmp != False:
                    valid = True
                else:
                    g_tmp = {}
                y, x = self.draw_screen(stdscr, groups, ungrouped, text, valid,
                                        g_tmp, g_off)

                # Get input
                c = stdscr.getch(y, x)
                if ord(' ') <= c <= ord('~'):
                    text += chr(c)
                elif c in [8, 127, curses.KEY_BACKSPACE] and len(text) > 0:
                    text = text[:-1]
                elif c in [10, 13, curses.KEY_ENTER]:
                    if "quit".startswith(text) or "exit".startswith(text):
                        break
                    if self.process_command(text, groups, ungrouped):
                        g_tmp = {}
                        text = ""
                elif c == 260:
                    # left
                    if g_off > 0:
                        g_off -= 1
                elif c == 261:
                    # right
                    if g_off < len(groups) - 1:
                        g_off += 1

        finally:
            # save groups
            filename = self.save_groups(groups, ungrouped)

            # Terminate curses
            curses.nocbreak()
            stdscr.keypad(False)
            curses.echo()
            curses.endwin()

            print(f"Session saved in {filename}")
Ejemplo n.º 48
0
def intercept(line):
    """
    Intercept requests and/or responses and edit them with before passing them along
    Usage: intercept <reqid>
    """
    global edit_queue
    args = shlex.split(line)
    intercept_requests = False
    intercept_responses = False

    req_names = ('req', 'request', 'requests')
    rsp_names = ('rsp', 'response', 'responses')

    if any(a in req_names for a in args):
        intercept_requests = True
    if any(a in rsp_names for a in args):
        intercept_responses = True

    if intercept_requests and intercept_responses:
        intercept_str = 'Requests and responses'
    elif intercept_requests:
        intercept_str = 'Requests'
    elif intercept_responses:
        intercept_str = 'Responses'
    else:
        intercept_str = 'NOTHING'

    mangle_macro = MangleInterceptMacro()
    mangle_macro.intercept_requests = intercept_requests
    mangle_macro.intercept_responses = intercept_responses

    add_intercepting_macro('pappy_intercept', mangle_macro)

    ## Interceptor loop
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        editnext = False
        stdscr.nodelay(True)
        while True:
            stdscr.addstr(0, 0, "Currently intercepting: %s" % intercept_str)
            stdscr.clrtoeol()
            stdscr.addstr(1, 0, "%d item(s) in queue." % len(edit_queue))
            stdscr.clrtoeol()
            if editnext:
                stdscr.addstr(
                    2, 0,
                    "Waiting for next item... Press 'q' to quit or 'b' to quit waiting"
                )
            else:
                stdscr.addstr(
                    2, 0,
                    "Press 'n' to edit the next item or 'q' to quit interceptor."
                )
            stdscr.clrtoeol()

            c = stdscr.getch()
            if c == ord('q'):
                break
            elif c == ord('n'):
                editnext = True
            elif c == ord('b'):
                editnext = False

            if editnext and edit_queue:
                editnext = False
                (to_edit, deferred) = edit_queue.pop(0)
                editor = 'vi'
                if 'EDITOR' in os.environ:
                    editor = os.environ['EDITOR']
                additional_args = []
                if editor == 'vim':
                    # prevent adding additional newline
                    additional_args.append('-b')
                subprocess.call([editor, to_edit] + additional_args)
                stdscr.clear()
                deferred.callback(None)
    finally:
        curses.nocbreak()
        stdscr.keypad(0)
        curses.echo()
        curses.endwin()
        try:
            remove_intercepting_macro('pappy_intercept')
        except PappyException:
            pass
        # Send remaining requests along
        while len(edit_queue) > 0:
            (fname, deferred) = edit_queue.pop(0)
            deferred.callback(None)
Ejemplo n.º 49
0
 def __init__(self):
     self.running = True
     self.paused = False
     self.DATA_Y = 1
     self.DATA_X = 0
     self.DATA_H = 29
     self.DATA_W = 32
     self.PLAYERS_Y = 1
     self.PLAYERS_X = self.DATA_X + self.DATA_W + 2
     self.PLAYERS_H = 21
     self.PLAYERS_W = 66
     self.MAP_Y = 1
     self.MAP_X = self.PLAYERS_X + self.PLAYERS_W + 2
     self.MAP_H = 0
     self.MAP_W = 0
     self.PATH_Y = self.PLAYERS_Y + self.PLAYERS_H + 3
     self.PATH_X = self.DATA_X + self.DATA_W + 2
     self.PATH_H = 5
     self.PATH_W = 66
     self.LOG_Y = self.DATA_Y + self.DATA_H + 2
     self.LOG_X = 0
     self.LOG_H = 12
     self.LOG_W = self.DATA_W + self.PLAYERS_W + 2
     self.HELP_Y = self.LOG_Y + self.LOG_H - 2
     self.HELP_X = 1
     self.HELP_H = 1
     self.HELP_W = self.LOG_W - 2
     self.TIME_Y = self.LOG_Y + self.LOG_H + 2
     self.TIME_X = 0
     self.TIME_H = 0
     self.TIME_W = 0
     self.MENU_Y = 0
     self.MENU_X = 0
     self.MENU_H = 24
     self.MENU_W = 0
     self.SUMMARY_Y = self.LOG_Y + 5
     self.SUMMARY_X = self.LOG_X + self.LOG_W + 2
     self.SUMMARY_H = 7
     self.SUMMARY_W = 20
     self.data_win = None
     self.map_win = None
     self.path_win = None
     self.log_win = None
     self.help_win = None
     self.players_win = None
     self.time_win = None
     self.menu_win = None
     self.time_win = None
     self.summary_win = None
     self.log_entries = []
     self.stdscr = curses.initscr()
     curses.start_color()
     # Basic color set
     curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_WHITE)
     curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED)
     curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
     curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
     curses.init_pair(5, curses.COLOR_GREEN, curses.COLOR_BLACK)
     curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLUE)
     curses.init_pair(7, curses.COLOR_CYAN, curses.COLOR_BLACK)
     curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
     curses.init_pair(9, curses.COLOR_WHITE, curses.COLOR_GREEN)
     curses.init_pair(10, curses.COLOR_WHITE, curses.COLOR_YELLOW)
     # check for minimal screen size
     screen_y, screen_x = self.stdscr.getmaxyx()
     if screen_y < MIN_LINES or screen_x < MIN_COLS:
         # Try resizing terminal
         curses.resizeterm(MIN_LINES, MIN_COLS)
         if not curses.is_term_resized(MIN_LINES, MIN_COLS):
             self.quit_ui()
             print "Unable to change your terminal size. Your terminal must be at least", \
                     MIN_LINES, "lines and", MIN_COLS, "columns and it actually has", \
                     screen_y, "lines and", screen_x, "columns."
             quit(1)
     # Screen is up
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     self.stdscr.keypad(1)
Ejemplo n.º 50
0
def game():
    screen.clear()  #clear the screen in the start
    curses.start_color()  #black background
    curses.curs_set(0)  # cursor visibility zero
    curses.noecho()  #does not echo the keys pressed
    screen.border()  # sets a border
    screen.nodelay(1)  # so we dont have to wait for anything to happen
    head = [random.randrange(1, h - 1), random.randrange(1, w - 1)]
    body = [head[:]] * startlength

    gameover = False
    direction = 0  # 0: right, 1: down, 2: left, 3: up
    q = 0
    deadcell = body[-1][:]
    foodmade = False

    while not gameover:
        while not foodmade:
            y, x = random.randrange(1, h - 1), random.randrange(1, w - 1)
            if screen.inch(y, x) == ord(' '):
                screen.addch(y, x, ord('$'))
                foodmade = True

        if deadcell not in body:
            screen.addch(deadcell[0], deadcell[1], ' ')

        action = screen.getch()
        if action == curses.KEY_UP and direction != 1:
            direction = 3
        if action == curses.KEY_DOWN and direction != 3:
            direction = 1
        if action == curses.KEY_LEFT and direction != 0:
            direction = 2
        if action == curses.KEY_RIGHT and direction != 2:
            direction = 0

        screen.addch(head[0], head[1], curses.ACS_CKBOARD)

        if direction == 0:
            head[1] += 1
        if direction == 2:
            head[1] -= 1
        if direction == 1:
            head[0] += 1
        if direction == 3:
            head[0] -= 1

        deadcell = body[-1][:]
        for z in range(len(body) - 1, 0, -1):
            body[z] = body[z - 1][:]

        body[0] = head[:]
        #check for border
        if screen.inch(head[0], head[1]) != ord(' '):
            if screen.inch(head[0], head[1]) == ord('$'):
                foodmade = False

                for i in range(growlength):
                    body.append(body[-1])

            else:
                gameover = True
        screen.refresh()
        if not accelration:
            time.sleep(speed[difficulty])
        else:
            time.sleep(15. * speed[difficulty] / len(body))

    screen.clear()
    screen.nodelay(0)
    message1 = "Game Over"
    message2 = 'Your Score is ' + str(
        int((len(body) - startlength) / growlength))
    message3 = 'Press Space to play again'
    message4 = 'Press Enter to quit'
    message5 = 'Press M to go back to the menu'
    screen.addstr(int(h / 2 - 1), int((w - len(message1)) / 2), message1)
    screen.addstr(int(h / 2), int((w - len(message2)) / 2), message2)
    screen.addstr(int(h / 2 + 1), int((w - len(message3)) / 2), message3)
    screen.addstr(int(h / 2 + 2), int((w - len(message4)) / 2), message4)
    screen.addstr(int(h / 2 + 3), int((w - len(message5)) / 2), message5)

    screen.refresh()
    while q not in [32, 10, 77, 109]:
        q = screen.getch()

    if q == 32:
        screen.clear()
        game()
    elif q == 10:
        curses.endwin()
    elif q in [77, 109]:
        menu()
Ejemplo n.º 51
0
def initCurses(scr):
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    scr.keypad(1)
    scr.nodelay(True)
Ejemplo n.º 52
0
def file_func():
    s = curses.newwin(6, 10, 2, 1)
    s.box()
    s.addstr(1, 2, "I", hotkey_attr)
    s.addstr(1, 3, "nput", menu_attr)
    s.addstr(2, 2, "O", hotkey_attr)
    s.addstr(2, 3, "utput", menu_attr)
    s.addstr(3, 2, "T", hotkey_attr)
    s.addstr(3, 3, "ype", menu_attr)
    s.addstr(4, 2, "U", hotkey_attr)
    s.addstr(4, 3, "pdate", menu_attr)
    s.addstr(1, 2, "", hotkey_attr)
    s.refresh()
    c = s.getch()
    if c in (ord('U'), ord('u')):  # Remote function update
        update_txt2html()
    elif c in (ord('I'), ord('i'), curses.KEY_ENTER, 10):
        curses.echo()
        s.erase()
        screen.addstr(5, 33, " " * 43, curses.A_UNDERLINE)
        cfg_dict['source'] = screen.getstr(5, 33)
        curses.noecho()
    elif c in (ord('O'), ord('o')):
        curses.echo()
        s.erase()
        screen.addstr(8, 33, " " * 43, curses.A_UNDERLINE)
        cfg_dict['target'] = screen.getstr(8, 33)
        curses.noecho()
    elif c in (ord('T'), ord('t')):
        s.addstr(3, 7, "->", menu_attr)
        s.refresh()
        s2 = curses.newwin(8, 15, 4, 10)
        s2.box()
        s2.addstr(1, 2, "H", hotkey_attr)
        s2.addstr(1, 3, "TML", menu_attr)
        s2.addstr(2, 2, "P", hotkey_attr)
        s2.addstr(2, 3, "ython", menu_attr)
        s2.addstr(3, 2, "F", hotkey_attr)
        s2.addstr(3, 3, "AQ", menu_attr)
        s2.addstr(4, 2, "S", hotkey_attr)
        s2.addstr(4, 3, "mart_ASCII", menu_attr)
        s2.addstr(5, 2, "R", hotkey_attr)
        s2.addstr(5, 3, "aw", menu_attr)
        s2.addstr(6, 2, "I", hotkey_attr)
        s2.addstr(6, 3, "nfer Type", menu_attr)
        s2.addstr(6, 2, "", hotkey_attr)
        s2.refresh()
        c = s2.getch()
        if c in (ord('I'), ord('i'), curses.KEY_ENTER, 10):
            cfg_dict['type'] = 'INFER'
        elif c in (ord('H'), ord('h')):
            cfg_dict['type'] = 'HTML'
        elif c in (ord('P'), ord('p')):
            cfg_dict['type'] = 'PYTHON'
        elif c in (ord('F'), ord('f')):
            cfg_dict['type'] = 'FAQ'
        elif c in (ord('S'), ord('s')):
            cfg_dict['type'] = 'SMART_ASCII'
        elif c in (ord('R'), ord('r')):
            cfg_dict['type'] = 'RAW'
        else:
            curses.beep()
        s2.erase()
        s.erase()
    else:
        curses.beep()
        s.erase()
    return CONTINUE
Ejemplo n.º 53
0
    def __init__(self, rcon, config):
        self.rcon = rcon
        self.logFile = None
        self.logThread = None
        self.cancelCommand = False

        self.setLogfile(config['logfile'])

        self.navigation = {
            'menu': self.showMenu,
            'playermenu': self.showPlayerMenu,
            'player': self.showPlayers,
            'missionmenu': self.showMissionMenu,
            'command': self.showCommandLine
        }
        self.mainmenu = [('Refresh Players', self.fetchPlayers),
                         ('Manage Whitelist', self.manageWhitelist),
                         ('Restart Mission...', self.fetchMissions),
                         ('Kick All', self.rcon.kickAll),
                         ('Shutdown Server', self.shutdownServer),
                         ('Restart Server (v1.65)', self.restartServer),
                         ('Exit', None)]

        self.playermenu = []
        self.missionmenu = []
        self.backMenu = [('Main Menu', self.getMainMenu)]

        self.__navigation = self.getMainMenu()
        self.__prevnav = None
        # menu cursor position
        self.position = 0
        # is whitelist
        self.isWhitelist = False
        # player cursor position
        self.playerpos = 0
        self.players = []

        self.posAndSize = {
            # height, width, ypos, xpos
            'menu': [27, 30, 1, 1],
            'log': [8, 131, 31, 1],
            'cmd': [3, 131, 28, 1],
            'cmdTextbox': [1, 120, 29, 3],
            'player': [27, 100, 1, 32]
        }

        try:
            self.screen = curses.initscr()

            if not self.checkMaxSize():
                curses.endwin()
                print('THE TERMINAL WINDOW IS TO SMALL (width/height)')
                return

            self.initColors()

            curses.cbreak()
            curses.noecho()
            curses.curs_set(0)

            self.menuWnd = self.screen.subwin(*self.posAndSize['menu'])
            self.menuWnd.keypad(1)

            self.logWnd = self.screen.subwin(*self.posAndSize['log'])

            self.cmdWnd = self.screen.subwin(*self.posAndSize['cmd'])
            self.cmdTextbox = self.screen.subwin(
                *self.posAndSize['cmdTextbox'])

            self.playerWnd = self.screen.subwin(*self.posAndSize['player'])

        except:
            curses.endwin()
            raise
Ejemplo n.º 54
0
"""

Filename:     snake_main.py
Author:       Kyle Cookerly

Description:  Console-based Snake clone, written in Python 3.5.1
              using the curses module.

"""
import curses                                  # For terminal control
from game import Game
from game_state_screens import draw_start_window, draw_game_over_window, draw_option_select_window


curses.initscr()                                # Starts screen
curses.noecho()                                 # Hides the keyboard input from the terminal
curses.curs_set(0)


def main():
    draw_start_window()
    game_mode = draw_option_select_window()     # Draws the option screen and assigns the value received to game_mode
    snake_game = Game(game_mode)

    while not snake_game.is_game_over():
        snake_game.run_game()

    snake_game.end_window()
    draw_game_over_window(snake_game.get_game_score())

if __name__ == "__main__":
Ejemplo n.º 55
0
from random import *
import time, sys
import curses as h
w = h.initscr()
h.noecho()  #
P, Q, m, s, e, p, a, q = 20, 10, 5, 300, {
    0: "· ",
    1: "██"
}, [
    [[1, 1]] * 2,
    [[0, 1, 0], [1] * 3, [0] * 3],
    [
        [
            1  #
            ,
            0,
            0
        ],
        [1] * 3,
        [0] * 3
    ],
    [[0, 0, 1], [1] * 3, [0] * 3],
    [[1, 1, 0], [0, 1, 1], [0] * 3],
    [
        [0, 1, 1],
        [
            1,
            1,
            0  #
        ],
        [0] * 3
Ejemplo n.º 56
0
    def __init__(
        self,
        web_port=26000,
        window_height=40,
        window_width=130,
        auto_scoll=True,
        max_log_lines=500,
        wait_on_quit=True,
        min_refresh_rate=1000,
        bytes_to_str=DEFAULT_HEX_TO_STR,
    ):
        """
        :type web_port: int
        :param web_port: Webinterface port. Default 26000

        :type window_height: int
        :param window_height: Default console heigth, set to on startup. Default 40

        :type window_width: int
        :param window_width: Default console width, set to on startup. Default 130

        :type auto_scoll: bool
        :param auto_scoll: Whether to auto-scoll the cases and crashed windows to allways display the last line if there
                           are too many lines to display all of them. Default True

        :type max_log_lines: int
        :param max_log_lines: Maximum log lines to keep in the internal storage. Additional lines exceeding this limit
                              will not be displayed. Default 500

        :type wait_on_quit: bool
        :param wait_on_quit: Whether to keep the GUI open and wait for user-input when the main thread is about to exit.
                             Default True

        :type min_refresh_rate: int
        :param min_refresh_rate: The delay between two checks for a resize of the terminal in milliseconds.
                                 Increment 100 ms. Default 1000 ms

        :type bytes_to_str: function
        :param bytes_to_str: Function that converts sent/received bytes data to string for logging.
        """

        self._title = "boofuzz"
        self._web_port = web_port
        self._max_log_lines = max_log_lines
        self._auto_scroll = auto_scoll
        self._current_data = None
        self._log_storage = []
        self._fail_storage = []
        self._wait_on_quit = wait_on_quit
        self._quit = False
        self._status = 0  # 0: Running 1: Paused 2: Done
        self._refresh_interval = min_refresh_rate
        self._event_resize = True
        self._event_log = False
        self._event_case_close = False
        self._event_crash = False

        self._total_index = 0
        self._total_num_mutations = 0
        self._current_name = ""
        self._current_index = 0
        self._current_num_mutations = 0

        self._format_raw_bytes = bytes_to_str
        self._version = helpers.get_boofuzz_version(helpers)

        # Resize console to minimum size
        self._width, self._height = get_terminal_size()
        if self._height < window_height or self._width < window_width:
            print("\x1b[8;{};{}t".format(window_height, window_width))
            self._height, self._width = window_height, window_width
        self._height_old = 0
        self._width_old = 0
        self._min_size_ok = True

        self._stdscr = curses.initscr()
        curses.start_color()
        curses.use_default_colors()
        curses.noecho()
        curses.curs_set(0)
        self._stdscr.nodelay(1)

        # Curses color pairs
        curses.init_pair(1, curses.COLOR_WHITE, -1)
        curses.init_pair(2, curses.COLOR_CYAN, -1)
        curses.init_pair(3, curses.COLOR_RED, -1)
        curses.init_pair(4, curses.COLOR_YELLOW, -1)
        curses.init_pair(5, curses.COLOR_GREEN, -1)
        curses.init_pair(6, curses.COLOR_MAGENTA, -1)
        curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_WHITE)

        # Start thread and restore the original SIGWINCH handler
        self._draw_thread = threading.Thread(name="curses_logger",
                                             target=self._draw_screen)
        current_signal_handler = signal.getsignal(signal.SIGWINCH)
        self._draw_thread.start()
        signal.signal(signal.SIGWINCH, current_signal_handler)
Ejemplo n.º 57
0
# This script calculates the distance between an HC-SR04 module and the nearest object.
# It is capable of handling multiple modules simultaneously.
#
# version: 1.0 (30.12.2019)

import RPi.GPIO as GPIO
import time
import curses  # keyboard input and interface

screen = curses.initscr()  # create new screen
screen.nodelay(True)  # .getch() is ignored if no keyboard input is detected
curses.noecho()  # do not ECHO_1 keyboard input
curses.cbreak()  # disable return-press for input
screen.keypad(True)  # enable special-keys

GPIO.setmode(GPIO.BCM)  # set GPIO mode

TRIG_1 = 18  # trigger pin of HC-SR04 module(front)
TRIG_2 = 23  # trigger pin of HC-SR04 module(side)
TRIG_3 = 25  # trigger pin of HC-SR04 module(back)
TRIG_4 = 24  # trigger pin of HC-SR04 module(back-angled)
ECHO_1 = 4  # echo pin of HC-SR04 module(front)
ECHO_2 = 17  # echo pin of HC-SR04 module(side)
ECHO_3 = 22  # echo pin of HC-SR04 module(back)
ECHO_4 = 27  # echo pin of HC-SR04 module(back-angled)

# define all trigger pins as outputs and all echo pins as inputs
# make sure all pins ar free to use to avoid data collision
GPIO.setup(TRIG_1, GPIO.OUT)
GPIO.setup(ECHO_1, GPIO.IN)
GPIO.setup(TRIG_2, GPIO.OUT)
Ejemplo n.º 58
0
    def init_curses(self):
        self.screen = curses.initscr()
        self.screen.keypad(True)

        curses.noecho()
        curses.mousemask(True)
Ejemplo n.º 59
0
def main(screen):
    log_close = False
    flood = "The pond breached its banks and flooded the farmer's field"
    dry = "The low water level led to catfish mutations.  They walked \ninto the farmer's fields and ate all the crops."
    success = "Well done! You have protected the farm's infrastructure.  \nThe lab is completed."
    clear = ' ' * 200
    buf = doMap()
    # Now create an int in the memory mapping
    water_level = ctypes.c_int.from_buffer(buf)
    pump_running = ctypes.c_int.from_buffer(buf, 4)
    loader_ready = ctypes.c_int.from_buffer(buf, 8)
    reset_counter = ctypes.c_int.from_buffer(buf, 12)
    while loader_ready.value == 0:
        time.sleep(1)
    logging.debug("physical_world,  loader must be ready")
    water_level.value = 20
    ''' rate of water leaving via drain (when open)'''
    out_flow_rate = 2
    ''' rate of water coming in '''
    in_flow_rate = 1
    curses.noecho()
    curses.cbreak()
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLUE)
    curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    screen.bkgd(curses.color_pair(2))
    #screen.keypad(1)
    screen.nodelay(1)
    screen.refresh()
    #win = curses.newwin(5,20,5,5)
    #win.bkgd(curses.color_pair(2))
    #win.box()

    paused = False
    screen.addstr(2, 1, "Status of Farmer Jones' catfish pond water level")
    lab_success = False
    while True:
        if not lab_success:
            lab_success = logWaterLevel(water_level.value, reset_counter.value)
        if pump_running.value == 1 and water_level.value > 0:
            water_level.value -= out_flow_rate
            #print('pump running')
            screen.addstr(8, 1, "Pump: running")
            sys.stdout.write('\x1b]2;Physical_World: Pump running\x07')
            sys.stdout.flush()
        else:
            screen.addstr(8, 1, "Pump: stopped")
            sys.stdout.write('\x1b]2;Physical_World: Pump stopped\x07')
            sys.stdout.flush()
        if water_level.value < 42:
            water_level.value += in_flow_rate
        screen.addstr(11, 1, "Pond water level: %4d" % water_level.value)
        #print('current level is %s' % water_level.value)
        if water_level.value > 40:
            screen.addstr(15, 1, flood)
            sys.stdout.write('\x1b]2;Physical_World: Fields Flooded\x07')
            sys.stdout.flush()
        elif water_level.value < 5:
            screen.addstr(15, 1, dry)
            sys.stdout.write('\x1b]2;Physical_World: Pond Dry\x07')
            sys.stdout.flush()
        elif lab_success:
            screen.addstr(15, 1, success)
            sys.stdout.write('\x1b]2;Physical_World: Success\x07')
            sys.stdout.flush()
        else:
            screen.addstr(15, 1, clear)
        screen.refresh()
        c = screen.getch()
        if c == 32:
            paused = not paused
        time.sleep(1)
    raw_input("any key to end")
Ejemplo n.º 60
0
import numpy as np
from skimage.measure import compare_ssim as ssim
from PIL import Image, ImageSequence
import cv2
import time
import curses

from process_font import font_image, font_size, CHARS

VIDEO_FILE = './test.mp4'

stdscr = curses.initscr()  # initialize the screen
curses.noecho()  # hide user key input

latest_scr = []


def main():
    vid = cv2.VideoCapture(VIDEO_FILE)
    while (True):
        ret, frame = vid.read()
        if not ret:
            break
        frame_pixels = np.mean(np.asarray(frame), -1)
        ratio = frame_pixels.shape[1] / \
            frame_pixels.shape[0] * font_size[1] / font_size[0]
        x = curses.COLS
        y = curses.LINES
        if (x / y > ratio):  # maintain aspect ratio
            x = int(y * ratio)
        else: