Beispiel #1
1
def draw_input_window(state, window, rpc_queue):
    color = curses.color_pair(1)
    if 'testnet' in state:
        if state['testnet']: color = curses.color_pair(2)

    window.clear()
    window.addstr(0, 1, g.rpc_deamon + "-ncurses " + g.version + " [transaction input mode]", color + curses.A_BOLD)
    window.addstr(1, 1, "please enter txid", curses.A_BOLD)
    window.refresh()

    entered_txid = getstr.getstr(67, 3, 1) # w, y, x

    if len(entered_txid) == 64: # TODO: better checking for valid txid here
        s = {'txid': entered_txid}
        rpc_queue.put(s)

        window.addstr(5, 1, "waiting for transaction (will stall here if not found)", color + curses.A_BOLD)
        window.refresh()
        state['mode'] = 'tx'

    else:
        window.addstr(5, 1, "not a valid txid", color + curses.A_BOLD)
        window.refresh()

        time.sleep(0.5)

        window.clear()
        window.refresh()
        state['mode'] = "monitor"
Beispiel #2
0
def draw_outputs(state):
    window_height = (state['y'] - 4) / 2
    win_outputs = curses.newwin(window_height, 75, 3+window_height, 0)
    if state['tx']['mode'] == 'outputs':
        win_outputs.addstr(0, 1, "outputs:                                             (UP/DOWN: scroll)", curses.A_BOLD + curses.color_pair(3))
    else:
        win_outputs.addstr(0, 1, "outputs:                                              (TAB: switch to)", curses.A_BOLD + curses.color_pair(5))

    offset = state['tx']['out_offset']

    for index in xrange(offset, offset+window_height-1):
        if index < len(state['tx']['vout_string']):
            condition = (index == offset+window_height-2) and (index+1 < len(state['tx']['vout_string']))
            condition = condition or ( (index == offset) and (index > 0) )
            if condition:
                win_outputs.addstr(index+1-offset, 1, "... ")
            else:
                string = state['tx']['vout_string'][index]
                if '[UNSPENT]' in string:
                    color = curses.color_pair(1)
                elif '[SPENT]' in string or '[UNCONFIRMED SPEND]' in string:
                    color = curses.color_pair(3)
                else:
                    color = 0
                win_outputs.addstr(index+1-offset, 1, string, color)
    win_outputs.refresh()
Beispiel #3
0
    def dir_list(self, path="/usr/share/snmp/mibs/"):
        self.window.clear()
        self.window.move(0,0)
        max_y, max_x = self.window.getmaxyx()
        beg_y, beg_x = self.window.getbegyx()
        cursor_y, cursor_x = self.window.getyx()

        #first output the [..] for parent dir
        self.window.addstr("../")
        cursor_y = cursor_y + 1
        self.window.move(cursor_y, 0)

        for dirname, dirnames, filenames in os.walk(path):

            for subdirname in dirnames:
                self.window.attron(curses.color_pair(5))
                self.window.addstr(subdirname[:25] + "/")
                self.window.attroff(curses.color_pair(5))
                cursor_y = cursor_y + 1
                self.window.move(cursor_y, 0)
            for file in filenames:
                if (cursor_y + 1 < max_y):
                    self.window.addstr(file)
                    cursor_y = cursor_y + 1
                    self.window.move(cursor_y, 0)

        self.window.move(0,0)
        self.window.chgat(curses.A_REVERSE)
        curses.curs_set(0)
Beispiel #4
0
 def start_combat(self, unit):
     attacker = unit
     self.enemy = attacker
     status = self.var_handler.get('status_handler')
     io = self.var_handler.get('io_handler')
     command_processor = self.var_handler.get('command_processor')
     player = self.var_handler.get('player')
     hud = self.var_handler.get('hud_handler')
     self.combat = True
     io.output("You enter combat with a {0}".format(attacker.display_name), curses.color_pair(2))
     status.end_sequence()
     status.output("You are attacked by: {0}".format(attacker.display_name))
     hud.text_update()
     while self.combat:
         curses.curs_set(1)
         input = io.get_input(">>>>>>>:", curses.color_pair(2))
         if input.split(" ")[0] in self.commands:
             if "attack" in input:
                 output = self.attack(player, attacker)
             elif input == "run":
                 output = self.run(attacker)
             elif input.split(" ")[0] == "cast":
                 output = self.cast(input.split(" ")[1])
             else:
                 output = command_processor.receive_command(input)
             if attacker.state == "dead":
                 self.combat = False
                 self.enemy = None
                 output = (output[0] + "\nYou kill the {0}".format(attacker.display_name), output[1])
         else:
             output = ("You can't do that in combat", curses.color_pair(2))
         io.output(output[0], output[1])
         hud.text_update()
     status.start_sequence()
Beispiel #5
0
        def update_patch(target):
            target.erase()
            color = config.COLOR_FOCUS
            if target.enabled and target.current_task > -1:
                if target.selected:
                    target.addstr(0,0,"\u25C0", curses.color_pair(color))
                else:
                    target.addstr(0,0,"\u25C0")
            else:
                if target.enabled and target.selected:
                    target.addstr(0,0,"\u25C1", curses.color_pair(color))
                else:
                    target.addstr(0,0,"\u25C1")

            if target.enabled and target.current_task+1 < len(target.task_list):
                if target.selected:
                    target.addstr(target.size[0]-3,0,"\u25B6", curses.color_pair(color))
                else:
                    target.addstr(target.size[0]-3,0,"\u25B6")
            else:
                if target.enabled and target.selected:
                    target.addstr(target.size[0]-3,0,"\u25B7", curses.color_pair(color))
                else:
                    target.addstr(target.size[0]-3,0,"\u25B7")

            if target.current_task >= 0:
                desc = globals.database.tasks[target.get_task()].desc
                target.addstr(3,0,desc)
Beispiel #6
0
 def attack(self, player, enemy):
     player_accuracy = (ceil(player.attack_current / 2.0) + player.proficiency_current) - (ceil(enemy.defense_current / 2.0) + enemy.proficiency_current)
     if player_accuracy < -10:
         player_accuracy = -10
     elif player_accuracy > 10:
         player_accuracy = 10
     player_accuracy = int(player_accuracy * 5) + 85 + randint(0, 5)
     enemy_accuracy  = (ceil(enemy.attack_current / 2.0) + enemy.proficiency_current) - (ceil(player.defense_current / 2.0) + player.proficiency_current)
     if enemy_accuracy < -10:
         enemy_accuracy = -10
     elif enemy_accuracy > 10:
         enemy_accuracy = 10
     enemy_accuracy = int(enemy_accuracy * 5) + 85 + randint(0, 5)
     player_damage = 0
     enemy_damage = 0
     state = "miss"
     if randint(0, 100) <= player_accuracy:
         player_damage = player.attack_current - int(enemy.defense_current * 0.65)
         if player_damage < 0:
             player_damage = 0
         state = enemy.take_damage(player_damage)
     if state == "alive" or state == "miss":
         if randint(0, 100) <= enemy_accuracy:
             enemy_damage = enemy.attack_current - int(player.defense_current * 0.65)
             if enemy_damage < 0:
                 enemy_damage = 0
             player.take_damage(enemy_damage)
         return ("You attack, dealing {0} damage and taking {1} damage".format(player_damage, enemy_damage), curses.color_pair(2))
     elif state == "miss":
         return ("You miss and take {0}".format(enemy_damage), curses.color_pair(2))
     elif state == "dead":
         return ("You attack, dealing {0} damage".format(player_damage), curses.color_pair(2))
     else:
         raise ValueError("Unit is not alive or dead")
Beispiel #7
0
    def print_line(self, w, i):
        num_line = self.win_y + i
        is_current_line = self.cursor_y == i
        x = 0
        force_exit = False

        for (string, col, is_bold) in self.token_lines[num_line]:
            if x + len(string) >= w:
                string = string[:w-x-1]
                force_exit = True
            
            c = color_pair(col)

            if is_current_line:
                c |= A_UNDERLINE

            if is_bold:
                c |= curses.A_BOLD

            self.screen.addstr(i, x, string, c)

            x += len(string)
            if force_exit:
                break

        if is_current_line and not force_exit:
            n = w - x - 1
            self.screen.addstr(i, x, " " * n, color_pair(0) | A_UNDERLINE)
            x += n

        self.highlight_search(i, w)
        self.screen.move(i, x)
Beispiel #8
0
    def _add_video_item(self, y, x, w, item):
        # Bail if we have _no_ horizontal space
        if w <= 0:
            return

        title = item['title']
        uploader = item['uploader']

        likes = int(item['likeCount']) if 'likeCount' in item else 0
        ratings = int(item['ratingCount']) if 'ratingCount' in item else 0
        comments = int(item['commentCount']) if 'commentCount' in item else 0
        views = int(item['viewCount']) if 'viewCount' in item else 0
        favorites = int(item['favoriteCount']) if 'favoriteCount' in item else 0

        # Show the title and uploader, prioritising the title
        if len(uploader) > w:
            self._main_win.addstr(y,x,truncate(title, w).encode(self._code), self._title_attr)
        else:
            self._main_win.addstr(y,x,truncate(title, w-len(uploader)).encode(self._code), self._title_attr)
            self._main_win.addstr(y,x+w-len(uploader), uploader.encode(self._code), self._uploader_attr)

        desc = item['description']
        if desc is None or len(desc.strip()) == 0:
            desc = 'No description'
        desc = re.sub(r'[\n\r]', r' ', desc)
        self._main_win.addstr(y+1,x,truncate(desc, w).encode(self._code), curses.color_pair(2))
        self._add_table_row([
                ('d', duration(item['duration'])),
                ('v', number(views)),
                ('c', number(comments)),
                ('l/d', '%s/%s' % (number(likes), number(ratings - likes)) ),
                ('f', number(favorites)),
            ], y+2, x, w, curses.color_pair(3) | curses.A_DIM, max_width=22)
Beispiel #9
0
 def draw_window(self):
     "Draw window."
     # Cusor of movies to display (first/last)
     first = self.cursor['first']
     last = self.cursor['first'] + self.cursor['show']
     lst_movies = self.lst_movies[first:last]
     # Title of window
     options = " - " + K_PLAY + ":Play " + K_SCAN + ":Refresh "
     options += K_PREV + ":Up " + K_NEXT + ":Down " + K_PPAG 
     options += ":PUp " + K_NPAG + ":PDown " + K_FIND + ":Find "
     options += K_QUIT + ":Quit"
     title = "PiMP V" + str(VERSION) + options
     self.draw_line_of_text(0, title, curses.color_pair(4))
     # List of movies
     self.clear_list_widget(1, self.H-2, self.W-1)
     i = 1
     for movie in lst_movies:
         if movie == self.get_current_movie():
             self.draw_line_of_text(i, "> "+movie, curses.color_pair(2))
         else:
             self.draw_line_of_text(i, "  "+movie)
         i += 1
     # Status
     self.draw_status(self.status)
     self.stdscr.refresh()
Beispiel #10
0
    def display_info(self, story):
        when = nice_date(datetime.datetime.fromtimestamp(story.unix_time), datetime.datetime.now())
        self.interface.body_win.addstr("    ")
        self.interface.body_win.addstr("points: ")
        if story.score == 1:
            points = "1"
        elif story.score > 1:
            points = "%d" % story.score
        else:
            points = "-"
        self.interface.body_win.addstr(points.ljust(5), curses.color_pair(2) | curses.A_BOLD)

        self.interface.body_win.addstr("comments: ")
        if story.comments == 1:
            comments = "1"
        elif story.comments >= 0:
            comments = "%d" % story.comments
        else:
            comments = '-'
        self.interface.body_win.addstr(comments.ljust(5), curses.color_pair(2) | curses.A_BOLD)
            
        self.interface.body_win.addstr("posted: ")
        self.interface.body_win.addstr(when.ljust(17), curses.color_pair(2) | curses.A_BOLD)

        self.interface.body_win.addstr("user: "******"\n")
