예제 #1
0
파일: main.py 프로젝트: froozen/tsnb
def tsnb(stdscr, parsed_args):
    # Initialize the colors
    curses.use_default_colors()

    curses.init_pair(1, -1, curses.COLOR_BLUE) # Selection
    curses.init_pair(2, curses.COLOR_CYAN, -1) # Tree-Symbols

    if parsed_args.notebook_id == None:
        # Start off in notebook_selection_scene
        import notebook_selection_scene
        notebook_selection_scene.init(stdscr)
        scene_handler.scene = notebook_selection_scene

    else:
        # Start off in selected notebook_editing_scene
        import notebook_editing_scene
        notebook_editing_scene.init(stdscr, parsed_args.notebook_id)
        scene_handler.scene = notebook_editing_scene
    
    run = True
    while run:
        scene_handler.scene.redraw(stdscr)
        stdscr.refresh()

        c = stdscr.getch()

        run = scene_handler.scene.handle_input(stdscr, c)

    notebooks.save_notebooks()
예제 #2
0
def main(window):

    curses.curs_set(0)
    curses.cbreak()
    curses.use_default_colors()
    window.nodelay(1)
    window.border(0)
    display_win = window.subwin(45, 100, 0, 0)

    chat_win = window.subwin(20, 80, 0, 101)
    chat_panel = curses.panel.new_panel(chat_win)
    chatbox = ChatBox(chat_panel, 20, 80)

    cl = EchoClientFactory(chatbox) 

    def mainloop():
        ch = window.getch()
        curses.flushinp()
        if ch > 0:
            chatbox.add_message(chr(ch))
            cl.sendMessage(chr(ch))
        display_win.refresh()


    point = TCP4ClientEndpoint(reactor, "localhost", 8123)

    d = point.connect(cl)
    d.addCallback(lambda data: chatbox.add_message('p'))

    l = task.LoopingCall(mainloop)
    l.start(0.1)
    #reactor.connectTCP('localhost', 8123, cl)
    
    reactor.run()
예제 #3
0
 def __init__(self):
     self.screen = curses.initscr()
     curses.start_color()
     curses.use_default_colors()
     curses.curs_set(0)
     self.use_black_text()
     self.shape = (curses.COLS - 1, curses.LINES - 1)
예제 #4
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()
예제 #5
0
def main(screen):
    # Setup a window object, misc
    curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    curses.cbreak()  # No need for [Return]
    curses.noecho()  # Stop keys being printed
    curses.curs_set(0)  # Invisible cursor
    screen.keypad(True)
    screen.clear()
    screen.border(0)

    # Setup color pairs
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)

    # Setup background
    screen.bkgd(' ', curses.color_pair(1))

    # Setup constants
    CENTER = get_pos_consts(screen)
    
    # Execute
    while True:
        choice = startup_menu(screen, CENTER)
        if choice.func is not None:
            choice(screen)
예제 #6
0
def main(win):
	curses.start_color()
	curses.use_default_colors()
	curses.init_color(curses.COLOR_GREEN, 797, 0, 0)
	curses.init_pair(1,curses.COLOR_GREEN,curses.COLOR_BLACK)
	win.addstr(str(curses.can_change_color()), curses.color_pair(1))
	win.refresh()
예제 #7
0
파일: ui.py 프로젝트: niksfirefly/ranger
    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()
예제 #8
0
파일: display.py 프로젝트: sankitch/percol
    def __init__(self, screen, encoding):
        self.screen   = screen
        self.encoding = encoding
        self.parser   = markup.MarkupParser()

        curses.start_color()

        self.has_default_colors = curses.COLORS > COLOR_COUNT

        if self.has_default_colors:
            # xterm-256color
            curses.use_default_colors()
            FG_COLORS["default"]    = -1
            BG_COLORS["on_default"] = -1
            self.init_color_pairs()
        elif curses.COLORS != 0:
            # ansi linux rxvt ...etc.
            curses.use_default_colors()
            self.init_color_pairs()
            FG_COLORS["default"]    = curses.COLOR_WHITE
            BG_COLORS["on_default"] = curses.COLOR_BLACK
        else: # monochrome, curses.COLORS == 0
            # vt100 x10term wy520 ...etc.
            FG_COLORS["default"]    = curses.COLOR_WHITE
            BG_COLORS["on_default"] = curses.COLOR_BLACK

        self.update_screen_size()
예제 #9
0
파일: uiTyrs.py 프로젝트: divarvel/tyrs
    def initColors (self):
        curses.start_color()

        if self.conf.params_transparency:
            curses.use_default_colors()
            bgcolor = -1
        else:
            bgcolor = 0

        # Setup colors
        # TODO, check the term capability before
        if curses.can_change_color():
            for i in range(len(self.conf.color_set)):
                if not self.conf.color_set[i]:
                    continue
                else:
                    rgb = self.conf.color_set[i]
                    curses.init_color(i, rgb[0], rgb[1], rgb[2])

        curses.init_pair(0, curses.COLOR_BLACK, bgcolor)    # 1 black
        curses.init_pair(1, curses.COLOR_RED, bgcolor)      # 2 red
        curses.init_pair(2, curses.COLOR_GREEN, bgcolor)    # 3 green
        curses.init_pair(3, curses.COLOR_YELLOW, bgcolor)   # 4 yellow
        curses.init_pair(4, curses.COLOR_BLUE, bgcolor)     # 5 blue
        curses.init_pair(5, curses.COLOR_MAGENTA, bgcolor)  # 6 magenta
        curses.init_pair(6, curses.COLOR_CYAN, bgcolor)     # 7 cyan
        curses.init_pair(7, curses.COLOR_WHITE, bgcolor)    # 8 white
예제 #10
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()
예제 #11
0
파일: beast.py 프로젝트: gwillem/hyperbeast
 def setup(cls):
     curses.start_color()
     curses.use_default_colors()
     # -1 = transparent
     curses.init_pair(cls.sand, curses.COLOR_YELLOW, curses.COLOR_YELLOW)
     curses.init_pair(cls.hero, curses.COLOR_GREEN, -1)
     curses.init_pair(cls.monster, curses.COLOR_RED, -1)
예제 #12
0
파일: monitor.py 프로젝트: eerimoq/cantools
    def __init__(self, stdscr, args):
        self._stdscr = stdscr
        self._dbase = database.load_file(args.database,
                                         encoding=args.encoding,
                                         frame_id_mask=args.frame_id_mask,
                                         strict=not args.no_strict)
        self._single_line = args.single_line
        self._filtered_sorted_message_names = []
        self._filter = ''
        self._compiled_filter = None
        self._formatted_messages = {}
        self._playing = True
        self._modified = True
        self._show_filter = False
        self._queue = Queue()
        self._nrows, self._ncols = stdscr.getmaxyx()
        self._received = 0
        self._discarded = 0
        self._basetime = None

        stdscr.nodelay(True)
        curses.use_default_colors()
        curses.curs_set(False)
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)

        bus = self.create_bus(args)
        self._notifier = can.Notifier(bus, [self])
예제 #13
0
파일: term.py 프로젝트: bbusse/hatcog
    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
예제 #14
0
    def __init__(self, stdscr, lineObjs):
        curses.use_default_colors()
        self.stdscr = stdscr
        self.colorPrinter = ColorPrinter(self.stdscr)

        self.lineObjs = lineObjs
        self.hoverIndex = 0
        self.scrollOffset = 0
        self.scrollBar = ScrollBar(self.colorPrinter, lineObjs, self)
        self.helperChrome = HelperChrome(self.colorPrinter, self)
        (self.oldmaxy, self.oldmaxx) = self.getScreenDimensions()
        self.mode = SELECT_MODE

        self.simpleLines = []
        self.lineMatches = []
        # lets loop through and split
        for key, lineObj in self.lineObjs.items():
            lineObj.setController(self)
            if (lineObj.isSimple()):
                self.simpleLines.append(lineObj)
            else:
                self.lineMatches.append(lineObj)

        self.numLines = len(lineObjs.keys())
        self.numMatches = len(self.lineMatches)

        self.setHover(self.hoverIndex, True)

        # the scroll offset might not start off
        # at 0 if our first real match is WAY
        # down the screen -- so lets init it to
        # a valid value after we have all our line objects
        self.updateScrollOffset()
        logger.addEvent('init')
예제 #15
0
파일: curses_test.py 프로젝트: MattCCS/PyZ
def main(stdscr):
    curses.start_color()
    curses.use_default_colors()

    for bg in range(256):
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, bg)
        try:
            for i in range(256):
                # c = str(i)
                c = curses.ACS_ULCORNER
                c = ord('a')
                c = u'\u239e'
                c = u'\u2588'
                # c = 9608
                # c = u'\u239e'.encode("utf-8")
                # c = u'\u0438'.encode('utf-8')
                stdscr.addstr(c, curses.color_pair(i))
                # stdscr.addch(9118)
                # stdscr.addstr('\\u239e')
                # stdscr.addch(c)
                if i < 16:
                    stdscr.addstr(' ', curses.color_pair(i))
                if i in (16,52,88,124,160,196,232,):
                    stdscr.addstr('\n', curses.color_pair(i))
            stdscr.addstr('\n', curses.color_pair(i))
        except curses.error:
            # End of screen reached
            pass
        if stdscr.getch() == ord('q'):
            break
        stdscr.clear()
예제 #16
0
    def start(self):
        """
        Initialize the screen and input mode.
        """
        assert self._started == False

        self.s = curses.initscr()
        self.has_color = curses.has_colors()
        if self.has_color:
            curses.start_color()
            if curses.COLORS < 8:
                # not colourful enough
                self.has_color = False
        if self.has_color:
            try:
                curses.use_default_colors()
                self.has_default_colors=True
            except _curses.error:
                self.has_default_colors=False
        self._setup_colour_pairs()
        curses.noecho()
        curses.meta(1)
        curses.halfdelay(10) # use set_input_timeouts to adjust
        self.s.keypad(0)
        
        if not self._signal_keys_set:
            self._old_signal_keys = self.tty_signal_keys()

        super(Screen, self).start()
예제 #17
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)
예제 #18
0
 def initcolors_1(self):
     curses.start_color()
     curses.use_default_colors()
     curses.init_pair(1, -1, -1)
     curses.init_pair(2, curses.COLOR_GREEN, -1)
     curses.init_pair(3, curses.COLOR_RED, -1)
     curses.init_pair(4, curses.COLOR_YELLOW, -1)
     curses.init_pair(5, curses.COLOR_BLUE, -1)
     curses.init_pair(6, curses.COLOR_CYAN, -1)
     
     color = {}
     color['normal'] = curses.color_pair(1)
     color['green']  = curses.color_pair(2)
     color['red']    = curses.color_pair(3)
     color['yellow'] = curses.color_pair(4)
     color['blue']   = curses.color_pair(5)
     color['cyan']   = curses.color_pair(6)
     self.color = color
     
     attribute = {}
     attribute['normal']   = curses.A_NORMAL
     attribute['standout'] = curses.A_STANDOUT
     attribute['bold']     = curses.A_BOLD
     self.attribute = attribute
     
     self.cursescolors = True
예제 #19
0
    def __init__(self, stdscr, seed, island):
        self.stdscr = stdscr
        if island:
            self.island = island
        else:
            self.island = model.Island(seed)

        curses.noecho()
        curses.cbreak()
        self.stdscr.keypad(1)
        curses.start_color()
        curses.use_default_colors()
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, -1)
        curses.init_pair(1, 33, 0) # soldier team 1
        curses.init_pair(2, 1, 7) # soldier team 2
        curses.init_pair(3, 2, 0) # tree
        curses.init_pair(4, 3, 0) # grass
        curses.init_pair(5, 7, 0) # path with enough APs, selected soldier name
        curses.init_pair(6, 7, 1) # path without enough APs, unselected soldier name, bullet
        curses.init_pair(7, 7, 3) # bullet hit
        curses.init_pair(8, 4, 0) # water
        curses.init_pair(9, 6, 0) # wall
        curses.init_pair(10, 7, 0) # floor
        curses.init_pair(11, 33, 7) # soldier team 1, selected

        self.stdscr.leaveok(0)
        self.view = BattlefieldView(self.stdscr, self.island, self.island)
예제 #20
0
    def main(stdscr):
        try:
            curses.use_default_colors()
            curses.init_pair(1, -1, curses.COLOR_CYAN)
            curses.init_pair(2, -1, curses.COLOR_BLUE)
        except:
            pass

        # add some numbers to background so we can see window
        for y in range(0, curses.LINES - 1):
            for x in range(0, curses.COLS):
                stdscr.addstr("%d" % ((y + x) % 10))
        stdscr.addstr(curses.LINES - 1, 0, "Press tab to quit.")
        stdscr.refresh()

        win = stdscr.subwin(22,50,5,5)
        win.bkgdset(ord(' '), curses.color_pair(1))
        win.clear()
        win.border()
        win.addstr(0, 2, "[ Window with an embedded ListBox ]")
        win.addstr(2, 3, "Select an item then press tab to")
        win.addstr(3, 3, "send selection to parent.")

        # generate list of test data
        data = map(lambda x: chr(x)+'_test'+str(x), range(ord('a'),ord('z')))

        lb = ListBox(win, 15, 30, 5, 5, data, 2)
        selection = lb.focus()

        win.erase()

        stdscr.clear()

        stdscr.addstr(10,10, "Selected item: %s" % selection)
        stdscr.getch()
예제 #21
0
    def startup(self):
        self.mode = CursesVisualizer.Mode.MAIN
        self.voice = 0
        self.scale = 0

        Visualizer.startup(self)
        curses.curs_set(0)
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.use_default_colors()
        self.screen.nodelay(True)
        self.screen.keypad(True)
        self.screen.clear()
        self.screen.refresh()

        for m in self.modeScreens.itervalues():
            m.startup()
        height = self.screen.getmaxyx()[0] - 1
        width = self.screen.getmaxyx()[1] - 1
        self.winToolbar = curses.newwin(2, width, height-2, 0)

        self.old_stdout = sys.stdout
        self.old_stderr = sys.stderr
        self.fakeOut = FakeSysOut()
        sys.stdout = self.fakeOut
        sys.stderr = self.fakeOut

        self.paint_toolbar()
        curses.doupdate()
예제 #22
0
def init_draw():
    curscr = None
    if enable_curses:
        curscr = curses.initscr()
        curses.curs_set(0)

    if enable_curses: # and enable_colors:
        if curses.has_colors():
            curses.start_color()
            curses.use_default_colors()
        else:
            enable_colors = False
            enable_color_players = False
            enable_color_walls = False
            pattern = classic

    if enable_curses: #and enable_colors:
        pair_number = 15
        for color in ('red', 'yellow', 'blue', 'green', 'default'):
            if color == 'red':
                fg = curses.COLOR_RED
            elif color == 'yellow':
                fg = curses.COLOR_YELLOW
            elif color == 'blue':
                fg = curses.COLOR_BLUE
            elif color == 'green':
                fg = curses.COLOR_GREEN
            else:
                fg = -1
            pair_number += 1
            curses.init_pair(pair_number, fg, -1)
    return curscr
예제 #23
0
파일: main.py 프로젝트: nexAkari/muz
    def cursesGameLoop(self, scr):
        curses.start_color()

        if self.config["use-default-colors"]:
            curses.use_default_colors()
            bg = -1
        else:
            bg = curses.COLOR_BLACK

        for c in xrange(8):
            curses.init_pair(c + 1, c, bg)

        curses.curs_set(0)
        mainwin = scr
        win = mainwin
        #win = curses.newwin(30, 100, 10, 10)
        win.nodelay(True)

        game = self.activity

        while True:
            game.clock.time = time.time() * 1000
            game.update()
            
            if game.paused:
                game.resume()

            game.renderer.draw(win)
예제 #24
0
    def __init__(self, stdscreen, data, labels, options, continuity=True):
        self.screen = stdscreen
        curses.curs_set(0)

        # curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.use_default_colors()

        # Loop over all rows, making selector menu each time
        menus = []
        counter = 0
        for data_idx,(guid,line) in enumerate(data):
            counter += 1

            max_width = self.screen.getmaxyx()[1] - 8
            lines = splitline(line, max_width, "    ")
            header = "Line [%d/%d]:\n\n%s\n" % (data_idx, len(data), "\n".join(lines))
            menu = SelectorMenu(self.screen, options, header=header,
                                hoffset=1, loc=(1,2), pad=(1,2),
                                close_delay=0.250)
            menus.append((data_idx,menu))

        # Display menus
        loc = 0
        lastmenu = None
        while True:
            data_idx, menu = menus[loc]

            # Show menu
            menu.display()

            status = menu.get_status()
            if status == menu.MENU_EXIT:
                break
            elif status == menu.MENU_SKIP_BACK:
                loc -= 1
            elif status == menu.MENU_SKIP_FRWD:
                loc += 1
            elif status == menu.MENU_CHOSEN: # OK
                # Record annotation
                guid, line = data[data_idx]
                choices[guid] = (line, options[menu.get_choice()][0])
                loc += 1
            else:
                loc += 1

            # Break loop
            if (loc >= len(menus) or loc < 0):
                exitmenu = SelectorMenu(self.screen, [], option0="Quit",
                                        loc=(10,10), size=(8, 40),
                                        header="All done? Press Enter to quit,\nor use arrow keys to return.")
                exitmenu.display()
                status = exitmenu.get_status()
                if status in [exitmenu.MENU_CHOSEN, exitmenu.MENU_EXIT]:
                    break
                elif status == exitmenu.MENU_SKIP_BACK:
                    loc = len(menus) - 1 # go back one
                elif status == exitmenu.MENU_SKIP_FRWD:
                    loc = 0 # wrap around

            lastmenu = menu
예제 #25
0
파일: ui.py 프로젝트: massimoca/nuncium
    def __init__(self):
        """
        Initialize the UI by creating a window object that represents the entire
        screen of the user interface. The screen will be divided into smaller
        windows, each representing a particular section of the UI.

        Raises:
            curses.error: curs_set() returned ERR. The terminal does not support
                          configuring the cursor state.
        """

        # Window object: The entire screen of the UI.
        self.screen = curses.initscr()

        # Disable echo of keys to the screen and enable input without requiring
        # the carriage return (Enter).
        curses.noecho()
        curses.cbreak()

        # Bool: Denotes if color is enabled.
        self.color_enabled = False

        # Enable color mode, if the terminal supports colors.
        if curses.has_colors():
            curses.start_color()
            curses.use_default_colors()
            self.color_enabled = True

        # Allow curses to interpret the escape sequences generated by some keys
        # and disable the display of the cursor.
        self.screen.keypad(True)
        curses.curs_set(False)
예제 #26
0
파일: pandora.py 프로젝트: freon27/pandora
def print_fireworks():
    stdscr = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    for i in range(0, curses.COLORS):
        curses.init_pair(i + 1, i, -1)
    curses.curs_set(0)
    xy = stdscr.getmaxyx()
    
    x = xy[0]
    y = xy[1]
    print x
    print y
    selected_x = random.randint(0, x )
    selected_y = random.randint(0, y )
    
    fireworks = []
    fireworks.append(Firework(stdscr, 133, 100, 25))
    
    for v in range(0, 30):
        if v == 7:
            fireworks.append(Firework(stdscr, 5 ,25, 50))
        elif v == 17:
            fireworks.append(Firework(stdscr, 230,150, 0))
        elif v == 12:
            fireworks.append(Firework(stdscr, 200,40, 25))
        elif v == 22:
            fireworks.append(Firework(stdscr, 30,125, 40))
        os.system('clear')
        for fw in fireworks:
            fw.draw()
        stdscr.refresh()
        time.sleep(0.1)
    curses.endwin()
