def choice(cscope_out):

  # TODO why isn't this in TM_SUPPORT_PATH??
  # sys.path.append(os.environ['TM_SUPPORT_PATH'])
  sys.path.append('/Applications/TextMate.app/Contents/SharedSupport/Support/lib')
  import dialog

  paths = []
  for i in cscope_out.readlines():    
    path, func, line, rest = i.split(' ', 3)
    
    # filter out current file
    if path in os.environ['TM_FILEPATH'] and line == os.environ['TM_LINE_NUMBER']:
      continue    
    
    full = (path, line)
    paths.append((path + ':' + line, full))
      
  if not paths:
    raise LookupError
  
  # TODO sort global def to top, local appearances
  paths.sort(key=lambda x: x[0])
  
  choice = dialog.menu(paths)
  
  if not choice:
    raise TypeError
  
  return choice
def choice_menu(cscope_out):
    """
    Display a dialog menu in TextMate with Cscope's output and wait for the
    user to choose a file to open.
    """
    paths = []
    for line in cscope_out:
        # TODO: What if the file has a space in its name? Switch to regexp?
        path, func, line, rest = line.split(' ', 3)
    
        # Filter out current file
        if path in os.environ['TM_FILEPATH'] and line == os.environ['TM_LINE_NUMBER']:
            continue    
    
        full = (path, line)
        paths.append((path + ':' + line, full))
      
    if not paths:
        raise LookupError
  
    # TODO sort global def to top, local appearances
    paths.sort(key=lambda x: x[0])
  
    # Display menu dialog in TextMate and wait for a choice
    choice = dialog.menu(paths)
  
    if not choice:
        raise TypeError
  
    return choice
Exemple #3
0
def frame():
    global g_paths
    global g_path
    choice = None

    # display the current frame and get the user's choice.
    choice = dialog.menu(g_frame.title, g_frame.description, g_frame.list)

    # did the user want to go back?
    if choice == None:
        g_paths.pop(len(g_paths) - 1)

        if len(g_paths) == 0:
            sys.exit(0)

        g_path = g_paths[len(g_paths) - 1]

        return

    # if the choice is a subframe, then go to it.
    if g_frame.entries[choice].type == TYPE_FRAME:
        g_path = g_frame.entries[choice].path
        g_paths.append(g_path)
    # otherwise, ask the user to enter a new value for the variable.
    elif g_frame.entries[choice].type == TYPE_VARIABLE:
        variable(choice)
Exemple #4
0
def main():
    cur_file = os.environ.get("TM_FILEPATH")
    source = sys.stdin.read()
    line_no = int(os.environ.get("TM_LINE_NUMBER"))
    cur_col = int(os.environ.get("TM_LINE_INDEX"))

    PYSMELLDICT = idehelper.findPYSMELLDICT(cur_file)
    line = source.splitlines()[line_no - 1]
    index = vimhelper.findBase(line, cur_col)
    base = line[index:cur_col]

    options = idehelper.detectCompletionType(cur_file, source, line_no, cur_col, base, PYSMELLDICT)
    completions = idehelper.findCompletions(base, PYSMELLDICT, options)

    if not completions:
        write('No completions found')
        sys.exit(206) #magic code for tooltip
    if len(completions) == 1:
        new_word = completions[0]['word']
        write(new_word)
    elif len(completions) > 1:
        dialogTuples = [
            (
              "%s - %s" % (comp.get('abbr', comp['word']), comp.get('menu', '')),
              index)
            for index, comp in enumerate(completions)
        ]
        compIndex = dialog.menu(dialogTuples)
        if compIndex is not None:
            write(completions[compIndex]['word'])
Exemple #5
0
def frame():
    global g_paths
    global g_path
    choice = None

    # display the current frame and get the user's choice.
    choice = dialog.menu(g_frame.title, g_frame.description, g_frame.list)

    # did the user want to go back?
    if choice == None:
        g_paths.pop(len(g_paths) - 1)

        if len(g_paths) == 0:
            sys.exit(0)

        g_path = g_paths[len(g_paths) - 1]

        return

    # if the choice is a subframe, then go to it.
    if g_frame.entries[choice].type == TYPE_FRAME:
        g_path = g_frame.entries[choice].path
        g_paths.append(g_path)
    # otherwise, ask the user to enter a new value for the variable.
    elif g_frame.entries[choice].type == TYPE_VARIABLE:
        variable(choice)