Beispiel #11
0
def draw_window(state, window):
    window.clear()
    window.refresh()
    win_header = curses.newwin(5, 75, 0, 0)

    if 'browse_height' in state['blocks']:
        height = str(state['blocks']['browse_height'])
        if height in state['blocks']:
            blockdata = state['blocks'][height]

            win_header.addstr(0, 1, "height: " + height.zfill(6) + "    (J/K: browse, HOME/END: quicker, L: latest, G: seek)", curses.A_BOLD)
            win_header.addstr(1, 1, "hash: " + blockdata['hash'], curses.A_BOLD)
            win_header.addstr(2, 1, "root: " + blockdata['merkleroot'], curses.A_BOLD)
            win_header.addstr(3, 1, str(blockdata['size']) + " bytes (" + str(blockdata['size']/1024) + " KB)       ", curses.A_BOLD)
            win_header.addstr(3, 26, "diff: " + "{:,d}".format(int(blockdata['difficulty'])), curses.A_BOLD)
            win_header.addstr(3, 52, time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(blockdata['time'])), curses.A_BOLD)
            win_header.addstr(4, 51, ("v" + str(blockdata['version'])).rjust(20), curses.A_BOLD)

            draw_transactions(state)
            state['blocks']['loaded'] = 1

        else:
            win_header.addstr(0, 1, "no block information loaded", curses.A_BOLD + curses.color_pair(3))
            win_header.addstr(1, 1, "press 'G' to enter a block hash, height, or timestamp", curses.A_BOLD)

    else:
        win_header.addstr(0, 1, "no block information loaded", curses.A_BOLD + curses.color_pair(3))
        win_header.addstr(1, 1, "press 'G' to enter a block hash, height, or timestamp", curses.A_BOLD)

    win_header.refresh()
    footer.draw_window(state)
Beispiel #12
0
    def _prepare_alert_description(self, alert):
        attrs = curses.color_pair(0)

        if alert['type'] == 'WEATHERHAZARD':
            if len(alert['subtype']) > 0:
                if alert['subtype'] == 'HAZARD_ON_ROAD_OBJECT':
                    typ = 'Object on road'
                elif alert['subtype'] == \
                        'HAZARD_ON_ROAD_CONSTRUCTION':
                    typ = 'Construction on road'
                elif alert['subtype'] == 'HAZARD_ON_ROAD_POT_HOLE':
                    typ = 'Pothole on road'
                elif alert['subtype'] in [
                        'HAZARD_ON_SHOULDER_CAR_STOPPED',
                        'HAZARD_ON_ROAD_CAR_STOPPED']:
                    typ = 'Car stopped'
                else:
                    typ = alert['subtype']
            else:
                typ = alert['type']
        elif alert['type'] == 'POLICEMAN':

            if alert['subtype'] == 'POLICE_VISIBLE':
                typ = 'Police visible'
            elif alert['subtype'] == 'POLICE_HIDING':
                typ = 'Police hiding'
            else:
                typ = 'Police'
            attrs = curses.color_pair(0) | curses.A_BOLD
        else:
            typ = alert['type']

        typ = typ.title()

        return (typ, attrs)
Beispiel #13
0
 def setData(self, data):
     # reset position
     self.linePos = 0
     self.colPos = 0
     # load new data
     self.text = data
     data = data.split("\n")
     if isinstance(data, str):
         data = [data]
     self.numLines = len(data)
     self.numCols = 0
     for line in data:
         if len(line) > self.numCols:
             self.numCols = len(line)
     self.pad.clear()
     self.pad.resize(self.numLines, self.numCols)
     for i in range(self.numLines):
         try:
             s = data[i]
             if isHighlightedErrorLine(s):
                 colors = curses.color_pair(ERROR_HIGHLIGHT_COLORS)
             else:
                 colors = curses.color_pair(REGULAR_COLORS)
             self.pad.addstr(i, 0, s, colors)
         except: pass
def draw_list():
    line = 0
    y = 2
    for item in mapping_list:
        string = item["Name"]
        if item["Type"] in ["Heading"]:
            x = 4
        elif item["Type"] in ["Room", "Scene"]:
            x = 6
        elif item["Type"] in ["Device"]:
            x = 8
            # if item["Type"] == "Heading":
            # 	y+=1
            # 	line += 1
        if line == hilight:
            if item["Status"].isdigit():
                if int(item["Status"]) > 0:
                    stdscr.addstr(y, x, string, curses.color_pair(4))
                elif int(item["Status"]) == 0:
                    stdscr.addstr(y, x, string, curses.color_pair(2))
            else:
                stdscr.addstr(y, x, string, curses.A_REVERSE)
        else:
            if item["Status"].isdigit():
                if int(item["Status"]) > 0:
                    stdscr.addstr(y, x, string, curses.color_pair(3))
                elif int(item["Status"]) == 0:
                    stdscr.addstr(y, x, string, curses.color_pair(1))
            else:
                stdscr.addstr(y, x, string)
        y += 1
        line += 1
Beispiel #15
0
def showHG():
    """
    Fonction permettant d'afficher le HighScore
    """

    #On créer une nouvelle fenetre
    win = createNewWin(curses)
    
    #On affiche le texte
    win.addstr(1, 4, 'SnakePY HighScore', curses.color_pair(1))
    win.addstr(2, 4, 'Press 1 to return previous menu', curses.color_pair(1))
    win.addstr(3, 4, '')


    #On boucle sur les HighScore
    i = 4
    #Pour chaque entrée dans le highscore...
    for hg in game.highscore.showHighScore():
        #On ajoute une ligne
        win.addstr(i, 4, "%s -- %s" %(hg[0], hg[1]), curses.color_pair(1))
        i+=1

    chooseMenu = 0
    #Tant que la touche 1 n'est pas pressée...
    while chooseMenu!= ord('1'):
        #On attend et on 'hook' les touches
        chooseMenu = win.getch()

    #Si on sort de la boucle (4), alors on
    #détruit les fenetres
    destroyWin()

    #...sinon on sort de la boucle et on affiche de
    #de nouveau le menu    
    menu()
Beispiel #16
0
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()
Beispiel #17
0
    def __init__(self, category, type, name):
        if type == "*" or category == "*":
            for folder in os.listdir('conf/items'):
                for file in os.listdir('conf/items/{0}'.format(folder if category == "*" else category)):
                    try:
                        self.info = self._load_stats("conf/items/{0}/{1}/{2}.yaml".format(folder if category == "*" else category, file if type == "*" else type, name))
                        break
                    except IOError:
                        pass
        else:
            self.info = self._load_stats("conf/items/{0}/{1}/{2}.yaml".format(category, type, name))

        try:
            self.info
        except:
            raise ValueError("That item does not exist")

        self.name = self.info['name']
        self.display_name = self.info['display_name']
        self.category = self.info['category']
        self.type = self.info['type']
        self.tier = self.info['tier']
        self.examine = self.info['examine']
        self.text_color = curses.color_pair(self.info['text_color'])
        self.frame_color = curses.color_pair(self.info['frame_color'])
        if self.category == "gear" or self.category == "consumables":
            if self.category == "gear":
                self.image = self.info['image']
                self.enchantment = None
            if self.category == "consumables":
                self.duration = self.info['duration']
            self.stats = self.info['stats']
            # Buffs that the item gives from enchantments on it
            self.buffs = []
Beispiel #18
0
def showGameOver():
    """
    Fonction permettant l'affichage du score
    """

    #On créer une nouvelle fenetre
    win = createNewWin(curses)

    #On affiche le texte
    win.addstr(1, 4, 'GAME OVER', curses.color_pair(3))
    win.addstr(2, 4, 'Your Score', curses.color_pair(1))    
    win.addstr(3, 4, '%s - %s' %(game.player.name, game.player.score), curses.color_pair(1))
    win.addstr(4, 4, 'Press 1 to return previous menu', curses.color_pair(1))
    win.addstr(5, 4, '')

    #Ajout dans le highscore
    game.highscore.addHighScore(game.player.name, game.player.score)
    game.highscore.writeHighScore()

    key = 0
    #Tant que la touche 1 n'est pas pressée...
    #while key!= 343 or key!=10:
    while key != ord('1'):
        #On attend et on 'hook' les touches
        key = win.getch()

    #Si on sort de la boucle (1), alors on
    #détruit les fenetres
    destroyWin()

    #A la fin de la partie (game over), on affiche l'écran    
    menu()
Beispiel #19
0
def makeInfoPanel(h,w, y,x, title, info):
    win = curses.newwin(h,w, y,x)
    win.erase()
    
    if title == "<Planet>":
        title = "Target: {}".format(info.name.capitalize())
        ln = 1
        ln += disWritePara(win, ln, 1, h, w, "{:^29}".format(info.empr))
        ln += disWritePara(win, ln, 1, h, w, "Population:{:>18}".format(info.popl))
        ln += disWritePara(win, ln, 1, h, w, "Tech:{:>24}".format(info.tech + " Age"))
        ln += disWritePara(win, ln, 1, h, w, "Wealth rating:{:>15}".format(info.wealth), )
        ln += disWritePara(win, ln, 1, h, w, "Production:{:>18}".format(info.prod))
        ln += disWritePara(win, ln, 1, h, w, "Avg. Temp:{:>19}".format(str(info.temp) + "*C"))
        ln += disWritePara(win, ln, 1, h, w, "Distance:{:>20}".format(str(info.range) + "ly"))
        win.addstr(8, 1, "+---------------------------+")
        win.addstr(8, 9, " Useful Notes ", curses.color_pair(16))
        ln += 1
        for item in info.desc:
            ln += disWritePara(win, ln, 1, h, w-2, "> " + item)
            if ln >= w:
                break;
        
    #disWritePara(win, 1, 1, h, w, text)
    win.border(0, 0, 0, 0, curses.ACS_TTEE, 0, curses.ACS_BTEE, curses.ACS_RTEE)
    win.addstr(0, int(w/2) - int((len(title)+2)/2), " {} ".format(title), curses.color_pair(16))
    
    panel = curses.panel.new_panel(win)
    return win, panel
Beispiel #20
0
    def build_playinfo(self,
                       song_name,
                       artist,
                       album_name,
                       quality,
                       start,
                       pause=False):
        curses.noecho()
        # refresh top 2 line
        self.screen.move(1, 1)
        self.screen.clrtoeol()
        self.screen.move(2, 1)
        self.screen.clrtoeol()
        if pause:
            self.screen.addstr(1, self.indented_startcol,
                               '_ _ z Z Z ' + quality, curses.color_pair(3))
        else:
            self.screen.addstr(1, self.indented_startcol,
                               '♫  ♪ ♫  ♪ ' + quality, curses.color_pair(3))

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

        self.screen.refresh()
Beispiel #21
0
    def choose_agent(window):
        agents = registry.get_names()
        curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLUE)
        window.addstr(10, 34, "Choose agent---SEER DIMENSIONS WAR")
        ch = 0
        selected = 0
        while ch != 10 and ch != 27:
            index = 0
            for agent in agents:
                if index == selected:
                    color = curses.color_pair(3)
                else:
                    color = curses.color_pair(0)
                window.addstr(index + 11, 25, "{:^30}".format(agent), color)
                index += 1

            window.refresh()
            ch = window.getch()
            if ch == curses.KEY_UP:
                selected -= 1
                if selected < 0:
                    selected = len(agents) - 1
            if ch == curses.KEY_DOWN:
                selected += 1
                if selected == len(agents):
                    selected = 0

        window.clear()
        if ch == 27:
            sys.exit(0)
        else:
            return registry.create_agent(agents[selected])