예제 #27
0
def show_welcome(stdscr, text):
    """
    Display a curses splash screen containing a welcome text

    Left and right margins are set to 3 chars. Including the border width (1),
    the text is wrapped to screen width - 3 * 2 - 1 *2 using:
        * stdscr.getmaxyx()[1] - 8
        * stdscr.addstr(i, 4, line)
    8 equals to margins(3*2) + borders(2*1)
    4 equals to left margin(3) + left border(1)
    """
    curses.use_default_colors()
    curses.curs_set(0)
    stdscr.border(0)

    i = 0
    for paragraph in text.splitlines():
        i += 1
        for line in textwrap.fill(paragraph,
                                  stdscr.getmaxyx()[1] - 8,
                                  replace_whitespace=False).splitlines():
            stdscr.addstr(i, 4, line)
            i += 1
    stdscr.addstr(i + 1, 4, "Continue", curses.A_STANDOUT)
    while True:
        key_pressed = stdscr.getch()
        if key_pressed == ord('\n'):
            break
예제 #28
0
파일: smmpchat.py 프로젝트: rxcomm/smmp
def windows():
    stdscr = curses.initscr()
    curses.noecho()
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_RED, -1)
    curses.init_pair(2, curses.COLOR_CYAN, -1)
    curses.init_pair(3, curses.COLOR_GREEN, -1)
    curses.cbreak()
    curses.curs_set(1)
    (sizey, sizex) = stdscr.getmaxyx()
    input_win = curses.newwin(8, sizex, sizey-8, 0)
    output_win = curses.newwin(sizey-9, sizex, 1, 0)
    title_win = curses.newwin(1, sizex, 0, 0)
    input_win.idlok(1)
    input_win.scrollok(1)
    input_win.nodelay(1)
    input_win.leaveok(0)
    input_win.timeout(100)
    input_win.attron(curses.color_pair(3))
    output_win.idlok(1)
    output_win.scrollok(1)
    output_win.leaveok(0)
    title_win.idlok(1)
    title_win.scrollok(1)
    title_win.leaveok(0)
    return stdscr, input_win, output_win, title_win
예제 #29
0
파일: menu.py 프로젝트: PasiSa/tmc.py
    def __init__(self, screen, title, items, selected, resp):
        self.resp = resp
        self.screen = screen
        self.items = list(items)
        self.position = 0
        if selected:
            for index, item in enumerate(self.items):
                if item.tid == selected.tid:
                    self.position = index
                    break
        self.offset = 0
        self.window = screen.subwin(0, 0)
        self.height = height = self.window.getmaxyx()[0]
        if self.position + 2 >= height:
            self.offset = self.position - 1

        if use_unicode:
            self.title = "┤ {0} (q to cancel) ├".format(title)
        else:
            self.title = "| {0} (q to cancel) |".format(title)

        self.window.keypad(1)
        self.panel = panel.new_panel(self.window)
        self.panel.hide()
        panel.update_panels()
        try:
            curses.curs_set(0)
            curses.use_default_colors()
        except curses.error:
            pass
        self.start()
예제 #30
0
    def main(stdscr):
        try:
            curses.use_default_colors()
            curses.init_pair(1, -1, curses.COLOR_CYAN)
            curses.init_pair(2, -1, curses.COLOR_BLUE)
        except:
            pass

        # add some numbers to background so we can see window
        for y in range(0, curses.LINES - 1):
            for x in range(0, curses.COLS):
                stdscr.addstr("%d" % ((y + x) % 10))
        stdscr.addstr(curses.LINES - 1, 0, "Press tab to select.")
        stdscr.refresh()

        win = stdscr.subwin(22,50,5,5)
        win.bkgdset(ord(' '), curses.color_pair(1))
        win.clear()
        win.border()
        win.addstr(0, 2, "[ Window with an embedded Button ]")

        button1 = Button(win, 4, 4, "Quit")
        button2 = Button(win, 6, 4, "Stay")

        while 1:
            if button1.focus():
                break
            button2.focus()
예제 #31
0
def show_options(title=None, subtitle=None, items=[], callback=None):
    try:
        screen = curses.initscr()
    except NameError:
        import sys
        from todo.utils.styles import Fore, Style
        print('''
{fail}{bold}\tSorry!{reset}
{warning}This command is not supported by your system.
{info}Learn more: {blue}https://github.com/francoischalifour/todo-cli{reset}
'''.format(
            fail=Fore.FAIL,
            bold=Style.BOLD,
            warning=Fore.WARNING,
            info=Fore.INFO,
            blue=Fore.BLUE,
            reset=Style.RESET_ALL,
        ))
        sys.exit(1)

    checked = lambda i: i.get('done')

    def get_action(subtitle):
        try:
            return subtitle.split(' ')[0].lower()
        except:
            return 'trigger'

    try:
        curses.start_color()
        curses.use_default_colors()

        curses.noecho()
        curses.curs_set(0)
        screen.keypad(1)

        curses.init_pair(1, curses.COLOR_BLUE, -1)
        highlighted = curses.color_pair(1)

        curses.init_pair(2, curses.COLOR_GREEN, -1)
        subtitle_style = curses.color_pair(2)

        curses.init_pair(3, curses.COLOR_BLACK, -1)
        info_style = curses.color_pair(3)

        current_pos = 0
        offset_y = 5

        while True:
            items_sorted = sorted(items, key=checked)
            no_items = len(items) if len(items) < 10 else 10
            if no_items == 0:
                return items

            screen.refresh()

            screen.addstr(2, 7, title, curses.A_BOLD | highlighted)
            screen.addstr(3, 7, subtitle, subtitle_style)

            pos = 0

            for item in items_sorted[:10]:
                is_done = item.get('done')
                status = ' ✓ ' if is_done else ' x '

                if pos == current_pos:
                    screen.addstr(pos + offset_y, 4,
                                  '❯ {}  {}'.format(status, item['title']),
                                  highlighted)
                else:
                    screen.addstr(pos + offset_y, 4,
                                  '  {}  {}'.format(status, item['title']))

                pos += 1

            if len(items) > 10:
                screen.addstr(pos + offset_y, 4, '   ...', info_style)

            screen.addstr(pos + offset_y + 1, 7, 'space',
                          curses.A_BOLD | info_style)
            screen.addstr(pos + offset_y + 1, 14,
                          'to {}'.format(get_action(subtitle)), info_style)
            screen.addstr(pos + offset_y + 2, 7, 'q',
                          curses.A_BOLD | info_style)
            screen.addstr(pos + offset_y + 2, 14, 'to exit', info_style)

            key = screen.getch()

            screen.erase()

            if key in (curses.KEY_DOWN, ord('j')):
                current_pos = current_pos + 1 if current_pos + 1 < no_items else 0
            elif key in (curses.KEY_UP, ord('k')):
                current_pos = current_pos - 1 if current_pos > 0 else no_items - 1
            elif key == SPACE_KEY:
                try:
                    item_index = items.index(items_sorted[current_pos])
                    items = callback(items, item_index)
                except:
                    pass
            elif key in EXIT_KEYS:
                return items
    finally:
        curses.endwin()
예제 #32
0
def main(stdscr):

    # Set up curses
    curses.curs_set(False)
    curses.use_default_colors()

    bkgd = 17  # Navy blue
    walls = 54  # Black/Gray
    rewar = 3  # Olive
    enemy = 12  # Light blue
    agent = 10  # Green
    curses.init_pair(1, walls, bkgd)  # Walls
    curses.init_pair(2, rewar, bkgd)  # Rewards
    curses.init_pair(3, enemy, bkgd)  # Enemies
    curses.init_pair(4, agent, bkgd)  # Player/Target

    # Set up controls
    dirmap = {'w': 0, 'a': 3, 's': 2, 'd': 1}
    atkmap = {'W': 0, 'A': 3, 'S': 2, 'D': 1}

    # Set up size information
    height, width = stdscr.getmaxyx()

    if height < 14 or width < 60:
        stdscr.addstr(1, 1, 'Window must be at least 60 x 14 to play!')
        stdscr.addstr(2, 1, 'Press any key to quit.')
        stdscr.refresh()
        stdscr.getkey()
        quit()

    dheight = (height - 10) // 2
    dwidth = (width - 3) // 2

    dby = dheight * 2 + 1

    # Cue to reset the game
    reset_status = True

    # Begin event loop
    while True:

        # Set up game state
        if reset_status:
            reset_status = False
            d, moves, attacks, enemies, score, done_status = make_new_dungeon(
                dheight, dwidth)

            stdscr.addstr(dby + 7, 0, ' ' * 59)
            stdscr.addstr(dby + 8, 0, ' ' * 59)

        # Move each of the enemies (assuming the player has already
        # moved at least once, to prevent insta-deaths)
        if moves > 0 and not done_status:
            for i in range(enemies):
                d.move_enemy(i)

        # Check for death
        if d.current_cell in d.enemies:
            stdscr.addstr(dby + 7, 0, 'You died!')
            score -= 100 if not done_status else 0
            done_status = True

        # Check for completion
        if d.current_cell == d.cell_ids[-1]:
            finish_score = dheight * dwidth - moves
            if finish_score > 0:
                finish_score_message = 'Well done!'
            else:
                finish_score_message = 'Try moving faster next time...'

            stdscr.addstr(
                dby + 7, 0,
                'Congratulations!  Dungeon complete in {} moves.'.format(
                    moves))
            stdscr.addstr(
                dby + 8, 0,
                'Bonus score: {} {}'.format(finish_score,
                                            finish_score_message))
            score += finish_score if not done_status else 0
            done_status = True

        # Obtain dungeon render
        layer0, layers = d.render()
        corner_x = 1
        corner_y = 1

        # Render the maze
        for i, l in enumerate(layer0):
            stdscr.addstr(corner_y + i, corner_x, l, curses.color_pair(1))

        render_layers(stdscr, layers, corner_x, corner_y)

        stdscr.addstr(
            dby + 2, 0,
            '[wasd] to move.               | Moves:        {:<4}'.format(
                moves))
        stdscr.addstr(
            dby + 3, 0,
            'Shift+[wasd] to attack.       | Attacks left: {:<4}'.format(
                attacks))
        stdscr.addstr(
            dby + 4, 0,
            '[r] to reset, [q] to quit.    | Enemies left: {:<4}'.format(
                enemies))
        stdscr.addstr(
            dby + 5, 0,
            'Goal: Reach the bottom right. | Score:        {:<4}'.format(
                score))

        # Refresh the screen
        stdscr.refresh()

        # Respond to key input
        enemies, attacks, dscore, quit_status, reset_status = \
         key_response(stdscr, d, dirmap, atkmap, enemies, attacks, done_status)
        score += dscore

        # Quit if requested
        if quit_status:
            break

        # Iterate the move counter and go back to the start of the loop
        moves += 1 if not done_status else 0
예제 #33
0
 def __call__(self, stdscr):
     curses.use_default_colors()
     self.stdscr = stdscr
     self.action = Action(stdscr)
     while self.state != 'exit':
         self.state = getattr(self, 'state_' + self.state)()
예제 #34
0
    sock.settimeout(2)
    s = ssl.wrap_socket(sock, certfile='cert.pem', keyfile='key.pem')  # SSL
    # connect to remote host
    try:
        s.connect((host, port))
    except Exception as e:
        traceback.print_exc(file=sys.stdout)
        print(e)
        print('Unable to connect')
        sys.exit()

    stdscr = curses.initscr()
    curses.echo()

    curses.start_color()
    curses.use_default_colors()
    for i in range(0, curses.COLORS):
        curses.init_pair(i + 1, i, -1)

    #stdscr.clear()
    stdscr.refresh()

    #print('--- CONNECTED. SEND YOUR MESSAGE')
    stdscr.clear()

    while 1:

        prompt()
        stdscr.refresh()
        socket_list = [sys.stdin, s]
예제 #35
0
def cursesMain(args):
    stdscr = curses.initscr()
    pad = curses.newpad(200, 100)
    pad_height, pad_width = stdscr.getmaxyx()
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_BLUE)
    curses.cbreak()

    stdscr.keypad(True)
    curses.noecho()
    curses.curs_set(0)
    lines = []

    if (len(sys.argv) >= 2):
        filename = sys.argv[1]
    else:
        filename = sys.argv[0]

    with open(filename, "r") as file:
        for line in file:
            lines.append(line)
    textvar = lines[0]
    completed_text = ""
    current_char_pos = 0
    current_char_val = textvar[0]
    current_line_num = 0
    while True:
        is_char_correct = False
        pad.addstr(0, 0, textvar, curses.color_pair(2))
        i = 0
        for item in textvar:
            if item == " ":
                pad.addstr(0, i, item, curses.color_pair(3))
            i += 1

        pad.addstr(0, 0, completed_text, curses.color_pair(1))
        for i in range(current_line_num + 1, len(lines)):
            pad.addstr(i - current_line_num, 0, lines[i])

        stdscr.refresh()

        pad.refresh(0, 0, 0, 0, pad_height - 1, pad_width - 1)
        c = pad.getch()
        # esc
        if c == 27:
            break
        # tab
        if c == 9:
            if textvar[current_char_pos:current_char_pos + 4] == 4 * " ":
                # tab key equal 4 spaces
                completed_text += 4 * " "
                current_char_pos += 4
                is_char_correct = True
        if c == ord(current_char_val):
            completed_text += current_char_val
            current_char_pos += 1
            is_char_correct = True
        if is_char_correct is True:
            if current_char_pos >= len(textvar):
                current_char_pos = 0
                current_line_num += 1
                if current_line_num >= len(lines):
                    current_line_num = 0
                textvar = lines[current_line_num]
                completed_text = ""
                stdscr.clear()
                pad.clear()
            current_char_val = textvar[current_char_pos]
예제 #36
0
def main(screen):

    global stdscr
    global votecount
    global window_width
    global max_yeacount_len
    global max_naycount_len
    global max_percentage_len
    global ballot_entries
    global votewin
    global masternodes
    global C_YELLOW, C_GREEN, C_RED, C_CYAN

    stdscr = screen
    stdscr.scrollok(1)

    git_describe = run_command(
        'GIT_DIR=%s GIT_WORK_TREE=%s git describe' %
        (git_dir + '/.git', git_dir)).rstrip("\n").split('-')
    try:
        GIT_VERSION = ('-').join((git_describe[i] for i in [1, 2]))
        version = 'v' + VERSION + ' (' + GIT_VERSION + ')'
    except IndexError:
        version = 'v' + VERSION

    try:
        curses.curs_set(2)
    except:
        pass
    if curses.has_colors():
        curses.start_color()
        curses.use_default_colors()
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, -1)

    C_CYAN = curses.color_pair(7)
    C_YELLOW = curses.color_pair(4)
    C_GREEN = curses.color_pair(3)
    C_RED = curses.color_pair(2)

    if dash_cli_path is None:
        # test dash-cli in path -- TODO make robust
        try:
            run_command('dash-cli getinfo')
        except subprocess.CalledProcessError:
            quit("--> cannot find dash-cli in $PATH\n" +
                 "    do: export PATH=/path/to/dash-cli-folder:$PATH\n" +
                 "    and try again\n")

    loadwin = curses.newwin(40, 40, 1, 2)

    loadwin.addstr(1, 2, 'dashvote version: ' + version, C_CYAN)
    loadwin.addstr(2, 2, 'loading votes. please wait...', C_GREEN)
    loadwin.refresh()

    mncount = int(run_dash_cli_command('masternode count'))
    block_height = int(run_dash_cli_command('getblockcount'))
    days_to_next_cycle = (16616 - (block_height % 16616)) / 576.0
    days_to_finalization = days_to_next_cycle - 3

    # get ballot
    ballots = json.loads(run_dash_cli_command('gobject list all'))
    ballot = {}

    for entry in ballots:

        # unescape data string
        ballots[entry]['_data'] = json.loads(
            ballots[entry][u'DataHex'].decode("hex"))

        (go_type, go_data) = ballots[entry]['_data'][0]
        ballots[entry][go_type] = go_data

        if str(go_type) == 'watchdog':
            continue

        if int(go_data[u'end_epoch']) < int(time.time()):
            continue

        ballots[entry][u'vote'] = 'SKIP'
        ballots[entry][u'votes'] = json.loads(
            run_dash_cli_command('gobject getvotes %s' % entry))
        ballot[entry] = ballots[entry]

    ballot_entries = sorted(ballot,
                            key=lambda s: ballot[s]['proposal']['start_epoch'])
    votecount = len(ballot_entries)
    max_proposal_len = 0
    max_yeacount_len = 0
    max_naycount_len = 0
    max_percentage_len = 0
    for entry in ballot_entries:
        yeas = ballot[entry][u'YesCount']
        nays = ballot[entry][u'NoCount']
        name = ballot[entry]['proposal'][u'name']
        percentage = "{0:.1f}".format((float(
            (yeas + nays)) / float(mncount)) * 100)
        ballot[entry][u'vote_turnout'] = percentage
        ballot[entry][u'vote_threshold'] = (
            yeas + nays) > mncount / 10 and True or False
        ballot[entry][u'vote_passing'] = (
            yeas - nays) > mncount / 10 and True or False
        max_proposal_len = max(max_proposal_len, len(name))
        max_yeacount_len = max(max_yeacount_len, len(str(yeas)))
        max_naycount_len = max(max_naycount_len, len(str(nays)))
        max_percentage_len = max(max_percentage_len, len(str(percentage)))

    # extract mnprivkey,txid-txidx from masternode.conf
    masternodes = {}
    with open(os.path.join(dash_conf_dir, 'masternode.conf'), 'r') as f:
        lines = list(line for line in (l.strip() for l in f)
                     if line and not line.startswith('#'))
        for line in lines:
            conf = line.split()
            masternodes[conf[3] + '-' + conf[4]] = {
                "alias": conf[0],
                "mnprivkey": conf[2],
                "fundtx": conf[3] + '-' + conf[4],
                "txid": conf[3],
                "txout": conf[4]
            }
    if not masternodes:
        # fallback to dash.conf entries if no masternode.conf entries
        with open(os.path.join(dash_conf_dir, 'dash.conf'), 'r') as f:
            lines = list(line for line in (l.strip() for l in f)
                         if line and not line.startswith('#'))
            conf = {}
            for line in lines:
                n, v = line.split('=')
                conf[n.strip(' ')] = v.strip(' ')
            if all(k in conf
                   for k in ('masternode', 'externalip', 'masternodeprivkey')):
                # get funding tx from dashninja
                import urllib2
                mninfo = urllib2.urlopen(
                    "https://dashninja.pl/api/masternodes?ips=[\"" +
                    conf['externalip'] + ":9999" + "\"]&portcheck=1").read()
                try:
                    mndata = json.loads(mninfo)
                    d = mndata[u'data'][0]
                except:
                    quit('cannot retrieve masternode info from dashninja')
                vin = str(d[u'MasternodeOutputHash'])
                vidx = str(d[u'MasternodeOutputIndex'])
                masternodes[vin + '-' + vidx] = {
                    "alias": conf['externalip'],
                    "mnprivkey": conf['masternodeprivkey'],
                    "fundtx": vin + '-' + vidx,
                    "txid": vin,
                    "txout": vidx
                }
            else:
                quit('cannot find masternode information in dash.conf')

    # TODO open previous votes/local storage something
    for entry in ballot:
        ballot[entry][u'previously_voted'] = 0
        for hash in ballot[entry][u'votes']:
            b = ballot[entry][u'votes'][hash]
            (vindx, ts, val,
             mode) = [b[16:80] + '-' + b[82:83]] + list(b.split(':')[1:4])
            if vindx in masternodes:
                if val == 'YES':
                    ballot[entry][u'previously_voted'] = 1
                elif val == 'NO':
                    ballot[entry][u'previously_voted'] = 2
                else:
                    ballot[entry][u'previously_voted'] = 3

    loadwin.erase()
    window_width = 35
    content_width = max_proposal_len + max_percentage_len + max_yeacount_len + max_naycount_len
    window_width = max(window_width, content_width + 3)
    votewin = curses.newwin(votecount + 9, window_width + 17, 1, 2)
    votewin.keypad(1)
    votewin.border()

    votewin.addstr(1, 2, 'dashvote version: ' + version, C_CYAN)
    votewin.addstr(
        2, 2,
        'use arrow keys to set votes for %s masternodes' % len(masternodes),
        C_YELLOW)
    votewin.addstr(3, 2, 'hit enter on CONFIRM to vote - q to quit', C_YELLOW)
    votewin.addstr(4, 3, '*', C_GREEN)
    votewin.addstr(4, 4, '/', C_CYAN)
    votewin.addstr(4, 5, '*', C_RED)
    votewin.addstr(4, 7, '== previously voted on proposal (yes/no)', C_YELLOW)
    _y = 5
    for entry in ballot_entries:
        _y += 1
        x = 4
        name = ballot[entry]['proposal'][u'name']
        yeas = ballot[entry][u'YesCount']
        nays = ballot[entry][u'NoCount']
        percentage = ballot[entry][u'vote_turnout']
        passing = ballot[entry][u'vote_passing']
        threshold = ballot[entry][u'vote_threshold']
        if ballot[entry][u'previously_voted'] > 0:
            direction = ballot[entry][u'previously_voted']
            votewin.addstr(_y, x - 1, '*', direction == 1 and C_GREEN or C_RED)

        fmt_entry = "%-" + str(max_proposal_len + 2) + "s"
        votewin.addstr(_y, x, fmt_entry % name, passing and C_GREEN
                       or threshold and C_RED or C_YELLOW)

        for x in range(max_yeacount_len - len(str(yeas))):
            votewin.addstr(' ')

        votewin.addstr(str(yeas), C_GREEN)
        votewin.addstr('/', C_CYAN)
        votewin.addstr(str(nays), C_RED)
        votewin.addstr(' ')

        for x in range(max_naycount_len - len(str(nays))):
            votewin.addstr(' ')

        for x in range(max_percentage_len - len(str(percentage))):
            votewin.addstr(' ')

        votewin.addstr(str(percentage) + "%", C_CYAN)

        votewin.addstr(' ')
        votewin.addstr('SKIP', C_CYAN)
    votewin.addstr(_y + 2, window_width + 7, 'confirm', C_YELLOW)
    votewin.move(0 + 6, window_width + 7)

    votewin.refresh()

    keys = {
        113: lambda s: quit(),
        curses.KEY_UP: lambda s: prev_vote(s),
        curses.KEY_DOWN: lambda s: next_vote(s),
        curses.KEY_RIGHT: lambda s: set_vote(ballot, s, 1),
        curses.KEY_LEFT: lambda s: set_vote(ballot, s, -1),
        107: lambda s: prev_vote(s),
        106: lambda s: next_vote(s),
        108: lambda s: set_vote(ballot, s, 1),
        104: lambda s: set_vote(ballot, s, -1),
        10: lambda s: submit_votes(stdscr, ballot, s)
    }

    sel_vote = 0
    while True:
        key = votewin.getch()
        f = keys.get(key)
        if hasattr(f, '__call__'):
            sel_vote = f(sel_vote)
            try:
                entry_vote = ballot[ballot_entries[sel_vote]][u'vote']
            except IndexError:
                # CONFIRM button
                entry_vote = ''
            if key != 10:
                update_vote_display(votewin, sel_vote, entry_vote)