Exemple #6
0
def mainloop():
    try:
        import dialog
        from dialog import Dialog
    except ImportError:
        print("This script requires dialog and pythondialog")
        exit(-1)

    global dialog
    dialog = Dialog(autowidgetsize=True)
    dialog.set_background_title("LFOS Configuration")
    dialog.msgbox(
        "Welcome to LFOS menuconfig\n\nPlease note that this utility is experimental, and it is recommended to configure the kernel manually using lfos_config.h")

    if os.path.isfile("config/kconfig.py") == 0:
        dialog.msgbox("Could not find config file. Please run this script with `make menuconfig`")
        os.system("clear")
        exit(-1)

    mainmenu = [
        ("Configure", "Configure the LFOS Kernel"),
        ("Build", "Build LFOS"),
        ("Exit", "Exit this configuration utility")
    ]

    while True:
        (exitcode, choice) = dialog.menu("What do you want to do?", choices=mainmenu, title="Main menu")

        if exitcode != "ok" or choice == "Exit":
            os.system("clear")
            exit(0)

        if choice == "Configure":
            defaults = fill_options("./config/kconfig.py")
            options = configure(defaults)

            configfile_content = "// Generated configuration file\n#ifndef LFOS_CONFIG_H\n#define LFOS_CONFIG_H\n\n"
            for option in options.values():
                configfile_content += option + "\n"
            configfile_content += "\n#endif /* LFOS_CONFIG_H */\n"

            dialog.msgbox(configfile_content, title="Config preview")

            if dialog.yesno("Do you want to save your configuration?") == "ok":
                with open("./kernel/lfos_config.h", "w") as configfile:
                    configfile.truncate()
                    configfile.write(configfile_content)

        elif choice == "Build":
            dialog.msgbox("This is not yet implemented. Please use the usual Makefile.", title="Sorry")
Exemple #7
0
def complete_tag():
    tags = ctags()
    current_word = os.environ['TM_CURRENT_WORD']
    entry = TagEntry()
    res = tags.find(entry, current_word, TAG_PARTIALMATCH | TAG_IGNORECASE)
    if res==0:
        sys.exit()
    matches = set([entry['name']])
    while tags.findNext(entry):
        matches.add(entry['name'])
    selected = menu(list(matches))
    if selected:
        sys.stdout.write(selected)
    else:
        sys.stdout.write(current_word)
Exemple #8
0
def determine_socket(path=default_path):
    """Determine the socket with which to connect."""
    sockets = list_sockets(path)

    if not len(sockets):
        return None

    if len(sockets) == 1:
        return os.path.join(path, sockets[0])
    
    try:
        import dialog
        # If we aren't running from within TM use the first socket found.
    except ImportError:
        sock = sockets[0]
    else:
        sock = dialog.menu(sockets)            

    return os.path.join(path, sock)
def determine_socket(path='~/.ipython'):
    """Find out which socket to connect to"""
    sockets = list_sockets(path)

    if not len(sockets):
        return None

    if len(sockets) == 1:
        return os.path.join(path, sockets[0])
    
    try:
        import dialog
        # If we aren't running from within TM use the first socket found.
    except ImportError:
        sock = sockets[0]
    else:
        sock = dialog.menu(sockets)            

    return os.path.join(path, sock)
Exemple #10
0
    def complete(self):
        if TM_PROJECT_DIRECTORY is None:
            return ''
        #from rope.contrib import autoimport
        project = Project(TM_PROJECT_DIRECTORY)
        #autoimport = autoimport.AutoImport(project)
        resource = project.get_resource(TM_FILEPATH.replace(TM_PROJECT_DIRECTORY, '')[1:])
        #project.validate(self.project_path)
        caret_index = self.source.find(TM_CURRENT_LINE) + TM_LINE_INDEX
        try:
            proposals = codeassist.code_assist(project, self.source, caret_index, resource)
        except:
            ass = PythonCodeAssist(project)
            proposals = ass.assist(self.source, caret_index, resource)
        try:
            if len(proposals) == 0:
                return ''
        except:
            return ''
        if len(proposals) == 1:
            selection = proposals[0].name
        else:
            proposals = codeassist.sorted_proposals(proposals)
            #autoimport.generate_cache()
            #autoimport.generate_modules_cache(modules)
            #project.pycore.analyze_module(resource)
            names = [proposal.name for proposal in proposals]
            #if self.starting.strip() and '.' not in self.expression:
            #        import_assists = self.autoimport.import_assist(self.starting)
            #        names.extend(x[0] + ' : ' + x[1] for x in import_assists)

            #plist = "{ menuItems=(%s);}"
            selection = dialog.menu(names)
            if selection is None:
                return ''
        if TM_CURRENT_WORD is None:
            return selection
        else:
            return selection.replace(TM_CURRENT_WORD, '')