Beispiel #22
0
def drawTrade(player, y,x, h,w, ptr=0):
    win = curses.newwin(h,w, y,x)
    win.erase()
    
    win.hline(3,1, curses.ACS_HLINE, w-2)
    win.vline(2,26, curses.ACS_VLINE, h-3)
    win.vline(2,34, curses.ACS_VLINE, h-3)
    win.vline(2,42, curses.ACS_VLINE, h-3)
    win.addstr(2,1, "Commodities")
    win.addstr(2,27, "Price")
    win.addstr(2,35, "Stock")
    win.addstr(2,43, "Cargo")
    
    line = 4
    
    for p in player.planet.comm:
        color = curses.color_pair(209)
        if line-4 == ptr:
            color = curses.color_pair(16)
        try:
            win.addstr(line, 1, player.planet.comname[line-4], color)    #name
            win.addstr(line, 27, str(p)+"c", color)                      #price
            win.addstr(line, 35, "inf", color)                           #stock
            win.addstr(line, 43, str(player.cargo[line-4])+"t", color)   #cargo
        except:
            pass
        line += 1
    
    win.border(0, 0, 0, 0, 0, curses.ACS_TTEE, curses.ACS_LTEE, curses.ACS_BTEE)
    win.addstr(0, int(w/2)-5, " {} ".format("Trading Screen"), curses.color_pair(16))
    win.addstr(1, 1, "Credits: {} | Hold: {}/{} ".format(player.credits, player.cargotot, player.cargomax), curses.color_pair(16))
    
    panel = curses.panel.new_panel(win)
    return win, panel
Beispiel #23
0
def draw_word(window, y, word, color, reversed=False):
  color = curses.color_pair(color) | curses.A_BOLD
  if reversed:
    color = color | curses.A_REVERSE

  if "$" in word:
    next_color    = color
    current_color = curses.color_pair(8) | curses.A_BOLD

    current_x = 6
    for chunk in word.split("$"):
      chunk_length = len(chunk)
      if chunk_length > 0:
        window.addstr(y, current_x, chunk, current_color)
        current_x += chunk_length
      current_color, next_color = next_color, current_color

  else: # just a normal word
    window.addstr(
      y,
      6,
      word,
      color)

  window.clrtoeol()
  window.refresh()
Beispiel #24
0
    def run(self):
        (height, width) = self.ncurses.chatWindow.getmaxyx()
        self.ncurses.textboxWindow.move(0, 0)

        while True:
            chatInput = self.ncurses.textbox.edit(self.inputValidator)

            # Don't send anything if we're not connected to a nick
            if self.ncurses.connectedNick is None:
                self.ncurses.appendMessage('', "Not connected to client", curses.color_pair(0))

            # Stop the thread if the stop flag is set
            if self.stop.is_set():
                self.ncurses.dialogDismissed.acquire()
                self.ncurses.dialogDismissed.notify()
                self.ncurses.dialogDismissed.release()
                return

            self.ncurses.screen.refresh()

            # Clear the chat input
            self.ncurses.textboxWindow.deleteln()
            self.ncurses.textboxWindow.move(0, 0)
            self.ncurses.textboxWindow.deleteln()

            # Add the new input to the chat window
            prefix = "(%s) %s: " % (utils.getTimestamp(), self.ncurses.nick)
            self.ncurses.appendMessage(prefix, chatInput[:-1], curses.color_pair(3))

            # Send the input to the client
            self.ncurses.connectionManager.getClient(self.ncurses.connectedNick).sendChatMessage(chatInput[:-1])
Beispiel #25
0
    def __init__ (self):
        self.board = puzzle_2048()
        
        self.screen = curses.initscr()
        self.screen.keypad(1)
        self.screen.leaveok(0)
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.noecho()
        curses.curs_set(0)
        
        self.screen.addstr(0,0,"To play: combine the tiles that match using the arrow keys, and press esc to exit")
        
        #Drawing the lines for the board
        self.screen.hline(5,10,"-", 29, curses.color_pair(1))
        self.screen.hline(9,10,"-", 29, curses.color_pair(1))
        self.screen.hline(13,10,"-", 29, curses.color_pair(1))
        self.screen.hline(17,10,"-", 29, curses.color_pair(1))
        self.screen.hline(21,10,"-", 29, curses.color_pair(1))
        self.screen.vline(5,10,"|", 17, curses.color_pair(1))
        self.screen.vline(5,17,"|", 17, curses.color_pair(1))
        self.screen.vline(5,24,"|", 17, curses.color_pair(1))
        self.screen.vline(5,31,"|", 17, curses.color_pair(1))
        self.screen.vline(5,38,"|", 17, curses.color_pair(1))
        
        self.Update_screen()

        self.run()
 def _updateMenu(self):
     menurow = self._screensize[0] - 1
     self._screen.addstr(menurow, 0, ' ' * (self._screensize[1] - 1), curses.color_pair(self.COLOR_HEADER_NORMAL))
     self._screen.move(menurow,4)
     for mnemonic, text in self._keys.iteritems():
         self._screen.addstr(' {0} '.format(mnemonic), curses.color_pair(self.COLOR_NORMAL) | curses.A_BOLD)
         self._screen.addstr('{0}'.format(text), curses.color_pair(self.COLOR_HEADER_NORMAL))
Beispiel #27
0
    def print_line(self, line, highlight=False,semi_highlight=False):
        """A thin wrapper around curses's addstr()."""
        try:
            try:
                max_ousy, max_x = self.win.getmaxyx()
                line = line.encode('utf-8')[0:max_x]
                if semi_highlight and highlight and self.time_to_highlight:
                    line += " " * (self.win.getmaxyx()[1] - len(line))
                    self.win.addstr(self.lineno, 0, line, curses.color_pair(1))
                elif semi_highlight:
                    line += " " * (self.win.getmaxyx()[1] - len(line))
                    self.win.addstr(self.lineno, 0, line, curses.A_STANDOUT)
                elif highlight:
                    line += " " * (self.win.getmaxyx()[1] - len(line))
                    self.win.addstr(self.lineno, 0, line, curses.color_pair(1))
                else:
                    self.win.addstr(self.lineno, 0, line, 0)
            except UnicodeEncodeError as e:
                self.win.addstr(self.lineno, 0, 'x', 0)

        except curses.error:
            self.lineno = 0
            self.win.refresh()
            raise
        else:
            self.lineno += 1
 def _initDialog(self, height, width, buttons=('OK',), caption=None):
     self._dialogpad = curses.newpad(height, width)
     self._dialogpad.bkgd(0x94, curses.color_pair(self.COLOR_HEADER_HI))
     self._dialogpad.clear()
     self._dialogpad.box()
     if caption:
        lh = (width / 2) - (len(caption) / 2) - 1
        self._dialogpad.addstr(0, lh, ' {0} '.format(caption), curses.color_pair(self.COLOR_NORMAL) | curses.A_STANDOUT)
     if buttons:
         if len(buttons) > 1:
             bwid = 0
             for bcap in buttons:
                 if len(bcap) > bwid: bwid = len(bcap)
             cellwid = (width - 4) / len(buttons)
             lpad = (cellwid - bwid) / 2 - 1
             rpad = cellwid - bwid - lpad - 1
             self._dialogpad.move(height - 2, 1)
         else:
             bwid = len(buttons[0])
             lpad = rpad = 1
             self._dialogpad.move(height - 2, (width / 2) - (bwid / 2) - 2)
         for button in buttons:
             self._dialogpad.addstr('{0:{wlpad}}<{1:^{wbwid}}>{0:{wrpad}}'.format('',button, wlpad=lpad, wbwid=bwid, wrpad=rpad))
     dt = (self._screensize[0] / 2) - (height / 2)
     dl = (self._screensize[1] / 2) - (width / 2)
     dc = padcoords(sminrow=dt,smincol=dl,smaxrow=dt+height - 1, smaxcol=dl+width - 1)
     self._dialogcoords = dc
     self._dialogpad.overlay(self._screen, 0, 0, dc.sminrow, dc.smincol, dc.smaxrow, dc.smaxcol)
     self._screen.refresh()
 def _updateDetail_Info(self, pad):
     node = self._selectedNode
     if node:
         #baudRate, basic, generic, specific, version, security
         self._deviceInfoColumns=['id','name','location','capabilities','neighbors','manufacturer','product','productType']
         if self._detailpos[self._detailview] >= len(self._deviceInfoColumns): self._detailpos[self._detailview]=len(self._deviceInfoColumns)-1
         editableColumns=['name','location','manufacturer','product']
         i = maxwid = 0
         for name in self._deviceInfoColumns: maxwid = len(name) if len(name) > maxwid else maxwid
         colwidth = maxwid + 2
         clr = self._getListItemColor(False)
         clr_rw = curses.color_pair(self.COLOR_ERROR)
         clr_ro = self._getListItemColor(True)
         clr_col = curses.color_pair(self.COLOR_OK)
         # TODO: If editable, should be textpad
         for column in self._deviceInfoColumns:
             val = str(getattr(node, column))
             pad.move(i + 1, 1)
             pad.addstr('{0:>{width}}'.format(column.title() + ':', width=colwidth), clr_col)
             selected = i == self._detailpos[self._detailview]
             thisclr = clr
             if selected: thisclr = clr_rw if column in editableColumns else clr_ro
             i += 1
             pad.addstr(' ')
             pad.addstr('{0:<{width}}'.format(val, width=30), thisclr)
Beispiel #30
0
	def setupCurses(self):

		self.titlewin = self.stdscr.subwin(1, 80, 0, 0)
		self.mainwin = self.stdscr.subwin(23, 80, 1, 0)
		self.progwin = self.stdscr.subwin(10, 60, 6, 10)
		self.statwin = self.stdscr.subwin(1, 80, 24, 0)

		self.progBar = progressBar(0, 100, 56)

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

		self.titlewin.bkgd(' ', curses.color_pair(1))
		self.statwin.bkgd(' ', curses.color_pair(1))
		self.mainwin.bkgd(' ', curses.color_pair(2))

		self.titlewin.addstr(0, 0, "Installing " + self.packageName)
		self.statwin.addstr(0, 0, "Please wait...")

		self.resetProgWin()

		self.stdscr.refresh()