예제 #37
0
def main():
    # new window
    win = C.initscr()

    C.start_color()
    C.use_default_colors()

    # color pairs
    C.init_pair(Colors.DEFAULT, C.COLOR_BLUE, -1)
    C.init_pair(Colors.SELECTED, C.COLOR_BLACK, C.COLOR_BLUE)
    C.init_pair(Colors.DOWNBAR, C.COLOR_BLUE, C.COLOR_BLACK)

    C.init_pair(Colors.NORMAL, C.COLOR_BLACK, C.COLOR_GREEN)
    C.init_pair(Colors.SEARCH, C.COLOR_BLACK, C.COLOR_RED)

    C.init_pair(Colors.NOTIFICATION_GOOD, C.COLOR_WHITE, C.COLOR_BLACK)
    C.init_pair(Colors.NOTIFICATION_BAD, C.COLOR_RED, C.COLOR_BLACK)

    # hiding typing and cursor
    C.noecho()
    C.curs_set(0)

    win.clear()
    win.refresh()

    MODE = Modes.NORMAL
    SORT = Sorts.ABC
    selected = 0
    firstNameIndexOffset = 0
    searchText = ""
    HEADER = random.choice(HEADERS)
    NAMES_START_OFFSET = len(HEADER) + 2

    movies = []
    for file in os.listdir(PROJECT_PATH + "/movieData/"):
        movies.append(Movie(file))
    movies = sorted(movies, key=lambda x: x.name)  # ABC sort default
    movies_drawlist = [
        movie for movie in movies if movie.searchFilter(searchText)
    ]

    # animation loop
    try:
        with ueberzug.Canvas() as c:
            showImg = c.create_placement(
                'show',
                x=50,
                y=9,
                scaler=ueberzug.ScalerOption.FIT_CONTAIN.value)
            showImg.path = ""
            showImg.visibility = ueberzug.Visibility.VISIBLE

            while True:
                win.erase()

                rows, cols = win.getmaxyx()
                PICS_LINE = int(cols * 0.65)

                ################################################################ UI

                if (rows < 35):
                    NAMES_START_OFFSET = 1
                else:
                    for i in range(len(HEADER)):
                        win.addstr(1 + i, 2, HEADER[i],
                                   C.color_pair(Colors.DEFAULT))
                    NAMES_START_OFFSET = len(HEADER) + 2

                for i in range(NAMES_START_OFFSET, rows - 2):
                    win.addstr(i, PICS_LINE, "▍", C.color_pair(Colors.DEFAULT))

                win.addstr(rows - 1, 1, " " * (cols - 2),
                           C.color_pair(Colors.DOWNBAR) + C.A_DIM)
                if (MODE == Modes.NORMAL):
                    win.addstr(rows - 1, 1, " NORMAL ",
                               C.color_pair(Colors.NORMAL) + C.A_BOLD)
                    win.addstr(rows - 1, 10, "{}".format(searchText),
                               C.color_pair(Colors.DOWNBAR))
                elif (MODE == Modes.SEARCH):
                    win.addstr(rows - 1, 1, " SEARCH ",
                               C.color_pair(Colors.SEARCH) + C.A_BOLD)
                    win.addstr(rows - 1, 10, searchText,
                               C.color_pair(Colors.DOWNBAR))

                if (SORT == Sorts.ABC):
                    win.addstr(rows - 1, cols - 8, "  ABC  ",
                               C.color_pair(Colors.SELECTED) + C.A_BOLD)
                elif (SORT == Sorts.SCORE):
                    win.addstr(rows - 1, cols - 8, " SCORE ",
                               C.color_pair(Colors.SELECTED) + C.A_BOLD)

                if (os.path.isdir(DISC_PATH)):
                    win.addstr(
                        rows - 1, cols - 10, "ﳜ",
                        C.color_pair(Colors.NOTIFICATION_GOOD) + C.A_BOLD)
                else:
                    win.addstr(
                        rows - 1, cols - 10, "ﳜ",
                        C.color_pair(Colors.NOTIFICATION_BAD) + C.A_BOLD)
                ################################################################ NAMES

                NAMES_MAX_COUNT = rows - NAMES_START_OFFSET - 3
                firstNameIndexOffset = max(
                    0,
                    min((len(movies_drawlist) - 1) - NAMES_MAX_COUNT,
                        selected - NAMES_MAX_COUNT // 2))

                for idx in range(firstNameIndexOffset, len(movies_drawlist)):

                    path = movies_drawlist[idx].path
                    name = movies_drawlist[idx].name
                    year = movies_drawlist[idx].year
                    resolution = movies_drawlist[idx].resolution
                    languages = movies_drawlist[idx].languages
                    subtitles = movies_drawlist[idx].subtitles
                    duration = movies_drawlist[idx].duration
                    score = movies_drawlist[idx].score

                    xPos = 1
                    yPos = NAMES_START_OFFSET + idx - firstNameIndexOffset

                    if (len(name) > PICS_LINE - 10):
                        name = name[:PICS_LINE - 10] + "..."

                    if (idx - firstNameIndexOffset > NAMES_MAX_COUNT):
                        break
                    if (selected == idx):
                        win.addstr(yPos, xPos,
                                   "{:3.0f}: {}".format(idx + 1, name),
                                   C.color_pair(Colors.SELECTED) + C.A_BOLD)

                        with c.lazy_drawing:
                            showImg.path = path
                            showImg.width = cols - PICS_LINE - 3
                            showImg.height = min(18, rows // 2 - 3)
                            showImg.x = PICS_LINE + 2
                            showImg.y = NAMES_START_OFFSET

                        ATTRIB_OFFSET = min(
                            NAMES_START_OFFSET + showImg.height + 1, rows - 10)
                        win.addstr(ATTRIB_OFFSET + 0, PICS_LINE + 2,
                                   "Year: {}".format(year),
                                   C.color_pair(Colors.DEFAULT))
                        win.addstr(ATTRIB_OFFSET + 1, PICS_LINE + 2,
                                   "Score: {}".format(score),
                                   C.color_pair(Colors.DEFAULT))
                        win.addstr(ATTRIB_OFFSET + 2, PICS_LINE + 2,
                                   "Resolution: {}".format(resolution),
                                   C.color_pair(Colors.DEFAULT))
                        win.addstr(ATTRIB_OFFSET + 3, PICS_LINE + 2,
                                   "Duration: {}".format(duration),
                                   C.color_pair(Colors.DEFAULT))
                        # win.addstr(ATTRIB_OFFSET+4, PICS_LINE + 2,
                        #            "Languages: {}".format(languages),
                        #             C.color_pair(Colors.DEFAULT))
                        # win.addstr(ATTRIB_OFFSET+5, PICS_LINE + 2,
                        #            "Subtitles: {}".format(subtitles),
                        #             C.color_pair(Colors.DEFAULT))

                        yOffset = 0
                        win.addstr(ATTRIB_OFFSET + 4, PICS_LINE + 2,
                                   "Languages:", C.color_pair(Colors.DEFAULT))
                        for lang in range(len(languages)):
                            win.addstr(ATTRIB_OFFSET + 4 + lang,
                                       PICS_LINE + 13,
                                       "{}".format(languages[lang]),
                                       C.color_pair(Colors.DEFAULT))
                            yOffset += 1

                        win.addstr(ATTRIB_OFFSET + 4 + yOffset, PICS_LINE + 2,
                                   "Subtitles:", C.color_pair(Colors.DEFAULT))
                        for sub in range(len(subtitles)):
                            win.addstr(ATTRIB_OFFSET + 4 + yOffset + sub,
                                       PICS_LINE + 13,
                                       "{}".format(subtitles[sub]),
                                       C.color_pair(Colors.DEFAULT))

                    else:
                        win.addstr(yPos, xPos,
                                   "{:3.0f}: {}".format(idx + 1, name),
                                   C.color_pair(Colors.DEFAULT))

                ################################################################ KEYS

                key = chr(win.getch(0, 0))
                if (MODE == Modes.NORMAL):
                    if (key == 'j'):  #MOVE DOWN
                        selected += 1
                        if (selected == len(movies_drawlist)):
                            selected = len(movies_drawlist) - 1
                    elif (key == 'k'):  #MOVE UP
                        selected -= 1
                        if (selected < 0): selected = 0
                    elif (key == '/'):  #TO SEARCH MODE
                        MODE = Modes.SEARCH
                    elif (key == "G"):  #TO LAST ITEM
                        selected = len(movies_drawlist) - 1
                    elif (key == "g"):  #TO FIRST ITEM
                        selected = 0
                    elif (key == "S"):  #CHANGE SORT
                        if (SORT == Sorts.ABC):
                            SORT = Sorts.SCORE
                            movies_drawlist = sorted(
                                movies_drawlist,
                                key=lambda x: x.score,
                                reverse=True)  # ABC sort default
                        else:
                            SORT = Sorts.ABC
                            movies_drawlist = sorted(
                                movies_drawlist,
                                key=lambda x: x.name)  # ABC sort default

                    elif (ord(key) == 10):  #PLAY
                        path = movies_drawlist[selected].Play()

                    elif (key == "q" or key == "Q"):  #QUIT
                        break
                    elif (key == "M" or key == "N"):  #Open NAUTILUS FOR MOUNT
                        os.system("nautilus ~/")
                        win.clear()

                else:
                    if (key == '/'):  #TO NORMAL MODE
                        MODE = Modes.NORMAL
                    elif (ord(key) == 10):  #ENTER
                        MODE = Modes.NORMAL
                    elif (ord(key) == 127):  #BACKSPACE
                        searchText = searchText[:-1]
                    elif (ord(key) == 32):  #SPACE
                        searchText += " "
                    elif (ord(key) == 27):  #ESCAPE
                        MODE = Modes.NORMAL
                    elif (key in
                          "1234567890&-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
                          ):
                        searchText += key
                        selected = 0

                    movies_drawlist = [
                        movie for movie in movies
                        if movie.searchFilter(searchText)
                    ]

                    if (SORT == Sorts.ABC):
                        movies_drawlist = sorted(
                            movies_drawlist,
                            key=lambda x: x.name)  # ABC sort default
                    else:
                        movies_drawlist = sorted(
                            movies_drawlist,
                            key=lambda x: x.score,
                            reversed=True)  # ABC sort default

                win.refresh()

    except KeyboardInterrupt:
        pass
    C.endwin()
예제 #38
0
def main(stdscr, args):
    search_range = (args.start if type(args.start) is int else args.start[0],
                    args.end if type(args.end) is int else args.end[0])
    procs = start_procs(search_range, args)

    if procs == 0:
        return 'The fuzzer binary was not found. It likely needs to be ' \
               'compiled with "make" first.'

    curses.use_default_colors()
    curses.cbreak()
    curses.noecho()
    curses.curs_set(False)
    stdscr.keypad(True)
    stdscr.nodelay(True)

    pad = curses.newpad(100, 100)
    pad.nodelay(True)
    pad.keypad(True)

    atexit.register(exit_handler, procs)

    extra_data = {'search_range': search_range, 'time_started': time.time()}

    quit_str = 'Done'
    statuses = [None] * len(procs)

    while True:
        try:
            update_statuses(procs, statuses)
            update_screen(pad, statuses, extra_data)
            refresh_pad(stdscr, pad)
            if stdscr.getch() == ord('q'):
                quit_str = 'User abort'
                break
            quit = False
            done = True
            for i in range(len(procs)):
                ret = procs[i].poll()
                if ret == 1:
                    outs, errs = procs[i].communicate()
                    quit_str = 'Worker {} crashed:\n{}'.format(
                        i, errs.decode('utf-8'))
                    quit = True
                    break
                elif ret != 0:
                    done = False
                    break
            if quit:
                break
            elif done:
                # All processes terminated sucessfully.
                # When done, update one last time, show a message and
                # wait for any key before quitting
                stdscr.nodelay(False)
                pad.nodelay(False)
                update_statuses(procs, statuses)
                update_screen(pad, statuses, extra_data)
                print_done(pad)
                refresh_pad(stdscr, pad)
                while stdscr.getch() != ord('q'):
                    pass
                break
            else:
                time.sleep(0.1)
        except FileNotFoundError:
            # Wait a little if the status files haven't been created yet
            time.sleep(0.1)
        except KeyboardInterrupt:
            quit_str = 'User abort'
            break

    curses.nocbreak()
    stdscr.keypad(False)
    pad.keypad(False)
    curses.echo()
    curses.curs_set(True)
    curses.endwin()

    return quit_str
예제 #39
0
    def __init__(self, config: 'SimpleConfig', daemon: 'Daemon',
                 plugins: 'Plugins'):

        self.config = config
        self.network = network = daemon.network
        if config.get('tor_auto_on', True):
            if network:
                proxy_modifiable = config.is_modifiable('proxy')
                if not proxy_modifiable or not network.detect_tor_proxy():
                    print(network.TOR_WARN_MSG_TXT)
                    c = ''
                    while c != 'y':
                        c = input("Continue without Tor (y/n)?")
                        if c == 'n':
                            exit()
        storage = WalletStorage(config.get_wallet_path())
        if not storage.file_exists():
            print("Wallet not found. try 'electrum-dash create'")
            exit()
        if storage.is_encrypted():
            password = getpass.getpass('Password:'******'')
        self.encoding = locale.getpreferredencoding()

        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)
        curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
        self.stdscr.keypad(1)

        if getattr(storage, 'backup_message', None):
            msg_key = 'Press any key to continue...'
            self.stdscr.addstr(f'{storage.backup_message}\n\n{msg_key}')
            self.stdscr.getch()

        self.stdscr.border(0)
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        self.set_cursor(0)
        self.w = curses.newwin(10, 50, 5, 5)

        console_stderr_handler.setLevel(logging.CRITICAL)
        self.tab = 0
        self.pos = 0
        self.popup_pos = 0

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""
        self.history = None
        def_dip2 = not self.wallet.psman.unsupported
        self.show_dip2 = self.config.get('show_dip2_tx_type', def_dip2)

        util.register_callback(self.update,
                               ['wallet_updated', 'network_updated'])

        self.tab_names = [
            _("History"),
            _("Send"),
            _("Receive"),
            _("Addresses"),
            _("Contacts"),
            _("Banner")
        ]
        self.num_tabs = len(self.tab_names)
예제 #40
0
    def main(self, stdscr) -> None:
        """
        Main program loop, handles user control and logical flow
        """
        curses.use_default_colors()
        self.stdscr = stdscr
        stdscr.keypad(1)
        height, width = stdscr.getmaxyx()  # Get screen size

        # Save these values
        self.height = height
        self.width = width - 1

        # Setup Output window
        output_start_row = 0  # Leave space for top border
        output_height = height - 3  # Leave space for command line
        self.last_row = output_height - output_start_row  # The last row we can write to
        # Create the window with these sizes
        self.outwin = curses.newwin(output_height, width - 1, output_start_row,
                                    0)
        self.outwin.refresh()

        # Setup Command line
        self.build_command_line()

        # Update the command line status
        self.reset_regex_status()

        # Disable cursor:
        curses.curs_set(0)

        # Start the main app loop
        while True:
            if not self.streams:
                self.setup_streams()
            # Update messages from the input stream's queues, track time
            t_0 = time.perf_counter()
            for stream in self.streams:
                while not stream.stderr.empty():
                    message = stream.stderr.get()
                    self.stderr_messages.append(message)

                while not stream.stdout.empty():
                    message = stream.stdout.get()
                    self.stdout_messages.append(message)

            # Prevent this loop from taking up 100% of the CPU dedicated to the main thread by delaying loops
            t_1 = time.perf_counter() - t_0
            # Don't delay if the queue processing took too long
            time.sleep(max(0, self.poll_rate - t_1))

            try:
                keypress = self.command_line.getkey()  # Get keypress
                if keypress == '/':
                    self.handle_regex_mode()
                if keypress == ':':
                    self.handle_command_mode()
                elif keypress == 'h':
                    self.previous_render = None  # Force render
                    if self.func_handle and self.highlight_match:
                        self.highlight_match = False
                    elif self.func_handle and not self.highlight_match:
                        self.highlight_match = True
                    else:
                        self.highlight_match = False
                elif keypress == 'i':
                    # Toggle insert mode
                    if self.insert_mode:
                        self.insert_mode = False
                    else:
                        self.insert_mode = True
                    self.build_command_line()
                elif keypress == 's':
                    self.previous_render = None  # Force render
                    # Swap stdout and stderr
                    self.reset_parser()
                    self.reset_regex_status()
                    if self.messages is self.stderr_messages:
                        self.messages = self.stdout_messages
                    else:
                        self.messages = self.stderr_messages
                elif keypress == 'p':
                    # Enable parser
                    if self.parser is not None:
                        self.reset_parser()
                    self.setup_parser()
                elif keypress == 'a':
                    # Enable analytics engine
                    if self.parser is not None:
                        self.last_index_processed = 0
                        self.parser.reset_analytics()
                        if self.analytics_enabled:
                            self.current_status = f'Parsing with {self.parser.get_name()}, field {self.parser.get_analytics_for_index(self.parser_index)}'
                            self.parsed_messages = []
                            self.analytics_enabled = False
                        else:
                            self.analytics_enabled = True
                            self.current_status = f'Parsing with {self.parser.get_name()}, analytics view'
                elif keypress == 'z':
                    # Tear down parser
                    self.reset_parser()
                elif keypress == 'KEY_UP':
                    # Scroll up
                    self.manually_controlled_line = True
                    self.stick_to_top = False
                    self.stick_to_bottom = False
                    self.current_end = max(0, self.current_end - 1)
                    self.previous_render = None  # Force render
                elif keypress == 'KEY_DOWN':
                    # Scroll down
                    self.manually_controlled_line = True
                    self.stick_to_top = False
                    self.stick_to_bottom = False
                    if self.matched_rows:
                        self.current_end = min(
                            len(self.matched_rows) - 1, self.current_end + 1)
                    else:
                        self.current_end = min(
                            len(self.messages) - 1, self.current_end + 1)
                    self.previous_render = None  # Force render
                elif keypress == 'KEY_RIGHT':
                    # Stick to bottom
                    self.stick_to_top = False
                    self.stick_to_bottom = True
                    self.manually_controlled_line = False
                elif keypress == 'KEY_LEFT':
                    # Stick to top
                    self.stick_to_top = True
                    self.stick_to_bottom = False
                    self.manually_controlled_line = False
            except curses.error:
                # If we have an active filter, process it, always render
                if self.exit_val == -1:
                    return
                if self.parser:
                    self.process_parser(
                    )  # This may block if there are a lot of messages
                if self.func_handle:
                    self.process_matches(
                    )  # This may block if there are a lot of messages
                self.render_text_in_output()
예제 #41
0
def start_prompter(ssh_table, max_len=20, system_argv=None):
    position = 0
    global search
    table = create_table_for_prompt(ssh_table)
    if len(table) == 0:
        start_ssh(system_argv[0])

    screen = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.start_color()
    curses.use_default_colors()

    curses.init_pair(1, curses.COLOR_CYAN, -1)

    curses.curs_set(0)

    height, width = screen.getmaxyx()
    title_position_y = 1

    box_y = 64
    box_position_y = title_position_y + 3
    position_x = max(int((width - 64) / 3 - 1), 0)

    max_row = max(height - box_position_y - 3, 5)

    box_search = curses.newwin(3, box_y, title_position_y, position_x)
    box_search.box()

    box = curses.newwin(max_row + 2, box_y, box_position_y, position_x)
    box.keypad(1)
    box.box()

    while True:
        screen.erase()
        box.erase()
        box.border(0)
        box_search.erase()
        box_search.border(0)
        box_search.addstr(0, 3, "Server List")
        box_search.addstr(1, 5, "Type to search : {}".format(search))
        for p, val in enumerate(table):
            if p > max_row:
                break
            if p == position:
                color = curses.A_REVERSE
            else:
                color = curses.A_NORMAL

            match = re.match(r"d/(\S+)/", val[0])

            if match:
                box.addstr(p + 1, 2, "+ {}".format(match.groups()[0]), color)
            else:
                box.addstr(
                    p + 1, 2,
                    "{}{}{}".format(val[0], " " * (max_len - len(val[0])),
                                    val[1]), color)

        screen.refresh()
        box.refresh()
        box_search.refresh()
        char = box.getch()

        if char == curses.KEY_UP:
            if len(table) > 0:
                position = (position - 1) % len(table)
        elif char == curses.KEY_DOWN and len(table) > 0:
            if len(table) > 0:
                position = (position + 1) % len(table)
        elif char == curses.KEY_RIGHT or char == curses.KEY_LEFT:
            pass
        elif char == curses.KEY_ENTER or char == 10:
            if len(table) == 0:
                curses.endwin()
                exit()
            match = re.match(r"d/(\S+)/", table[position % len(table)][0])
            if match:
                search = table[position % len(table)][0]
            else:
                break
        elif char == curses.KEY_DC or char == 127 or char == curses.KEY_BACKSPACE:
            search = search[:-1]
        elif char == 27:
            curses.endwin()
            exit()
        else:
            search += chr(char)

        table = create_table_for_prompt(ssh_table)
        if len(table):
            position = position % len(table)

    curses.endwin()

    if len(table) == 0:
        exit()
    start_ssh(table[position % len(table)][0],
              table[position % len(table)][1],
              port=table[position % len(table)][3],
              ping=table[position % len(table)][4])
예제 #42
0
파일: redpill.py 프로젝트: wklaebe/redpill
def start(stdscr):
    global server, base_url, username, access_token, password
    global size, room, rooms, all_rooms, lastEventRoom, room_keys

    curses.curs_set(0)
    curses.use_default_colors()
    size = stdscr.getmaxyx()

    stdscr.addstr(0, 0, "loading...")
    stdscr.refresh()
    loadCredentials("./credentials.json")

    client = MatrixClient(base_url,
                          token=access_token,
                          user_id='@{}:{}'.format(username, server))
    if access_token is None:
        access_token = client.login_with_password(username, password, size[0])

    rooms = client.get_rooms()

    all_rooms = "all rooms"
    rooms[all_rooms] = all_rooms

    room_keys = list(rooms.keys())
    room = all_rooms

    curses.halfdelay(10)
    maxDisplayName = 24
    displayNamestartingPos = 20
    PAD_COMMENTS = True
    pause = False

    client.add_listener(processMessage)
    client.start_listener_thread()

    curses.echo()
    stdscr.keypad(True)
    inputBuffer = ""
    lastEventRoom = all_rooms
    the_room_to_post_to = None  # store the last room we saw before we started typing

    while (True):
        size = stdscr.getmaxyx()
        maxChars = size[1] - 1 - len(username) - 3

        stdscr.clear()

        line = "redpill v0.7"
        line += " · screen size: " + str(size)
        if isinstance(rooms[room], Room):
            line += " · chat size: " + str(len(rooms[room].events))
        line += " · room: "

        # we want NAME aka ALIAS[0] (ROOM_ID)
        # or 2nd choice: ALIAS[0] (ROOM_ID)
        # or fallback: ROOM_ID

        if room == all_rooms:
            line += str(room)
        elif rooms[room].name:
            if len(rooms[room].aliases) > 0 and rooms[room].aliases[0] != room:
                line += rooms[room].name + " aka " + getFirstRoomAlias(
                    rooms[room]) + " (" + str(room) + ")"
            elif rooms[room].name != room:
                line += rooms[room].name + " (" + str(room) + ")"
            else:
                line += str(room)
        elif len(rooms[room].aliases) > 0 and rooms[room].aliases[0] != room:
            line += rooms[room].aliases[0] + " (" + str(line) + ")"
        else:
            line += str(room)

        if isinstance(rooms[room], Room) and rooms[room].topic is not None:
            line += " · topic: " + rooms[room].topic

        line += " · variables: room: " + room + ", last: " + lastEventRoom

        stdscr.addstr(0, 0, line, curses.A_UNDERLINE)

        current = len(rooms[room].events) - 1 if isinstance(rooms[room],
                                                            Room) else -1

        if True:
            y = 1
            if current >= 0:

                # TODO: something when the first event is a typing event
                currentLine = size[0] - 1

                # input
                space = ""
                for i in range(size[1] - 1):
                    space += " "
                stdscr.addstr(currentLine, 0, space, curses.A_DIM)
                stdscr.addstr(currentLine, 0, "<" + username + ">",
                              curses.A_DIM)
                stdscr.addstr(currentLine - 1, 0, space, curses.A_UNDERLINE)

                for event in reversed(rooms[room].events):
                    log(event)
                    log("maxDisplayName: {}, size: {}, currentLine: {}".format(
                        maxDisplayName, size, currentLine))

                    if event["type"] == "m.typing":
                        #if True:
                        continue  # do something clever
                    elif event["type"] == "m.presence":
                        #if True:
                        continue  # do something clever

                    elif event["type"] == "m.roomchange":
                        room_id = event["room_id"]
                        #lin = (str(rooms[room_id].name) + " aka " + getFirstRoomAlias(rooms[room_id]) + " (" +
                        #    rooms[room_id].room_id + ")")
                        line = room_id
                        if line == all_rooms:
                            pass
                        elif rooms[line].name is None:
                            if len(
                                    rooms[room_id].aliases
                            ) > 0 and rooms[room_id].aliases[0] != room_id:
                                line = rooms[room_id].aliases[
                                    0] + " (" + line + ")"
                        else:
                            if len(
                                    rooms[room_id].aliases
                            ) > 0 and rooms[room_id].aliases[0] != room_id:
                                line = rooms[
                                    room_id].name + " aka " + getFirstRoomAlias(
                                        rooms[room_id]) + " (" + line + ")"
                            else:
                                if rooms[room_id].name != room_id:
                                    line = rooms[
                                        room_id].name + " (" + line + ")"

                        #if rooms[room].topic is not None:
                        #    line += " · topic: " + rooms[room].topic

                        currentLine -= 1
                        stdscr.addstr(currentLine, 0, "Event(s) from " + line,
                                      curses.A_DIM)

                    else:
                        #currentLine = size[0] - y
                        #currentLine -= 1

                        if currentLine < 3:  # how many lines we want to reserve
                            break
                        #if currentLine == 5:
                        #    currentLine -= 1
                        y += 1
                        if "origin_server_ts" in event:
                            convertedDate = datetime.datetime.fromtimestamp(
                                int(event["origin_server_ts"] /
                                    1000)).strftime('%Y-%m-%d %H:%M:%S')

                        # assumption: body == normal message
                        length = len(
                            event["sender"]) if "sender" in event else 0
                        log("length: {}, currentLine: {}".format(
                            length, currentLine))

                        if "body" in event["content"]:

                            rawText = event["content"][
                                "body"]  # .encode('utf-8')

                            if event["content"]["msgtype"] == "m.emote":
                                if len(rawText) > 0 and rawText[0] == " ":
                                    rawText = rawText[1:]

                            linesNeeded = 0

                            buf = ""
                            lineByLineText = []
                            first = True
                            bufSinceLastWord = ""
                            for char in rawText:
                                if True:  #for char in line:

                                    bufSinceLastWord += char

                                    if char == '\n':
                                        linesNeeded += 1
                                        buf += bufSinceLastWord

                                        if PAD_COMMENTS or first:
                                            linesNeeded += int(
                                                (displayNamestartingPos +
                                                 maxDisplayName + 3 + len(buf))
                                                / size[1])
                                        else:
                                            linesNeeded += int(
                                                len(buf) / size[1])

                                        first = False
                                        lineByLineText.append(buf)
                                        buf = ""
                                        bufSinceLastWord = ""
                                    else:
                                        if ((PAD_COMMENTS and
                                             (displayNamestartingPos +
                                              maxDisplayName + 3 +
                                              len(buf + bufSinceLastWord))
                                             == size[1] - 1) or
                                            (not PAD_COMMENTS and
                                             (len(buf + bufSinceLastWord))
                                             == size[1] - 1)):

                                            #if (displayNamestartingPos + maxDisplayName + 3 + len(buf + bufSinceLastWord)) == size[1] - 1:
                                            if len(buf) == 0:
                                                buf += bufSinceLastWord
                                                bufSinceLastWord = ""

                                            if char.isspace():
                                                buf += bufSinceLastWord
                                                lineByLineText.append(buf)
                                                bufSinceLastWord = ""
                                                buf = ""
                                            else:
                                                lineByLineText.append(buf)
                                                buf = bufSinceLastWord
                                                bufSinceLastWord = ""
                                            linesNeeded += 1

                                    if char.isspace():
                                        buf += bufSinceLastWord
                                        bufSinceLastWord = ""


#                                if (displayNamestartingPos + maxDisplayName + 3 + len(buf + bufSinceLastWord)) == size[1] - 1:
                                if ((PAD_COMMENTS and
                                     (displayNamestartingPos + maxDisplayName +
                                      3 + len(buf + bufSinceLastWord))
                                     == size[1] - 1)
                                        or (not PAD_COMMENTS and
                                            (len(buf + bufSinceLastWord))
                                            == size[1] - 1)):

                                    buf += bufSinceLastWord
                                    bufSinceLastWord = ""
                                    lineByLineText.append(buf)
                                    linesNeeded += 1
                                    buf = ""
                                    #elif char == ' ':   # skip all whitespace
                                    #    self.X += 1
                            buf += bufSinceLastWord
                            lineByLineText.append(buf)
                            linesNeeded += int(
                                (displayNamestartingPos + maxDisplayName + 3 +
                                 len(buf)) / size[1])
                            buf = ""

                            if currentLine - linesNeeded < 2:  # how many lines we want to reserve
                                break

                            if PAD_COMMENTS:
                                pad = displayNamestartingPos + maxDisplayName + 3

                                linesNeeded += 1
                                currentLine -= linesNeeded

                                for i in range(linesNeeded):
                                    buf = rawText[:size[1] - pad]
                                    rawText = rawText[size[1] - pad:]

                                    if currentLine + i == size[0] - 2:
                                        stdscr.addstr(
                                            currentLine + i,
                                            displayNamestartingPos +
                                            maxDisplayName + 3,
                                            lineByLineText[i],
                                            curses.A_BOLD + curses.A_UNDERLINE)
                                    else:
                                        try:
                                            stdscr.addstr(
                                                currentLine + i,
                                                displayNamestartingPos +
                                                maxDisplayName + 3,
                                                lineByLineText[i],
                                                curses.A_BOLD)
                                        except:
                                            e = sys.exc_info()[0]
                                            print(
                                                "Error: unable to start thread. "
                                                + str(e))
                                            stdscr.addstr(1, 0, str(e))

                            else:
                                # TODO: need to split this out to get proper underline

                                currentLine -= linesNeeded
                                if currentLine == size[0] - 2:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        maxDisplayName + 3, rawText,
                                        curses.A_BOLD + curses.A_UNDERLINE)
                                else:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        maxDisplayName + 3, rawText,
                                        curses.A_BOLD)

                            usern = event["sender"]

                            if length > maxDisplayName:
                                usern = usern[:maxDisplayName - 3] + "..."

                            if event["content"]["msgtype"] == "m.emote":
                                usern = "* " + usern
                                if currentLine == size[0] - 2:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        max(0, maxDisplayName - length),
                                        str(usern),
                                        curses.A_UNDERLINE + curses.A_BOLD)
                                else:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        max(0, maxDisplayName - length),
                                        str(usern), curses.A_BOLD)
                            else:
                                usern = "<" + usern + ">"
                                if currentLine == size[0] - 2:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        max(0, maxDisplayName - length),
                                        str(usern), curses.A_UNDERLINE)
                                else:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        max(0, maxDisplayName - length),
                                        str(usern))

                            if currentLine == size[0] - 2:
                                stdscr.addstr(currentLine, 0, convertedDate,
                                              curses.A_UNDERLINE)
                            else:
                                stdscr.addstr(currentLine, 0, convertedDate)

                            #if currentLine == size[1]:  # last line
                            #    stdscr.addstr(
                            #        currentLine, displayNamestartingPos +
                            #        maxDisplayName + 3, buf[:size[1] -
                            #        (displayNamestartingPos + maxDisplayName + 4)],
                            #         curses.A_BOLD
                            #    )
                            #else:
                            #    stdscr.addstr(
                            #        currentLine, displayNamestartingPos +
                            #        maxDisplayName + 3, buf,
                            #        curses.A_BOLD
                            #    )

                        # membership == join/leave events
                        elif "membership" in event["content"]:
                            buf = " invited someone"
                            if event["content"]["membership"] == "invite":
                                if "state_key" in event:
                                    buf = " invited " + event["state_key"]
                            elif event["content"]["membership"] == "join":
                                buf = " has joined"
                            elif event["content"]["membership"] == "leave":
                                buf = " has left"

                            currentLine -= 1
                            if length > maxDisplayName:
                                if currentLine == size[0] - 2:
                                    stdscr.addstr(
                                        currentLine,
                                        displayNamestartingPos + 1,
                                        str(event["sender"]),
                                        curses.A_DIM + curses.A_UNDERLINE)
                                    stdscr.addstr(
                                        currentLine,
                                        displayNamestartingPos + length + 1,
                                        buf, curses.A_DIM + curses.A_UNDERLINE)
                                else:
                                    stdscr.addstr(currentLine,
                                                  displayNamestartingPos + 1,
                                                  str(event["sender"]),
                                                  curses.A_DIM)
                                    stdscr.addstr(
                                        currentLine,
                                        displayNamestartingPos + length + 1,
                                        buf, curses.A_DIM)

                            else:
                                if currentLine == size[0] - 2:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        1 + maxDisplayName - length,
                                        str(event["sender"]),
                                        curses.A_DIM + curses.A_UNDERLINE)
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        maxDisplayName + 1, buf,
                                        curses.A_DIM + curses.A_UNDERLINE)
                                else:
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        1 + maxDisplayName - length,
                                        str(event["sender"]), curses.A_DIM)
                                    stdscr.addstr(
                                        currentLine, displayNamestartingPos +
                                        maxDisplayName + 1, buf, curses.A_DIM)

                    current -= 1
        if pause:
            stdscr.addstr(
                int(size[0] / 2) - 1, int(size[1] / 2), "          ",
                curses.A_REVERSE)
            stdscr.addstr(int(size[0] / 2), int(size[1] / 2), "  PAUSED  ",
                          curses.A_REVERSE)
            stdscr.addstr(
                int(size[0] / 2) + 1, int(size[1] / 2), "          ",
                curses.A_REVERSE)
        try:
            stdscr.addstr(size[0] - 1,
                          len(username) + 3, inputBuffer[-maxChars:])
        except:
            e = sys.exc_info()[0]
            print("Error: unable to start thread. " + str(e))
            stdscr.addstr(1, 0, str(e))

        stdscr.refresh()

        #       getInput(stdscr)

        #def getInput(stdscr):
        #   if True:
        try:

            c = stdscr.getch(size[0] - 1, len(username) + 3)
            #c = stdscr.getkey(size[0] - 1, len(username) + 3)

            #stri = stdscr.getstr(size[0] - 1, len(username) + 3, 10)
            if c == -1:
                stdscr.addstr(1, 0, "timeout")
            else:
                if c <= 256 and c != 10 and c != 9:  ## enter and tab
                    inputBuffer += chr(c)
                if len(inputBuffer) == 1:  # e.g. just started typing
                    if lastEventRoom != all_rooms:
                        the_room_to_post_to = lastEventRoom

            if c == 9:
                #stdscr.addstr(1, 0, "%s was pressed\n" % c)
                log("key pressed: 0x{:X}".format(c))
                room = room_keys[(room_keys.index(room) + 1) % len(rooms)]
                the_room_to_post_to = None
            elif c == 10:  # enter
                with open('redpill-sends.log', 'a') as the_file:
                    the_file.write("the_room_to_post_to:" +
                                   str(the_room_to_post_to) + "\n")
                    the_file.write("lastEventRoom: " + str(lastEventRoom) +
                                   "\n")
                    the_file.write("room: " + str(room) + "\n")
                    the_file.write("inputBuffer: " + str(inputBuffer) + "\n")
                    the_file.write("---\n")

                if inputBuffer.startswith("/invite"):
                    user_id = inputBuffer[7:].strip()
                    rooms[room].invite_user(user_id)
                elif inputBuffer.startswith("/kick"):
                    user_id = inputBuffer[5:].strip()
                    reason = "no reason..."
                    rooms[room].kick_user(user_id, reason)
                elif inputBuffer.startswith("/power"):
                    user_id = inputBuffer[7:].strip()
                    power_level = 50
                    rooms[room].set_power_level(user_id, power_level)
                elif inputBuffer.startswith("/op"):
                    user_id = inputBuffer[2:].strip()
                    rooms[room].set_power_level(user_id)
                elif inputBuffer.startswith("/ban"):  # reason
                    user_id = inputBuffer[4:].strip()
                    reason = "sux"  #FIXME
                    rooms[room].ban(user_id, reason)
                elif inputBuffer.startswith(
                        "/join"):  # there's a /join that supports aliases
                    room_alias = inputBuffer[5:].strip()
                    client.join_room(room_alias)
                elif inputBuffer.startswith("/j"):
                    room_alias = inputBuffer[2:].strip()
                    client.join_room(room_alias)
                elif inputBuffer.startswith("/leave"):
                    rooms[room].leave_room(room_id)
                elif inputBuffer.startswith("/create"):  # create a new room
                    is_public = True
                    invitees = ()
                    #     def create_room(self, alias=None, is_public=False, invitees=()):
                    room_alias = inputBuffer[7:].strip()
                    client.create_room(room_alias, is_public, invitees)
                elif inputBuffer.startswith("/topic"):  # get or set topic
                    new_topic = inputBuffer[6:].strip()
                    if len(new_topic) > 0:
                        rooms[room].topic = new_topic
                    else:
                        pass
                        #rooms[room].topic = "fail"
                else:
                    if room == all_rooms:
                        if the_room_to_post_to is None:
                            if lastEventRoom != all_rooms:
                                the_room_to_post_to = lastEventRoom
                            else:
                                stdscr.addstr(1, 0,
                                              "No idea what room to post to!")
                                stdscr.refresh()
                                inputBuffer = "No idea what room to post to!"
                                continue
                    else:
                        the_room_to_post_to = room

                    if inputBuffer.startswith("/me"):
                        rooms[the_room_to_post_to].send_emote(inputBuffer[3:])
                    else:
                        rooms[the_room_to_post_to].send_text(inputBuffer)

                inputBuffer = ""
                the_room_to_post_to = None
            elif c == curses.KEY_DC:
                inputBuffer = ""
                the_room_to_post_to = None
            elif c == curses.KEY_BACKSPACE:
                if len(inputBuffer) > 0:
                    inputBuffer = inputBuffer[:-1]
                if len(inputBuffer) == 0:
                    the_room_to_post_to = None
            elif c == curses.KEY_IC:
                pause = not (pause)
                if pause:
                    curses.nocbreak()
                    curses.cbreak()
                    stdscr.timeout(-1)
                    stdscr.addstr(
                        int(size[0] / 2) - 1, int(size[1] / 2), "          ",
                        curses.A_REVERSE)
                    stdscr.addstr(int(size[0] / 2), int(size[1] / 2),
                                  " PAUSING  ", curses.A_REVERSE)
                    stdscr.addstr(
                        int(size[0] / 2) + 1, int(size[1] / 2), "          ",
                        curses.A_REVERSE)
                    stdscr.refresh()
                else:
                    stdscr.addstr(
                        int(size[0] / 2) - 1, int(size[1] / 2), "          ",
                        curses.A_REVERSE)
                    stdscr.addstr(int(size[0] / 2), int(size[1] / 2),
                                  " RESUMING ", curses.A_REVERSE)
                    stdscr.addstr(
                        int(size[0] / 2) + 1, int(size[1] / 2), "          ",
                        curses.A_REVERSE)
                    stdscr.refresh()
                    curses.halfdelay(10)
                    stdscr.timeout(1)
            elif c == 27:  # need to test for alt combo or ESC
                curses.cbreak()
                curses.echo()
                #curses.curs_set(1)
                stdscr.keypad(0)
                curses.endwin()
                quit()
            elif c == curses.KEY_F2:
                PAD_COMMENTS = not PAD_COMMENTS

            #stdscr.addstr(2, 0, "time() == %s\n" % time.time())

        finally:
            do_nothing = True