Exemple #11
0
def showPatr():
    ret = ''
    aux = mp.labels.keys()
    aux.sort()
    while ret != 'Salvar':
        list = []
        for k in aux:
            v = mp.labels[k]
            text = normalize(v.getText())
            value = normalize(dict['text'+k])
            list.append((text, value))
        
        list.append(('', ''))
        list.append(('Salvar', 'Envia os valores para o gerente web'))
        list.append(('Sair', 'Encerra sem enviar os valores para o gerente web'))
        ret = dialog.menu("MapaCACIC - Patrimonio", "Selecione para editar", 0, 0, 0, list)
        if ret == 'Salvar' or ret == 'Sair':
            break;
        selectValor(ret)
        
    if ret == 'Salvar':
        valores = {}
        valores['id_unid_organizacional_nivel1a'] = dict['1a']
        valores['id_unid_organizacional_nivel2'] = dict['2']
        valores['te_localizacao_complementar'] = dict['text3']
        valores['te_info_patrimonio1'] = dict['text4']
        valores['te_info_patrimonio2'] = dict['text5']
        valores['te_info_patrimonio3'] = dict['text6']
        valores['te_info_patrimonio4'] = dict['text7']
        valores['te_info_patrimonio5'] = dict['text8']
        valores['te_info_patrimonio6'] = dict['text9']
        showStatus("Enviando informacoes...")
        if mp.save(valores):
            showInfo("Informacoes enviadas com sucesso.")
        else:
            showInfo("Erro enviando informacoes.")
Exemple #12
0
                           "UnicodeData.txt.zip'").read().decode("UTF-8")
    if UnicodeData:
        for c in UnicodeData.split('\n'):
            uniData = c.strip().split(';')
            if len(uniData) > 1: unames[uniData[0]] = uniData[1]

sugglist = []

for c in suggestions:
    name = ""
    try:
        name = unames["%04X" % int(c)]
    except KeyError:
        name = getNameForRange(c)
    if name[0] == '<':
        name = getNameForRange(c)
    theChar = re.sub(r"(?=[\"])", r'\\', wunichr(c))
    if theChar == '"': theChar = '\\"'
    sugglist.append("%s\t:   U+%-5s\t :   %s" %
                    (theChar, "%04X" % int(c), name))

try:
    result = dialog.menu(sugglist)
    if not result: sys.exit(200)
    sys.__stdout__.write("".join(map(wunichr, head)).encode("UTF-8"))
    sys.__stdout__.write(result.split('\t')[0].encode("UTF-8"))
    sys.__stdout__.write(tail.encode("UTF-8"))
    sys.exit(201)
except KeyError:
    sys.exit(206)
Exemple #13
0
  if word and word[-1] == '-':
    # If the last char in the word is a _ we don't show the word in the completion list,
    # to enable the user to continue typing. See: array_⌥⎋
    skip_prefix = True
  names = [] 

  regex = re.compile(word+"(.*?)(%|$)")
  for line in functions :

    mat = regex.match(line)
    if skip_prefix:
      names.append(mat.group(1))
    else:
      names.append(word + mat.group(1))
  
  choice = dialog.menu(names)
  if not choice:
    exit()
  choice_check = choice 
  if skip_prefix:
    choice_check = word + choice
  choice = [f for f in functions if f[0:len(choice_check)]==choice_check].pop()
else:
  choice = functions.pop()


function, prototype = choice.split('%')

offset = len(word) 
  
if regExp:
    UnicodeData = os.popen("zgrep -E '^(" + "|".join(regExp.keys()) + ");' '" + bundleLibPath + "UnicodeData.txt.zip'").read().decode("UTF-8")
    if UnicodeData:
        for c in UnicodeData.split('\n'):
            uniData = c.strip().split(';')
            if len(uniData) > 1: unames[uniData[0]] = uniData[1]

sugglist = []

for c in suggestions:
    name = ""
    try:
        name = unames["%04X" % int(c)]
    except KeyError:
        name = getNameForRange(c)
    if name[0] == '<':
        name = getNameForRange(c)
    theChar = re.sub(r"(?=[\"])", r'\\', wunichr(c))
    if theChar == '"': theChar = '\\"'
    sugglist.append("%s\t:   U+%-5s\t :   %s" % (theChar, "%04X" % int(c), name))

try:
    result=dialog.menu(sugglist)
    if not result: sys.exit(200)
    sys.__stdout__.write("".join(map(wunichr, head)).encode("UTF-8"))
    sys.__stdout__.write(result.split('\t')[0].encode("UTF-8"))
    sys.__stdout__.write(tail.encode("UTF-8"))
    sys.exit(201)
except KeyError:
    sys.exit(206)