Beispiel #31
0
def call(address, frequency):
    # RPS calculation
    last_tot_time = time.time()
    last_reqnumber_per_worker = defaultdict(int)
    last_reqnumber_per_core = defaultdict(int)

    # 0 - do not show async core
    # 1 - merge core statistics with worker statistics
    # 2 - display active cores under workers
    async_mode = 0
    fast_screen = 0

    screen = init_screen()
    http_stats, sfamily, addr, host = parse_address(address)

    need_reset = True

    def game_over():
        if need_reset:
            curses.echo()
            curses.endwin()

    def exc_hook(type, value, tb):
        need_reset = False
        if screen:
            curses.echo()
            curses.endwin()
        traceback.print_exception(type, value, tb)

    atexit.register(game_over)
    sys.excepthook = exc_hook

    while True:

        if fast_screen == 1:
            screen.timeout(100)
        else:
            screen.timeout(frequency * 1000)

        screen.clear()

        js = ''
        try:
            js = reads(http_stats, addr, sfamily)
        except IOError as e:
            if e.errno != errno.EINTR:
                raise
            continue
        except:
            raise Exception("unable to get uWSGI statistics")

        dd = json.loads(js)

        uversion = ''
        if 'version' in dd:
            uversion = '-' + dd['version']

        if 'listen_queue' not in dd:
            dd['listen_queue'] = 0

        cwd = ""
        if 'cwd' in dd:
            cwd = "- cwd: %s" % dd['cwd']

        uid = ""
        if 'uid' in dd:
            uid = "- uid: %d" % dd['uid']

        gid = ""
        if 'gid' in dd:
            gid = "- gid: %d" % dd['gid']

        masterpid = ""
        if 'pid' in dd:
            masterpid = "- masterpid: %d" % dd['pid']

        screen.addstr(
            1, 0, "node: %s %s %s %s %s" % (host, cwd, uid, gid, masterpid))

        if 'vassals' in dd:
            screen.addstr(
                0, 0, "uwsgi%s - %s - emperor: %s - tyrant: %d" %
                (uversion, time.ctime(), dd['emperor'], dd['emperor_tyrant']))
            if dd['vassals']:
                vassal_spaces = max([len(v['id']) for v in dd['vassals']])
                screen.addstr(2, 0,
                              " VASSAL%s\tPID\t" % (' ' * (vassal_spaces - 6)),
                              curses.A_REVERSE)
                pos = 3
                for vassal in dd['vassals']:
                    screen.addstr(
                        pos, 0, " %s\t%d" %
                        (vassal['id'].ljust(vassal_spaces), vassal['pid']))
                    pos += 1

        elif 'workers' in dd:
            tot = sum([worker['requests'] for worker in dd['workers']])

            rps_per_worker = {}
            rps_per_core = {}
            cores = defaultdict(list)
            dt = time.time() - last_tot_time
            total_rps = 0
            for worker in dd['workers']:
                wid = worker['id']
                curr_reqnumber = worker['requests']
                last_reqnumber = last_reqnumber_per_worker[wid]
                rps_per_worker[wid] = (curr_reqnumber - last_reqnumber) / dt
                total_rps += rps_per_worker[wid]
                last_reqnumber_per_worker[wid] = curr_reqnumber
                if not async_mode:
                    continue
                for core in worker.get('cores', []):
                    if not core['requests']:
                        # ignore unused cores
                        continue
                    wcid = (wid, core['id'])
                    curr_reqnumber = core['requests']
                    last_reqnumber = last_reqnumber_per_core[wcid]
                    rps_per_core[wcid] = (curr_reqnumber - last_reqnumber) / dt
                    last_reqnumber_per_core[wcid] = curr_reqnumber
                    cores[wid].append(core)
                cores[wid].sort(key=reqcount)

            last_tot_time = time.time()

            if async_mode == 1:
                merge_worker_with_cores(dd['workers'], rps_per_worker, cores,
                                        rps_per_core)

            tx = human_size(sum([worker['tx'] for worker in dd['workers']]))
            screen.addstr(
                0, 0, "uwsgi%s - %s - req: %d - RPS: %d - lq: %d - tx: %s" %
                (uversion, time.ctime(), tot, int(
                    round(total_rps)), dd['listen_queue'], tx))
            screen.addstr(
                2, 0,
                " WID\t%\tPID\tREQ\tRPS\tEXC\tSIG\tSTATUS\tAVG\tRSS\tVSZ\tTX\tReSpwn\tHC\tRunT\tLastSpwn",
                curses.A_REVERSE)
            pos = 3

            dd['workers'].sort(key=reqcount, reverse=True)
            for worker in dd['workers']:
                sigs = 0
                wtx = human_size(worker['tx'])
                wlastspawn = "--:--:--"

                wrunt = worker['running_time'] / 1000
                if wrunt > 9999999:
                    wrunt = "%sm" % str(int(wrunt / (1000 * 60)))
                else:
                    wrunt = str(wrunt)

                if worker['last_spawn']:
                    wlastspawn = time.strftime(
                        "%H:%M:%S", time.localtime(worker['last_spawn']))

                color = curses.color_pair(0)
                if 'signals' in worker:
                    sigs = worker['signals']
                if worker['status'] == 'busy':
                    color = curses.color_pair(1)
                if worker['status'] == 'cheap':
                    color = curses.color_pair(2)
                if worker['status'].startswith('sig'):
                    color = curses.color_pair(4)
                if worker['status'] == 'pause':
                    color = curses.color_pair(5)

                wid = worker['id']

                rps = int(round(rps_per_worker[wid]))

                try:
                    screen.addstr(
                        pos, 0,
                        " %s\t%.1f\t%d\t%d\t%d\t%d\t%d\t%s\t%dms\t%s\t%s\t%s\t%s\t%s\t%s\t%s"
                        % (wid, calc_percent(
                            tot, worker['requests']), worker['pid'],
                           worker['requests'], rps, worker['exceptions'], sigs,
                           worker['status'], worker['avg_rt'] / 1000,
                           human_size(worker['rss']), human_size(
                               worker['vsz']), wtx, worker['respawn_count'],
                           worker['harakiri_count'], wrunt, wlastspawn), color)
                except:
                    pass
                pos += 1
                if async_mode != 2:
                    continue
                for core in cores[wid]:
                    color = curses.color_pair(0)
                    if core['in_request']:
                        status = 'busy'
                        color = curses.color_pair(1)
                    else:
                        status = 'idle'

                    cid = core['id']
                    rps = int(round(rps_per_core[wid, cid]))
                    try:
                        screen.addstr(
                            pos, 0,
                            "  :%s\t%.1f\t-\t%d\t%d\t-\t-\t%s\t-\t-\t-\t-\t-" %
                            (
                                cid,
                                calc_percent(tot, core['requests']),
                                core['requests'],
                                rps,
                                status,
                            ), color)
                    except:
                        pass
                    pos += 1

        screen.refresh()

        ch = screen.getch()
        if ch == ord('q'):
            game_over()
            break
        elif ch == ord('a'):
            async_mode = (async_mode + 1) % 3
        elif ch == ord('f'):
            fast_screen = (fast_screen + 1) % 2
Beispiel #32
0
def draw_inputs(state):
    window_height = (state['y'] - 4) // 2
    window_width = state['x']
    win_inputs = curses.newwin(window_height, window_width, 3, 0)
    if state['tx']['mode'] == 'inputs':
        # win_inputs.addstr(0, 1, "inputs:                     (UP/DOWN: select, ENTER: view, V: verbose)", curses.A_BOLD + curses.color_pair(3))
        win_inputs.addstr(
            0, 1,
            "inputs:                                               (TAB: switch to)",
            curses.A_BOLD + curses.color_pair(5))
    else:
        # win_inputs.addstr(0, 1, "inputs:                                   (TAB: switch to, V: verbose)", curses.A_BOLD + curses.color_pair(5))
        win_inputs.addstr(
            0, 1,
            "inputs:                                               (TAB: switch to)",
            curses.A_BOLD + curses.color_pair(5))

    # reset cursor if it's been resized off the bottom
    if state['tx']['cursor'] > state['tx']['offset'] + (window_height - 2):
        state['tx']['offset'] = state['tx']['cursor'] - (window_height - 2)

    offset = state['tx']['offset']

    for index in range(offset, offset + window_height - 1):
        if index < len(state['tx']['vin']):
            if 'txid' in state['tx']['vin'][index]:

                buffer_string = state['tx']['vin'][index][
                    'txid'] + ":" + "%03d" % state['tx']['vin'][index]['vout']
                if 'prev_tx' in state['tx']['vin'][index]:
                    vout = state['tx']['vin'][index]['prev_tx']

                    if 'value' in vout:
                        if vout['scriptPubKey']['type'] == "pubkeyhash":
                            buffer_string = "% 14.8f" % vout[
                                'value'] + ": " + vout['scriptPubKey'][
                                    'addresses'][0].ljust(34)
                        else:
                            if len(vout['scriptPubKey']
                                   ['asm']) > window_width - 37:
                                buffer_string = "% 14.8f" % vout[
                                    'value'] + ": ..." + vout['scriptPubKey'][
                                        'asm'][-(window_width - 40):]
                            else:
                                buffer_string = "% 14.8f" % vout[
                                    'value'] + ": " + vout['scriptPubKey'][
                                        'asm']

                        length = len(buffer_string)
                        if length + 72 < window_width:
                            buffer_string += " " + state['tx']['vin'][index][
                                'txid'] + ":" + "%03d" % state['tx']['vin'][
                                    index]['vout']
                        else:
                            buffer_string += " " + state['tx']['vin'][index][
                                'txid'][:(window_width - length -
                                          14)] + "[...]:" + "%03d" % state[
                                              'tx']['vin'][index]['vout']

                if index == (state['tx']['cursor']):
                    win_inputs.addstr(index + 1 - offset, 1, ">",
                                      curses.A_REVERSE + curses.A_BOLD)

                condition = (index == offset + window_height -
                             2) and (index + 1 < len(state['tx']['vin']))
                condition = condition or ((index == offset) and (index > 0))
                if condition:
                    win_inputs.addstr(index + 1 - offset, 3, "...")
                else:
                    win_inputs.addstr(index + 1 - offset, 3, buffer_string)

            elif 'coinbase' in state['tx']['vin'][index]:
                coinbase = "[coinbase] " + state['tx']['vin'][index]['coinbase']
                coinbase_bytes = binascii.unhexlify(
                    state['tx']['vin'][index]['coinbase'])

                # strip non-ASCII characters
                coinbase_bytes = bytes(x for x in coinbase_bytes
                                       if 31 < x < 127)
                coinbase_string = " [strings] {}".format(
                    coinbase_bytes.decode("utf-8"))

                if len(coinbase) > window_width - 1:
                    win_inputs.addstr(index + 1 - offset, 1,
                                      coinbase[:window_width - 5] + " ...")
                else:
                    win_inputs.addstr(index + 1 - offset, 1,
                                      coinbase[:window_width - 1])

                if len(coinbase_string) > window_width - 1:
                    win_inputs.addstr(
                        index + 2 - offset, 1,
                        coinbase_string[:window_width - 5] + " ...")
                else:
                    win_inputs.addstr(index + 2 - offset, 1,
                                      coinbase_string[:window_width - 1])

    win_inputs.refresh()
Beispiel #33
0
def runmenu(menu):
    global screen
    global screenHeight
    global topLineNum
    global highlightLineNum
    global up
    global down
    
    up = -1
    down = 1
    screenHeight = 0
    topLineNum = 0
    highlightLineNum = 0
    oldHighlightLineNum=None 
    screenHeight = curses.LINES - 6 # - 1 border - 5 title lines
    
    x = None 
    # Loop until return key is pressed
    while x !=ord('\n'):
        # reset screen
        screen.clear()
        screen.border(0)
        
        # print title
        screen.addstr(2,2, menu['title'].encode('utf-8'), curses.A_STANDOUT)
        
        top = topLineNum
        bottom = topLineNum + screenHeight
        # print lines
        for (index,menuItem,) in enumerate(menu['options'][top:bottom]):
            linenum = topLineNum + index 
            # print normal            
            if index != highlightLineNum:
                screen.addstr(index + 5, 5, "     " + menuItem['title'].encode('utf-8'), curses.A_NORMAL )
                # bold Cancel
                if index == len(menu['options'])  - 1:
                    screen.addstr(index + 5, 5, "     " + menuItem['title'].encode('utf-8'), curses.A_BOLD)
            else:
                # print highlight current line
                screen.addstr(index + 5, 5, " ->  " + menuItem['title'].encode('utf-8'), curses.color_pair(1))
        
        screen.refresh()
        # get user input
        x = screen.getch()
        if x == curses.KEY_UP:
            moveUpDown(up, menu)
        elif x == curses.KEY_DOWN:
            moveUpDown(down, menu)
        screen.refresh()
    
    # return index of the selected item
    return topLineNum + highlightLineNum