예제 #43
0
 def config_curses(self):
     # use the default colors of the terminal
     curses.use_default_colors()
     # hide the cursor
     curses.curs_set(0)
예제 #44
0
def drawTorMonitor(stdscr, startTime):
    """
  Main draw loop context.
  
  Arguments:
    stdscr    - curses window
    startTime - unix time for when arm was started
  """

    initController(stdscr, startTime)
    control = getController()

    # provides notice about any unused config keys
    for key in conf.getConfig("arm").getUnusedKeys():
        log.log(CONFIG["log.configEntryUndefined"],
                "Unused configuration entry: %s" % key)

    # tells daemon panels to start
    for panelImpl in control.getDaemonPanels():
        panelImpl.start()

    # allows for background transparency
    try:
        curses.use_default_colors()
    except curses.error:
        pass

    # makes the cursor invisible
    try:
        curses.curs_set(0)
    except curses.error:
        pass

    # logs the initialization time
    msg = "arm started (initialization took %0.3f seconds)" % (time.time() -
                                                               startTime)
    log.log(CONFIG["log.startTime"], msg)

    # main draw loop
    overrideKey = None  # uses this rather than waiting on user input
    isUnresponsive = False  # flag for heartbeat responsiveness check
    if not torTools.getConn().isAlive(): overrideKey = ord('w')  # shows wizard

    while not control.isDone():
        displayPanels = control.getDisplayPanels()
        isUnresponsive = heartbeatCheck(isUnresponsive)

        # sets panel visability
        for panelImpl in control.getAllPanels():
            panelImpl.setVisible(panelImpl in displayPanels)

        # redraws the interface if it's needed
        control.redraw(False)
        stdscr.refresh()

        # wait for user keyboard input until timeout, unless an override was set
        if overrideKey:
            key, overrideKey = overrideKey, None
        else:
            curses.halfdelay(CONFIG["features.redrawRate"] * 10)
            key = stdscr.getch()

        if key == curses.KEY_RIGHT:
            control.nextPage()
        elif key == curses.KEY_LEFT:
            control.prevPage()
        elif key == ord('p') or key == ord('P'):
            control.setPaused(not control.isPaused())
        elif key == ord('m') or key == ord('M'):
            cli.menu.menu.showMenu()
        elif key == ord('q') or key == ord('Q'):
            # provides prompt to confirm that arm should exit
            if CONFIG["features.confirmQuit"]:
                msg = "Are you sure (q again to confirm)?"
                confirmationKey = cli.popups.showMsg(msg, attr=curses.A_BOLD)
                quitConfirmed = confirmationKey in (ord('q'), ord('Q'))
            else:
                quitConfirmed = True

            if quitConfirmed: control.quit()
        elif key == ord('x') or key == ord('X'):
            # provides prompt to confirm that arm should issue a sighup
            msg = "This will reset Tor's internal state. Are you sure (x again to confirm)?"
            confirmationKey = cli.popups.showMsg(msg, attr=curses.A_BOLD)

            if confirmationKey in (ord('x'), ord('X')):
                try:
                    torTools.getConn().reload()
                except IOError, exc:
                    log.log(
                        log.ERR, "Error detected when reloading tor: %s" %
                        sysTools.getFileErrorMsg(exc))
        elif key == ord('h') or key == ord('H'):
            overrideKey = cli.popups.showHelpPopup()
    def ui_open(self):
        """
        Initialize the ncurses user interface.
        """
        self.stdscr = curses.initscr()

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

        # Set the basic colors.
        if curses.has_colors():
            curses.start_color()
            curses.use_default_colors()
            curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
            curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
            curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
            curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)
            curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
            curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
            curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)

        # Get a list of colours
        self.colour_list = []
        for i in range(1, 8):
            self.colour_list.append(curses.color_pair(i))

        self.col_white = curses.color_pair(7)
        self.col_white_bold = curses.color_pair(7) | curses.A_BOLD
        self.col_selected = curses.color_pair(2)
        self.col_cursor = curses.color_pair(3)
        self.col_cursor |= curses.A_BOLD
        self.col_cursor |= curses.A_REVERSE

        self.stdscr.bkgdset(' ', self.col_white)
        self.stdscr.keypad(1)

        # Create a pad with a border.
        with os.popen('stty size') as tty:
            nrows, ncols = map(int, tty.read().split())
        for i in range(nrows - 2):
            self.stdscr.addstr(i + 1, 1, (ncols - 2) * ' ')
        self.size = (nrows, ncols)

        self.info_win = curses.newwin(nrows - 4, 2 * ncols / 5 - 6, 2, 4)
        self.info_border = self.col_white
        self.display_info()

        self.pickup_win = curses.newwin(nrows - 4, 3 * ncols / 5 - 6, 2,
                                        2 * ncols / 5 + 2)
        self.pu_border = self.col_white
        self.pickup_win.bkgdset(' ', self.col_white)
        self.pickup_win.border(0)
        waiting = 'Waiting for connection...'
        self.pickup_win.addstr(2, 4, waiting, self.col_white)

        self.stdscr.refresh()
        self.info_win.refresh()
        self.pickup_win.refresh()

        # Have a loading screen waiting for the socket.
        self.socket_init()
