Exemple #1
0
def main(scr):
    h, w = scr.getmaxyx()
    hghts = [h // 3 + (1 if 3 - h % 3 <= i else 0) for i in range(3)]
    pr = 0
    wins = []
    for i in hghts:
        wins.append(newwin(i, w, pr, 0))
        pr += i
    for i in range(3):
        wins[i].box(0, 0)
    panels = [new_panel(i) for i in wins]
    update_panels()
    doupdate()
    x = 0
    while x != ord('q'):
        x = scr.getch()
        wn = wins[0]
        wn.addstr(1, 1, "%x" % x)
        wn.addstr(2, 1, repr([
            i for i in dir(wn) if not i.startswith('__')])[:w-3])
        def_prog_mode()
        endwin()
        print(dir(wn))
        reset_prog_mode()
        wins[0].refresh()
Exemple #2
0
 def edit(self, win):
     curses.def_prog_mode()
     curses.endwin()
     run_editor(self.files)
     self.blocks = get_all_blocks(self.files)
     curses.reset_prog_mode()
     self.redraw(win)
Exemple #3
0
def processmenu(menu, parent=None):
  optioncount = len(menu['options'])
  exitmenu = False
  while not exitmenu: #Loop until the user exits the menu
    getin = runmenu(menu, parent)
    if getin == optioncount:
        exitmenu = True
    elif menu['options'][getin]['type'] == COMMAND:
      curses.def_prog_mode()    # save curent curses environment
      os.system('reset')
      if menu['options'][getin]['title'] == 'Pianobar':
        os.system('amixer cset numid=3 1') # Sets audio output on the pi to 3.5mm headphone jack
      screen.clear() #clears previous screen
      os.system(menu['options'][getin]['command']) # run the command
      screen.clear() #clears previous screen on key press and updates display based on pos
      curses.reset_prog_mode()   # reset to 'current' curses environment
      curses.curs_set(1)         # reset doesn't do this right
      curses.curs_set(0)
      os.system('amixer cset numid=3 2') # Sets audio output on the pi back to HDMI
    elif menu['options'][getin]['type'] == MENU:
          screen.clear() #clears previous screen on key press and updates display based on pos
          processmenu(menu['options'][getin], menu) # display the submenu
          screen.clear() #clears previous screen on key press and updates display based on pos
    elif menu['options'][getin]['type'] == EXITMENU:
          exitmenu = True
def launch_game(stdscr, world, settings_dict):
    stdscr.clear()
    try:
        settings_dict = game_main.game_main(stdscr,world, settings_dict)
    except Exception as e:
        curses.reset_shell_mode()
        print('Error occured')
        print(type(e))
        print(e.args)
        tb = traceback.format_exc()
        print(tb)
        print('')
        print('I''m sorry =(. Thank you for playing though.')
        print('')
        print('Typical things that cause this are:')
        print('  > Resizing the window to be too small')
        print('Please don''t do these things')
        input('Press Enter to continue, and the game will return to the main menu.')
        curses.reset_prog_mode()
    finally:
        # Then reboot main setup
        window_setup(stdscr)
        
    # Return the settings dictionary
    return settings_dict
Exemple #5
0
def processmenu(menu, parent=None):
    optioncount = len(menu['options'])
    exitmenu = False
    while not exitmenu:  #Loop until the user exits the menu
        getin = runmenu(menu, parent)
        if getin == optioncount:
            exitmenu = True
        elif menu['options'][getin]['type'] == "COMMAND":
            curses.def_prog_mode()  # save curent curses environment
            os.system('reset')
            screen.clear()  #clears previous screen
            os.system(menu['options'][getin]['command'])  # run the command
            screen.clear(
            )  #clears previous screen on key press and updates display based on pos
            curses.reset_prog_mode()  # reset to 'current' curses environment
            curses.curs_set(1)  # reset doesn't do this right
            curses.curs_set(0)
        elif menu['options'][getin]['type'] == "MENU":
            screen.clear(
            )  #clears previous screen on key press and updates display based on pos
            processmenu(menu['options'][getin], menu)  # display the submenu
            screen.clear(
            )  #clears previous screen on key press and updates display based on pos
        elif menu['options'][getin]['type'] == EXITMENU:
            exitmenu = True
Exemple #6
0
 def clean_up(self):
     self.submenu.join()
     self.menu.clear_screen()
     curses.reset_prog_mode()
     curses.curs_set(1)
     curses.curs_set(0)
     self.menu.resume()
Exemple #7
0
def processmenu(menu, parent=None):
    global screen
    global highlightColor
    global normalColor
    optioncount = len(menu['options'])
    exitmenu = False
    while not exitmenu:
        getin = runmenu(menu, parent)
        if getin == optioncount:
            exitmenu = True
        elif menu['options'][getin]['type'] == COMMAND:
            ###############################
            curses.endwin()
            print "========================================================"
            methodCall = globals()[menu['options'][getin]['command']]
            methodCall()
            print "--------------------------------------------------------"
            raw_input("\nPress \"enter\" to return to the menu...\n")
            ###############################
            screen = curses.initscr()
            screen.clear()
            curses.reset_prog_mode()
            curses.curs_set(1)
            curses.curs_set(0)
        elif menu['options'][getin]['type'] == MENU:
            screen.clear()
            processmenu(menu['options'][getin], menu)
            screen.clear()
        elif menu['options'][getin]['type'] == EXITMENU:
            exitmenu = True
Exemple #8
0
def main():
    """ Entry point for example 12
    """
    screen = curses.initscr()  # Start curses mode
    screen.addstr("Hello World !!!\n")  # Print Hello World
    screen.refresh()  # Print it on to the real screen

    # Wait for user input to see printed message (added during porting)
    screen.getch()

    curses.def_prog_mode()  # Save the tty mode
    curses.endwin()  # End curses mode temporarily

    os.system("/bin/sh")  # Do whatever you like in cooked mode

    curses.reset_prog_mode(
    )  # Return to the previous tty mode stored by def_prog_mode()

    screen.refresh()  # Do refresh() to restore the screen contents
    screen.addstr("Another String\n"
                  )  # Back to curses use the full capabilities of curses
    screen.refresh()

    # Wait for user input to see printed message (added during porting)
    screen.getch()

    curses.endwin()  # End curses mode

    sys.exit(0)
Exemple #9
0
def processmenu(menu, parent=None):
    optioncount = len(menu['options'])
    exitmenu = False
    pm = PropertyManager("Domains/domains.properties")

    jbossHome = pm.getValue("jboss.home")
    controller = pm.getValue("controller")
    user = pm.getValue("user")
    password = pm.getValue("password")
    while not exitmenu: #Loop until the user exits the menu
        getin = runmenu(menu, parent)
        if getin == optioncount:
            exitmenu = True
        elif menu['options'][getin]['type'] == COMMAND:
            curses.def_prog_mode()    # save curent curses environment
            os.system('reset')
            screen.clear() #clears previous screen
            command = menu['options'][getin]['command'] # run the command
            command.execute(jbossHome,controller,user,password)
            screen.clear() #clears previous screen on key press and updates display based on pos
            curses.reset_prog_mode()   # reset to 'current' curses environment
            curses.curs_set(1)         # reset doesn't do this right
            curses.curs_set(0)
        elif menu['options'][getin]['type'] == MENU:
            screen.clear() #clears previous screen on key press and updates display based on pos
            processmenu(menu['options'][getin], menu) # display the submenu
            screen.clear() #clears previous screen on key press and updates display based on pos
        elif menu['options'][getin]['type'] == EXITMENU:
            exitmenu = True
def wrapper_fork(call_function, reset=True):
    pid = os.fork()
    if pid:
        # Parent
        os.waitpid(pid, 0)
        if reset:
            external_reset()
    else:
        locale.setlocale(locale.LC_ALL, '')
        _SCREEN = curses.initscr()
        try:
            curses.start_color()
        except:
            pass
        _SCREEN.keypad(1)
        curses.noecho()
        curses.cbreak()
        curses.def_prog_mode()
        curses.reset_prog_mode()
        return_code = call_function(_SCREEN)
        _SCREEN.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()
        sys.exit(0)
Exemple #11
0
def renderMenu(menu, parent=None):
    global myMenu
    options = len(menu['options'])
    exitMenu = False
    if parent == None:
        menu = myMenu
    while not exitMenu:
        currentPosition = listOptionsInMenu(menu, parent)
        if currentPosition == options:
            exitMenu = True
        elif menu['options'][currentPosition]['type'].upper() == "MENU":
            screen.clear()
            menu = myMenu
            renderMenu(menu['options'][currentPosition], menu)
            screen.clear()
        elif menu['options'][currentPosition]['type'].upper() == "COMMAND":
            screen.clear()
            curses.def_prog_mode()
            os.system('reset')
            os.system(menu['options'][currentPosition]['command'])
            if menu['options'][currentPosition]['wait'] == True:
                print('The job is finished, press Enter to continue...')
                input()
            screen.clear()
            curses.reset_prog_mode()
            curses.curs_set(1)
            curses.curs_set(0)
def wrapper_fork(call_function, reset=True):
    pid = os.fork()
    if pid:
        # Parent
        os.waitpid(pid, 0)
        if reset:
            external_reset()
    else:
        locale.setlocale(locale.LC_ALL, '')
        _SCREEN = curses.initscr()
        try:
            curses.start_color()
        except Exception:
            pass
        _SCREEN.keypad(1)
        curses.noecho()
        curses.cbreak()
        curses.def_prog_mode()
        curses.reset_prog_mode()
        call_function(_SCREEN)
        _SCREEN.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()
        sys.exit(0)
Exemple #13
0
def processmenu(menu, parent=None):
  optioncount = len(menu['options'])
  exitmenu = False
  while not exitmenu: #Loop until the user exits the menu
    getin = runmenu(menu, parent)
    if getin == optioncount:
        exitmenu = True
    elif menu['options'][getin]['type'] == COMMAND:
      curses.def_prog_mode()    # save curent curses environment
      os.system('reset')
      if menu['options'][getin]['title'] == 'Pianobar':
        os.system('amixer cset numid=3 1') # Sets audio output on the pi to 3.5mm headphone jack
      screen.clear() #clears previous screen
      os.system(menu['options'][getin]['command']) # run the command
      screen.clear() #clears previous screen on key press and updates display based on pos
      curses.reset_prog_mode()   # reset to 'current' curses environment
      curses.curs_set(1)         # reset doesn't do this right
      curses.curs_set(0)
      os.system('amixer cset numid=3 2') # Sets audio output on the pi back to HDMI
    elif menu['options'][getin]['type'] == MENU:
          screen.clear() #clears previous screen on key press and updates display based on pos
          processmenu(menu['options'][getin], menu) # display the submenu
          screen.clear() #clears previous screen on key press and updates display based on pos
    elif menu['options'][getin]['type'] == EXITMENU:
          exitmenu = True
    def createStepperProgram(self):
        top = panel.top_panel()
        menu = top.userptr()
        menu.window.clear()
        menu.window.refresh()
        curses.reset_shell_mode()

        prog = []
        build = 1
        speed = 0
        revolutions = 0
        while build:
            while True:
                try:
                    speed = int(raw_input('Enter Speed (-160 - 160 RPM: '))
                    if speed >= -160 and speed <= 160:
                        break
                    else:
                        print "Speed out of range. Try again..."
                except Exception as e:
                    print "Invalid input for speed. Try again..."
                    continue

            while True:
                try:
                    revolutions = abs(float(raw_input('Enter Revolutions: ')))
                    break
                except Exception as e:
                    print "Invalid input for revolutions. Try again..."
                    continue

            while True:
                cont = raw_input(
                    'Would you like to additional steps to your program? (Yes/No)'
                ).lower()
                if cont == "yes" or cont == "y":
                    break
                elif cont == "no" or cont == "n":
                    build = 0
                    break
                else:
                    print "Invalid input... Try again."

            prog.append([speed, revolutions])

        fileName = raw_input('Please enter the name of the program:')

        with open("programs/" + fileName + ".pgm", 'wb') as f:
            pickle.dump(prog, f)

        print "Created file " + fileName
        print tabulate(prog, headers=["speed", "revolutions"])

        raw_input('Hit enter to continue:')

        curses.reset_prog_mode()
        menu.window.clear()
        menu.window.refresh()
        curses.doupdate()
Exemple #15
0
 def restore_teminal(self):
     curses.def_prog_mode()
     curses.endwin()
     try:
         yield
     finally:
         curses.reset_prog_mode()
         self.mainframe.refresh()
Exemple #16
0
 def restore_teminal(self):
     curses.def_prog_mode()
     curses.endwin()
     try:
         yield
     finally:
         curses.reset_prog_mode()
         self.mainframe.refresh()
Exemple #17
0
 def prog_mode(self):
     self.lock.acquire()
     try:
         curses.reset_prog_mode()
         self.active=True
         self.redraw()
     finally:
         self.lock.release()
Exemple #18
0
 def edit_all(self, win):
     curses.def_prog_mode()
     curses.endwin()
     run_editor(self.files)
     self.blockno = 0
     self.blocks = get_all_blocks(self.files)
     curses.reset_prog_mode()
     self.redraw(win)
Exemple #19
0
 def clean_up(self):
     """
     This class overrides this method
     """
     self.menu.clear_screen()
     curses.reset_prog_mode()
     curses.curs_set(1)  # reset doesn't do this right
     curses.curs_set(0)
     self.menu.resume()
Exemple #20
0
	def read_string_readline(self, prompt):
		self.scr.move(self.h, 0)
		self.scr.clrtoeol()
		self.scr.refresh()
		curses.reset_shell_mode()
		s = input(prompt)
		curses.reset_prog_mode()
		self.scr.redrawwin()
		return s
Exemple #21
0
 def clean_up(self):
     """
     This class overrides this method
     """
     self.menu.clear_screen()
     curses.reset_prog_mode()
     curses.curs_set(1)  # reset doesn't do this right
     curses.curs_set(0)
     self.menu.resume()
Exemple #22
0
 def edit(self, win):
     curses.def_prog_mode()
     curses.endwin()
     block = self.blocks[self.blockno]
     run_editor([block.filename])
     self.blocks = get_all_blocks(self.files)
     if self.blockno >= len(self.blocks):
         self.blockno = 0
     curses.reset_prog_mode()
     self.redraw(win)
Exemple #23
0
    def do(self):
        curses.reset_shell_mode()
        subprocess.call(self.path + '/do.sh', shell=True)

        str_end = '[INSTALLER] Task ' + str(
            self.name) + ' finished, press key to continue'
        print('_' * len(str_end) + '\n')
        print(str_end)

        curses.reset_prog_mode()
 def addUser(self):
     top = panel.top_panel()
     menu = top.userptr()
     menu.window.clear()
     menu.window.refresh()
     curses.reset_shell_mode()
     userdb.cliAddUser()
     self.updateAdminMenu()
     curses.reset_prog_mode()
     menu.window.clear()
     menu.window.refresh()
Exemple #25
0
def CallSubShell(subshell):
    """Call this function if you need to execute an external command in a subshell (os.system).  All the usual warnings apply -- the command line will be
    expanded by the shell, so make sure it is safe before passing it to this function."""
    curses.def_prog_mode()
    #curses.endwin() # Probably causes a memory leak.

    rtn = os.system("%s" % (subshell))
    curses.reset_prog_mode()
    if rtn is not 0: return False
    else: return True

    curses.reset_prog_mode()
Exemple #26
0
def CallSubShell(subshell):
    """Call this function if you need to execute an external command in a subshell (os.system).  All the usual warnings apply -- the command line will be
    expanded by the shell, so make sure it is safe before passing it to this function."""
    curses.def_prog_mode()
    #curses.endwin() # Probably causes a memory leak.
    
    rtn = os.system("%s" % (subshell))
    curses.reset_prog_mode()
    if rtn is not 0: return False
    else: return True

    curses.reset_prog_mode()
Exemple #27
0
def init():
    screen=curses.initscr()
    curses.start_color()
    curses.cbreak()
    curses.meta(1)
    curses.noecho()
    curses.nonl()
    curses.def_prog_mode()
    curses.endwin()
    curses.def_shell_mode()
    curses.reset_prog_mode()
    return Screen(screen)
Exemple #28
0
def init():
    screen = curses.initscr()
    curses.start_color()
    curses.cbreak()
    curses.meta(1)
    curses.noecho()
    curses.nonl()
    curses.def_prog_mode()
    curses.endwin()
    curses.def_shell_mode()
    curses.reset_prog_mode()
    return Screen(screen)
 def changePassword(self):
     top = panel.top_panel()
     menu = top.userptr()
     menu.window.clear()
     menu.window.refresh()
     curses.reset_shell_mode()
     userdb.cliChangePassword(self.curUserName, 1)
     userdb.resetPassword(self.curUserName)
     curses.reset_prog_mode()
     menu.window.clear()
     menu.window.refresh()
     self.print_msg(self.curUserName + " Password Changed", 10, 10)
 def addEmail(self):
     top = panel.top_panel()
     menu = top.userptr()
     menu.window.clear()
     menu.window.refresh()
     curses.reset_shell_mode()
     email = raw_input("Email address:")
     userdb.editEmail(self.curUserName, email)
     curses.reset_prog_mode()
     menu.window.clear()
     menu.window.refresh()
     self.print_msg(email + " added", 10, 10)
Exemple #31
0
def shell_cmd(scr, cmd, args):
    scr.clear()
    scr.refresh()
    curses.reset_shell_mode()
    if args == None:
        args = ""
    cmd = cmd[1:]
    os.system("{} {}".format(cmd, args))
    input("\nPress any key to return to program...")
    curses.reset_prog_mode()
    scr.clear()
    cdraw(scr)
Exemple #32
0
def grep(option, target):

    if not target:
        doc = document.Document()
        mode = GrepMode()
        doc.setmode(mode)
    else:
        doc = target.document
        doc.delete(0, doc.endpos())
        mode = doc.mode

    doc.set_title('<grep>')
    mode.grepoption = option.clone()
    mode.encoding = mode.grepoption.encoding
    mode.newlilne = mode.grepoption.newline

    dir = os.path.abspath(os.path.expanduser(option.directory))
    if not os.path.isdir(dir):
        s = 'Cannot find directory `{}`.'.format(dir)
        doc.append(s)
    else:
        try:
            # Restore to cooked mode to accept ^C.
            curses.def_prog_mode()
            curses.endwin()

            try:
                print('Hit ^C to cancel grep.')
                nfiles, nhits = _search(dir, option, doc)
            finally:
                curses.reset_prog_mode()
                kaa.app.mainframe.refresh()

        except KeyboardInterrupt:
            kaa.app.messagebar.set_message('Grep canceled')
            return

        if not nfiles:
            s = 'Cannot find file `{}`.'.format(option.filenames)
            doc.append(s)
        elif not nhits:
            s = 'Cannot find `{}`.'.format(option.text)
            doc.append(s)
        else:
            s = 'Found {} times in {} files'.format(nhits, nfiles)

    kaa.app.messagebar.set_message(s)

    if not target:
        kaa.app.show_doc(doc)
    else:
        target.activate()
Exemple #33
0
 def markLine(self):
     curses.def_prog_mode()    # save curent curses environment
     os.system('reset')
     
     linenum = self.topLineNum + self.highlightLineNum
     pair = self.outputLines[linenum].split(",")
     search_line_num = pair[1][pair[1].rfind(" ") + 1:]
     subprocess.call(shlex.split('vim +' + search_line_num + " ../txt/" + pair[0]))
     
     self.screen.clear() 
     curses.reset_prog_mode()   # reset to 'current' curses environment
     curses.curs_set(1)         # reset doesn't do this right
     curses.curs_set(0)
Exemple #34
0
def replyEmailApp(MainSession, emlData, currentSelect, stdscr):
    curses.def_prog_mode(); stdscr.clear(); stdscr.refresh()
    curses.reset_shell_mode(); print PROC_ORIGINAL
    msgCodec = Proc(MainSession.IMAP.fetchMsg(\
            emlData[3][currentSelect])[1][0][1])        # Fetch original Msg
    toSendMsg = constructReply(MainSession, msgCodec)   # Gather reply MIME
    if toSendMsg == None:        # User cancelled sending
        curses.reset_prog_mode(); stdscr.clear(); stdscr.refresh()
        return emlData
    try: MainSession.SMTP.session.sendmail(toSendMsg["From"], 
            ParseAddr(toSendMsg["To"])[1], toSendMsg.as_string())
    except Exception as err: print SEND_ERR % err; raw_input()
    else:       # If sending is successful, then ask whether save to draft.
Exemple #35
0
def processmenu(menu, parent=None):
    optioncount = len(menu['options'])
    exitmenu = False
    while not exitmenu:  #Loop until the user exits the menu
        getin = runmenu(menu, parent)
        if getin == optioncount:
            exitmenu = True
        elif menu['options'][getin]['type'] == COMMAND:
            # Prepare for command
            os.system("sudo pkill -f python\ viinputdaemon")
            # Stop daemon
            curses.def_prog_mode()  # Save menu status
            os.system('reset')
            screen.clear()

            # Run input daemon with new parameters
            if 'newsbeuter' in menu['options'][getin]['command']:
                subprocess.Popen([
                    "nohup", "sudo", "python", "viinputdaemon.py",
                    "newsbeuter", "&"
                ])
            elif 'man ' in menu['options'][getin]['command']:
                subprocess.Popen([
                    "nohup", "sudo", "python", "viinputdaemon.py", "man", "&"
                ])
            else:
                subprocess.Popen([
                    "nohup", "sudo", "python", "viinputdaemon.py",
                    menu['options'][getin]['command'], "&"
                ])

            # Run Program
            os.system(menu['options'][getin]['command'])

            # Reset Daemon
            os.system("sudo pkill -f python\ viinputdaemon")
            subprocess.Popen(
                ["nohup", "sudo", "python", "viinputdaemon.py", "viui", "&"])
            os.system('clear')

            # Cleanup
            screen.clear()
            curses.reset_prog_mode()
            curses.curs_set(1)
            curses.curs_set(0)
        elif menu['options'][getin]['type'] == MENU:
            screen.clear()
            processmenu(menu['options'][getin], menu)  # display the submenu
            screen.clear()
        elif menu['options'][getin]['type'] == EXITMENU:
            exitmenu = True
Exemple #36
0
        def callback(w, s):
            s = s.strip()
            if s:
                # todo: move these lines to kaa.cui.*
                curses.def_prog_mode()
                curses.endwin()
                try:
                    ret = self._exec_cmd(s)
                finally:
                    curses.reset_prog_mode()
                    wnd.mainframe.refresh()

                from kaa.ui.makeoutput import makeoutputmode
                makeoutputmode.show(ret)
Exemple #37
0
    def markLine(self):
        curses.def_prog_mode()  # save curent curses environment
        os.system('reset')

        linenum = self.topLineNum + self.highlightLineNum
        pair = self.outputLines[linenum].split(",")
        search_line_num = pair[1][pair[1].rfind(" ") + 1:]
        subprocess.call(
            shlex.split('vim +' + search_line_num + " ../txt/" + pair[0]))

        self.screen.clear()
        curses.reset_prog_mode()  # reset to 'current' curses environment
        curses.curs_set(1)  # reset doesn't do this right
        curses.curs_set(0)
Exemple #38
0
def process_selection_menu(menu):
    global screen

    i = runmenu(menu)
    if i != len(menu['options']) :
        curses.endwin()
        screen = curses.initscr()
        screen.clear()
        curses.reset_prog_mode()
        curses.curs_set(1)
        curses.curs_set(0)
        return menu['options'][i]['id']
    else:
        return None
Exemple #39
0
 def launch_edit(self,filename):
     """
     Starts a text editor on a named file
     """
     if sys.platform[:3] == "win":
         editor = os.getenv("EDITOR","edit")
     else:
         editor = os.getenv("EDITOR","vi")
         
     #Save and restore curses mode.
     # =Can't guarantee - curses is availble.
     if self.in_curses: curses.reset_shell_mode()
     os.system(editor +" "+ filename)
     if self.in_curses: curses.reset_prog_mode()
Exemple #40
0
def processmenu(menu, parent=None):
  optioncount = len(menu['options'])
  exitmenu = False
  while not exitmenu: #Loop until the user exits the menu
    getin = runmenu(menu, parent)
    if getin == optioncount:
      exitmenu = True
    elif menu['options'][getin]['type'] == COMMAND:
      curses.def_prog_mode()    # save curent curses environment
      os.system('reset')
      if menu['options'][getin]['title'] == 'Authenticate using local credentials file':
        getcreds()
      #os.system(menu['options'][getin]['command']) # run a bash command if necessary
      if menu['options'][getin]['title'] == 'Enter credentials manually':
        input_user_creds()
      if menu['options'][getin]['title'] == 'List Servers':
        try:
          auth_check()
        except:
          not_authed()
        serverlist()
      if menu['options'][getin]['title'] == 'List My Images':
        getimagelist()
      if menu['options'][getin]['title'] == 'List Base Images':
        getimagelist(base=True)
      if menu['options'][getin]['title'] == 'Show Credentials':
        show_credentials()
      if menu['options'][getin]['title'] == 'List Load Balancers':
        getLBlist()
      if menu['options'][getin]['title'] == 'List Flavors':
        flavorlist()
      if menu['options'][getin]['title'] == 'List Cloud Files':
        getCNlist()
      if menu['options'][getin]['title'] == 'List DNS Records':
        getDNSlist()
      if menu['options'][getin]['title'] == 'List Databases':
        getDBlist()
      # reset to 'current' curses environment
      curses.reset_prog_mode()
      # reset doesn't do this right
      curses.curs_set(1)
      curses.curs_set(0)
    elif menu['options'][getin]['type'] == MENU:
      #clears previous screen on key press and updates display based on pos
      screen.clear() 
      processmenu(menu['options'][getin], menu) # display the submenu
      #clears previous screen on key press and updates display based on pos
      screen.clear()
    elif menu['options'][getin]['type'] == EXITMENU:
      exitmenu = True
Exemple #41
0
        def callback(w, s):
            s = s.strip()
            if s:
                kaa.app.config.hist('makecommand').add(s)
                # todo: move these lines to kaa.cui.*
                curses.def_prog_mode()
                curses.endwin()
                try:
                    ret = self._exec_cmd(s)
                finally:
                    curses.reset_prog_mode()
                    wnd.mainframe.refresh()

                from kaa.ui.makeoutput import makeoutputmode
                makeoutputmode.show(s, ret)
Exemple #42
0
 def suspended(self):
     """
     A context manager that pauses all commands for the duration of the
     execution of the `with` block and allows other applications to take
     over the screen.
     """
     curses.def_prog_mode()
     self.screen.clear_and_refresh()
     self.running.clear()
     try:
         yield
     finally:
         self.running.set()
         curses.reset_prog_mode()
         self.screen.clear_and_refresh()
Exemple #43
0
def run_menu(parent='.'):
    pos = 0  #pos is the zero-based index of the hightlighted menu option. Every time runmenu is called, position returns to 0, when runmenu ends the position is returned and tells the program what opt$
    x = None  #control for while loop, let's you scroll through options until return key is pressed then returns pos to program
    options = [
        i for i in os.listdir(parent)
        if not i.startswith('.') and not i == "menu.py"
    ]
    while True:
        curses.curs_set(0)  # Make cursor invisible
        screen.border(0)
        screen.addstr(1, 2,
                      "Project Euler %s" % '' if parent == '.' else parent,
                      curses.A_STANDOUT)
        i = 0
        for i, entry in enumerate(options):
            if pos == i: textstyle = curses.color_pair(1)  # highlight
            else: textstyle = curses.A_NORMAL
            screen.addstr(4 + i, 4, "%d - %s" % (i + 1, entry), textstyle)
        #screen.addstr(4 + i, 4, "%d - Exit" % i + 1, textstyle)

        x = screen.getch()  # get user input
        if x == ord('j') or x == 258:
            pos += 1
        elif x == ord('k') or x == 259:
            pos -= 1
        elif x == ord('q') or x == ord('h'):
            break
        elif x == ord('\n') or x == ord('l'):
            if parent == '.':
                screen.clear()
                run_menu(options[pos])
                screen.clear()
            else:
                curses.def_prog_mode()
                os.system('reset')
                os.system('cd %s && time python3 %s; cd ..' %
                          (parent, options[pos]))
                os.system('read -n1')
                screen.clear()
                curses.reset_prog_mode()
                curses.curs_set(0)  # Make cursor invisible again
        pos %= len(options)
Exemple #44
0
def processmenu(menu, parent=None):
	optioncount = len(menu['options'])
	exitmenu = False
	while not exitmenu: #Loop until the user exits the menu
		getin = runmenu(menu, parent)
		if getin == optioncount:
			exitmenu = True
		elif menu['options'][getin]['type'] == COMMAND:
			# Prepare for command
			os.system("sudo pkill -f python\ viinputdaemon"); # Stop daemon
			curses.def_prog_mode() # Save menu status
			os.system('reset')
			screen.clear()
	
			# Run input daemon with new parameters
			if 'newsbeuter' in menu['options'][getin]['command']:
				subprocess.Popen(["nohup","sudo","python","viinputdaemon.py","newsbeuter","&"])
			elif 'man ' in menu['options'][getin]['command']:
				subprocess.Popen(["nohup","sudo","python","viinputdaemon.py","man","&"])
			else:
				subprocess.Popen(["nohup","sudo","python","viinputdaemon.py",menu['options'][getin]['command'],"&"])
	
			# Run Program
			os.system(menu['options'][getin]['command'])
			
			# Reset Daemon
			os.system("sudo pkill -f python\ viinputdaemon"); 
			subprocess.Popen(["nohup","sudo","python","viinputdaemon.py","viui","&"])
			os.system('clear')

			# Cleanup
			screen.clear()
			curses.reset_prog_mode()
			curses.curs_set(1)
			curses.curs_set(0)
		elif menu['options'][getin]['type'] == MENU:
			screen.clear()
			processmenu(menu['options'][getin], menu) # display the submenu
			screen.clear()
		elif menu['options'][getin]['type'] == EXITMENU:
			exitmenu = True
def processmenu(menu, parent=None):
  optioncount = len(menu['options'])
  exitmenu = False
  while not exitmenu: #Loop until the user exits the menu
    getin = runmenu(menu, parent)
    if getin == optioncount:
        exitmenu = True
    elif menu['options'][getin]['type'] == COMMAND:
      curses.def_prog_mode()    # save curent curses environment
      os.system('reset')
      screen.clear() #clears previous screen
      os.system(menu['options'][getin]['command']) # run the command
      screen.clear() #clears previous screen on key press and updates display based on pos
      curses.reset_prog_mode()   # reset to 'current' curses environment
      curses.curs_set(1)         # reset doesn't do this right
      curses.curs_set(0)
    elif menu['options'][getin]['type'] == MENU:
          screen.clear() #clears previous screen on key press and updates display based on pos
          processmenu(menu['options'][getin], menu) # display the submenu
          screen.clear() #clears previous screen on key press and updates display based on pos
    elif menu['options'][getin]['type'] == EXITMENU:
          exitmenu = True
Exemple #46
0
    def update(self, clear=True):
        curses.def_prog_mode()
        curses.reset_shell_mode()

        sys.stdout.write('\033[2J')
        sys.stdout.write('\033[H')

        def bool_map(v):
            return "On" if v else "Off"

        sys.stdout.write(
            "[a]ntialiasing: {} [d]ither: {} [f]it horizontal: {}\n".format(
                bool_map(self.antialiasing), bool_map(self.dither),
                bool_map(self.fit)))

        for i in range(
                self.start_display_at, self.start_display_at +
                min(len(self.values) - self.start_display_at,
                    self.height - 2)):
            sys.stdout.write(self.values[i])
            sys.stdout.write("\n")

        curses.reset_prog_mode()
Exemple #47
0
    def processmenu(self, menu, parent = None):
        optioncount = len(menu['options'])
        exitmenu = False

        while not exitmenu: #Loop until the user exits the menu
            getin = self.runmenu(menu, parent)

            if getin == optioncount:
                exitmenu = True
            elif menu['options'][getin]['type'] == self.COMMAND:
                curses.def_prog_mode()    # Save curent curses environment
                os.system('reset')
                if menu['options'][getin]['command'] == 'print_graph':
                    self._graph.print_data()
                elif menu['options'][getin]['command'] == 'dijkstra':
                    self._dijkstra.run()
                    print('Iterations: %d' % self._dijkstra.iterations)
                    print('Comparison: %d' % self._dijkstra.comparison)
                    print('Moviments: %d' % self._dijkstra.moviments)
                elif menu['options'][getin]['command'] == 'a_star':
                    self._a_star.run()
                    print('Iterations: %d' % self._a_star.iterations)
                    print('Comparison: %d' % self._a_star.comparison)
                    print('Moviments: %d' % self._a_star.moviments)

                print('Press ENTER key to return.')
                input()
                self.screen.clear() # Clears previous screen on key press and updates display based on pos
                curses.reset_prog_mode()   # Reset to 'current' curses environment
                curses.curs_set(1)         # Reset doesn't do this right
                curses.curs_set(0)
            elif menu['options'][getin]['type'] == self.MENU:
                self.screen.clear() # Clears previous screen on key press and updates display based on pos
                processmenu(menu['options'][getin], menu) # display the submenu
                self.screen.clear() # Clears previous screen on key press and updates display based on pos
            elif menu['options'][getin]['type'] == self.EXITMENU:
                exitmenu = True
Exemple #48
0
    def processmenu(self, menu, parent=None):
        optioncount = len(menu['options'])
        exitmenu = False

        while not exitmenu:
            selected = self.runmenu(menu, parent)

            if selected == optioncount:
                exitmenu = True

            elif menu['options'][selected]['type'] == "menu":
                self.stdscr.clear()
                self.processmenu(menu['options'][selected], menu)
                self.stdscr.clear()

            elif menu['options'][selected]['type'] == "command":
                curses.def_prog_mode()
                os.system('reset')
                username = raw_input('Username: '******'ssh ' + username + '@' +
                          menu['options'][selected]['ip_addr'])
                self.stdscr.clear()
                curses.reset_prog_mode()
                curses.curs_set(1)
                curses.curs_set(0)

            elif menu['options'][selected]['type'] == "prompt":
                curses.def_prog_mode()
                os.system('reset')
                ip_address = raw_input('IP / Hostname: ')
                os.system('clear')
                username = raw_input('Username: '******'ssh ' + username + '@' + ip_address)
                self.stdscr.clear()
                curses.reset_prog_mode()
                curses.curs_set(1)
                curses.curs_set(0)
Exemple #49
0
def processmenu(menu, parent = None):
  optioncount = len(menu['options'])
  exitmenu = False

  while not exitmenu:
    getin = runmenu(menu, parent)

    if getin == optioncount:
        exitmenu = True
    elif menu['options'][getin]['type'] == COMMAND:
      curses.def_prog_mode()
      os.system('reset')
      screen.clear()
      os.system(menu['options'][getin]['command'])
      screen.clear()
      curses.reset_prog_mode()
      curses.curs_set(1)
      curses.curs_set(0)
    elif menu['options'][getin]['type'] == MENU:
          screen.clear()
          processmenu(menu['options'][getin], menu)
          screen.clear()
    elif menu['options'][getin]['type'] == EXITMENU:
          exitmenu = True
Exemple #50
0
    def processmenu(menu_data, parent=None):
        optioncount = len(menu_data['options'])
        exitmenu = False

        while not exitmenu:
            getin = runmenu(menu_data, parent)

            if getin == optioncount:
                exitmenu = True
            elif menu_data['options'][getin]['type'] == "command":
                curses.def_prog_mode()
                os.system('reset')
                screen.clear()
                os.system(menu_data['options'][getin]['command'])
                screen.clear()
                curses.reset_prog_mode()
                curses.curs_set(1)
                curses.curs_set(0)
            elif menu_data['options'][getin]['type'] == "menu":
                screen.clear()
                processmenu(menu_data['options'][getin], menu_data)
                screen.clear()
            elif menu_data['options'][getin]['type'] == "exitmenu":
                exitmenu = True
Exemple #51
0
def emailLister(MainSession, msgNOs, stdscr):
    curses.def_shell_mode(); curses.reset_prog_mode()    # Back to curses
    curses.curs_set(0); stdscr.clear(); stdscr.refresh() # Init curses
    maxY, maxX = stdscr.getmaxyx(); stdscr.clear(); stdscr.box()
    stdscr.addstr(0, max(0, (maxX - len(JIMMY_MAIL)) / 2), JIMMY_MAIL)
    stdscr.addstr(min(2,maxY-1),max(0,(maxX-len(PLEASE_WAIT))/2),PLEASE_WAIT)
    stdscr.refresh()
    emlData = fetchList(MainSession, msgNOs, stdscr)    # Retrieve Messages
    (maxDigit,flag,event,currentTop,currentSelect)=(digitNo(len(msgNOs)),
            True, None, 0, 0)
    while flag:
        maxY, maxX = stdscr.getmaxyx(); stdscr.clear(); stdscr.box()
        stdscr.addstr(0, max(0, (maxX - len(JIMMY_MAIL)) / 2), JIMMY_MAIL)
        # Draw the Email list by calling drawList().
        drawList(MainSession, stdscr, emlData, currentTop, currentSelect)
        # Draw the footnotes by calling drawInstruction().
        drawInstruction(MainSession, stdscr)
        event = stdscr.getch();
        # Respond to key stroke events.
        (flag, event, currentSelect, currentTop, maxY, msgNOs, emlData) =\
            emailListResponder(event, MainSession, emlData, currentSelect,
                    currentTop, maxY, msgNOs, flag, stdscr)
    stdscr.clear(); stdscr.refresh()
    curses.reset_shell_mode(); curses.curs_set(1)   # Restore to shell mode.
Exemple #52
0
def processmenu(path_dirs, menu, parent=None):
    """ processes the execution of the interaction sent to the menu """
    optioncount = len(menu['options'])
    exitmenu = False
    while not exitmenu:
        getin = runmenu(menu, parent)
        if getin == optioncount:
            exitmenu = True
        elif menu['options'][getin]['type'] in [PROMPT]:
            curses.def_prog_mode()
            os.system('reset')
            screen.clear()
            if prompt():
                os.system(menu['options'][getin]['command'])

            screen.clear()
            curses.reset_prog_mode()
            try:
                curses.curs_set(1)
                curses.curs_set(0)
            except Exception as e:
                pass
        elif menu['options'][getin]['type'] in [COMMAND, CONFIRM]:
            curses.def_prog_mode()
            os.system('reset')
            screen.clear()
            os.system(menu['options'][getin]['command'])

            if menu['options'][getin]['type'] == CONFIRM:
                if menu['title'] == "Remove Plugins":
                    exitmenu = True
                confirm()

            screen.clear()
            curses.reset_prog_mode()
            try:
                curses.curs_set(1)
                curses.curs_set(0)
            except Exception as e:
                pass
        elif menu['options'][getin]['type'] in [INFO, DISPLAY]:
            pass
        elif menu['options'][getin]['type'] == INPUT:
            if menu['options'][getin]['title'] == "Add Plugins":
                plugin_url = get_param("Enter the HTTPS Git URL that contains the new plugins, e.g. https://github.com/CyberReboot/vent-plugins.git:")
                curses.def_prog_mode()
                os.system('reset')
                screen.clear()
                if not "https://" in plugin_url:
                    os.system("echo No plugins added, url is not formatted correctly.")
                    os.system("echo Please use a git url, e.g. https://github.com/CyberReboot/vent-plugins.git")
                else:
                    os.system("python2.7 "+path_dirs.data_dir+"plugin_parser.py add_plugins "+plugin_url+" "+path_dirs.base_dir+" "+path_dirs.data_dir)
                confirm()
                screen.clear()
                os.execl(sys.executable, sys.executable, *sys.argv)
            elif menu['options'][getin]['title'] == "Files":
                filename = get_param("Enter the name of the processed file to lookup logs for:")
                curses.def_prog_mode()
                os.system('reset')
                os.system("clear")
                screen.clear()
                try:
                    # ensure directory exists
                    os.system("if [ ! -d /tmp/vent_logs ]; then mkdir /tmp/vent_logs; fi;")
                    # check logs exist for that file
                    found = call("python2.7 "+path_dirs.info_dir+"get_logs.py -f "+filename+" | grep "+filename, shell=True)
                    if found == 0:
                        # print logs
                        os.system("python2.7 "+path_dirs.info_dir+"get_logs.py -f "+filename+" | tee /tmp/vent_logs/vent_file_"+filename+" | less")
                    else:
                        os.system("echo \"No logs found for that file.\" | less")
                except Exception as e:
                    os.system("echo \"Error retrieving logs for that file.\" | less")
                screen.clear()
                curses.reset_prog_mode()
                try:
                    curses.curs_set(1)
                    curses.curs_set(0)
                except Exception as e:
                    pass
        elif menu['options'][getin]['type'] == MENU:
            if menu['options'][getin]['title'] == "Remove Plugins":
                screen.clear()
                installed_plugins = get_installed_plugin_repos(path_dirs, CONFIRM, "remove")
                processmenu(path_dirs, installed_plugins, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Show Installed Plugins":
                screen.clear()
                installed_plugins = get_installed_plugin_repos(path_dirs, DISPLAY, "")
                processmenu(path_dirs, installed_plugins, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Update Plugins":
                screen.clear()
                installed_plugins = get_installed_plugin_repos(path_dirs, CONFIRM, "update")
                processmenu(path_dirs, installed_plugins, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Status":
                screen.clear()
                plugins = get_plugin_status(path_dirs)
                processmenu(path_dirs, plugins, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Services":
                screen.clear()
                containers = get_container_menu(path_dirs)
                processmenu(path_dirs, containers, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Namespaces":
                screen.clear()
                namespaces = get_namespace_menu(path_dirs)
                processmenu(path_dirs, namespaces, menu)
                screen.clear()
            else:
                screen.clear()
                processmenu(path_dirs, menu['options'][getin], menu)
                screen.clear()
        elif menu['options'][getin]['type'] == EXITMENU:
            exitmenu = True
Exemple #53
0
def processmenu(path_dirs, menu, parent=None):
    optioncount = len(menu['options'])
    exitmenu = False
    while not exitmenu:
        getin = runmenu(menu, parent)
        if getin == optioncount:
            exitmenu = True
        elif menu['options'][getin]['type'] == COMMAND:
            curses.def_prog_mode()
            os.system('reset')
            screen.clear()
            if "&&" in menu['options'][getin]['command']:
                commands = menu['options'][getin]['command'].split("&&")
                for c in commands:
                    success = os.system(c)
                    if success == 0:
                        continue
                    else:
                        print "FAILED command: " + c
                        break
            else:
                os.system(menu['options'][getin]['command'])
            screen.clear()
            curses.reset_prog_mode()
            curses.curs_set(1)
            curses.curs_set(0)
        elif menu['options'][getin]['type'] == INFO2:
            curses.def_prog_mode()
            os.system('reset')
            screen.clear()
            if "&&" in menu['options'][getin]['command']:
                commands = menu['options'][getin]['command'].split("&&")
                for c in commands:
                    success = os.system(c)
                    if success == 0:
                        continue
                    else:
                        print "FAILED command: " + c
                        break
            else:
                os.system(menu['options'][getin]['command'])
            if menu['title'] == "Remove Plugins":
                update_images(path_dirs)
                exitmenu = True
            elif menu['title'] == "Update Plugins":
                update_images(path_dirs)
                os.system("/bin/sh /data/build_images.sh")
            confirm()
            screen.clear()
            curses.reset_prog_mode()
            curses.curs_set(1)
            curses.curs_set(0)
        # !! TODO
        elif menu['options'][getin]['type'] == INFO:
            pass
        elif menu['options'][getin]['type'] == DISPLAY:
            pass
        # !! TODO
        elif menu['options'][getin]['type'] == SETTING:
            curses.def_prog_mode()
            os.system('reset')
            screen.clear()
            os.system(menu['options'][getin]['command'])
            screen.clear()
            curses.reset_prog_mode()
            curses.curs_set(1)
            curses.curs_set(0)
        elif menu['options'][getin]['type'] == INPUT:
            if menu['options'][getin]['title'] == "Add Plugins":
                plugin_url = get_param("Enter the HTTPS Git URL that contains the new plugins, e.g. https://github.com/CyberReboot/vent-plugins.git")
                curses.def_prog_mode()
                os.system('reset')
                screen.clear()
                if not "https://" in plugin_url:
                    os.system("echo No plugins added, url is not formatted correctly.")
                    os.system("echo Please use a git url, e.g. https://github.com/CyberReboot/vent-plugins.git")
                else:
                    os.system("python2.7 /data/plugin_parser.py add_plugins "+plugin_url)
                confirm()
                screen.clear()
                os.execl(sys.executable, sys.executable, *sys.argv)
        elif menu['options'][getin]['type'] == MENU:
            if menu['options'][getin]['title'] == "Remove Plugins":
                screen.clear()
                installed_plugins = get_installed_plugin_repos(path_dirs, INFO2, "remove")
                processmenu(path_dirs, installed_plugins, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Show Installed Plugins":
                screen.clear()
                installed_plugins = get_installed_plugin_repos(path_dirs, DISPLAY, "")
                processmenu(path_dirs, installed_plugins, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Update Plugins":
                screen.clear()
                installed_plugins = get_installed_plugin_repos(path_dirs, INFO2, "update")
                processmenu(path_dirs, installed_plugins, menu)
                screen.clear()
            elif menu['options'][getin]['title'] == "Status":
                screen.clear()
                plugins = get_plugin_status(path_dirs)
                processmenu(path_dirs, plugins, menu)
                screen.clear()
            else:
                screen.clear()
                processmenu(path_dirs, menu['options'][getin], menu)
                screen.clear()
        elif menu['options'][getin]['type'] == EXITMENU:
            exitmenu = True
Exemple #54
0
def hyltMain (meta_screen, starting_filename):
   """The core Hylt functionality.  Contains the main input and
   display loops, lots of initialization, and so on.
   """

   curses.curs_set(0)

   # Remember: Parameters are in the order of (y, x).
   meta_y, meta_x = meta_screen.getmaxyx()
   core_state = {"y": meta_y, "x": meta_x}

   # Change to the base path.
   if "" != os.path.dirname (starting_filename):
      os.chdir (os.path.dirname (starting_filename))
   core_state["curr_base_path"] = ""
   

   # There are three windows: a top status bar, a primary screen, and a bottom
   # status bar.  There is also the main screen, of course.  Create them.
   top = meta_screen.subwin (1, meta_x, 0, 0)
   main = meta_screen.subwin (meta_y - 2, meta_x, 1, 0)
   bottom = meta_screen.subwin (1, meta_x, meta_y - 1, 0)

   # Read in the configuration.
   config = core_state["config"] = generateConfiguration ()

   editor = config["pyui"]["editor"]

   # Okay.  History's actually a bad name for this right now, but it'll have
   # to do.  This is a list of pages; it normally tracks history, but can
   # also track search results.  At the beginning, the only element in the
   # history is the starting page; others will be added, subtracted, etc.
   core_state["history"] = []
   historyAdd(core_state, os.path.basename (starting_filename))
   core_state["history_position"] = 0

   fresh_page = True
   done = False

   curses.def_prog_mode ()

   main_needs_redraw = True

   while not done:
      current_loc = core_state["history"][core_state["history_position"]]
      if fresh_page:

         filename = current_loc["filename"]
         core_state["curr_base_path"] = os.path.dirname (filename)

         readHyltFile (filename, core_state) 
#        debugPrintPage (core_state["data_array"])

         core_state["title"] = generateTitle (filename)

         # Links can be removed between page loads, and the history
         # jumper defaults to link 0, which doesn't exist on a page
         # with no links.  In either case, we're safe if we just
         # change the link count to something more appropriate.
         current_loc["selected_link"] = min(current_loc["selected_link"], core_state["link_count"] - 1)
         if current_loc["selected_link"] == -1:
            current_loc["selected_link"] = None
     
         dir_delta = 1
         fresh_page = False
         main_needs_redraw = True
         displayHeader (top, core_state)
         displayLinkInfo (bottom, core_state)

      fixCursorCoords (core_state)
      if main_needs_redraw:
         displayPage (main, core_state)
      curses.doupdate ()
      keypress = meta_screen.getch()
      if ord ('q') == keypress:
         done = True
      elif ord ('h') == keypress:
         current_loc["cx"] -= min (max (1, meta_x / 2), 8)
         main_needs_redraw = True
      elif ord ('j') == keypress:
         current_loc["cy"] += min (max (1, meta_x / 2), 8)
         main_needs_redraw = True
      elif ord ('k') == keypress:
         current_loc["cy"] -= min (max (1, meta_x / 2), 8)
         main_needs_redraw = True
      elif ord ('l') == keypress:
         current_loc["cx"] += min (max (1, meta_x / 2), 8)
         main_needs_redraw = True
      elif ord ('x') == keypress:
         exportToHTML (filename[:-4] + "html",
          core_state["data_array"], core_state["link_list"])
         displayNote (bottom, "Exported to '" + filename[:-4]
          + "html' ...", core_state["x"])
      elif curses.KEY_NPAGE == keypress:
         current_loc["cy"] += meta_y - 4
         main_needs_redraw = True
      elif curses.KEY_PPAGE == keypress:
         current_loc["cy"] -= meta_y - 4
         main_needs_redraw = True
      elif ord ('[') == keypress:
         current_loc["cx"] -= meta_x - 4
         main_needs_redraw = True
      elif ord (']') == keypress:
         current_loc["cx"] += meta_x - 4
         main_needs_redraw = True
      elif ord ('r') == keypress:
         fresh_page = True

      # Extended regular expression based pathname matching, working directory
      # tree breadth-first traversing and search result based forward page
      # history list creating 'go' feature (note: full room service is not
      # included in trial version)
      elif ord ('g') == keypress:
         result = smartGo(bottom, core_state)
         if len(result):
            historyCut (core_state)
            for page in result:
               historyAdd (core_state, page)
            historyMove (core_state, 1)
            fresh_page = True
         else:
            displayNote(bottom, "No matching files found", core_state["x"] - 1)
         
      elif (curses.KEY_LEFT == keypress or curses.KEY_BACKSPACE == keypress or
       ord (',') == keypress):
         if historyMove (core_state, -1):
            fresh_page = True

      elif ord ('.') == keypress:
         if historyMove (core_state, 1):
            fresh_page = True

      elif ord ('e') == keypress:
         if config["collection"]["editable"]:
            invokeEditor (editor, filename)

            curses.reset_prog_mode ()
            curses.curs_set(1)
            curses.curs_set(0)
            fresh_page = True
            curr_loc_info = None

      elif ord ('d') == keypress:
         if os.path.isfile (config["pyui"]["documentation_root"]):
            current_directory = os.getcwd ()
            hyltMain (meta_screen,config["pyui"]["documentation_root"])
            os.chdir (current_directory)
         
      elif ord ('?') == keypress:
         if os.path.isfile (config["pyui"]["keyboard_reference"]):
            current_directory = os.getcwd ()
            hyltMain (meta_screen,config["pyui"]["keyboard_reference"])
            os.chdir (current_directory)

      # Don't even bother with link actions if there are no links.
      elif core_state["link_count"] > 0:
         if curses.KEY_UP == keypress:
            if current_loc["selected_link"] == 0:
               current_loc["cy"] -= min (max (1, meta_x / 2), 8)
               dir_delta = -1
            else:
               current_loc["selected_link"] -= 1
               moveCursorForLink (core_state, -1)
               displayLinkInfo (bottom, core_state)
            main_needs_redraw = True

         elif curses.KEY_DOWN == keypress:
            if current_loc["selected_link"] == core_state["link_count"] - 1:
               current_loc["cy"] += min (max (1, meta_x / 2), 8)
               dir_delta = -1
            else:
               current_loc["selected_link"] += 1
               moveCursorForLink (core_state, 1)
               displayLinkInfo (bottom, core_state)
            main_needs_redraw = True

         elif ord (' ') == keypress:
            moveCursorForLink (core_state, dir_delta)
            main_needs_redraw = True

         elif ord ('E') == keypress:
            if config["collection"]["editable"]:
               dest = os.path.join (core_state["curr_base_path"],
                core_state["link_list"][current_loc["selected_link"]])

               invokeEditor (editor, dest)

               curses.reset_prog_mode ()
               curses.curs_set(1)
               curses.curs_set(0)
               main_needs_redraw = True
               displayHeader (top, core_state)
               displayLinkInfo (bottom, core_state)

         elif (curses.KEY_RIGHT == keypress or 10 == keypress or
          curses.KEY_ENTER == keypress):
         
            # The big one--jump to a new Hylt page.  First, make sure it's a
            # real page.
            rel_name = core_state["link_list"][current_loc["selected_link"]]
            real_path = os.path.normpath (os.path.join (
             core_state["curr_base_path"], rel_name))
            if os.path.isfile (real_path):
               historyCut (core_state)
               historyAdd (core_state, real_path)
               historyMove (core_state, 1)
               fresh_page = True
            else:
               displayNote (bottom, "|" + rel_name +
                "| not found. Do you want to create this file? [y/N] ",
                core_state["x"] - 1)
               response = bottom.getch (0, 0)
               if ord ('y') == response or ord ('Y') == response:
                  invokeEditor (editor, real_path)

                  curses.reset_prog_mode ()
                  curses.curs_set(1)
                  curses.curs_set(0)
               displayNote(bottom, real_path, core_state["x"] - 1)
Exemple #55
0
 def resume(self):
     curses.reset_prog_mode()
Exemple #56
0
def config():
    global screen, items

    screen.clear()
    curses.curs_set(1)         # reset doesn't do this right
    curses.curs_set(0)

    item_map = {}
    for item in items:
        item_map[item['name']] = item['selected']

    devnull = open(os.devnull, 'wb')
    pos = 0

    if item_map['Vim']:
        pos += 1

        screen.addstr(pos, 2, 'Configuring Vim...')
        screen.refresh()

        subprocess.call('curl melvon.com/config/vim.tar.gz > vim.tar.gz', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('tar xzf vim.tar.gz -C ~', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('rm -rf vim.tar.gz', shell=True, stdout=devnull, stderr=devnull)
        screen.addstr(pos, 2, 'Configuring Vim... Done')

    if item_map['MacVim']:
        pos += 1

        screen.addstr(pos, 2, 'Installing MacVim...')
        screen.refresh()

        subprocess.call('brew install wget', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('wget https://github.com/b4winckler/macvim/releases/download/snapshot-73/MacVim-snapshot-73-Mavericks.tbz', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('tar xjf MacVim-snapshot-73-Mavericks.tbz', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('mv MacVim-snapshot-73/MacVim.app /Applications/MacVim.app', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('mv MacVim-snapshot-73/mvim /usr/local/bin', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('ln -s /usr/local/bin/mvim /usr/local/bin/gvim', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('rm -r MacVim-snapshot-73 MacVim-snapshot-73-Mavericks.tbz', shell=True, stdout=devnull, stderr=devnull)

        screen.addstr(pos, 2, 'Installing MacVim... Done')

    if item_map['Slate']:
        pos += 1

        screen.addstr(pos, 2, 'Installing Slate...')
        screen.refresh()

        subprocess.call('curl http://slate.ninjamonkeysoftware.com/versions/slate-latest.tar.gz > slate.tar.gz', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('tar xzf slate.tar.gz', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('mv Slate.app /Applications/Slate.app', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('open /Applications/Slate.app', shell=True, stdout=devnull, stderr=devnull)
        subprocess.call('rm slate.tar.gz', shell=True, stdout=devnull, stderr=devnull)

        screen.addstr(pos, 2, 'Installing Slate... Done')

        pos += 1
        screen.addstr(pos, 2, 'Configuring Slate...')
        screen.refresh()

        subprocess.call('curl melvon.com/config/.slate > ~/.slate', shell=True, stdout=devnull, stderr=devnull)

        screen.addstr(pos, 2, 'Configuring Slate... Done')

    if item_map['Homebrew']:
        pos += 1

        screen.addstr(pos, 2, 'Installing Homebrew...')

        curses.def_prog_mode()
        os.system('ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"')
        curses.reset_prog_mode()   # reset to 'current' curses environment
        curses.curs_set(1)         # reset doesn't do this right
        curses.curs_set(0)

        screen.addstr(pos, 2, 'Installing Homebrew... Done')

    pos += 1
    screen.addstr(pos, 2, 'Press any key to finish')
    screen.getch()
Exemple #57
0
def hyltMain (meta_screen, starting_filename):

   curses.curs_set(0)

# Remember: Parameters in the order of (y, x).
   meta_y, meta_x = meta_screen.getmaxyx()
   core_state = {"y": meta_y, "x": meta_x}

# Keep the "base path", as all Hylt links are relative.
# TODO: Keep people from backing out of the base path using .. or the like.
   core_state["base_path"] = os.path.dirname (starting_filename)
   filename = os.path.basename (starting_filename)
   

# There are three windows: a top status bar, a primary screen, and a bottom
# status bar.  There is also the main screen, of course.  Create them.
   top = meta_screen.subwin (1, meta_x, 0, 0)
   main = meta_screen.subwin (meta_y - 2, meta_x, 1, 0)
   bottom = meta_screen.subwin (1, meta_x, meta_y - 1, 0)

   window_dict = {
      "top": {"w": top, "r": True},
      "main": {"w": main, "r": True},
      "bottom": {"w": bottom, "r": True}
   }

   core_state["history"] = []

   fresh_page = True
   done = False

   curses.def_prog_mode ()

   while not done:

      if fresh_page:
         readHyltFile (filename, core_state) 

         core_state["title"] = generateTitle (filename)
         core_state["cx"] = 0
         core_state["cy"] = 0
         if core_state["link_count"] > 0:
            core_state["selected_link"] = 0
         else:
            core_state["selected_link"] = None
     
         window_dict["top"]["r"] = True
         window_dict["main"]["r"] = True
         window_dict["bottom"]["r"] = True
         dir_delta = 1
         fresh_page = False

      fixCursorCoords (core_state)
      if True == window_dict["top"]["r"]:
         displayHeader (top, core_state)
      if True == window_dict["main"]["r"]:
         displayPage (main, core_state)
      if True == window_dict["bottom"]["r"]:
         displayLinkInfo (bottom, core_state)
      redrawWindows (window_dict)
      keypress = meta_screen.getch()
      if ord ('q') == keypress:
         done = True
      elif ord ('h') == keypress:
         core_state["cx"] -= min (max (1, meta_x / 2), 8)
         window_dict["main"]["r"] = True
      elif ord ('j') == keypress:
         core_state["cy"] += min (max (1, meta_x / 2), 8)
         window_dict["main"]["r"] = True
      elif ord ('k') == keypress:
         core_state["cy"] -= min (max (1, meta_x / 2), 8)
         window_dict["main"]["r"] = True
      elif ord ('l') == keypress:
         core_state["cx"] += min (max (1, meta_x / 2), 8)
         window_dict["main"]["r"] = True
      elif curses.KEY_NPAGE == keypress:
         core_state["cy"] += meta_y - 4
         window_dict["main"]["r"] = True
      elif curses.KEY_PPAGE == keypress:
         core_state["cy"] -= meta_y - 4
         window_dict["main"]["r"] = True
      elif ord ('r') == keypress:
         fresh_page = True

      elif curses.KEY_LEFT == keypress:
         if len (core_state["history"]) > 0:
            filename = core_state["history"][-1]
            core_state["history"].pop ()
            fresh_page = True

# Don't even bother with arrow keys other than back unless link count > 0.
      elif core_state["link_count"] > 0:
         if curses.KEY_UP == keypress:
            if core_state["selected_link"] == 0:
               core_state["cy"] -= min (max (1, meta_x / 2), 8)
               dir_delta = -1
            else:
               core_state["selected_link"] -= 1
               moveCursorForLink (core_state, -1)
               window_dict["bottom"]["r"] = True
            window_dict["main"]["r"] = True

         elif curses.KEY_DOWN == keypress:
            if core_state["selected_link"] == core_state["link_count"] - 1:
               core_state["cy"] += min (max (1, meta_x / 2), 8)
               dir_delta = -1
            else:
               core_state["selected_link"] += 1
               moveCursorForLink (core_state, 1)
               window_dict["bottom"]["r"] = True

            window_dict["main"]["r"] = True

         elif ord (' ') == keypress:
            moveCursorForLink (core_state, dir_delta)
            window_dict["main"]["r"] = True

         elif ord ('e') == keypress:
            if None != os.getenv ("EDITOR", None):
               rel_name = core_state["link_list"][core_state["selected_link"]]
               real_filename = os.path.join (core_state["base_path"], rel_name)
               os.system (os.getenv ("EDITOR") + " \"" + real_filename + "\"")

               curses.reset_prog_mode ()
               curses.curs_set(1)
               curses.curs_set(0)
               window_dict["top"]["r"] = True
               window_dict["main"]["r"] = True
               window_dict["bottom"]["r"] = True

         elif ord ('E') == keypress:
            if None != os.getenv ("EDITOR", None):
               real_filename = os.path.join (core_state["base_path"], filename)
               os.system (os.getenv ("EDITOR") + " \"" + real_filename + "\"")
              
               curses.reset_prog_mode ()
               curses.curs_set(1)
               curses.curs_set(0)
               fresh_page = True

         elif curses.KEY_RIGHT == keypress:
# The big one--jump to a new Hylt page.  First, make sure it's a real page.
            rel_name = core_state["link_list"][core_state["selected_link"]]
            real_filename = os.path.join (core_state["base_path"], rel_name)
            if os.path.isfile (real_filename):
# Go!  Add this page to the history so we can come back.
               core_state["history"].append (filename)
               filename = rel_name
               fresh_page = True
            else:
               noteMissingPage (bottom, rel_name, core_state["x"])
               window_dict["bottom"]["r"] = True