Beispiel #34
0
    def update(self, card):
        self.win.clear()
        self.selected = -1
        self.field_count = 0
        self.fields = None

        if card is not None:
            # find logest label
            field_idx = 0
            self.longest = 0
            self.fields = card['fields']
            self.field_count = 0

            for f in card['fields']:
                if f['value'] is None:
                    field_idx += 1
                    continue

                self.field_count += 1
                label_len = len(f['name'])
                if label_len > self.longest:
                    self.longest = label_len

                if (self.selected == -1 and f['type']
                        in ('password', 'one_time_password', 'secret', 'pin')):
                    self.selected = field_idx

                field_idx += 1

            if self.field_count and self.selected == -1:
                self.selected = 0

            # print title
            y_pos = self.lines - self.field_count - 2
            self.win.addstr(y_pos, self.longest + 3, card['title'],
                            curses.color_pair(3) | curses.A_BOLD)

            # print fields
            field_idx = 0
            for f in card['fields']:
                if f['value'] is None:
                    field_idx += 1
                    continue

                if f['type'] in ('password', 'one_time_password', 'secret'):
                    text = '**********'
                elif f['type'] == 'pin':
                    text = '***'
                else:
                    text = f['value']

                label = f['name']
                x_pos = self.longest - len(label) + 1
                y_pos += 1
                self.win.addstr(y_pos, x_pos, f'{label}:',
                                curses.color_pair(4) | curses.A_BOLD)
                self.win.addstr(y_pos, self.longest + 3, text)

                if field_idx == self.selected:
                    self.win.addstr(y_pos, self.longest + 2, '>',
                                    curses.color_pair(1))

                field_idx += 1

        self.panel.top()
Beispiel #35
0
    def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3):
        self.popup_pos = 0

        self.w = curses.newwin( 5 + len(list(items))*interval + (2 if buttons else 0), 50, y_pos, 5)
        w = self.w
        out = {}
        while True:
            w.clear()
            w.border(0)
            w.addstr( 0, 2, title)

            num = len(list(items))

            numpos = num
            if buttons: numpos += 2

            for i in range(num):
                item = items[i]
                label = item.get('label')
                if item.get('type') == 'list':
                    value = item.get('value','')
                elif item.get('type') == 'satoshis':
                    value = item.get('value','')
                elif item.get('type') == 'str':
                    value = item.get('value','')
                elif item.get('type') == 'password':
                    value = '*'*len(item.get('value',''))
                else:
                    value = ''
                if value is None:
                    value = ''
                if len(value)<20:
                    value += ' '*(20-len(value))

                if 'value' in item:
                    w.addstr( 2+interval*i, 2, label)
                    w.addstr( 2+interval*i, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1) )
                else:
                    w.addstr( 2+interval*i, 2, label, curses.A_REVERSE if self.popup_pos%numpos==i else 0)

            if buttons:
                w.addstr( 5+interval*i, 10, "[  ok  ]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-2) else curses.color_pair(2))
                w.addstr( 5+interval*i, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2))

            w.refresh()

            c = self.stdscr.getch()
            if c in [ord('q'), 27]: break
            elif c in [curses.KEY_LEFT, curses.KEY_UP]: self.popup_pos -= 1
            elif c in [curses.KEY_RIGHT, curses.KEY_DOWN]: self.popup_pos +=1
            else:
                i = self.popup_pos%numpos
                if buttons and c==10:
                    if i == numpos-2:
                        return out
                    elif i == numpos -1:
                        return {}

                item = items[i]
                _type = item.get('type')

                if _type == 'str':
                    item['value'] = self.edit_str(item['value'], c)
                    out[item.get('label')] = item.get('value')

                elif _type == 'password':
                    item['value'] = self.edit_str(item['value'], c)
                    out[item.get('label')] = item ['value']

                elif _type == 'satoshis':
                    item['value'] = self.edit_str(item['value'], c, True)
                    out[item.get('label')] = item.get('value')

                elif _type == 'list':
                    choices = item.get('choices')
                    try:
                        j = choices.index(item.get('value'))
                    except Exception:
                        j = 0
                    new_choice = choices[(j + 1)% len(choices)]
                    item['value'] = new_choice
                    out[item.get('label')] = item.get('value')

                elif _type == 'button':
                    out['button'] = item.get('label')
                    break

        return out
Beispiel #36
0
 def print_send_tab(self):
     self.stdscr.clear()
     self.print_edit_line(3, _("Pay to"), self.str_recipient, 0, 40)
     self.print_edit_line(5, _("Description"), self.str_description, 1, 40)
     self.print_edit_line(7, _("Amount"), self.str_amount, 2, 15)
     self.print_edit_line(9, _("Fee"), self.str_fee, 3, 15)
     self.stdscr.addstr( 12, 15, _("[Send]"), curses.A_REVERSE if self.pos%6==4 else curses.color_pair(2))
     self.stdscr.addstr( 12, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2))
     self.maxpos = 6
Beispiel #37
0
 def print_edit_line(self, y, label, text, index, size):
     text += " "*(size - len(text) )
     self.stdscr.addstr( y, 2, label)
     self.stdscr.addstr( y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1))
Beispiel #38
0
 def get_color_pair(self, fg, bg):
     return curses.color_pair(self.get_pair_number(fg, bg))
 def on_draw(self):
     self.window.border(0)
     self.window.addstr("Pretty text", curses.color_pair(1))
Beispiel #40
0
curses.cbreak()
#curses.curs_set(0)

if curses.has_colors():
    curses.start_color()

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_BLUE, curses.COLOR_BLACK)

stdscr.addstr("Select Solos to swarmify", curses.A_REVERSE)
stdscr.chgat(-1, curses.A_REVERSE)

stdscr.addstr(curses.LINES - 1, 0, "Press 'ESC' to go back, 'Q' to quit")

stdscr.chgat(curses.LINES - 1, 7, 1, curses.A_BOLD | curses.color_pair(2))

outer_window = curses.newwin(curses.LINES - 2, curses.COLS, 1, 0)
text_window = outer_window.subwin(curses.LINES - 6, curses.COLS - 4, 3, 2)
text_window.addstr("Sololink_whatever")
outer_window.box()

stdscr.noutrefresh()
outer_window.noutrefresh()

curses.doupdate()

while True:
    c = outer_window.getch()

    if c == ord('r') or c == ord('R'):
Beispiel #41
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Topmenu and the submenus are based of the example found at this location http://blog.skeltonnetworks.com/2010/03/python-curses-custom-menu/
# The rest of the work was done by Matthew Bennett and he requests you keep these two mentions when you reuse the code :-)
# Basic code refactoring by Andrew Scheller

import curses, os #curses is the interface for capturing key presses on the menu, os launches the files
screen = curses.initscr() #initializes a new window for capturing key presses
curses.noecho() # Disables automatic echoing of key presses (prevents program from input each key twice)
curses.cbreak() # Disables line buffering (runs each key as it is pressed rather than waiting for the return key to pressed)
curses.start_color() # Lets you use colors when highlighting selected menu option
screen.keypad(1) # Capture input from keypad

# Change this to use different colors when highlighting
curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_WHITE) # Sets up color pair #1, it does black text with white background 
h = curses.color_pair(1) #h is the coloring for a highlighted menu option
n = curses.A_NORMAL #n is the coloring for a non highlighted menu option

MENU = "menu"
COMMAND = "command"