예제 #46
0
def main(screen=None):
    #Set the timeout
    screen.timeout(250)

    #Turn off input echoing
    curses.noecho()

    #Enable cbreaking
    curses.cbreak()

    #Respond to special keys
    screen.keypad(True)

    #Set cursor visibility
    curses.curs_set(0)

    #Use terminal colours
    curses.use_default_colors()

    #Initial clear
    screen.clear()

    #Create the colour list
    curses.init_pair(1, -1, -1)  #Clear

    curses.init_pair(2, curses.COLOR_MAGENTA, -1)  #Magenta
    curses.init_pair(3, curses.COLOR_RED, -1)  #Red
    curses.init_pair(4, 166, -1)  #Orange
    curses.init_pair(5, curses.COLOR_YELLOW, -1)  #Yellow
    curses.init_pair(6, curses.COLOR_GREEN, -1)  #Green
    curses.init_pair(7, curses.COLOR_BLUE, -1)  #Blue
    curses.init_pair(8, curses.COLOR_CYAN, -1)  #Cyan

    curses.init_pair(9, curses.COLOR_WHITE, -1)  #White
    curses.init_pair(10, curses.COLOR_BLACK, -1)  #Black

    #Custom colours
    curses.init_pair(11, 42, -1)  #Purplish
    curses.init_pair(12, 231, -1)  #Stark white
    curses.init_pair(13, 161, -1)  #
    #curses.init_pair(14, , -1) #
    #curses.init_pair(15, , -1) #
    #curses.init_pair(16, , -1) #
    #END colour list

    #Create a configuration
    cfg = {
        'GOOD': curses.color_pair(6) | curses.A_BOLD,
        'OKAY': curses.color_pair(5) | curses.A_BOLD,
        'LOW': curses.color_pair(4) | curses.A_BOLD,
        'BAD': curses.color_pair(3) | curses.A_BOLD,
        'CRIT': curses.color_pair(13) | curses.A_BOLD,
        'H1': curses.color_pair(11) | curses.A_BOLD,
        'H2': curses.color_pair(12) | curses.A_BOLD,
        #Just kinda used the HTML tag names <h1> and <h2>
        # b/c I couldn't think of something better, atm.
        # Will probably change this later.

        #Generic colours
        'GREEN': curses.color_pair(6) | curses.A_BOLD,
        'YELLOW': curses.color_pair(5) | curses.A_BOLD,
        'RED': curses.color_pair(3) | curses.A_BOLD,
        'NONE': curses.color_pair(10)  #Clear
    }

    #Volume variables
    reset_vol = 50  #Select a default volume to reset to
    mute_vol = 0  #Store muted volume (to reset)
    step = 2  #Set volume step
    vol_bar = "█"  #Character to use in volume bar

    #Get OS info
    os_name = get_os()
    kernel = get_kernel()
    architecture = get_arch()
    hostname = get_host()

    #Get CPU info
    threads = psutil.cpu_count()
    cores = psutil.cpu_count(logical=False)
    max_freq = cpu_max()
    min_freq = cpu_min()

    #Get RAM info
    mem_denom = math.pow(2, 20)  #Divide memory to achieve desired output
    mem_postfix = "MB"
    mem_tot = mem_total(mem_denom)

    #Start the loop
    while True:
        #Clear the screen each time
        screen.clear()

        #Get the current time
        ##Using this so that the time remains consistent
        time_now = time.time()

        #Create a playback mixer
        '''
			Must be done IN loop, because it doesn't seem
			to recognise changes if made outside.
		'''
        pb = alsaaudio.Mixer(control='Master', device='default')
        vols = pb.getvolume()
        max_vol = max(vols)
        min_vol = min(vols)

        #Title
        screen.addstr("++SYSTEM INFO++\n", cfg['H1'])  #Application header

        #Date and time
        screen.addstr(" DATE AND TIME\n", cfg['H1'])  #Date/time header
        screen.addstr("  {} {}\n".format(fmt_date(time_now),
                                         fmt_localtime(time_now)),
                      cfg['H2'])  #Date and time

        #System uptime
        screen.addstr(" SYSTEM UPTIME\n", cfg['H1'])  #Uptime header
        screen.addstr("  {}\n".format(get_uptime(time_now)),
                      cfg['H2'])  #Current uptime

        #System info
        screen.addstr(" SYSTEM INFO\n", cfg['H1'])  #SysInfo header
        screen.addstr("  OS: {}\n".format(os_name), cfg['H2'])  #OS
        screen.addstr("  Kernel: {}\n".format(kernel), cfg['H2'])  #Kernel
        screen.addstr("  Arch: {}\n".format(architecture),
                      cfg['H2'])  #Architecture
        screen.addstr("  Hostname: {}\n".format(hostname),
                      cfg['H2'])  #Hostname

        #CPU info
        screen.addstr(" CPU STATUS" + '\n', cfg['H1'])  #CPU header
        screen.addstr(
            "  Cores: {}C/{}T @{:7.2f} Mhz\n".format(cores, threads,
                                                     cpu_current()), cfg['H2'])
        screen.addstr("  Min/Max: {} / {} Mhz\n".format(min_freq, max_freq),
                      cfg['H2'])

        cpu_used = psutil.cpu_percent(interval=0, percpu=False)
        screen.addstr(
            "  Utilisation: {}%\n".format(str(cpu_used)),
            cfg['CRIT'] if cpu_used > 95.0 else
            cfg['BAD'] if cpu_used > 85.0 else cfg['LOW'] if cpu_used > 70.0
            else cfg['OKAY'] if cpu_used > 40.0 else cfg['GOOD'])
        #percpu=True returns each CPU's usage, but this takes up a lot of space

        #Memory info
        screen.addstr(" FREE MEMORY\n", cfg['H1'])  #Memory header

        perc_used = mem_perc(mem_denom, mem_tot)
        screen.addstr(
            "  {:.0f} {} / {:.0f} {} ({:.2f}%)\n".format(
                mem_used(mem_denom), mem_postfix, mem_tot, mem_postfix,
                perc_used), cfg['CRIT'] if perc_used < 15.0 else
            cfg['BAD'] if perc_used < 25.0 else cfg['LOW'] if perc_used < 30.0
            else cfg['OKAY'] if perc_used < 40.0 else cfg['GOOD'])

        #Process count
        screen.addstr(" PROCESSES\n", cfg['H1'])  #Processes header
        screen.addstr("  Count: {}\n".format(str(get_pids(True))),
                      cfg['H2'])  #Count of processes

        #Volume management
        lv, _ = divmod(vols[0], 5)
        rv, _ = divmod(vols[1], 5)
        lbarg = vol_bar * (lv if lv < 8 else 8)
        rbarg = vol_bar * (rv if rv < 8 else 8)
        lbary = vol_bar * (lv - 8 if (lv < 16) else 8)
        rbary = vol_bar * (rv - 8 if (rv < 16) else 8)
        lbarr = vol_bar * (lv - 16 if (lv < 20) else 4)
        rbarr = vol_bar * (lv - 16 if (rv < 20) else 4)
        screen.addstr(" VOLUME\n", cfg['H1'])
        screen.addstr("  L ({:3}%):".format(vols[0]), cfg['H2'])
        screen.addstr(lbarg, cfg['GREEN'])
        screen.addstr("{}".format(lbary), cfg['YELLOW'])
        screen.addstr("{}".format(lbarr), cfg['RED'])
        screen.addstr("\n")
        screen.addstr("  R ({:3}%):".format(vols[1]), cfg['H2'])
        screen.addstr(rbarg, cfg['GREEN'])
        screen.addstr("{}".format(rbary), cfg['YELLOW'])
        screen.addstr("{}".format(rbarr), cfg['RED'])
        screen.addstr("\n")
        screen.addstr("  Stored mute volume: {}\n".format(str(mute_vol)),
                      cfg['H2'])
        screen.addstr("  Configured reset volume: {}\n".format(str(reset_vol)),
                      cfg['H2'])

        #Get the key
        key = screen.getch()
        #RAISE the volume
        if key in [ord("A"), ord("a")]:  #Both up
            inc_volume(pb, max_vol, step)
        #LOWER the volume
        elif key in [ord("Z"), ord("z")]:  #Both down
            dec_volume(pb, min_vol, step)
        #RESET the volume
        elif key in [ord("R"), ord("r")]:
            reset_volume(pb, reset_vol)
        #MUTE the volume
        elif key in [ord("M"), ord("m")]:
            mute_vol = mute_volume(pb, mute_vol, max_vol)
        elif key in [
                27,  #Escape
                #10, #Enter
                ord("q"),
                ord("Q")
        ]:
            break