menu_data = {
  'title': "Welcome to the Almond box! Please setup your Wifi Network by entering the ssid and password", 'type': MENU, 'subtitle': " ",
  'options': [

    { 'title': "Enter Wifi Password information", 'type': COMMAND, 'command': 'sudo nano /etc/network/interfaces' },  
    { 'title': "Update Launcher Menu", 'type': COMMAND, 'command': 'sudo sh /home/pi/update.sh' },   
    {
      'title': "Entertainment", 'type': MENU, 'subtitle': "Shows, Movies, games and More",
      'options': [
        { 'title': "Kodi", 'type': COMMAND, 'command': 'kodi-standalone' },
Beispiel #42
0
 def write_label(self):
     label_start = 0
     label_end = 17
     label_color = curses.color_pair(5)
     self.write(label_start, label_end, f" {self.label}", label_color)
Beispiel #43
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
    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.setupterm(fd=sys.__stdout__.fileno())
    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)
        curses.pair_number(0)

    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)
Beispiel #44
0
def draw_char(stdscr, height, width, y, x, char):
    if y == height - 1 and x == width - 1:
        # If it's the lower-right corner, addch() throws an error. Use insch() instead.
        stdscr.insch(y, x, char, curses.color_pair(1))
    else:
        stdscr.addch(y, x, char, curses.color_pair(1))
Beispiel #45
0
        def run(stdscr):
          current_optimizer = 'Adam'
          train_tensors = adam_train_tensors
          current_step = 0
          curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
          curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
          curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
          curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
          curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)
          curses.init_pair(6, curses.COLOR_BLUE, curses.COLOR_BLACK)
          curses.init_pair(7, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
          stdscr.clrtoeol()
          stdscr.addstr('\t')
          stdscr.addstr('{}\n'.format(self.save_dir), curses.A_STANDOUT)
          stdscr.clrtoeol()
          stdscr.addstr('\t')
          stdscr.addstr('GPU: {}\n'.format(self.cuda_visible_devices), curses.color_pair(1) | curses.A_BOLD)
          stdscr.clrtoeol()
          stdscr.addstr('\t')
          stdscr.addstr('Current optimizer: {}\n'.format(current_optimizer), curses.color_pair(1) | curses.A_BOLD)
          stdscr.clrtoeol()
          stdscr.addstr('\t')
          stdscr.addstr('Epoch: {:3d}'.format(0), curses.color_pair(1) | curses.A_BOLD)
          stdscr.addstr(' | ')
          stdscr.addstr('Step: {:5d}\n'.format(0), curses.color_pair(1) | curses.A_BOLD)
          stdscr.clrtoeol()
          stdscr.addstr('\t')
          stdscr.addstr('Moving acc: {:5.2f}'.format(0.), curses.color_pair(1) | curses.A_BOLD)
          stdscr.addstr(' | ')
          stdscr.addstr('Best moving acc: {:5.2f}\n'.format(0.), curses.color_pair(1) | curses.A_BOLD)
          stdscr.clrtoeol()
          stdscr.addstr('\t')
          stdscr.addstr('Steps since improvement: {:4d}\n'.format(0),  curses.color_pair(1) | curses.A_BOLD)
          stdscr.clrtoeol()
          stdscr.move(2,0)
          stdscr.refresh()
          try:
            current_epoch = 0
            best_accuracy = 0
            current_accuracy = 0
            steps_since_best = 0
            while (not self.max_steps or current_step < self.max_steps) and \
                  (not self.max_steps_without_improvement or steps_since_best < self.max_steps_without_improvement) and \
                  (not self.n_passes or current_epoch < len(trainset.conllu_files)*self.n_passes):
              if steps_since_best >= 500 and self.switch_optimizers:
                train_tensors = amsgrad_train_tensors
                current_optimizer = 'AMSGrad'
              for batch in trainset.batch_iterator(shuffle=True):
                train_outputs.restart_timer()
                start_time = time.time()
                feed_dict = trainset.set_placeholders(batch)
                _, train_scores = sess.run(train_tensors, feed_dict=feed_dict)
                train_outputs.update_history(train_scores)
                current_step += 1
                if current_step % self.print_every == 0:
                  for batch in devset.batch_iterator(shuffle=False):
                    dev_outputs.restart_timer()
                    feed_dict = devset.set_placeholders(batch)
                    dev_scores = sess.run(dev_tensors, feed_dict=feed_dict)
                    dev_outputs.update_history(dev_scores)
                  current_accuracy *= .5
                  current_accuracy += .5*dev_outputs.get_current_accuracy()
                  if current_accuracy >= best_accuracy:
                    steps_since_best = 0
                    best_accuracy = current_accuracy
                    if self.save_model_after_improvement:
                      saver.save(sess, os.path.join(self.save_dir, 'ckpt'), global_step=self.global_step, write_meta_graph=False)
                    if self.parse_devset:
                      self.parse_files(devset, dev_outputs, sess, print_time=False)
                  else:
                    steps_since_best += self.print_every
                  current_epoch = sess.run(self.global_step)
                  stdscr.addstr('\t')
                  stdscr.addstr('Current optimizer: {}\n'.format(current_optimizer), curses.color_pair(1) | curses.A_BOLD)
                  stdscr.clrtoeol()
                  stdscr.addstr('\t')
                  stdscr.addstr('Epoch: {:3d}'.format(int(current_epoch)), curses.color_pair(1) | curses.A_BOLD)
                  stdscr.addstr(' | ')
                  stdscr.addstr('Step: {:5d}\n'.format(int(current_step)), curses.color_pair(1) | curses.A_BOLD)
                  stdscr.clrtoeol()
                  stdscr.addstr('\t')
                  stdscr.addstr('Moving acc: {:5.2f}'.format(current_accuracy), curses.color_pair(1) | curses.A_BOLD)
                  stdscr.addstr(' | ')
                  stdscr.addstr('Best moving acc: {:5.2f}\n'.format(best_accuracy), curses.color_pair(1) | curses.A_BOLD)
                  stdscr.clrtoeol()
                  stdscr.addstr('\t')
                  stdscr.addstr('Steps since improvement: {:4d}\n'.format(int(steps_since_best)),  curses.color_pair(1) | curses.A_BOLD)
                  stdscr.clrtoeol()
                  train_outputs.print_recent_history(stdscr)
                  dev_outputs.print_recent_history(stdscr)
                  print('')
                  stdscr.move(2,0)
                  stdscr.refresh()
              current_epoch = sess.run(self.global_step)
              sess.run(update_step)
              trainset.load_next()
            with open(os.path.join(self.save_dir, 'SUCCESS'), 'w') as f:
              pass
          except KeyboardInterrupt:
            pass

          line = 0
          stdscr.move(line,0)
          instr = stdscr.instr().rstrip()
          while instr:
            screen_output.append(instr)
            line += 1
            stdscr.move(line,0)
            instr = stdscr.instr().rstrip()
Beispiel #46
0
def main(stdscr):
    # Setup the default colors
    curses.use_default_colors()

    # Clear the screen
    stdscr.clear()

    # Display the logo and wait for user input
    stdscr.addstr(LOGO)
    stdscr.refresh()
    stdscr.getch()

    # Initialize the game grid display
    stdscr.clear()
    for y in range(NUM_ROWS):
        for x in range(NUM_COLS):
            stdscr.addstr(y, x, STR_COVERED)
    stdscr.move(0, 0)
    stdscr.refresh()

    # Initialize colors
    initialize_color_pairs()

    # Initialize the Minesweeper game
    minesweeper = Minesweeper(NUM_ROWS, NUM_COLS, NUM_MINES)

    # Run the game logic
    while True:
        c = stdscr.getch()
        (y, x) = stdscr.getyx()

        # This is a good place for a switch statement!!!

        if c == ord('e'):
            break
        elif c == curses.KEY_LEFT:
            stdscr.move(y, max(x - 1, 0))
        elif c == curses.KEY_RIGHT:
            stdscr.move(y, min(x + 1, NUM_COLS - 1))
        elif c == curses.KEY_UP:
            stdscr.move(max(y - 1, 0), x)
        elif c == curses.KEY_DOWN:
            stdscr.move(min(y + 1, NUM_ROWS - 1), x)
        elif c == ord('c'):
            # Check for double click on revealed tile which has proper number
            # of marked flags
            if ord('1') <= (stdscr.inch(y, x) & 0xff) <= ord('8') and str(
                    countSurroundingFlags(
                        x, y, stdscr)) == chr(stdscr.inch(y, x) & 0xff):
                revealSurrounding(x, y, stdscr, minesweeper)
            else:
                revealTile(x, y, stdscr, minesweeper)

            # Avoid moving the cursor. There's probably a nicer way to do this
            stdscr.move(y, x)
            stdscr.refresh()
        elif c == ord('f'):
            stdscr.addstr(STR_FLAG, curses.color_pair(PAIR_FLAG))

            # Avoid moving the cursor.
            stdscr.move(y, x)
            stdscr.refresh()
Beispiel #47
0
 def build_loading(self):
     self.screen.addstr(6, 19, '尽享高品质音乐...', curses.color_pair(1))
     self.screen.refresh()        
Beispiel #48
0
    def build_menu(self, datatype, title, datalist, offset, index, step):
    	# keep playing info in line 1
        curses.noecho()
        self.screen.move(4,1)
        self.screen.clrtobot()
        self.screen.addstr(4, 19, title, curses.color_pair(1))

        if len(datalist) == 0:
            self.screen.addstr(8, 19, '这里什么都没有 -,-')

        else:
            if datatype == 'main':
                for i in range( offset, min( len(datalist), offset+step) ):
                    if i == index:
                        self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2))
                    else:
                        self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i])

            elif datatype == 'songs':
                for i in range(offset, min( len(datalist), offset+step) ):
                    # this item is focus
                    if i == index:
                        self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['song_name'] + '   -   ' + datalist[i]['artist'] + '  < ' + datalist[i]['album_name'] + ' >', curses.color_pair(2))
                    else:
                        self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['song_name'] + '   -   ' + datalist[i]['artist'] + '  < ' + datalist[i]['album_name'] + ' >')

            elif datatype == 'artists':
                for i in range(offset, min( len(datalist), offset+step) ):
                    if i == index:
                        self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['artists_name'] + '   -   ' + str(datalist[i]['alias']), curses.color_pair(2))
                    else:
                        self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['artists_name'] + '   -   ' + datalist[i]['alias'])

            elif datatype == 'albums':
                for i in range(offset, min( len(datalist), offset+step) ):
                    if i == index:
                        self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['albums_name'] + '   -   ' + datalist[i]['artists_name'], curses.color_pair(2))
                    else:
                        self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['albums_name'] + '   -   ' + datalist[i]['artists_name'])

            elif datatype == 'playlists':
                for i in range(offset, min( len(datalist), offset+step) ):
                    if i == index:
                        self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['playlists_name'] + '   -   ' + datalist[i]['creator_name'], curses.color_pair(2))
                    else:
                        self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['playlists_name'] + '   -   ' + datalist[i]['creator_name'])

            elif datatype == 'djchannels':
                for i in range(offset, min( len(datalist), offset+step) ):
                    if i == index:
                        self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['song_name'], curses.color_pair(2))
                    else:
                        self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['song_name'])

            elif datatype == 'help':
                for i in range(offset, min( len(datalist), offset+step) ):
                    if i == index:
                        self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. \'' + datalist[i][0] + '\'   ' + datalist[i][1] + '   ' + datalist[i][2], curses.color_pair(2))
                    else:
                        self.screen.addstr(i - offset +8, 19, str(i) + '. \'' + datalist[i][0] + '\'   ' + datalist[i][1] + '   ' + datalist[i][2])
                self.screen.addstr(20, 6, 'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存')
                self.screen.addstr(21, 10, '按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~')
                self.screen.addstr(22, 19, 'Build with love to music by @vellow')

        self.screen.refresh()
Beispiel #49
0
    def build_menu(self, datatype, title, datalist, offset, index, step,
                   start):
        # keep playing info in line 1
        curses.noecho()
        self.screen.move(5, 1)
        self.screen.clrtobot()
        self.addstr(5, self.startcol, title, curses.color_pair(1))

        if len(datalist) == 0:
            self.addstr(8, self.startcol, '这里什么都没有 -,-')

        else:
            if datatype == 'main':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(i - offset + 9, self.indented_startcol,
                                    '-> ' + str(i) + '. ' + datalist[i],
                                    curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 9, self.startcol,
                                    str(i) + '. ' + datalist[i])

            elif datatype == 'songs' or datatype == 'fmsongs':
                iter_range = min(len(datalist), offset + step)
                for i in range(offset, iter_range):
                    # this item is focus
                    if i == index:
                        self.addstr(i - offset + 8, 0, ' ' * self.startcol)
                        lead = '-> ' + str(i) + '. '
                        self.addstr(i - offset + 8, self.indented_startcol,
                                    lead, curses.color_pair(2))
                        name = '{}{}{}  < {} >'.format(
                            datalist[i]['song_name'], self.space,
                            datalist[i]['artist'], datalist[i]['album_name'])

                        # the length decides whether to scoll
                        if truelen(name) < self.x - self.startcol - 1:
                            self.addstr(i - offset + 8,
                                        self.indented_startcol + len(lead),
                                        name, curses.color_pair(2))
                        else:
                            name = scrollstring(name + '  ', start)
                            self.addstr(i - offset + 8,
                                        self.indented_startcol + len(lead),
                                        str(name), curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 8, 0, ' ' * self.startcol)
                        self.addstr(
                            i - offset + 8, self.startcol,
                            '{}. {}{}{}  < {} >'.format(
                                i, datalist[i]['song_name'], self.space,
                                datalist[i]['artist'],
                                datalist[i]['album_name'])[:int(self.x * 2)])

                self.addstr(iter_range - offset + 8, 0, ' ' * self.x)

            elif datatype == 'comments':
                # 被选中的评论在最下方显示全部字符,其余评论仅显示一行
                for i in range(offset, min(len(datalist), offset + step)):
                    maxlength = min(int(1.8 * self.startcol), len(datalist[i]))
                    if i == index:
                        try:
                            self.addstr(20, self.indented_startcol,
                                        '-> ' + str(i) + '. ' + datalist[i],
                                        curses.color_pair(2))
                        except:
                            self.addstr(
                                20, self.indented_startcol, '-> ' + str(i) +
                                '. ' + 'This comment is invalid',
                                curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 9, self.startcol,
                                    str(i) + '. ' + datalist[i][:maxlength])

            elif datatype == 'artists':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(
                            i - offset + 9, self.indented_startcol, '-> ' +
                            str(i) + '. ' + datalist[i]['artists_name'] +
                            self.space + str(datalist[i]['alias']),
                            curses.color_pair(2))
                    else:
                        self.addstr(
                            i - offset + 9, self.startcol,
                            str(i) + '. ' + datalist[i]['artists_name'] +
                            self.space + datalist[i]['alias'])

            elif datatype == 'albums':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(
                            i - offset + 9, self.indented_startcol, '-> ' +
                            str(i) + '. ' + datalist[i]['albums_name'] +
                            self.space + datalist[i]['artists_name'],
                            curses.color_pair(2))
                    else:
                        self.addstr(
                            i - offset + 9, self.startcol,
                            str(i) + '. ' + datalist[i]['albums_name'] +
                            self.space + datalist[i]['artists_name'])

            elif datatype == 'playlists':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(
                            i - offset + 9, self.indented_startcol,
                            '-> ' + str(i) + '. ' + datalist[i]['title'],
                            curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 9, self.startcol,
                                    str(i) + '. ' + datalist[i]['title'])

            elif datatype == 'top_playlists':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(
                            i - offset + 9, self.indented_startcol, '-> ' +
                            str(i) + '. ' + datalist[i]['playlists_name'] +
                            self.space + datalist[i]['creator_name'],
                            curses.color_pair(2))
                    else:
                        self.addstr(
                            i - offset + 9, self.startcol,
                            str(i) + '. ' + datalist[i]['playlists_name'] +
                            self.space + datalist[i]['creator_name'])

            elif datatype == 'toplists':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(i - offset + 9, self.indented_startcol,
                                    '-> ' + str(i) + '. ' + datalist[i],
                                    curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 9, self.startcol,
                                    str(i) + '. ' + datalist[i])

            elif datatype in ('playlist_classes', 'playlist_class_detail'):
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(i - offset + 9, self.indented_startcol,
                                    '-> ' + str(i) + '. ' + datalist[i],
                                    curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 9, self.startcol,
                                    str(i) + '. ' + datalist[i])

            elif datatype == 'djchannels':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(
                            i - offset + 8, self.indented_startcol,
                            '-> ' + str(i) + '. ' + datalist[i]['song_name'],
                            curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 8, self.startcol,
                                    str(i) + '. ' + datalist[i]['song_name'])

            elif datatype == 'search':
                self.screen.move(6, 1)
                self.screen.clrtobot()
                self.screen.timeout(-1)
                self.addstr(8, self.startcol, '选择搜索类型:', curses.color_pair(1))
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(i - offset + 10, self.indented_startcol,
                                    '-> ' + str(i) + '.' + datalist[i - 1],
                                    curses.color_pair(2))
                    else:
                        self.addstr(i - offset + 10, self.startcol,
                                    str(i) + '.' + datalist[i - 1])
                self.screen.timeout(100)

            elif datatype == 'help':
                for i in range(offset, min(len(datalist), offset + step)):
                    if i == index:
                        self.addstr(
                            i - offset + 9, self.indented_startcol,
                            '-> {}. \'{}{}   {}'.format(
                                i, (datalist[i][0].upper() + '\'').ljust(11),
                                datalist[i][1], datalist[i][2]),
                            curses.color_pair(2))
                    else:
                        self.addstr(
                            i - offset + 9,
                            self.startcol, '{}. \'{}{}   {}'.format(
                                i, (datalist[i][0].upper() + '\'').ljust(11),
                                datalist[i][1], datalist[i][2]))

                self.addstr(20, 6,
                            'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存')
                self.addstr(21, 10, '按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~')
                self.addstr(22, self.startcol,
                            'Build with love to music by omi')

        self.screen.refresh()
Beispiel #50
0
    def __init__(self, stdscreen, options_file):
        self.screen = stdscreen

        # Init the colors
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
        curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(4, curses.COLOR_RED, curses.COLOR_WHITE)

        self.screen.bkgd(' ', curses.color_pair(1))

        self.maxy, self.maxx = self.screen.getmaxyx()
        self.screen.addstr(self.maxy - 1, 0,
                           '  Arrow keys make selections; <Enter> activates.')
        curses.curs_set(0)

        self.cd_path = None

        kernel_params = subprocess.check_output(['cat', '/proc/cmdline'])

        # check the kickstart param
        ks_config = None
        m = re.match(r".*ks=(\S+)\s*.*\s*", kernel_params)
        if m != None:
            ks_config = self.get_config(m.group(1))

        # check for the repo param
        m = re.match(r".*repo=(\S+)\s*.*\s*", kernel_params)
        if m != None:
            rpm_path = m.group(1)
        else:
            # the rpms should be in the cd
            self.mount_RPMS_cd()
            rpm_path = os.path.join(self.cd_path, "RPMS")

        # This represents the installer screen, the bool indicated if I can go back to this window or not
        items = []
        if not ks_config:
            random_id = '%12x' % random.randrange(16**12)
            random_hostname = "photon-" + random_id.strip()
            install_config = {'iso_system': False}
            license_agreement = License(self.maxy, self.maxx)
            select_disk = SelectDisk(self.maxy, self.maxx, install_config)
            select_partition = PartitionISO(self.maxy, self.maxx,
                                            install_config)
            package_selector = PackageSelector(self.maxy, self.maxx,
                                               install_config, options_file)

            self.alpha_chars = range(65, 91)
            self.alpha_chars.extend(range(97, 123))
            partition_accepted_chars = list(range(48, 58))
            hostname_accepted_chars = list(self.alpha_chars)
            # Adding the numeric chars
            hostname_accepted_chars.extend(range(48, 58))
            # Adding the . and -
            hostname_accepted_chars.extend([ord('.'), ord('-')])

            hostname_reader = WindowStringReader(
                self.maxy,
                self.maxx,
                10,
                70,
                'hostname',
                None,  # confirmation error msg if it's a confirmation text
                None,  # echo char
                hostname_accepted_chars,  # set of accepted chars
                self.validate_hostname,  # validation function of the input
                None,  # post processing of the input field
                'Choose the hostname for your system',
                'Hostname:',
                2,
                install_config,
                random_hostname,
                True)
            root_password_reader = WindowStringReader(
                self.maxy,
                self.maxx,
                10,
                70,
                'password',
                None,  # confirmation error msg if it's a confirmation text
                '*',  # echo char
                None,  # set of accepted chars
                self.validate_password,  # validation function of the input
                None,  # post processing of the input field
                'Set up root password',
                'Root password:'******'password',
                "Passwords don't match, please try again.",  # confirmation error msg if it's a confirmation text
                '*',  # echo char
                None,  # set of accepted chars
                None,  # validation function of the input
                self.
                generate_password_hash,  # post processing of the input field
                'Confirm root password',
                'Confirm Root password:'******'ostree_repo_url',
                None,  # confirmation error msg if it's a confirmation text
                None,  # echo char
                None,  # set of accepted chars
                self.
                validate_ostree_url_input,  # validation function of the input
                None,  # post processing of the input field
                'Please provide the URL of OSTree repo',
                'OSTree Repo URL:',
                2,
                install_config,
                "http://")
            ostree_ref_reader = OSTreeWindowStringReader(
                self.maxy,
                self.maxx,
                10,
                70,
                'ostree_repo_ref',
                None,  # confirmation error msg if it's a confirmation text
                None,  # echo char
                None,  # set of accepted chars
                self.
                validate_ostree_refs_input,  # validation function of the input
                None,  # post processing of the input field
                'Please provide the Refspec in OSTree repo',
                'OSTree Repo Refspec:',
                2,
                install_config,
                "photon/1.0/x86_64/minimal")

            items = items + [
                (license_agreement.display, False),
                (select_disk.display, True),
                (select_partition.display, False),
                (select_disk.guided_partitions, False),
                (package_selector.display, True),
                (hostname_reader.get_user_string, True),
                (root_password_reader.get_user_string, True),
                (confirm_password_reader.get_user_string, False),
                (ostree_server_selector.display, True),
                (ostree_url_reader.get_user_string, True),
                (ostree_ref_reader.get_user_string, True),
            ]
        else:
            install_config = ks_config
            install_config['iso_system'] = False

        installer = InstallerContainer(install_config,
                                       self.maxy,
                                       self.maxx,
                                       True,
                                       rpm_path=rpm_path,
                                       log_path="/var/log",
                                       ks_config=ks_config)

        items = items + [(installer.install, False)]

        index = 0
        params = None
        while True:
            result = items[index][0](params)
            if result.success:
                index += 1
                params = result.result
                if index == len(items) - 1:
                    self.screen.clear()
                if index == len(items):
                    break
            else:
                index -= 1
                while index >= 0 and items[index][1] == False:
                    index -= 1
                if index < 0:
                    index = 0
Beispiel #51
0
    def build_process_bar(self, now_playing, total_length, playing_flag,
                          pause_flag, playing_mode):
        if (self.storage.database['player_info']['idx'] >= len(
                self.storage.database['player_info']['player_list'])):
            return
        curses.noecho()
        self.screen.move(3, 1)
        self.screen.clrtoeol()
        self.screen.move(4, 1)
        self.screen.clrtoeol()
        if not playing_flag:
            return
        if total_length <= 0:
            total_length = 1
        if now_playing > total_length or now_playing <= 0:
            now_playing = 0
        process = '['
        for i in range(0, 33):
            if i < now_playing / total_length * 33:
                if (i + 1) > now_playing / total_length * 33:
                    if not pause_flag:
                        process += '>'
                        continue
                process += '='
            else:
                process += ' '
        process += '] '
        now_minute = int(now_playing / 60)
        if now_minute > 9:
            now_minute = str(now_minute)
        else:
            now_minute = '0' + str(now_minute)
        now_second = int(now_playing - int(now_playing / 60) * 60)
        if now_second > 9:
            now_second = str(now_second)
        else:
            now_second = '0' + str(now_second)
        total_minute = int(total_length / 60)
        if total_minute > 9:
            total_minute = str(total_minute)
        else:
            total_minute = '0' + str(total_minute)
        total_second = int(total_length - int(total_length / 60) * 60)
        if total_second > 9:
            total_second = str(total_second)
        else:
            total_second = '0' + str(total_second)
        process += '(' + now_minute + ':' + now_second + '/' + total_minute + ':' + total_second + ')'  # NOQA
        if playing_mode == 0:
            process = '顺序播放 ' + process
        elif playing_mode == 1:
            process = '顺序循环 ' + process
        elif playing_mode == 2:
            process = '单曲循环 ' + process
        elif playing_mode == 3:
            process = '随机播放 ' + process
        elif playing_mode == 4:
            process = '随机循环 ' + process
        else:
            pass
        self.addstr(3, self.startcol - 2, process, curses.color_pair(1))
        song = self.storage.database['songs'][
            self.storage.database['player_info']['player_list'][
                self.storage.database['player_info']['idx']]]
        if 'lyric' not in song.keys() or len(song['lyric']) <= 0:
            self.now_lyric = '暂无歌词 ~>_<~ \n'
            if dbus_activity and self.config.get_item('osdlyrics'):
                self.now_playing = song['song_name'] + ' - ' + song[
                    'artist'] + '\n'

        else:
            key = now_minute + ':' + now_second
            for line in song['lyric']:
                if key in line:
                    if 'tlyric' not in song.keys() or len(song['tlyric']) <= 0:
                        self.now_lyric = line
                    else:
                        self.now_lyric = line
                        for tline in song['tlyric']:
                            if key in tline and self.config.get_item(
                                    'translation'):
                                self.now_lyric = tline + ' || ' + self.now_lyric  # NOQA
        self.now_lyric = re.sub('\[.*?\]', '', self.now_lyric)
        if dbus_activity and self.config.get_item('osdlyrics'):
            try:
                bus = dbus.SessionBus().get_object('org.musicbox.Bus', '/')
                if self.now_lyric == '暂无歌词 ~>_<~ \n':
                    bus.refresh_lyrics(self.now_playing,
                                       dbus_interface='local.musicbox.Lyrics')
                else:
                    bus.refresh_lyrics(self.now_lyric,
                                       dbus_interface='local.musicbox.Lyrics')
            except Exception as e:
                log.error(e)
                pass
        self.addstr(4, self.startcol - 2, str(self.now_lyric),
                    curses.color_pair(3))
        self.screen.refresh()
Beispiel #52
0
 def build_loading(self):
     self.addstr(7, self.startcol, '享受高品质音乐,loading...',
                 curses.color_pair(1))
     self.screen.refresh()