예제 #47
0
def main(stdscr):
    global args

    curses.start_color()
    curses.use_default_colors()
    curses.cbreak()
    curses.noecho()

    # Warning
    curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)

    # Tag message
    curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)

    # Log message
    curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)

    # Command message
    curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLACK)

    # Wait message
    curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)

    # User prompt
    curses.init_pair(6, curses.COLOR_MAGENTA, curses.COLOR_BLACK)

    stdscr.scrollok(True)
    stdscr.idlok(True)
    stdscr.nodelay(True)  # Don't wait for keypresses
    stdscr.keypad(True)

    commands = []
    for cur_file in args.json_files:
        with open(cur_file, "rt") as fp:
            commands += json.load(fp)

    if not args.dry_run:
        print(f"{len(commands)} commands ready to be executed, let's go!")
        print("Going to establish a connection with the server…")
        conn = StripConnection()
        conn.login()
        if close_tags(stdscr, conn):
            return

        print("…connection established")

        if (not args.dry_run) and (not args.do_not_round):
            conn.round_all_files()
    else:
        conn = None

    open_tags = set([])
    indent_level = 0
    for cur_command in commands:
        cmddict = cur_command["command"]
        print_fn = None

        indent_level_incr = 0
        curpath = cur_command["path"]
        if cur_command["kind"] == "tag":
            print_fn = tagmsg
            if cmddict["type"] == "START":
                command_descr = f"start of tag {cmddict['tag']}"
                open_tags.add(cmddict["tag"])
                indent_level_incr = 4
            else:
                if not cmddict["tag"] in open_tags:
                    msg = f"Tag {cmddict['tag']} is being closed, but the tags currently open are {', '.join(open_tags)}"
                    warning(stdscr, msg)
                else:
                    open_tags.discard(cmddict["tag"])

                command_descr = f"end of tag {cmddict['tag']}"
                indent_level = -4

        elif cur_command["kind"] == "log":
            print_fn = logmsg
            command_descr = f"log message '{cmddict['message']}' ({cmddict['level']})"
        elif cur_command["kind"] == "command":
            print_fn = commandmsg
            method, base_addr, data = [
                cmddict[x] for x in ("method", "base_addr", "data")
            ]

            datastr = ", ".join([str(x) for x in data])
            command_descr = f"command {method} {base_addr}, data={datastr}"
        elif cur_command["kind"] == "wait":
            print_fn = waitmsg
            curpath = "/waitcmd"
            command_descr = f"wait for {cur_command['command']['wait_time_s']} s"
        else:
            warning(
                stdscr,
                f"\"{cur_command['kind']}\" is not recognized as a valid command type",
            )
            print_fn = prompt

        print_fn(stdscr, " " * indent_level + f"{curpath}: {command_descr}")

        try:
            if cur_command["kind"] != "wait":
                if not args.dry_run:
                    conn.post(cur_command["path"], message=cmddict)

                time.sleep(args.wait_time)
            else:
                wait_time = cmddict["wait_time_s"]
                if args.waitcmd_time is not None:
                    wait_time = args.waitcmd_time
                time.sleep(wait_time)
        except Exception as e:
            if cur_command["kind"] == "tag":
                warning(
                    stdscr, f"Error while submitting tag {cmddict['tag']}, ignoring it"
                )
            else:
                warning_msg = f"Error in \"{cur_command['kind']}\" command: {e}"
                warning(stdscr, warning_msg)

        indent_level += indent_level_incr
        if indent_level < 0:
            indent_level = 0

        # Check for keypresses
        key = stdscr.getch()
        if key != curses.ERR:
            if key in [ord(" "), ord("p")]:
                # Pause
                curses.flash()
                prompt(stdscr, "Paused, press any key to resume")
                stdscr.nodelay(False)
                stdscr.getch()
                stdscr.nodelay(True)
            elif key == ord("q"):
                # Quit
                curses.flash()
                prompt(stdscr, "Are you sure you want to quit? (y/n)")
                choice = readkey(stdscr)
                if choice.upper() == "Y":
                    break
            elif key == ord("l"):
                # Log message
                curses.flash()
                prompt(stdscr, "Enter a log message:")
                stdscr.nodelay(False)
                curses.echo()
                msg = stdscr.getstr()
                curses.noecho()
                stdscr.nodelay(True)

                if not args.dry_run:
                    conn.post("/rest/log", message={"level": "INFO", "message": msg})

                logmsg(stdscr, f'Custom log message "{msg}" sent to the server')

    prompt(stdscr, "Execution completed, press a key to exit")
    readkey(stdscr)
    if not args.dry_run:
        if conn and (not args.do_not_round):
            conn.round_all_files()

        conn.logout()

    if warnings:
        print("Here are the warning messages produced during the execution:")
        for msg in warnings:
            print(msg)
예제 #48
0
def main(stdscr):
    global run
    global degrees
    global pascals
    global humidity
    global ppm
    global lux
    global bus_lock
    global co2_restart_hour
    global co2_sensor_starting
    global hours
    global minutes
    global light1_on
    global light2_on
    global exhaust_on
    global heat_on
    global cool_on
    global circulation_on
    global co2_on
    global dehumidifier_on
    global start_delay
    global cooling_enable
    global dehumidifier_enable
    global co2_restart_wait
    try:
        relays.write_gpio([0xFF])
        relays.write_iodir([0x00])
        co2_sensor.power_on()
        d = threading.Thread(target=co2_sensor_delay)
        q = threading.Thread(target=startup_delay)
        d.start()
        q.start()
# restart co2 sensor every 12 hours to avoid auto calabration
        co2_restart_hour = localtime().tm_hour + 12
        if co2_restart_hour >= 24:
            co2_restart_hour = co2_restart_hour - 24
        stdscr.nodelay(1)
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED)
        curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_YELLOW)
        color_on = curses.color_pair(1)
        color_off = curses.color_pair(2)
        color_delay = curses.color_pair(3)
        while 1:
            k = stdscr.getch()
            if k == ord('q'):
                run = 0
                while bus_lock == 1:
                    time.sleep(.01)
                bus_lock = 1
                relays.write_gpio([0xFF])
                co2_sensor.power_off()
                bus_lock = 0
                exit(0)
            hectopascals = pascals / 100
            hours = localtime().tm_hour
            minutes = localtime().tm_min
            seconds = localtime().tm_sec

# lock the I2C bus ---------------------------------

            while bus_lock == 1:
                time.sleep(.01)
            bus_lock = 1

# do stuff -------------------------------------------

            read_sensors()
            control_relays()
            if hours == co2_restart_hour and co2_sensor_starting == 0 and co2_restart_wait == 0:
                co2_restart_wait = 1
                m = threading.Thread(target=co2_sensor_restart)
                m.start()

# unlock the I2C bus ---------------------------------

            bus_lock = 0

# display sensor output ------------------------------

            stdscr.erase()
            stdscr.addstr(0, 0, 'Time      = %s:%s:%s' % (str(hours).zfill(2), str(minutes).zfill(2), str(seconds).zfill(2)))
            stdscr.addstr(1, 0, 'Temp      = %0.3f deg C (%0.3f deg F)' % (degrees, ((degrees*9/5)+32)))
            stdscr.addstr(2, 0, 'Pressure  = %0.2f hPa' % hectopascals)
            stdscr.addstr(3, 0, 'Humidity  = %0.2f %%' % humidity)
            stdscr.addstr(4, 0, 'Light     = %s lux' % lux)
            stdscr.addstr(5, 0, 'CO2       = %s ppm' % ppm)

# display light 1 status

            if light1_on == 0:
                color_status = color_off
            else:
                color_status = color_on

            stdscr.addstr(7, 0, '[Light 1]', color_status)

# display light 2 status

            if light2_on == 0:
                color_status = color_off
            else:
                color_status = color_on

            stdscr.addstr(7, 10, '[Light 2]', color_status)

# display exhaust status

            if exhaust_on == 0 and start_delay == 0:
                color_status = color_off
            elif exhaust_on == 1 and start_delay == 0:
                color_status = color_on
            elif start_delay == 1:
                color_status = color_delay

            stdscr.addstr(7, 20, '[Exhaust]', color_status)

# display heating status

            if heat_on == 0 and start_delay == 0:
                color_status = color_off
            elif heat_on == 1 and start_delay == 0:
                color_status = color_on
            elif start_delay == 1:
                color_status = color_delay

            stdscr.addstr(7, 30, '[Heat]', color_status)

# display cooling status

            if cool_on == 0 and cooling_enable == 1 and start_delay == 0:
                color_status = color_off
            elif cool_on == 1 and cooling_enable == 1 and start_delay == 0:
                color_status = color_on
            elif  cooling_enable == 0 or start_delay == 1:
                color_status = color_delay

            stdscr.addstr(7, 37, '[Cool]', color_status)

# display circulation status

            if circulation_on == 0:
                color_status = color_off
            else:
                color_status = color_on

            stdscr.addstr(7, 44, '[Circulation]', color_status)

# display CO2 status

            if co2_on == 0 and co2_sensor_starting == 0:
                color_status = color_off
            elif co2_on == 1 and co2_sensor_starting == 0:
                color_status = color_on
            elif co2_sensor_starting == 1:
                color_status = color_delay

            stdscr.addstr(7, 58, '[CO2]', color_status)

# display dehumidifier status

            if dehumidifier_on == 0 and dehumidifier_enable == 1 and start_delay == 0:
                color_status = color_off
            elif dehumidifier_on == 1 and dehumidifier_enable == 1 and start_delay == 0:
                color_status = color_on
            elif dehumidifier_enable == 0 or start_delay == 1:
                color_status = color_delay

            stdscr.addstr(7, 64, '[Dehumidifier]', color_status)

            stdscr.addstr(9, 0, 'Press Q key to exit...')
            stdscr.refresh()

    except Exception as e:
        pass
    finally:
        run = 0
        co2_sensor.power_off()
        relays.write_gpio([0xFF])
        bus_lock = 0
        exit(1)
예제 #49
0
    def show_ui(self, stdscr):
        global mainwin
        mainwin = stdscr
        curses.use_default_colors()
        # w/o this for some reason takes 1 cycle to draw wins
        stdscr.refresh()

        signal.signal(signal.SIGWINCH, sigwinch_handler)

        TIMEOUT = 250
        stdscr.timeout(TIMEOUT)

        server_count = len(self.servers)
        maxy, maxx = stdscr.getmaxyx()
        uis = (SummaryUI(maxy, maxx, server_count),
               ServerUI(maxy, maxx, server_count),
               SessionUI(maxy, maxx, server_count))

        # start the polling threads
        pollers = [StatPoller(server) for server in self.servers]
        for poller in pollers:
            poller.setName("PollerThread:" + poller.server)
            poller.setDaemon(True)
            poller.start()

        LOG.debug("starting main loop")
        global resized_sig
        flash = None
        while True:
            try:
                if resized_sig:
                    resized_sig = False
                    self.resize(uis)
                    wakeup_poller()

                while not q_stats.empty():
                    zkserver = q_stats.get_nowait()
                    for ui in uis:
                        ui.update(zkserver)

                ch = stdscr.getch()
                if 0 < ch <= 255:
                    if ch == ord('q'):
                        return
                    elif ch == ord('h'):
                        flash = "Help: q:quit r:reset stats spc:refresh"
                        flash_count = 1000/TIMEOUT * 5
                    elif ch == ord('r'):
                        for server in self.servers:
                            try:
                                reset_server_stats(server)
                            except:
                              pass

                        flash = "Server stats reset"
                        flash_count = 1000/TIMEOUT * 5
                        wakeup_poller()
                    elif ch == ord(' '):
                        wakeup_poller()

                stdscr.move(1, 0)
                if flash:
                    stdscr.addstr(1, 0, flash)
                    flash_count -= 1
                    if flash_count == 0:
                        flash = None
                stdscr.clrtoeol()

                curses.doupdate()

            except KeyboardInterrupt:
                break
예제 #50
0
            def curses_loop(screen):

                curses.use_default_colors()  # don't change terminal background
                screen.nodelay(1)  # sets `screen.getch()` to non-blocking

                while True:

                    # get info from daemon
                    activity = m.get_activity()
                    status = m.status
                    n_errors = len(m.sync_errors)

                    # create header
                    lines = [
                        f"Status: {status}, Sync errors: {n_errors}",
                        "",
                    ]

                    # create table

                    file_names = ["PATH"]
                    states = ["STATUS"]
                    col_len = 4

                    for event in activity:

                        dbx_path = cast(str, event["dbx_path"])
                        direction = cast(str, event["direction"])
                        status = cast(str, event["status"])
                        size = cast(int, event["size"])
                        completed = cast(int, event["completed"])

                        filename = os.path.basename(dbx_path)
                        file_names.append(filename)

                        if completed > 0:
                            done_str = natural_size(completed, sep=False)
                            todo_str = natural_size(size, sep=False)
                            states.append(f"{done_str}/{todo_str}")
                        else:
                            if status == "syncing" and direction == "up":
                                states.append("uploading")
                            elif status == "syncing" and direction == "down":
                                states.append("downloading")
                            else:
                                states.append(status)

                        col_len = max(len(filename), col_len)

                    for fn, s in zip(file_names, states):  # create rows
                        lines.append(fn.ljust(col_len + 2) + s)

                    # print to console screen
                    screen.clear()
                    try:
                        screen.addstr("\n".join(lines))
                    except curses.error:
                        pass
                    screen.refresh()

                    # abort when user presses 'q', refresh otherwise
                    key = screen.getch()
                    if key == ord("q"):
                        break
                    elif key < 0:
                        time.sleep(1)
def curses_fingers_interface(screen, hand):
    # don't change the terminal colors
    curses.use_default_colors()
    # don't display the cursor
    curses.curs_set(0)

    SCREEN_X_DIM = screen.getmaxyx()[1]
    SCREEN_Y_DIM = screen.getmaxyx()[0]
    screen.refresh()

    title_win = curses.newwin(1, SCREEN_X_DIM, 0, 0)
    title_str = "Interactive ReflexSF Controller"
    center_justify(title_win, title_str)

    keys_win = curses.newwin(13, 50, 1, 0)
    instr = """\
                    tighten
                      _____
                     |     |
                     |  ^  |
                _____|_____|_____
               |     |     |     |
  prev finger  |  <  |  v  |  >  |  next finger
               |_____|_____|_____|
  
                     loosen
  q : Quit
"""
    keys_win.addstr(1, 1, instr)
    keys_win.box()
    keys_win.refresh()

    finger_win = curses.newwin(1, SCREEN_X_DIM, 14, 0)
    fingers = hand.fingerNames
    finger_node_names = [
        "%s_%s" % (hand.namespace, finger) for finger in fingers
    ]
    finger_index = 0

    commands_win = curses.newwin(SCREEN_Y_DIM - 15, SCREEN_X_DIM, 15, 0)
    commands_win.scrollok(True)
    commands_win.idlok(1)
    #commands_win.setscrreg(16,19)

    running = True
    while running:
        finger_win.erase()
        finger_win.addstr("Current Finger", curses.A_UNDERLINE)
        finger_win.addstr(": ")
        finger_win.addstr(fingers[finger_index % 4])
        finger_win.refresh()

        ch = screen.getkey()
        if ch == 'KEY_UP':
            commands_win.insertln()
            commands_win.addstr("Tightening %s\n" %
                                (fingers[finger_index % 4]))
            commands_win.move(0, 0)
            #Tighten the finger
            hand.motors[finger_node_names[finger_index % 4]].tighten()
        elif ch == 'KEY_DOWN':
            commands_win.insertln()
            commands_win.addstr("Loosening %s\n" % (fingers[finger_index % 4]))
            commands_win.move(0, 0)
            #Loosen the finger
            hand.motors[finger_node_names[finger_index % 4]].loosen()
        elif ch == 'KEY_LEFT':
            finger_index -= 1
        elif ch == 'KEY_RIGHT':
            finger_index += 1
        elif ch == 'q':
            running = False
        commands_win.refresh()
예제 #52
0
 def drawBoard(stdscr):
     curses.noecho()
     curses.curs_set(0)
     stdscr.keypad(True)
     stdscr.clear()
     curses.start_color()
     curses.use_default_colors()
     curses.init_color(11, 1000, 0, 0)
     curses.init_color(12, 0, 1000, 0)
     curses.init_pair(1, 11, -1)
     curses.init_pair(2, 12, -1)
 
     moveList = [stoneMove(2, '1', 0, 2), stoneMove(3, '2', 1, 1), stoneMove(13, curses.ACS_CKBOARD, pid=1, side=0)] 
     
     dbf = open("debug", "w")
 
     height, width = stdscr.getmaxyx()
     dbf.write(f"H: {height} W: {width}\n")
 
     xscale = floor((width-1) / 16)
     yscale = floor((height-1) / 6)
     dbf.write(f"XSCL {xscale} YSCL {yscale}\n")
    
     if xscale > 2*yscale:
         xscale = yscale * 2
     else:
         xscale -= 1 if xscale % 2 == 1 else 0
         yscale = int(xscale/2)
     dbf.write(f"POST XSCL {xscale} YSCL {yscale}\n")
 
     cellSize = (2*xscale - 1, 2*yscale - 1)
     
     p = 0
     selected = [0,0]
 
     while True:
         stdscr.erase()
         for y in range(0, (6*yscale) + 1):
             for x in range(0, (16*xscale) + 1):
                 duplet = place_table[selected[p]][p] if type(place_table[selected[p]][p]) is tuple else place_table[selected[p]]
                 if (xscale*(duplet[0]-1)) < x < (xscale*(duplet[0]+1)) and (yscale*(duplet[1]-1)) < y < (yscale*(duplet[1]+1)):
                     stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), ' ', curses.A_REVERSE)
 
                 if y == 0:
                     if x in [0, (12*xscale)]:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_ULCORNER)
                     elif x in [(8*xscale), (16*xscale)]:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_URCORNER)
                     elif x < (12*xscale) and x > (8*xscale):
                         continue
                     elif x % (2*xscale) == 0:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_TTEE)
                     else:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_HLINE)
                 elif y == (6*yscale):
                     if x in [0, (12*xscale)]:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_LLCORNER)
                     elif x in [(8*xscale), (16*xscale)]:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_LRCORNER)
                     elif x < (12*xscale) and x > (8*xscale):
                         continue
                     elif x % (2*xscale) == 0:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_BTEE)
                     else:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_HLINE)
                 elif y % (2*yscale) != 0:
                     if 0 < y < (2*yscale) or  (4*yscale) < y < (6*yscale):
                         if x < (12*xscale) and x > (8*xscale):
                             continue
                         if x in [xscale, 13*xscale] or (y in [yscale, 5*yscale] and (0 < x < 2*xscale or 12*xscale < x < 14*xscale)):
                             stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), 'X')
                     if (x == (7*xscale) and 2*yscale < y < 4*yscale) or (y == 3*yscale and 6*xscale < x < 8*xscale):
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), 'X')
                     if x % (2*xscale) == 0:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_VLINE)
                 elif y in [2*yscale,4*yscale]:
                     if x == 0:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_LTEE)
                     elif x == (16*xscale):
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_RTEE)
                     elif x == (10*xscale):
                         if y == (2*yscale):
                             stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_TTEE)
                         elif y == (4*yscale):
                             stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_BTEE)
                     elif x % (2*xscale) == 0:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_PLUS)
                     else:
                         stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), curses.ACS_HLINE)
 
         for y in range(0, 6*yscale, yscale):
             for x in range(0, 16*xscale, xscale):
                 #if y in [yscale, 3*yscale, 5*yscale]:
                 for stone in moveList:
                     tmp = []
                     if stone.pos in [0,1,2,3,12,13,14] and stone.side == -1:
                         continue
                     if stone.pos not in [0,1,2,3,12,13,14] and stone.side != -1:
                         stone.side = -1
                     if stone.side != -1:
                         tmp = place_table[stone.pos][stone.side]
                     else:
                         tmp = place_table[stone.pos]
                     if x == tmp[0]*xscale and y == tmp[1]*yscale:
                         if cellSize[0] <= 3 or cellSize[1] <= 3:
                             stdscr.addch(int((height/2 - (6*yscale)/2) + y), int((width/2 - (16*xscale)/2) + x), stone.owner)
                         else:
                             smaller = cellSize[0] if cellSize[0] <= cellSize[1] else cellSize[1]
                             for y2 in range(y-int((smaller-1)/2-1), y+int((smaller-1)/2)):
                                 for x2 in range(x-int((smaller-1)/2-1), x+int((smaller-1)/2)):
                                     if x == x2 and y == y2:
                                         stdscr.addch(int((height/2 - (6*yscale)/2) + y2), int((width/2 - (16*xscale)/2) + x2), curses.ACS_DIAMOND)
                                     else:
                                         stdscr.addch(int((height/2 - (6*yscale)/2) + y2), int((width/2 - (16*xscale)/2) + x2), stone.owner, curses.color_pair(stone.pid))
 
         
 
 
         stdscr.refresh()
         c = stdscr.getch()
         if chr(c) == 'q':
             break
         elif c == curses.KEY_RESIZE:
             height, width = stdscr.getmaxyx()
             dbf.write(f"H: {height} W: {width}\n")
 
             xscale = floor((width-1) / 16)
             yscale = floor((height-1) / 6)
             dbf.write(f"XSCL {xscale} YSCL {yscale}\n")
    
             if xscale > 2*yscale:
                 xscale = yscale * 2
             else:
                 xscale -= 1 if xscale % 2 == 1 else 0
                 yscale = int(xscale/2)
             dbf.write(f"POST XSCL {xscale} YSCL {yscale}\n")
             cellSize = (2*xscale - 1, 2*yscale - 1)
         elif c == curses.KEY_UP:
             selected[p] = selected[p]+1 if selected[p] != 13 else 0
         elif c == curses.KEY_DOWN:
             selected[p] = selected[p]-1 if selected[p] != 0 else 13