Beispiel #53
0
def show_stat(stdscr, file, dira):
    """
        show stats on right panel
    """
    h, w = stdscr.getmaxyx()
    wn = 37
    if (w < wn * 2):
        return

    if file == "Empty Folder":
        for i in range(2, 10):
            stdscr.addstr(i, w - wn, " " * wn, curses.color_pair(11))
        stdscr.addstr(1, w - wn + wn // 2 - 1, "Stats", curses.color_pair(11))
        stdscr.addstr(2, w - wn + wn // 2 - 7, "Nothing to show",
                      curses.color_pair(11))
        return
    stdscr.addstr(h - 3, w - wn, " " * wn, curses.color_pair(11))
    try:
        st = os.stat(file)
    except:
        for i in range(2, 10):
            stdscr.addstr(i, w - wn, " " * wn, curses.color_pair(11))
        stdscr.addstr(1, w - wn + wn // 2 - 1, "Stats", curses.color_pair(11))
        stdscr.addstr(2, w - wn + wn // 2 - 7, "Permission Denied",
                      curses.color_pair(11))
        return
    if dira:
        dira = "Folder"
    else:
        dira = "File"
    kb = 2**10

    stdscr.addstr(1, w - wn + wn // 2 - 1, "Stats", curses.color_pair(11))
    stdscr.addstr(2, w - wn + 1, "Created  : " + str(time.ctime(st.st_ctime)),
                  curses.color_pair(11))
    stdscr.addstr(3, w - wn + 1, "Modified : " + str(time.ctime(st.st_atime)),
                  curses.color_pair(11))
    stdscr.addstr(4, w - wn + 1, "Accessed : " + str(time.ctime(st.st_mtime)),
                  curses.color_pair(11))
    stdscr.addstr(5, w - wn, " " * wn, curses.color_pair(11))
    stdscr.addstr(5, w - wn + 1,
                  "Size (KB): " + str(round(st.st_size / kb, 3)),
                  curses.color_pair(11))
    stdscr.addstr(6, w - wn, " " * wn, curses.color_pair(11))
    stdscr.addstr(6, w - wn + 1, "Type     : " + dira, curses.color_pair(11))
    stdscr.addstr(7, w - wn + 1, "User ID  : " + str(st.st_uid),
                  curses.color_pair(11))
    stdscr.addstr(8, w - wn + 1, "Group ID : " + str(st.st_gid),
                  curses.color_pair(11))
    stdscr.addstr(9, w - wn + 1, "Inode    : " + str(st.st_ino),
                  curses.color_pair(11))
    bar_single(stdscr, h, w)
Beispiel #54
0
 def draw_title(self, row):
     self.addstr_color(row, 0, self.stretch('   TIMESTAMP  MESSAGE'),
                       curses.color_pair(1))
Beispiel #55
0
    def update_array(stdscr, self):

        while self.thread_list[0].is_alive():
            for index, val in enumerate(self.cell_array):
                stdscr.addstr(index + 1, 0, val, curses.color_pair(1))
            time.sleep(0.05)
Beispiel #56
0
 def set_fg_bg_attr(self, fg, bg, attr):
     try:
         self.win.attrset(curses.color_pair(get_color(fg, bg)) | attr)
     except _curses.error:
         pass
Beispiel #57
0
    def display_pizza(self, color_pair):
        self.scr.addstr(3, 14, ", - ~~ - ,", curses.color_pair(color_pair))

        self.scr.addstr(4, 10, ", '", curses.color_pair(color_pair))
        self.scr.addstr(4, 25, "' ,", curses.color_pair(color_pair))

        self.scr.addstr(5, 8, ",", curses.color_pair(color_pair))
        self.scr.addstr(5, 29, ",", curses.color_pair(color_pair))

        self.scr.addstr(6, 7, ",", curses.color_pair(color_pair))
        self.scr.addstr(6, 30, ",", curses.color_pair(color_pair))

        self.scr.addstr(7, 6, ",", curses.color_pair(color_pair))
        self.scr.addstr(7, 31, ",", curses.color_pair(color_pair))

        self.scr.addstr(8, 6, ",", curses.color_pair(color_pair))
        self.scr.addstr(8, 31, ",", curses.color_pair(color_pair))

        self.scr.addstr(9, 6, ",", curses.color_pair(color_pair))
        self.scr.addstr(9, 31, ",", curses.color_pair(color_pair))

        self.scr.addstr(10, 7, ",", curses.color_pair(color_pair))
        self.scr.addstr(10, 30, ",", curses.color_pair(color_pair))

        self.scr.addstr(11, 8, ",", curses.color_pair(color_pair))
        self.scr.addstr(11, 29, ",", curses.color_pair(color_pair))

        self.scr.addstr(12, 10, ",", curses.color_pair(color_pair))
        self.scr.addstr(12, 28, ",", curses.color_pair(color_pair))

        self.scr.addstr(13, 12, "' - , __ , - '",
                        curses.color_pair(color_pair))

        self.scr.refresh()
def visualize(device):
    chunk = 2048  # Change if too fast/slow, never less than 1024
    scale = 200  # Change if bars too short/long
    exponent = .5  # Change if too little/too much difference between loud and quiet sounds
    sample_rate = 44100

    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
                    channels=1,
                    rate=sample_rate,
                    input=True,
                    frames_per_buffer=chunk,
                    input_device_index=device)

    print "Starting, use Ctrl+C to stop"
    screen = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    curses.curs_set(0)  # invisible cursor
    curses.init_pair(1, -1, curses.COLOR_BLUE)
    curses.init_pair(2, -1, -1)

    term_height = screen.getmaxyx()[0]
    term_width = screen.getmaxyx()[1]

    min_bar_height = 1
    bar_width = 4
    bar_spacing = 2
    vertical_offset = 2
    bins = term_width / (bar_width + bar_spacing)

    bars = []
    for i in range(bins):
        xcoord = bar_spacing + i * (bar_width + bar_spacing)
        bars.append(
            curses.newwin(min_bar_height, bar_width,
                          term_height - vertical_offset, xcoord))

    try:
        while True:
            # handle terminal resizing
            if curses.is_term_resized(term_height, term_width):
                screen.clear()
                screen.refresh()

                term_height = screen.getmaxyx()[0]
                term_width = screen.getmaxyx()[1]

                bins = term_width / (bar_width + bar_spacing)
                bars = []

                for i in range(bins):
                    xcoord = bar_spacing + i * (bar_width + bar_spacing)
                    bars.append(
                        curses.newwin(min_bar_height, bar_width,
                                      term_height - vertical_offset, xcoord))

            data = stream.read(chunk)
            levels = analyze(data, chunk, sample_rate, bins)

            for i in range(bins):
                height = max(min((levels[i] * 1.0) / scale, 1.0), 0.0)
                height = height**exponent
                height = int(height * term_height * 1.5)

                prev_coords = bars[i].getbegyx()
                prev_bar_height = bars[i].getmaxyx()[0]

                bars[i].bkgd(' ', curses.color_pair(2))  # recolor to default
                bars[i].erase()
                bars[i].refresh()

                new_bar_height = max(height, min_bar_height)
                bars[i] = curses.newwin(
                    new_bar_height, bar_width,
                    prev_coords[0] - (new_bar_height - prev_bar_height),
                    prev_coords[1])
                bars[i].bkgd(' ', curses.color_pair(1))  # set color
                bars[i].refresh()

    except KeyboardInterrupt:
        pass
    finally:
        print "\nStopping"
        stream.close()
        p.terminate()
        curses.endwin()
Beispiel #59
0
    def display_pizza_edge(self, color_pair):
        self.scr.addstr(2, 13, ", -  ~~  - ,", curses.color_pair(color_pair))

        self.scr.addstr(3, 9, ", '", curses.color_pair(color_pair))
        self.scr.addstr(3, 26, "' ,", curses.color_pair(color_pair))

        self.scr.addstr(4, 7, ",", curses.color_pair(color_pair))
        self.scr.addstr(4, 30, ",", curses.color_pair(color_pair))

        self.scr.addstr(5, 6, ",", curses.color_pair(color_pair))
        self.scr.addstr(5, 31, ",", curses.color_pair(color_pair))

        self.scr.addstr(6, 5, ",", curses.color_pair(color_pair))
        self.scr.addstr(6, 32, ",", curses.color_pair(color_pair))

        self.scr.addstr(7, 5, ",", curses.color_pair(color_pair))
        self.scr.addstr(7, 32, ",", curses.color_pair(color_pair))

        self.scr.addstr(8, 5, ",", curses.color_pair(color_pair))
        self.scr.addstr(8, 32, ",", curses.color_pair(color_pair))

        self.scr.addstr(9, 5, ",", curses.color_pair(color_pair))
        self.scr.addstr(9, 32, ",", curses.color_pair(color_pair))

        self.scr.addstr(10, 5, ",", curses.color_pair(color_pair))
        self.scr.addstr(10, 32, ",", curses.color_pair(color_pair))

        self.scr.addstr(11, 6, ",", curses.color_pair(color_pair))
        self.scr.addstr(11, 31, ",", curses.color_pair(color_pair))

        self.scr.addstr(12, 7, ",", curses.color_pair(color_pair))
        self.scr.addstr(12, 30, ",", curses.color_pair(color_pair))

        self.scr.addstr(13, 9, ",", curses.color_pair(color_pair))
        self.scr.addstr(13, 28, ",", curses.color_pair(color_pair))

        self.scr.addstr(14, 11, "' - ,  __  , - '",
                        curses.color_pair(color_pair))

        self.scr.move(self.y, self.x)
        self.scr.refresh()
Beispiel #60
0
    def draw(self):
        with self.lock:
            win = self.win
            self.handle_keypress()
            x = LEFT_BORDER_OFFSET
            y = blank_line = count(2)
            my, mx = win.getmaxyx()
            win.erase()
            win.bkgd(' ', curses.color_pair(1))
            win.border()
            win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5))
            next(blank_line)
            win.addstr(next(y), x, self.format_row('UUID', 'TASK',
                                                   'WORKER', 'TIME', 'STATE'),
                       curses.A_BOLD | curses.A_UNDERLINE)
            tasks = self.tasks
            if tasks:
                for row, (uuid, task) in enumerate(tasks):
                    if row > self.display_height:
                        break

                    if task.uuid:
                        lineno = next(y)
                    self.display_task_row(lineno, task)

            # -- Footer
            next(blank_line)
            win.hline(my - 6, x, curses.ACS_HLINE, self.screen_width - 4)

            # Selected Task Info
            if self.selected_task:
                win.addstr(my - 5, x, self.selected_str, curses.A_BOLD)
                info = 'Missing extended info'
                detail = ''
                try:
                    selection = self.state.tasks[self.selected_task]
                except KeyError:
                    pass
                else:
                    info = selection.info()
                    if 'runtime' in info:
                        info['runtime'] = '{0:.2f}'.format(info['runtime'])
                    if 'result' in info:
                        info['result'] = abbr(info['result'], 16)
                    info = ' '.join(
                        '{0}={1}'.format(key, value)
                        for key, value in items(info)
                    )
                    detail = '... -> key i'
                infowin = abbr(info,
                               self.screen_width - len(self.selected_str) - 2,
                               detail)
                win.addstr(my - 5, x + len(self.selected_str), infowin)
                # Make ellipsis bold
                if detail in infowin:
                    detailpos = len(infowin) - len(detail)
                    win.addstr(my - 5, x + len(self.selected_str) + detailpos,
                               detail, curses.A_BOLD)
            else:
                win.addstr(my - 5, x, 'No task selected', curses.A_NORMAL)

            # Workers
            if self.workers:
                win.addstr(my - 4, x, self.online_str, curses.A_BOLD)
                win.addstr(my - 4, x + len(self.online_str),
                           ', '.join(sorted(self.workers)), curses.A_NORMAL)
            else:
                win.addstr(my - 4, x, 'No workers discovered.')

            # Info
            win.addstr(my - 3, x, self.info_str, curses.A_BOLD)
            win.addstr(
                my - 3, x + len(self.info_str),
                STATUS_SCREEN.format(
                    s=self.state,
                    w_alive=len([w for w in values(self.state.workers)
                                 if w.alive]),
                    w_all=len(self.state.workers),
                ),
                curses.A_DIM,
            )

            # Help
            self.safe_add_str(my - 2, x, self.help_title, curses.A_BOLD)
            self.safe_add_str(my - 2, x + len(self.help_title), self.help,
                              curses.A_DIM)
            win.refresh()