예제 #53
0
    def __init__(
        self,
        web_port=26000,
        window_height=40,
        window_width=130,
        auto_scroll=True,
        max_log_lines=500,
        wait_on_quit=True,
        min_refresh_rate=1000,
        bytes_to_str=helpers.hex_to_hexstr,
    ):
        """
        :type web_port: int
        :param web_port: Webinterface port. Default 26000

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

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

        :type auto_scroll: bool
        :param auto_scroll: Whether to auto-scroll the cases and crashed windows to always 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_scroll
        self._current_data = None
        self._log_storage = []
        self._fail_storage = []
        self._wait_on_quit = wait_on_quit
        self._quit = False
        self._status = STATUS_RUNNING
        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

        sys.stdout = sys.stderr = self._std_buffer = StringIO()
        atexit.register(self._cleanup)

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

        # Curses color pairs
        curses.init_pair(COLOR_PAIR_WHITE, curses.COLOR_WHITE, -1)
        curses.init_pair(COLOR_PAIR_CYAN, curses.COLOR_CYAN, -1)
        curses.init_pair(COLOR_PAIR_RED, curses.COLOR_RED, -1)
        curses.init_pair(COLOR_PAIR_YELLOW, curses.COLOR_YELLOW, -1)
        curses.init_pair(COLOR_PAIR_GREEN, curses.COLOR_GREEN, -1)
        curses.init_pair(COLOR_PAIR_MAGENTA, curses.COLOR_MAGENTA, -1)
        curses.init_pair(COLOR_PAIR_BLACK, 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)
        self._draw_thread.setDaemon(True)
        current_signal_handler = signal.getsignal(signal.SIGWINCH)
        self._draw_thread.start()
        signal.signal(signal.SIGWINCH, current_signal_handler)
def interactive_cli(stdscr, items, border=0):
    curses.curs_set(0)
    curses.use_default_colors()

    def win_size():
        size = stdscr.getmaxyx()
        return max(1, size[0] - 2 * border), max(1, size[1] - 2 * border)

    def win_draw(win, items, hl=None,
                 item_len_min=10, bar_len_min=10,
                 bar_caps=lambda bar='': ' [ ' + bar + ' ]'):
        win_rows, win_len = win.getmaxyx()
        if win_len <= 1:
            return

        item_len_max = items.max_key_len
        mute_button_len = 2
        bar_len = win_len - item_len_max - mute_button_len - len(bar_caps())
        if bar_len < bar_len_min:
            item_len_max = max(item_len_min,
                               item_len_max + bar_len - bar_len_min)
            bar_len = win_len - item_len_max - mute_button_len - len(bar_caps())
            if bar_len <= 0:
                item_len_max = win_len  # just draw labels
            if item_len_max < item_len_min:
                item_len_max = min(items.max_key_len, win_len)

        win.erase()  # cleanup old entries
        for row, item in enumerate(items):
            if row >= win_rows - 1:
                # Not sure why bottom window row seem to be unuseable
                break

            attrs = curses.A_REVERSE if item == hl else curses.A_NORMAL

            win.addstr(row, 0, item[:item_len_max].encode(optz.encoding), attrs)
            if win_len > item_len_max + mute_button_len:
                if items.get_mute(item):
                    mute_button = " M"
                else:
                    mute_button = " -"
                win.addstr(row, item_len_max, mute_button)

                if bar_len > 0:
                    bar_fill = int(round(items.get_volume(item) * bar_len))
                    bar = bar_caps('#' * bar_fill + '-' * (bar_len - bar_fill))
                    win.addstr(row, item_len_max + mute_button_len, bar)

    win = curses.newwin(*(win_size() + (border, border)))
    win.keypad(True)

    hl = next(iter(items)) if items else ''
    optz.adjust_step /= 100.0

    while True:
        if os.waitpid(child_pid, os.WNOHANG)[0]:
            log.fatal('DBus signal monitor died unexpectedly')
            sys.exit(1)

        while items.updates:
            items.update()
        if not items:
            items.refresh()

        try:
            win_draw(win, items, hl=hl)
        except PAUpdate:
            continue

        if items.updates:
            continue

        try:
            key = win.getch()
        except curses.error:
            continue
        log.debug('Keypress event: %s', key)

        try:
            if key in (curses.KEY_DOWN, ord('j'), ord('n')):
                hl = items.next_key(hl)
            elif key in (curses.KEY_UP, ord('k'), ord('p')):
                hl = items.prev_key(hl)
            elif key in (curses.KEY_LEFT, ord('h'), ord('b')):
                items.set_volume(hl, items.get_volume(hl) - optz.adjust_step)
            elif key in (curses.KEY_RIGHT, ord('l'), ord('f')):
                items.set_volume(hl, items.get_volume(hl) + optz.adjust_step)
            elif key in (ord(' '), ord('m')):
                items.set_mute(hl, not items.get_mute(hl))
            elif key < 255 and key > 0 and chr(key) == 'q':
                exit()
            elif key in (curses.KEY_RESIZE, ord('\f')):
                curses.endwin()
                stdscr.refresh()
                win = curses.newwin(*(win_size() + (border, border)))
                win.keypad(True)
        except PAUpdate:
            continue
예제 #55
0
    def init_colors(self, theme):
        """
        define and set console colors
        :return:
        """
        # use the default colors of the terminal
        curses.use_default_colors()

        id_color_green_on_white = 1
        id_color_black_on_white = 2
        id_color_black_on_green = 3
        id_color_green_on_black = 4
        id_color_cyan_on_white = 5
        id_color_white_on_black = 6
        id_color_white_on_cyan = 7
        id_color_white_on_green = 8
        id_color_cyan = 9
        id_color_green = 10
        id_color_black = 11

        curses.init_pair(id_color_black, curses.COLOR_BLACK, -1)
        self.color_hash_tag_disable = curses.color_pair(
            id_color_black) | curses.A_BOLD
        # set colors
        if theme == ConfigReader.THEME_AZURE:
            curses.init_pair(id_color_cyan, curses.COLOR_CYAN, -1)
            curses.init_pair(id_color_green_on_white, curses.COLOR_GREEN,
                             curses.COLOR_WHITE)
            curses.init_pair(id_color_black_on_white, curses.COLOR_BLACK,
                             curses.COLOR_WHITE)
            curses.init_pair(id_color_white_on_cyan, curses.COLOR_WHITE,
                             curses.COLOR_CYAN)
            curses.init_pair(id_color_cyan_on_white, curses.COLOR_CYAN,
                             curses.COLOR_WHITE)

            self.color_search_input = curses.color_pair(
                id_color_cyan) | curses.A_BOLD
            self.color_cmd_sample = curses.color_pair(id_color_cyan)
            self.color_hash_tag = curses.color_pair(id_color_cyan)
            self.color_tab_no_focus = curses.color_pair(
                id_color_black_on_white)
            self.color_selected_row = curses.color_pair(
                id_color_black_on_white) | curses.A_BOLD
            self.color_selected_row_no_focus = curses.color_pair(
                id_color_white_on_cyan) | curses.A_BOLD
            self.color_search = curses.color_pair(
                id_color_white_on_cyan) | curses.A_BOLD
            self.color_hash_tag_selected = curses.color_pair(
                id_color_cyan_on_white)
            self.color_selector = curses.color_pair(id_color_black_on_white)
            self.color_columns_title = curses.color_pair(
                id_color_white_on_cyan) | curses.A_BOLD
        else:
            curses.init_pair(id_color_green_on_black, curses.COLOR_GREEN,
                             curses.COLOR_BLACK)
            curses.init_pair(id_color_white_on_black, curses.COLOR_WHITE,
                             curses.COLOR_BLACK)
            curses.init_pair(id_color_black_on_white, curses.COLOR_BLACK,
                             curses.COLOR_WHITE)
            curses.init_pair(id_color_black_on_green, curses.COLOR_BLACK,
                             curses.COLOR_GREEN)
            curses.init_pair(id_color_white_on_green, curses.COLOR_WHITE,
                             curses.COLOR_GREEN)
            curses.init_pair(id_color_green, curses.COLOR_GREEN, -1)

            self.color_search_input = curses.color_pair(
                id_color_green) | curses.A_BOLD
            self.color_cmd_sample = curses.color_pair(id_color_green)
            self.color_hash_tag = curses.color_pair(
                id_color_green) | curses.A_BOLD
            self.color_tab_no_focus = curses.color_pair(
                id_color_green_on_black)
            self.color_selected_row = curses.color_pair(
                id_color_white_on_black) | curses.A_BOLD
            self.color_selected_row_no_focus = curses.color_pair(
                id_color_white_on_green) | curses.A_BOLD
            self.color_search = curses.color_pair(
                id_color_white_on_green) | curses.A_BOLD
            self.color_hash_tag_selected = curses.color_pair(
                id_color_green_on_black) | curses.A_BOLD
            self.color_selector = curses.color_pair(id_color_green_on_black)
            self.color_columns_title = curses.color_pair(
                id_color_black_on_green) | curses.A_BOLD
        self.color_tab_focus = self.color_columns_title
예제 #56
0
def main(stdscr: Window) -> None:
    universe = dict[Point, int]()

    curses.use_default_colors()
    curses.curs_set(0)

    stdscr.nodelay(True)

    for i in range(1, 12):
        curses.init_pair(i, curses.COLORS - 2 * 13 + 2 * i, -1)

    with open(Path(__file__).parent / "input.txt") as file:
        for i, line in enumerate(file):
            for j, brightness in enumerate(line.strip()):
                universe[i, j] = int(brightness)
    flashes = 0
    match sys.argv:
        case [_, m]:
            multiplier = float(f"0.{m}")
        case _:
            multiplier = 0.1
    for step in count():
        match stdscr.getch():
            case 113:
                return

        stdscr.addstr(0, 0, f"Flashes: {flashes}")
        stdscr.addstr(1, 0, f"Steps: {step}")
        stdscr.addstr(13, 0, 'Press "q" to quit', curses.A_RIGHT)
        for i in range(11):
            stdscr.addstr(12, i, "██", curses.color_pair(i + 1))
        for i in range(10):
            for j in range(10):
                if universe[i, j] == 0:
                    continue
                if universe[i, j] > 9:
                    stdscr.addstr(i + 2, j * 2, "██", curses.color_pair(11))
                else:
                    stdscr.addstr(
                        i + 2, j * 2, "██", curses.color_pair(universe[i, j] + 1)
                    )

        # zero flashed
        for point in universe:
            if universe[point] > 9:
                flashes += 1
                universe[point] = 0

        for point in universe:
            universe[point] += 1

        flashed = set()
        while True:
            flashing = [
                point
                for point in universe
                if universe[point] > 9 and point not in flashed
            ]
            if not flashing:
                break

            for point in flashing:
                flashed.add(point)
                for n in neighborhood(point):
                    if n not in universe:
                        continue
                    universe[n] += 1

        time.sleep(multiplier)
예제 #57
0
def module_funcs(stdscr):
    "Test module-level functions"

    for func in [curses.baudrate, curses.beep, curses.can_change_color,
                 curses.cbreak, curses.def_prog_mode, curses.doupdate,
                 curses.filter, curses.flash, curses.flushinp,
                 curses.has_colors, curses.has_ic, curses.has_il,
                 curses.isendwin, curses.killchar, curses.longname,
                 curses.nocbreak, curses.noecho, curses.nonl,
                 curses.noqiflush, curses.noraw,
                 curses.reset_prog_mode, curses.termattrs,
                 curses.termname, curses.erasechar, curses.getsyx]:
        func()

    # Functions that actually need arguments
    if curses.tigetstr("cnorm"):
        curses.curs_set(1)
    curses.delay_output(1)
    curses.echo() ; curses.echo(1)

    f = tempfile.TemporaryFile()
    stdscr.putwin(f)
    f.seek(0)
    curses.getwin(f)
    f.close()

    curses.halfdelay(1)
    curses.intrflush(1)
    curses.meta(1)
    curses.napms(100)
    curses.newpad(50,50)
    win = curses.newwin(5,5)
    win = curses.newwin(5,5, 1,1)
    curses.nl() ; curses.nl(1)
    curses.putp('abc')
    curses.qiflush()
    curses.raw() ; curses.raw(1)
    curses.setsyx(5,5)
    curses.tigetflag('hc')
    curses.tigetnum('co')
    curses.tigetstr('cr')
    curses.tparm('cr')
    curses.typeahead(sys.__stdin__.fileno())
    curses.unctrl('a')
    curses.ungetch('a')
    curses.use_env(1)

    # Functions only available on a few platforms
    if curses.has_colors():
        curses.start_color()
        curses.init_pair(2, 1,1)
        curses.color_content(1)
        curses.color_pair(2)
        curses.pair_content(curses.COLOR_PAIRS - 1)
        curses.pair_number(0)

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

    if hasattr(curses, 'keyname'):
        curses.keyname(13)

    if hasattr(curses, 'has_key'):
        curses.has_key(13)

    if hasattr(curses, 'getmouse'):
        curses.mousemask(curses.BUTTON1_PRESSED)
        curses.mouseinterval(10)
        # just verify these don't cause errors
        m = curses.getmouse()
        curses.ungetmouse(*m)
예제 #58
0
파일: app.py 프로젝트: zmapi/tdom
def start_gui():

    # do not print out key presses unless specifically asked to
    curses.noecho()
    # cbreak mode: respond to key presses without pressing enter
    curses.cbreak()
    # activate navigation key shortcuts
    g.screen.keypad(True)
    # no cursor is needed
    curses.curs_set(False)
    # enable support for transparent color (-1)
    curses.use_default_colors()
    # enable colors
    curses.start_color()
    if curses.has_colors():
        if curses.COLORS < 255:
            exit("terminal with 255 color support is required")
    else:
        exit("terminal does not support colors")
    init_colors()

    echo_status("[{}] getting ticker info ...".format(g.args.ticker_id))
    get_ticker_info()
    get_converters(g.ticker_info)
    echo_status("[{}] getting snapshot ...".format(g.args.ticker_id))
    get_snapshot()
    echo_status("[{}] subscribing ...".format(g.args.ticker_id))
    res = subscribe()
    s = "[{}] subscribed".format(g.args.ticker_id)
    if g.args.num_levels < sys.maxsize:
        s += " ({})".format(g.args.num_levels)
    echo_status(s)

    # Threading based design with message passing and ui manipulating event
    # loop running on main thread is not easy to implement here. When terminal
    # gets resized, SIGWINCH is emitted and it's automatically caught by curses
    # library. Curses library emits "KEY_RESIZE" special key stroke to signal
    # the application about this. This signal is only emitted to the main
    # thread and if stdin listening loop (stdscr.getkey) is running on another
    # thread it won't be emitted and curses internal structures won't be
    # updated. This desing decision by curses library makes it hard to
    # implement any threading model without modifying source code of curses
    # library itself on C level. Falling back on polling desing, which seems to
    # be fine for a lightweight application.

    # TODO: adjust polling frequency
    g.screen.nodelay(True)

    while True:

        refreshing = False

        # handle curses events
        key = None
        try:
            key = g.screen.getkey()
        except Exception:
            pass
        if key is not None:
            L.debug("{!r}".format(key))
        if key == "KEY_RESIZE":
            L.debug("handling resize...")
            refreshing = True
        elif key == "KEY_UP":
            g.y_pos -= 1
            refreshing = True
        elif key == "KEY_DOWN":
            g.y_pos += 1
            refreshing = True
        elif key == " ":
            g.y_pos = 0
            refreshing = True
        elif key == "KEY_PPAGE":
            y_max, _ = g.screen.getmaxyx()
            g.y_pos -= y_max // 2
            refreshing = True
        elif key == "KEY_NPAGE":
            y_max, _ = g.screen.getmaxyx()
            g.y_pos += y_max // 2
            refreshing = True

        # handle zmq messages
        try:
            msg_parts = g.sock_sub.recv_multipart(zmq.NOBLOCK)
        except zmq.error.Again:
            pass
        else:
            topic, msg = msg_parts
            try:
                msg = json.loads(msg.decode())
                if topic[-1] == 1:
                    handle_depth_update(msg)
                    refreshing = True
                elif topic[-1] == 2:
                    handle_trade(msg)
                    refreshing = True
                elif topic[-1] == 3:
                    handle_quote(msg)
            except Exception:
                L.exception("exception on sub_listener:\n", exc_info=True)

        if refreshing:
            refresh_screen()
예제 #59
0
def main(stds, jisho):
    #stds = curses.initscr();
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, -1, curses.COLOR_RED)
    curses.init_pair(2, -1, 234)
    curses.init_pair(3, -1, -1)
    curses.init_pair(4, 10, curses.COLOR_RED)
    curses.init_pair(5, 10, 234)
    curses.init_pair(6, 10, -1)
    curses.init_pair(7, 233, 3)
    #current tag

    curses.init_pair(20, -1, 23)
    #35 #tagged entry
    curses.init_pair(21, 10, 23)
    #highlight query in tagged entry

    for i in range(8, 16):
        curses.init_pair(i, i, -1)

    curses.noecho()
    curses.cbreak()
    stds.keypad(True)

    layout = Layout(stds, jisho)

    layout.set(layout.QUERY)
    focus = stds

    while True:
        try:
            c = focus.getch()
            if c == curses.KEY_RESIZE:
                (h, w) = stds.getmaxyx()
                stds.clear()
                stds.refresh()

                layout.wsbox.resize(1, w - 4)
                layout.wrbox.resize(h - 3, w - 4)
                layout.webox.resize(h - 3, w - 4)
                layout.wtbox.resize(h - 3, w - 4)

                layout.ebox.resize()

                layout.set()

            elif focus is layout.sbox.win:
                if c == 10:
                    query = layout.sbox.gather()
                    if len(query) > 5 and query[0:5] == ":tag ":
                        layout.tbox.tagsel = query[5:]
                    focus = stds
                elif c in (10, 27):
                    focus = stds
                elif layout.sbox.input(c):
                    query = layout.sbox.gather()

                    results = []
                    dup = set()

                    if '*' in query or '?' in query:
                        m = fnmatch.filter(jisho.jindex, query)
                        for i in m:
                            for j in jisho.jindex[i]:
                                if j in dup:
                                    continue
                                dup.add(j)

                                results.append(jisho.jmdict[j])
                    else:
                        m = difflib.get_close_matches(query,
                         [x for x in jisho.rindex \
                          if query in x and (len(query) > 1 or len(x) < 3) \
                          and (len(query) > 3 or len(x) < 6)],12)
                        for i in m:
                            for j in jisho.rindex[i]:
                                if j in dup:
                                    continue
                                dup.add(j)

                                results.append(jisho.jmdict[j])

                    layout.rbox.clear()
                    layout.rbox.set(results, query, 0)
                    layout.rbox.render()

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

            elif focus is layout.ebox.win:
                if c in (ord('h'), curses.KEY_LEFT, 27):
                    stds.erase()

                    focus = stds
                    layout.flashmode = False

                    layout.rbox.sel = layout.ebox.sel
                    layout.set(layout.QUERY)

                elif c in (ord('l'), curses.KEY_RIGHT):
                    layout.ebox.render(False)

                elif c in (ord('t'), ord(' ')):
                    entry = layout.ebox.gather()
                    if entry is not None:
                        try:
                            td = jisho.tagdict[layout.tbox.tagsel]
                            try:
                                td.remove(entry["ent_seq"])
                            except ValueError:
                                td.append(entry["ent_seq"])
                        except KeyError:
                            jisho.tagdict[layout.tbox.tagsel] = [
                                entry["ent_seq"]
                            ]
                    layout.ebox.render(layout.flashmode)

                elif c == ord('T'):
                    entry = layout.ebox.gather()
                    if entry is not None:
                        jisho.tagdict[jisho.tagdef].append(entry["ent_seq"])

                elif c == ord('X'):
                    entry = layout.ebox.gather()
                    if entry is not None:
                        for te in jisho.tagdict:
                            if entry["ent_seq"] in jisho.tagdict[te]:
                                jisho.tagdict[te].remove(entry["ent_seq"])
                    layout.ebox.render(layout.flashmode)

                else:
                    layout.ebox.input(c)
                    layout.ebox.render(layout.flashmode)

            elif focus is layout.tbox.win:
                if c in (ord('h'), ord('i'), curses.KEY_LEFT, 27):
                    stds.erase()

                    if c == ord('i'):
                        layout.sbox.clear()
                        focus = layout.sbox.win
                    else:
                        focus = stds

                    #layout.rbox.sel = layout.ebox.sel;
                    layout.set(layout.QUERY)

                elif c in (ord('l'), curses.KEY_RIGHT):
                    stds.erase()

                    focus = stds

                    results = []
                    for te in jisho.tagdict[layout.tbox.gather()]:
                        for de in jisho.jmdict:
                            if te == de["ent_seq"]:
                                results.append(de)
                                break

                    layout.rbox.clear()
                    layout.rbox.set(results, "", 0)
                    layout.set(layout.QUERY)

                else:
                    layout.tbox.input(c)
                    layout.tbox.render()

            else:  #focus on stds
                if c == ord('E'):
                    results = []
                    tg = jisho.tagdict.get(layout.tbox.tagsel)
                    if tg is not None:
                        for te in tg:
                            for de in jisho.jmdict:
                                if te == de["ent_seq"]:
                                    results.append(de)
                                    break
                        layout.rbox.set(results, "", 0)
                        layout.rbox.render()

                elif c == ord('e'):
                    focus = layout.tbox.win

                    layout.tbox.set()
                    layout.set(layout.TAGBR)

                elif c == ord(
                        'r'):  #flashcards from the currently visible list
                    if len(layout.rbox.results) > 0:
                        flashcards = layout.rbox.results
                        shuffle(flashcards)
                        stds.erase()

                        focus = layout.ebox.win
                        layout.flashmode = True

                        layout.ebox.set(flashcards, 0)
                        layout.set(layout.ENTRY)
                        #layout.ebox.render(layout.flashmode);

                elif c in (ord('t'), ord(' ')):
                    entry = layout.rbox.gather()
                    if entry is not None:
                        try:
                            td = jisho.tagdict[layout.tbox.tagsel]
                            try:
                                td.remove(entry["ent_seq"])
                            except ValueError:
                                td.append(entry["ent_seq"])
                        except KeyError:
                            jisho.tagdict[layout.tbox.tagsel] = [
                                entry["ent_seq"]
                            ]
                    layout.rbox.render()

                elif c == ord('T'):
                    entry = layout.rbox.gather()
                    if entry is not None:
                        jisho.tagdict[jisho.tagdef].append(entry["ent_seq"])
                    layout.rbox.render()

                elif c == ord('X'):
                    entry = layout.rbox.gather()
                    if entry is not None:
                        for te in jisho.tagdict:
                            if entry["ent_seq"] in jisho.tagdict[te]:
                                jisho.tagdict[te].remove(entry["ent_seq"])
                    layout.rbox.render()

                elif c == ord('i'):
                    layout.sbox.clear()
                    focus = layout.sbox.win

                elif c == ord(':'):
                    layout.sbox.clear()
                    focus = layout.sbox.win
                    layout.sbox.input(c)

                elif c in (ord('l'), curses.KEY_RIGHT):
                    entry = layout.rbox.gather()
                    if entry is not None:
                        stds.erase()

                        focus = layout.ebox.win

                        layout.ebox.set(layout.rbox.results, layout.rbox.sel)
                        layout.set(layout.ENTRY)

                else:
                    layout.rbox.input(c)
                    layout.rbox.render()
        except KeyboardInterrupt:
            focus = stds

    curses.nocbreak()
    stds.keypad(False)
    curses.echo()
    curses.endwin()
예제 #60
0
def main(screen):
    screen = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    screen.keypad(True)

    # Set variables and create the calendar
    max_x = curses.COLS - 1
    max_y = curses.LINES - 1
    tmp_cursor_month = 0  # This value stores the month when navigating up to the year selector.
    cur_time = datetime.datetime.now()  # type: datetime
    key_press = ""
    cursor_position = [-2, -2,
                       -2]  # Initializes cursor_position at the year selector
    tmp_cursor_position = cursor_position  # Initializes a temporary cursor position variable for error recovery
    cal = calendar.Calendar(0)
    cal_year = cur_time.year
    year = cal.yeardayscalendar(cal_year, 12)
    cal_month = [
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"
    ]  # List of names to draw on for Calendar months
    days_of_week = " Mo Tu We Th Fr Sa Su"  # String to be printed for each calendar
    conf_directory = os.environ['HOME'] + "/.damnJournal/"  # type: object
    curses.init_pair(2, 0, 7)
    curses.init_pair(3, 6, 0)

    while key_press != "q" and key_press != "Q":

        # Check for Terminal resizing
        if curses.is_term_resized(max_y, max_x):
            max_x = curses.COLS - 1
            max_y = curses.LINES - 1

        if key_press == "y" or key_press == "Y":  # Gives option to return to year selector in navigation
            cursor_position = [-2, -2, -2]
            tmp_cursor_position = [-2, -2, -2]

        if (key_press == "e" or key_press
                == "E") and cursor_position[1] >= 0:  # Manages Edit function
            day = str(year[0][cursor_position[0]][cursor_position[1]][
                cursor_position[2]])
            filename = "{}{:0>4}{:0>2}{:0>2}.dat".format(
                conf_directory, str(cal_year), str(cursor_position[0] + 1),
                str(day))
            tmpfile = '/tmp/dj_' + tmp_generate()
            if os.path.isfile(filename):
                openfile = open(filename, 'r')
                contents = decrypt(
                    password, openfile.read())  # Get contents of current file
                openfile.close()
                openfile = open(tmpfile, 'w')
                openfile.write(contents)
                openfile.close()
                os.system("editor " + tmpfile)
                openfile = open(tmpfile, 'r')
                contents = encrypt(password, openfile.read())
                openfile.close()
                openfile = open(filename, 'w')
                openfile.write(contents)
                openfile.close()
                os.system("rm -f {}".format(tmpfile))
            else:
                openfile = open(tmpfile, 'w')
                openfile.write("")
                openfile.close()
                os.system("editor " + tmpfile)
                openfile = open(tmpfile, 'r')
                contents = encrypt(password, openfile.read())
                openfile.close()
                openfile = open(filename, 'w')
                openfile.write(contents)
                openfile.close()
                os.system("rm -f {}".format(tmpfile))

        if (key_press == "r" or key_press
                == "R") and cursor_position[1] >= 0:  # Manages Edit function
            day = str(year[0][cursor_position[0]][cursor_position[1]][
                cursor_position[2]])
            filename = "{}{:0>4}{:0>2}{:0>2}.dat".format(
                conf_directory, str(cal_year), str(cursor_position[0] + 1),
                str(day))
            if os.path.isfile(filename):
                os.system("mv -f {} {}.old".format(filename, filename))

        if (key_press == "u" or key_press
                == "U") and cursor_position[1] >= 0:  # Manages Edit function
            day = str(year[0][cursor_position[0]][cursor_position[1]][
                cursor_position[2]])
            filename = "{}{:0>4}{:0>2}{:0>2}.dat".format(
                conf_directory, str(cal_year), str(cursor_position[0] + 1),
                str(day))
            if os.path.isfile("{}.old".format(
                    filename)):  # Verify if file to undelete exists
                if os.path.isfile(
                        filename):  # Check if new content has been added
                    os.system("cat {}.old >> {}".format(
                        filename, filename))  # Append old file to new file
                    os.system("rm -f {}.old".format(filename))
                else:
                    os.system("mv -f {}.old {}".format(filename, filename))

        if "kLFT" in key_press and cursor_position[
                0] == -2:  # Handle Control and Alt Left Year Selector
            if key_press[4] == "5" and cal_year > 10:
                cal_year -= 10
            if key_press[4] == "5" and cal_year < 10:
                cal_year = 1
            if key_press[4] == "7" and cal_year > 100:
                cal_year -= 100
            if key_press[4] == "7" and cal_year < 100:
                cal_year = 1

        if key_press == "KEY_RIGHT" or key_press == "C":  # Manages the Right Arrow key press
            if cursor_position[
                    1] == -2 and cal_year < 9999:  # Selector is on Year
                cal_year += 1
                year = cal.yeardayscalendar(cal_year, 12)
            elif cursor_position[1] == -1 and cursor_position[
                    0] < 11:  # Selector is on Month
                cursor_position[0] += 1
            elif -1 <= cursor_position[0] and cursor_position[
                    2] < 6:  # Selector is in Calendar navigation
                tmp_cursor_position = [
                    cursor_position[0], cursor_position[1], cursor_position[2]
                ]
                cursor_position[2] += 1

        if key_press == "KEY_LEFT" or key_press == "D":  # Manages the Left Arrow key press
            if cursor_position[1] == -2 and cal_year > 1:  # Selector is on Year
                cal_year -= 1
                year = cal.yeardayscalendar(cal_year, 12)
            elif cursor_position[1] == -1 and cursor_position[
                    0] > 0:  # Selector is on Month
                cursor_position[0] -= 1
            elif cursor_position[0] >= 0 and cursor_position[
                    2] > 0:  # Selector is in Calendar Navigation
                tmp_cursor_position = [
                    cursor_position[0], cursor_position[1], cursor_position[2]
                ]
                cursor_position[2] -= 1

        if key_press == "KEY_DOWN" or key_press == "B":  # Manages the Down Arrow key press
            if cursor_position[0] == -2:
                if tmp_cursor_month != 0:
                    cursor_position = [tmp_cursor_month, -1, -1]
                else:
                    cursor_position = [0, -1, -1]
            elif cursor_position[1] == -1:
                if cursor_position[0] > 0:
                    cursor_position[1] = 0
                    cursor_position[2] = next(
                        (i
                         for i, x in enumerate(year[0][cursor_position[0]][0])
                         if x), None)
                else:
                    cursor_position[0] = 0
                    cursor_position[1] = 0
                    cursor_position[2] = next(
                        (i
                         for i, x in enumerate(year[0][cursor_position[0]][0])
                         if x), None)

            elif not (not (cursor_position[0] > -1) or not (
                    -1 < cursor_position[1] <=
                (len(year[0][cursor_position[0]][cursor_position[1]]) + 1))):
                tmp_cursor_position = [
                    cursor_position[0], cursor_position[1], cursor_position[2]
                ]
                try:
                    if year[0][cursor_position[0]][cursor_position[1] +
                                                   1][cursor_position[2]] == 0:
                        b = cursor_position[1] + 1
                        for i, item in enumerate(
                                year[0][cursor_position[0]][b]):
                            if item != 0:
                                cursor_position[2] = i
                        cursor_position[1] += 1
                    else:
                        cursor_position[1] += 1
                except:  # If anything goes awry, return to last known good cursor location
                    cursor_position = tmp_cursor_position

        if key_press == "KEY_UP" or key_press == "A":  # Manages the Up Arrow key press
            if cursor_position[0] > -1 and cursor_position[1] == 0:
                cursor_position[1] = -1
                cursor_position[2] = -1
            elif cursor_position[1] == -1:
                tmp_cursor_month = cursor_position[0]
                cursor_position = [-2, -2, -2]
            elif cursor_position[0] > -1 and cursor_position[1] >= 0:
                tmp_cursor_position = [
                    cursor_position[0], cursor_position[1], cursor_position[2]
                ]
                b = cursor_position[1] - 1
                if year[0][cursor_position[0]][b][cursor_position[2]] == 0:
                    cursor_position[1] -= 1
                    cursor_position[2] = next(
                        (i
                         for i, x in enumerate(year[0][cursor_position[0]][b])
                         if x), None)
                else:
                    cursor_position[1] -= 1

        # Once key_press is processed, make one last test of cursor position to ensure there is no Index Error
        if cursor_position[1] > -1:
            try:
                test = year[0][cursor_position[0]][cursor_position[1]][
                    cursor_position[2]]
            except IndexError:
                cursor_position = tmp_cursor_position

        # One last check to ensure the cursor isn't on a zero-day.
        current_day = year[0][cursor_position[0]][cursor_position[1]][
            cursor_position[2]]
        if cursor_position[1] > -1 and current_day == 0:
            cursor_position = tmp_cursor_position

        # Clear the screen, and reset the values back to base for drawing text and shapes.
        screen.clear()

        uy = 3
        ux = 1
        counter = 1

        # Programmatically print the month, days of week, and divider
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
        for i in range(0, len(cal_month)):
            weeks = cal.monthdayscalendar(cal_year, i + 1)
            if cursor_position[0] == i and cursor_position[1] == -1:
                screen.insstr(uy, ux, "{:^21s}".format(cal_month[i]),
                              curses.A_REVERSE)
            else:
                screen.insstr(uy, ux, "{:^21s}".format(cal_month[i]))
            screen.insstr(uy + 1, ux, "{:^21s}".format(days_of_week))
            screen.insstr(uy + 2, ux, " {:~>20s}".format(""))
            # We need to convert the week to a string
            for j in range(0, len(weeks)):
                for k in range(0, len(weeks[j])):

                    if weeks[j][k] == 0 and (cursor_position[0] == i
                                             and cursor_position[1] == j
                                             and cursor_position[2] == k):
                        screen.addstr(uy + 3 + j, ux + (k * 3),
                                      " {:2}".format(" "), curses.A_REVERSE)

                    elif weeks[j][k] == 0 and (cursor_position[0] != i
                                               or cursor_position[1] != j
                                               or cursor_position[2] != k):
                        screen.addstr(uy + 3 + j, ux + (k * 3),
                                      " {:2}".format(" "))

                    elif weeks[j][k] != 0 and (cursor_position[0] == i
                                               and cursor_position[1] == j
                                               and cursor_position[2] == k):
                        filename = "{}{:0>4}{:0>2}{:0>2}.dat".format(
                            conf_directory, str(cal_year), str(i + 1),
                            str(weeks[j][k]))
                        if os.path.isfile(filename):
                            screen.addstr(uy + 3 + j, ux + (k * 3),
                                          " {:0>2}".format(str(weeks[j][k])),
                                          curses.color_pair(1))
                        else:
                            screen.addstr(uy + 3 + j, ux + (k * 3),
                                          " {:0>2}".format(str(weeks[j][k])),
                                          curses.color_pair(2))

                    elif weeks[j][k] != 0 and (cursor_position[0] != i
                                               or cursor_position[1] != j
                                               or cursor_position[2] != k):
                        filename = "{}{:0>4}{:0>2}{:0>2}.dat".format(
                            conf_directory, str(cal_year), str(i + 1),
                            str(weeks[j][k]))
                        if os.path.isfile(filename):
                            screen.addstr(uy + 3 + j, ux + (k * 3),
                                          " {:0>2}".format(str(weeks[j][k])),
                                          curses.color_pair(3))
                        else:
                            screen.addstr(uy + 3 + j, ux + (k * 3),
                                          " {:0>2}".format(str(weeks[j][k])))

            # Increment the X position of the written text, then if the counter has reached 4, move down to next Y.
            ux += 24
            if counter == 4:
                ux = 1
                uy += 10
                counter = 1
            else:
                counter += 1

        # Draw Rectangles with 3 lines for the header, 6 lines for the body, 20 spaces wide programmatically
        # Reset the positioning variables
        uy = 2
        ux = 0
        ly = 12
        lx = 23

        for i in range(0, 3):  # Rows
            for j in range(0, 4):  # Columns. 4 rows of 3
                rectangle(screen, uy, ux, ly, lx)
                # Increment x to draw the next column
                ux += 24
                lx += 24
            # Increment y to draw on the next row
            uy += 10
            ux = 0
            ly += 10
            lx = 23

        # Draw the Rectangle and Text for the Year Selector
        rectangle(screen, 0, 0, 2, 95)
        if cursor_position[0] == -2:
            screen.addstr(1, 1,
                          "{:^94s}".format("<    " + str(cal_year) + "    >"),
                          curses.A_REVERSE)
        else:
            screen.addstr(1, 1,
                          "{:^94s}".format("<    " + str(cal_year) + "    >"))

        if cursor_position[1] > -1:
            rectangle(screen, 32, 0, 34, 95)
            current_day = year[0][cursor_position[0]][cursor_position[1]][
                cursor_position[2]]
            filename = "{}{:0>4}{:0>2}{:0>2}.dat".format(
                conf_directory, str(cal_year), str(cursor_position[0] + 1),
                str(current_day))
            datestamp = cal_month[cursor_position[0]] + " " + str(
                current_day) + ", " + str(cal_year)
            if os.path.isfile(filename):
                screen.addstr(33, 1, "{:^94s}".format(datestamp),
                              curses.color_pair(3))
                rectangle(screen, 34, 0, max_y, 95)
                openfile = open(filename, 'r')
                contents = textwrap.wrap(decrypt(password, openfile.read()),
                                         width=85,
                                         replace_whitespace=False)
                formatted_contents = []
                for i in range(0, len(contents)):
                    formatted_contents = formatted_contents + str.splitlines(
                        contents[i])
                # textbox = [word for line in contents for word in line.split()]
                wordwrap = 1
                line = 35
                col = 3
                #
                # for i in range(0, len(textbox)):
                #     wordwrap += len(textbox[i]) + 1
                #     if wordwrap > 85:
                #         line += 1
                #         wordwrap = 0
                #         col = 3
                #     if line < max_y:
                #         screen.addstr(line, col, str(textbox[i]))
                #         col += len(textbox[i]) + 1
                for i in range(0, len(formatted_contents)):
                    if i < 20:
                        screen.addstr(i + 36, 3, formatted_contents[i])
            else:
                screen.addstr(33, 1, "{:^94s}".format(datestamp))

        # Calendar draw is done, refresh, get a key press, and get out
        screen.refresh()
        key_press = screen.getkey()
    screen.clear()