Ejemplo n.º 1
0
class Plain:
    def __init__(self):
        self.macro = Macro()

    def eat(self):
        pass

    def get_input(self):
        while True:
            print(f"[0]: Add waypoint")
            print(f"[1]: Edit waypoint")
            print(f"[2]: Delete waypoint")
            print(f"[3]: Show waypoints")
            print(f"[4]: Start donut")
            print(f"[5]: Quit")

            choice = int(input("What would you like to do: "))

            if choice == 0:
                self.macro.add_waypoint()
            elif choice == 1:
                pass
            elif choice == 2:
                self.macro.show_waypoints()
                index = int(input("Waypoint to remove: "))
                self.macro.delete_waypoint(index)
            elif choice == 3:
                self.macro.show_waypoints()
            elif choice == 4:
                self.macro.start()
            elif choice == 5:
                break
Ejemplo n.º 2
0
    def __init__(self):
        pygame.init()
        self.screen_blit = pygame.display.set_mode(BLIT_SIZE)
        self.screen = pygame.Surface(WINDOW_SIZE)
        self.editor = Editor()
        self.sel = CharacterSelect(self.screen_blit).sel
        self.player = Player(self, 0, 0, idx=self.sel)
        self.camera = Camera()
        self.level = 0

        self.black_screen = pygame.Surface(WINDOW_SIZE).convert()
        self.black_screen.fill((0, 0, 0))
        self.black_alpha = 255.0
        self.black_screen.set_alpha(self.black_alpha)
        self.black_shade = DOWN

        self.load_level()
        self.delay = 0
        self.command_font = pygame.font.SysFont("monospace", 12)
        self.command_rectangles = {}
        test_macro = Macro()
        test_macro.add_block(Right())
        test_macro.add_block(AttackRight())
        test_macro.add_block(Left())
        self.player.macros[0] = test_macro

        self.heart = pygame.image.load("heart.png")
        self.hheart = pygame.image.load("half_heart.png")
        self.eheart = pygame.image.load("empty_heart.png")
        self.heart_width = self.heart.get_width()

        self.mana_bar = pygame.image.load("mana_outer_bar.png")
        self.mana_fill = pygame.image.load("mana_inner_bar.png")
        self.display_mana = self.player.mana
Ejemplo n.º 3
0
    def apply(self, line, state):
        result = OperationResult(line, False)
        # strings = [] # string start and end positions as StringPos instances

        trimmed = stripComments(line)
        output = line
        expanded_line = line

        # find the directive
        dirsearch = regex['directive'].search(trimmed)
        if dirsearch:
            directive = dirsearch.group(1)
            identifier = dirsearch.group(2)

            origline = output
            output = commentLine(line)

            if directive == "#define":
                macro = Macro(dirsearch, trimmed)
                if macro != None:
                    state.macros[macro.name] = macro
            elif directive == "#undef":
                temp_macro = Macro(dirsearch, trimmed)
                if temp_macro.name in state.macros:
                    del state.macros[temp_macro.name]
                else:
                    warnings.add(
                        state.row, "Trying to undefine a nonexistent macro " +
                        temp_macro.name)
            elif directive == "#pragma":
                if state.args.verbose: print("pragma: " + identifier)
                state.args = handlePragma(identifier, state.args)
            elif directive == "#include":
                if state.args.filedir:
                    self.handleInclude(state, trimmed, state.args.filedir)
            else:
                # we'll leave #ifdef, #ifndef and #else to the other operators
                output = origline

        else:
            if state.args.nomacros:
                return result

            visited = Stack()

            #for name in self.macros:
            output = expandAll(line, state.macros, visited, state)

        result.line = output
        return result
Ejemplo n.º 4
0
    def parameters_replace(self):
        """
        For values in the target_parameters dict, update the query_text
        Replace key with target_value

        Macros
        ## <DATEID> ==> today regardles of what replace with is
        ## <TABLEID-1> ==> Table_name_guid regardless of replace with
        """
        for key, replacement_dict in self.target_parameters.iteritems():
            macro = Macro(key_pattern=replacement_dict['search_for'],
                          replace_value=str(replacement_dict['replace_with']))
            self.query.query_text = macro.replace_text(self.query.query_text)
        date_macro = DateMacro()
        self.query.query_text = date_macro.replace_text(self.query.query_text)
Ejemplo n.º 5
0
    def __init__(self, root):
        version = subprocess.check_output('git rev-list --count HEAD').decode(
            'utf-8')
        root.title(f'Auto Disenchanter v{version}')
        root.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.builder = builder = pygubu.Builder()
        builder.add_from_file('main_frame.ui')
        builder.get_object('main_frame', root)
        builder.connect_callbacks(self)

        self.builder_wrapper = Builder(builder)
        self.root = root

        self.logger = TkinterLogger(self.builder, '%H:%M:%S')
        self.settings = get_settings(self.logger, debug=True)
        self.logger.log_format = self.settings.log_time_format
        self.macro = Macro(self.logger, self.settings)

        self.incidents = Incidents(self.logger, self.settings)
        self.incidents.start_thread()

        root.resizable(False, False)
        root.wm_attributes("-topmost", 1)

        state = load_state()
        if state is not None and 'options' in state:
            self.builder_wrapper.init_checkboxes(state['options'])
        else:
            self.builder_wrapper.init_checkboxes(dict.fromkeys(OPTIONS, False))
        if state is not None and 'accounts' in state:
            self.accounts = state['accounts']
            self.builder_wrapper.set_treeview('accounts', self.accounts)
        else:
            self.accounts = []
Ejemplo n.º 6
0
    def parameters_replace(self):
        """
        For values in the target_parameters dict, update the query_text
        Replace key with target_value

        Macros
        ## <DATEID> ==> today regardles of what replace with is
        ## <TABLEID-1> ==> Table_name_guid regardless of replace with
        """
        for key, replacement_dict in self.target_parameters.iteritems():
            macro = Macro(
                key_pattern=replacement_dict['search_for'],
                replace_value=str(replacement_dict['replace_with'])
            )
            self.query.query_text = macro.replace_text(self.query.query_text)
        date_macro = DateMacro()
        self.query.query_text = date_macro.replace_text(self.query.query_text)
Ejemplo n.º 7
0
    def __init__(self, master):
        LogWriter(self)
        import pygubu  # pylint:disable=import-outside-toplevel

        self.accounts = []

        self.master = master

        self.master.title('Auto watcher client')
        self.builder = builder = pygubu.Builder()
        self.builder.add_from_file('main_frame.ui')
        self.mainwindow = builder.get_object('main_frame', master)
        # self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.builder.connect_callbacks(self)
        self.init_checkboxes()

        self.macro = Macro(RiotConnection(), LeagueConnection())
Ejemplo n.º 8
0
    def dispatch_macro(self, path):
        """
        Execute custom macro
        
        @path to the custom macro file
        """
        macro = Macro(path)

        for cmd in macro.commands:
            self.dispatch_command(cmd)
Ejemplo n.º 9
0
    def create_data(self):
        # Write variables
        variables = ProjectVariables(self.data)
        variables.define_variable()
        files = ProjectFiles(self.data)
        files.write_variables()
        variables.define_project()
        variables.define_target()

        # Write Macro
        macros = Macro()
        macros.write_macro(self.data)

        # Write Output Variables
        variables.write_output()

        # Write Include Directories
        depends = Dependencies(self.data)
        if self.data['includes']:
            depends.write_include_dir()
        else:
            send('Include Directories is not set.', '')

        # Write Dependencies
        depends.write_dependencies()

        # Add additional code or not
        if self.data['additional_code'] is not None:
            files.add_additional_code(self.data['additional_code'])

        # Write Flags
        all_flags = Flags(self.data)
        all_flags.write_flags()

        # Write and add Files
        files.write_files()
        files.add_artefact()

        # Link with other dependencies
        depends.link_dependencies()

        # Close CMake file
        self.data['cmake'].close()
Ejemplo n.º 10
0
 def get_macro(self):
     macro = Macro(len(self.tile_containers))
     for i, container in enumerate(self.tile_containers):
         if container.tiles:
             macro.add_block(container.tiles[0], i)
         else:
             macro.add_block(False, i)
     return macro
 def createMacro(self):
     newMacro = Macro(self.charIndex,self.page,self.slot)
     newMacro.name = self.guiName.getValue()
     newMacro.description = self.guiToolTip.getValue()
     hotkey = self.guiHotkey.getValue()
     if hotkey == 'None':
         newMacro.hotkey = ''
     else:
         newMacro.hotkey = hotkey
     newMacro.icon = self.icon
     newMacro.waitAll = int(self.guiWaitAll.getValue()) == 1
     try:
         manualDelay = int(self.guiManualDelay.getValue)
         if manualDelay < 0:
             manualDelay = 0
     except:
         manualDelay = 0
     newMacro.manualDelay = manualDelay
     
     for lineIndex in xrange(10):
         lineCommand = self.guiLines[lineIndex].getValue().lstrip().rstrip()
         mandatory = int(self.guiMandatory[lineIndex].getValue()) == 1
         try:
             lineDelay = int(self.guiDelays[lineIndex].getValue())
             if lineDelay < 0:
                 lineDelay = 0
         except:
             lineDelay = 0
         if not lineCommand and not lineDelay:
             continue
         newMacroLine = MacroLine(lineCommand,mandatory,lineDelay)
         newMacro.insertMacroLine(lineIndex,newMacroLine)
     
     if newMacro.macroLineNum == 0:
         del newMacro
         return None
     
     return newMacro
Ejemplo n.º 12
0
        return "#   Copyright (c) %(year)s %(name)s" % a


def countSpaces(line):
    for i in range(len(line)):
        if not line[i].isspace():
            break
    return i


if len(sys.argv) != 3:
    raise Exception("invalid command line syntax: %s" %
                    ' '.join(map(repr, sys.argv)))
(m4File, outFile) = sys.argv[1:]
assert outFile != m4File
m = Macro(m4File, computeSerialNumber=True)
for i in range(len(m.description)):
    para = m.description[i]
    if para[0][0].isspace():
        spaces = min(list(map(countSpaces, para)))
        if spaces > 1:
            m.description[i] = ['  ' + l[spaces:] for l in para]
url = "http://www.gnu.org/software/autoconf-archive/%s.html" % m.name
lineLen = max(len(url) + 2, 75)
m.url = "# %s\n# %s\n# %s" % ('=' * lineLen, (' ' * int(
    (lineLen - len(url)) / 2)) + url, '=' * lineLen)
if m.__dict__.get("obsolete"):
    m.obsolete = "# OBSOLETE MACRO\n#\n" + '\n#\n'.join(
        map(formatParagraph, m.obsolete)) + "\n#\n"
else:
    m.obsolete = ""
Ejemplo n.º 13
0
def getMacroKeys(macrodict, state):
	macrokeys = list(macrodict.keys())
	linenum = Macro(None, "")
	linenum.name = "__LINE__" 
	linenum.payload = str(state.row)
	linenum.nameregex = lineNameRegex

	filename= Macro(None, "")
	filename.name = "__FILE__" 
	filename.payload = str('"' + state.filename + '"')
	filename.nameregex = fileNameRegex

	# temporary concatenation macro, must run LAST
	concat = Macro(None, "")
	concat.name = " ## " 
	concat.payload = ""
	concat.nameregex = concatNameRegex

	macrodict[linenum.name] = linenum
	macrodict[filename.name] = filename
	macrodict[concat.name] = concat
	macrokeys = list(macrodict.keys())
	macrokeys.append(linenum.name)
	macrokeys.append(filename.name)
	macrokeys.append(concat.name)
	
	return macrokeys
Ejemplo n.º 14
0
from macro import Macro

stu_no = input('stu_no: ')
pw = input('pw: ')
grade = int(input('grade: '))
index = int(input('index: '))
method = int(input('method(0:전공, 1:장바구니): '))

flag = True
while flag:
    macro = Macro(stu_no, pw, grade, index, method)
    try:
        flag = macro.run()
    except:
        macro.driver.close()
        flag = True
Ejemplo n.º 15
0
        return "#   Copyright (c) %(year)s %(name)s" % a


def countSpaces(line):
    for i in range(len(line)):
        if not line[i].isspace():
            break
    return i


if len(sys.argv) != 3:
    raise Exception("invalid command line syntax: %s" %
                    ' '.join(map(repr, sys.argv)))
(m4File, outFile) = sys.argv[1:]
assert outFile != m4File
m = Macro(m4File)
for i in range(len(m.description)):
    para = m.description[i]
    if para[0][0].isspace():
        spaces = min(map(countSpaces, para))
        if spaces > 1:
            m.description[i] = map(lambda l: '  ' + l[spaces:], para)
url = "http://www.gnu.org/software/autoconf-archive/%s.html" % m.name
lineLen = max(len(url) + 2, 75)
m.url = "# %s\n# %s\n# %s" % ('=' * lineLen, (' ' * (
    (lineLen - len(url)) / 2)) + url, '=' * lineLen)
if m.__dict__.get("obsolete"):
    m.obsolete = "# OBSOLETE MACRO\n#\n" + '\n'.join(
        map(formatParagraph, m.obsolete)) + "\n#\n"
else:
    m.obsolete = ""
Ejemplo n.º 16
0
def macro(bot, update, bot_globals):
    """user defined macro editor"""

    def no_flood(u):
        bot_globals['last_commands'][u] = time.time() - bot_globals['MESSAGE_TIMEOUT'] * 2

    global MACROS

    message = update.message
    message_user = message.from_user.username if message.from_user.username is not None else message.from_user.name

    modes = {'eval': 'macro',
             'text': 'macro',
             'inline': 'macro',
             'photo': 'macro',
             'e621': 'macro',
             'alias': 'macro',
             'markov': 'macro',
             'remove': 'write',
             'hide': 'write',
             'protect': 'write',
             'clean': 'write',
             'modify': 'write',
             'rename': 'write',
             'nsfw': 'write',
             'contents': 'read',
             'list': 'read'}

    err = 'Macro editor error:\n\n'
    expr = clean(message.text)

    if expr == '':
        update.message.text = '/macro_help' + bot.name.lower()
        no_flood(message_user)
        call_macro(bot, update, bot_globals)
        return

    args = expr.split()
    mode = args[0]
    name = ''

    if mode not in modes.keys():
        message.reply_text(text=err + 'Unknown mode {}.'.format(mode))
        return

    if len(args) > 1:
        name = args[1].split('\n')[0]
    elif not (modes[mode] == 'read' or mode == 'clean'):
        message.reply_text(text=err + 'Missing macro name.')
        return

    user = message_user.lower()
    if name in MACROS:
        if MACROS[name].protected and not is_mod(user) and not modes[mode] == 'read':
            message.reply_text(text=err + 'Macro {} is write protected.'.format(name))
            return

    if len(args) > 2:
        expr = expr.replace(' '.join(args[:2]), '').strip()
        if len(args[1].split('\n')) == 2:
            expr = args[1].split('\n')[1] + expr
    else:
        expr = None

    if modes[mode] == 'macro' and name not in MACROS:
        if expr:
            try:
                MACROS.add(Macro(name, mode.upper(), expr, hidden=False, protected=is_mod(user), nsfw=False,
                                 creator={'user': message_user,
                                          'chat': message.chat.id,
                                          'chat_type': message.chat.type}))

                message.reply_text(text='{} macro "{}" created.'.format(mode, name))
            except ValueError:
                message.reply_text(text=err + 'Bad photo url.')
        else:
            message.reply_text(text=err + 'Missing macro contents.')

    elif mode == 'modify':
        if name in MACROS and expr is not None:
            try:
                MACROS[name].content = expr
                message.reply_text(text='Macro "{}" modified.'.format(name))
            except ValueError:
                message.reply_text(text=err + 'Bad photo url.')
        elif expr is None:
            message.reply_text(text=err + 'Missing macro text/code.')
        else:
            message.reply_text(text=err + 'No macro with name {}.'.format(name))

    elif mode == 'clean':
        if is_mod(user):
            MACROS = MACROS.subset(protected=True)
            message.reply_text('Cleaned up macros.')
        else:
            message.reply_text(text=err + 'Only bot mods can do that.')

    elif mode == 'remove':
        if name in MACROS:
            MACROS.remove(name)
            message.reply_text(text='Macro "{}" removed.'.format(name))
        else:
            message.reply_text(text=err + 'No macro with name {}.'.format(name))

    elif mode == 'rename':
        if name in MACROS:
            new_name = args[1]
            MACROS[name].name = new_name
            message.reply_text(text='Macro "{}" renamed to {}'.format(name, new_name))
        else:
            message.reply_text(text=err + 'No macro with name {}.'.format(name))

    elif mode == 'list':
        if is_mod(user):
            filt = {i.split(':')[0]: i.split(':')[1] for i in args[1:] if ':' in i}
            include = {i.split(':')[0]: i.split(':')[1] for i in args[1:] if ':' in i and not i.startswith('-')}
            exclude = {i.split(':')[0][1:]: i.split(':')[1] for i in args[1:] if ':' in i and i.startswith('-')}

            try:
                macros = MACROS.subset(filt=include)
                if exclude:
                    macros -= MACROS.subset(filt=exclude)
            except ValueError:
                message.reply_text(text=err + 'Unknown key in list filter: {}.'.format(filt))
                return

            if macros:
                names = ((bot.name + ' ') * (m.variety == Macro.INLINE) + m.name for m in macros.sort())
                message.reply_text('Macros:\n' + ', '.join(names))
            else:
                message.reply_text(text=err + 'No macros found.')
        else:
            names = ((bot.name + ' ') * (m.variety == Macro.INLINE) + m.name for m in MACROS.subset())
            message.reply_text('Visible macros:\n' + ', '.join(names))

    elif mode == 'contents':
        if name in MACROS:
            if not MACROS[name].hidden or is_mod(user):
                message.reply_text('Contents of {} macro {}: {}'
                                   .format(MACROS[name].variety.lower(), name, MACROS[name].content))
            else:
                message.reply_text(text=err + 'Macro {} contents hidden.'.format(name))
        else:
            message.reply_text(text=err + 'No macro with name {}.'.format(name))

    elif mode == 'hide':
        if name in MACROS:
            if is_mod(user):
                MACROS[name].hidden ^= True
                message.reply_text('Hide macro {}: {}'.format(name, MACROS[name].hidden))
            else:
                message.reply_text(text=err + 'Only bot mods can hide or show macros.')
        else:
            message.reply_text(text=err + 'No macro with name {}.'.format(name))

    elif mode == 'protect':
        if name in MACROS:
            if is_mod(user):
                MACROS[name].protected ^= True
                message.reply_text('Protect macro {}: {}'.format(name, MACROS[name].protected))
            else:
                message.reply_text(text=err + 'Only bot mods can protect macros.')
        else:
            message.reply_text(text=err + 'No macro with name {}.'.format(name))

    elif mode == 'nsfw':
        if name in MACROS:
            if is_mod(user):
                MACROS[name].nsfw ^= True
                message.reply_text('NSFW macro {}: {}'.format(name, MACROS[name].nsfw))
            else:
                message.reply_text(text=err + 'Only bot mods can change macro nsfw state.')
        else:
            message.reply_text(text=err + 'No macro with name {}.'.format(name))

    elif name in MACROS:
        message.reply_text(text=err + 'Macro already exists.')
Ejemplo n.º 17
0
from interface import window
from PySimpleGUI import WIN_CLOSED

# Ignore warnings
filterwarnings("ignore")

while True:
    event, values = window.read()
    if (event == "Exit") or (event == WIN_CLOSED):
        break
    # Trigger the comparison only if all the fields are filled
    if (event == "COMPARE") and all(
        [values[key] for key in ['LUA', 'AUTOCAD', 'BOX', 'PATH', 'NAME']]):
        window['LOGBOX'].reroute_stderr_to_here()
        window['LOGBOX'].reroute_stdout_to_here()
        file_name = values['NAME']
        if '.' not in file_name:
            file_name += '.xlsx'
        output = join(values['PATH'], file_name)
        try:
            macro = Macro(values['LUA'], values['AUTOCAD'], values['BOX'])
            macro.get_indexes()
            macro.compare()
            macro.adjust_columns()
            macro.save_result(output)
            print('File successfully generated at: {}\n'.format(output))
        except Exception as e:
            print(e, '\n')

window.close()
Ejemplo n.º 18
0
class Application:
    ''' Main gui class '''
    def __init__(self, master):
        LogWriter(self)
        import pygubu  # pylint:disable=import-outside-toplevel

        self.accounts = []

        self.master = master

        self.master.title('Auto watcher client')
        self.builder = builder = pygubu.Builder()
        self.builder.add_from_file('main_frame.ui')
        self.mainwindow = builder.get_object('main_frame', master)
        # self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.builder.connect_callbacks(self)
        self.init_checkboxes()

        self.macro = Macro(RiotConnection(), LeagueConnection())

    # def on_closing(self):
    #     ''' Kills the game processes when closing '''
    #     kill_process(LEAGUE_CLIENT_PROCESS)
    #     kill_process(RIOT_CLIENT_PROCESS)
    #     self.master.destroy()

    def init_checkboxes(self):
        ''' Checks all the checkboxes at the start '''
        for option in OPTIONS:
            self.init_checkbox(option, True)

    def get_options(self):
        ''' Returns a list of options from checkboxes '''
        options = []
        for option in OPTIONS:
            if self.builder.get_object(option).instate(['selected']):
                options.append(option)
        return options

    def start(self):
        ''' Starts the macro thread '''
        if self.accounts == []:
            logging.error('No accounts imported')
            return
        thread = threading.Thread(target=self.start_macro)
        thread.daemon = True
        thread.start()

    def start_macro(self):
        ''' Starts the main batch process '''
        options = self.get_options()
        self.builder.get_object('start')['state'] = 'disabled'

        kill_process(LEAGUE_CLIENT_PROCESS)
        kill_process(RIOT_CLIENT_PROCESS)
        for idx, account in enumerate(self.accounts):
            tree = self.builder.get_object('accounts')
            child_id = tree.get_children()[idx]
            tree.focus(child_id)
            tree.selection_set(child_id)

            try:
                self.macro.do_macro(options, *account)
            except AuthenticationFailureException:
                logging.info('Account %s has invalid credentials', account[0])
            except ConsentRequiredException:
                logging.info('Account %s needs consent', account[0])
            progress = (idx + 1) * 100 // len(self.accounts)
            self.builder.get_object('progress')['value'] = progress
        self.builder.get_object('start')['state'] = 'normal'

    def import_csv(self):
        ''' Called when import button is pressed '''
        self.accounts = import_csv()
        self.set_treeview('accounts', self.accounts)

    def export_csv(self):
        ''' Called when export button is pressed '''
        if export_csv(self.accounts):
            logging.info('Successfully exported')

    def set_treeview(self, name, values):
        ''' Sets the treeview component '''
        for value in values:
            self.set_row(name, value)

    def clear_treeview(self, name):
        ''' Clears the treeview component '''
        tree = self.builder.get_object(name)
        tree.delete(*tree.get_children())

    def set_row(self, name, value):
        ''' Sets a row value of a treeview component '''
        self.builder.get_object(name).insert('', 'end', values=value)

    def init_checkbox(self, name, value):
        ''' Intializes a checkout component '''
        self.builder.get_object(name).state(['!alternate'])
        if value:
            self.builder.get_object(name).state(['selected'])
        else:
            self.builder.get_object(name).state(['!selected'])

    def write_console(self, text):
        ''' Writes the messages to console textbox component '''
        self.builder.get_object('console').insert(tk.END, text)
        self.builder.get_object('console').see('end')
def GetDefaultCommandAsMacro(cmd, charIndex, page, slot):
    from macro import Macro, MacroLine

    # Initialize the default macro to None,
    #  in case we don't find the desired command.
    defaultMacro = None

    # Try to get the default command from the local dictionary.
    defaultCommand = DEFAULTCOMMANDS.get(cmd)
    # If it's not one of the default commands here,
    #  check if it's a skill in the skillInfo dictionary
    #  and create a macro from that.
    if not defaultCommand:
        skillInfo = GetSkillInfo(cmd, False)
        if skillInfo:
            defaultMacro = Macro(charIndex, page, slot)
            defaultMacro.name = cmd
            defaultMacro.icon = skillInfo.icon
            if not defaultMacro.icon.startswith("SPELLICON_"):
                defaultMacro.icon = "icons/%s" % defaultMacro.icon
            defaultMacro.description = skillInfo.name
            defaultMacro.appendMacroLine(MacroLine(command="/skill %s" % cmd))
    else:
        defaultMacro = Macro(charIndex, page, slot)
        defaultMacro.name = defaultCommand.name
        defaultMacro.icon = defaultCommand.icon
        if not defaultMacro.icon.startswith("SPELLICON_"):
            defaultMacro.icon = "icons/%s" % defaultMacro.icon
        defaultMacro.description = defaultCommand.tooltip
        defaultMacro.appendMacroLine(MacroLine(command=defaultCommand.command))

    # Return the default macro.
    return defaultMacro
Ejemplo n.º 20
0
 def __init__(self):
     self.macro = Macro()
Ejemplo n.º 21
0
    def apply(self, line, state):
        result = OperationResult(line, False)

        trimmed = stripComments(line)
        output = line
        expanded_line = line

        # find the directive
        dirsearch = regex['directive'].search(trimmed)
        if dirsearch:
            directive = dirsearch.group(1)
            identifier = dirsearch.group(2)

            output = commentLine(line)

            if directive == "#macro":
                if self.macro:
                    warnings.add(
                        "Trying to define multiline macro %s inside other macro %s"
                        % (identifier, self.macro.name))
                    return result

                self.macro = Macro(dirsearch, trimmed)
                self.payload = ""
            elif directive == "#endmacro":
                #print ("macro %s ends") % (self.macro.name)
                self.macro.payload = self.macro.payload.rstrip('\n')
                self.multimacros[self.macro.name] = self.macro
                self.macro = None

            # TODO this is basically duplicate of the above functionality, clean it up
            elif directive == "#lambda":
                if self.macro:
                    warnings.add(
                        "Trying to define multiline lambda %s inside other macro %s"
                        % (identifier, self.macro.name))
                    return result

                self.macro = Macro(dirsearch, trimmed)
                self.macro.oneliner = True
                self.payload = ""

            elif directive == "#endlambda":
                #print ("macro %s ends") % (self.macro.name)
                self.macro.payload = self.macro.payload.rstrip('\n')
                self.macro.payload = re.sub("\n+", r':', self.macro.payload)
                self.multimacros[self.macro.name] = self.macro
                self.macro = None
            elif directive == "#undef":
                temp_macro = Macro(dirsearch, trimmed)
                if temp_macro.name in self.multimacros:
                    del self.multimacros[temp_macro.name]

            else:
                output = output

        else:
            if state.args.nomacros:
                return result

            # Expand collected macros only if not inside a multiline macro.
            if self.macro:
                line_trimmed = line

                if self.macro.oneliner:
                    line_trimmed = line.lstrip(" ").lstrip("\t")

                self.macro.payload += line_trimmed
                output = commentLine(output)
            else:
                output = expandAll(line, self.multimacros, Stack(), state)

        result.line = output
        return result
Ejemplo n.º 22
0
def full_evaluate(expression, environment):
    """
    Fully evaluate an expression until its basic representation
    """

    while True:
        if is_thunk(expression):
            if not expression.is_evaluated:
                expression.is_evaluated = True
                expression.expression = full_evaluate(expression.expression,
                                                      expression.environment)
            return expression.expression
        elif is_symbol(expression):
            expression = environment[expression]
            continue
        elif (is_atom(expression) or is_nil(expression)
              or is_procedure(expression) or is_macro(expression)
              or callable(expression)):
            return expression
        elif not is_pair(expression):
            raise ValueError("Cannot evaluate: %s" % expression)
        elif car(expression) == 'delay':
            if len(expression) != 2:
                raise SyntaxError(
                    "Unexpected delay form: %s. Should be (delay <expression>)"
                    % expression)
            return Thunk(cadr(expression), environment)
        elif car(expression) == 'defined?':
            if len(expression) != 2:
                raise SyntaxError(
                    "Unexpected defined? form: %s. Should be (defined? <symbol>)"
                    % expression)
            name = cadr(expression)
            if not is_symbol(name):
                raise SyntaxError(
                    "Argument of defined? form should be a symbol. Evaluating: %s"
                    % expression)
            return environment.exists(name)
        elif car(expression) == 'define':
            if len(expression) != 3:
                raise SyntaxError(
                    "Unexpected define form: %s. Should be (define <symbol> <expression>)"
                    % expression)
            name = cadr(expression)
            if not is_symbol(name):
                raise SyntaxError(
                    "First argument of define form should be a symbol. Evaluating: %s"
                    % expression)
            environment[name] = Thunk(caddr(expression), environment)
            return name
        elif car(expression) == 'quote':
            if len(expression) != 2:
                raise SyntaxError(
                    "Unexpected quote form: %s. Should be (quote <expression>)"
                    % expression)
            return cadr(expression)
        elif car(expression) == 'eval':
            if len(expression) != 2:
                raise SyntaxError(
                    "Unexpected eval form: %s. Should be (eval <expression>)" %
                    expression)
            expression = full_evaluate(cadr(expression), environment)
            continue
        elif car(expression) == 'if':
            if len(expression) != 4:
                raise SyntaxError(
                    "Unexpected if form: %s. Should be (if <condition> <consequent> <alternative>)"
                    % expression)
            condition = full_evaluate(cadr(expression), environment)
            expression = caddr(expression) if condition else cadddr(expression)
            continue
        elif car(expression) == 'lambda':
            if len(expression) < 3:
                raise SyntaxError(
                    "Unexpected lambda form: %s. Should be (lambda (<param> ...) <expression> ...)"
                    % expression)
            parameters = cadr(expression)
            if is_pair(parameters):
                current = parameters
                while is_pair(current):
                    if not is_symbol(car(current)):
                        raise SyntaxError(
                            "Lambda parameters should be symbols. In %s" %
                            expression)
                    current = cdr(current)
                if not is_nil(current) and not is_symbol(current):
                    raise SyntaxError(
                        "Lambda optional parameter should be a symbol or nil. In %s"
                        % expression)
            elif not is_symbol(parameters) and not is_nil(parameters):
                raise SyntaxError(
                    "Lambda parameters should be a symbol or a list of zero or more. In %s"
                    % expression)

            return Procedure(
                parameters,  # parameters
                cddr(expression),  # body (list of expressions)
                environment)
        elif car(expression) == 'macro':
            if len(expression) < 3:
                raise SyntaxError(
                    "Unexpected define macro: %s. Should be (macro (<resword> ...) (<pattern> <transformation> ...) ...)"
                    % expression)
            res_words = cadr(expression)
            rules = cddr(expression)
            if not is_nil(res_words) and not is_pair(res_words):
                raise SyntaxError(
                    "Macro reserved words should be a list of symbols or nil. In %s"
                    % expression)
            if is_pair(res_words):
                for word in res_words:
                    if not is_symbol(word):
                        raise SyntaxError(
                            "Macro reserved words should all be symbols. In %s"
                            % expression)
            for rule in rules:
                if len(rule) < 2:
                    raise SyntaxError(
                        "Macro rule should be in the form (<pattern> <expression> ...). In %s"
                        % expression)
            return Macro(
                [(car(e), cdr(e)) for e in rules],  # rules
                []
                if not res_words else set(iter(res_words)))  # reserved words
        else:
            # evaluate head
            operator = full_evaluate(car(expression), environment)

            if is_macro(operator):
                # evaluate recursively only the inner expressions (not the last)
                current = operator.transform(expression)
                while cdr(current) is not None:
                    full_evaluate(car(current), environment)
                    current = cdr(current)
                expression = car(current)
                continue
            else:
                # The unevaluated operands
                unev_operands = cdr(expression)

                if callable(operator):
                    # evaluate each operand recursively
                    operands = [
                        full_evaluate(e, environment) for e in unev_operands
                    ] if unev_operands else []
                    # return the application of the built-in procedure
                    return operator(make_list(operands))
                elif is_procedure(operator):
                    # create Thunks (promise to evaluate) for each operand
                    unev_op_list = list(
                        iter(unev_operands)) if unev_operands else []
                    proc_environment = Environment(parent=operator.environment)
                    # if the lambda parameters is not in the format ( () [. <symbol>] )
                    # for taking zero or more arguments
                    if len(operator.parameters) != 1 or not is_nil(
                            operator.parameters[0]):
                        for name in operator.parameters:
                            try:
                                # take next argument
                                proc_environment[name] = Thunk(
                                    unev_op_list.pop(0), environment)
                            except IndexError:
                                raise ValueError(
                                    "Insufficient parameters for procedure %s. It should be at least %d"
                                    % (operator, len(operator.parameters)))
                    if not is_nil(operator.optional):
                        # the optional argument is something, that when
                        # evaluated, yields the list of rest of the operands
                        # evaluated
                        proc_environment[operator.optional] = Thunk(
                            cons(lambda x: x, make_list(unev_op_list)),
                            environment)
                    elif unev_op_list:
                        raise ValueError(
                            "Too much parameters for procedure %s. It should be %d."
                            % (operator, len(operator.parameters)))

                    # evaluate recursively only the inner procedure expressions
                    # (not the last)
                    current = operator.body
                    while cdr(current) is not None:
                        full_evaluate(car(current), proc_environment)
                        current = cdr(current)

                    environment = proc_environment
                    expression = car(current)
                    # continue not-recursively to evaluate the procedure's body
                    # in the extended environment
                    continue
                else:
                    raise ValueError("Not an operator: %s, in expression: %s" %
                                     (operator, expression))
Ejemplo n.º 23
0
    def createMacro(self):
        newMacro = Macro(self.charIndex, self.page, self.slot)
        newMacro.name = self.guiName.getValue()
        newMacro.description = self.guiToolTip.getValue()
        hotkey = self.guiHotkey.getValue()
        if hotkey == 'None':
            newMacro.hotkey = ''
        else:
            newMacro.hotkey = hotkey
        newMacro.icon = self.icon
        newMacro.waitAll = int(self.guiWaitAll.getValue()) == 1
        try:
            manualDelay = int(self.guiManualDelay.getValue)
            if manualDelay < 0:
                manualDelay = 0
        except:
            manualDelay = 0
        newMacro.manualDelay = manualDelay

        for lineIndex in xrange(10):
            lineCommand = self.guiLines[lineIndex].getValue().lstrip().rstrip()
            mandatory = int(self.guiMandatory[lineIndex].getValue()) == 1
            try:
                lineDelay = int(self.guiDelays[lineIndex].getValue())
                if lineDelay < 0:
                    lineDelay = 0
            except:
                lineDelay = 0
            if not lineCommand and not lineDelay:
                continue
            newMacroLine = MacroLine(lineCommand, mandatory, lineDelay)
            newMacro.insertMacroLine(lineIndex, newMacroLine)

        if newMacro.macroLineNum == 0:
            del newMacro
            return None

        return newMacro
Ejemplo n.º 24
0
def getMacroKeys(macrodict, state):
    macrokeys = list(macrodict.keys())
    linenum = Macro(None, "")
    linenum.name = "__LINE__"
    linenum.payload = str(state.row)
    linenum.nameregex = lineNameRegex

    filename = Macro(None, "")
    filename.name = "__FILE__"
    filename.payload = str('"' + state.filename + '"')
    filename.nameregex = fileNameRegex

    # temporary concatenation macro, must run LAST
    concat = Macro(None, "")
    concat.name = " ## "
    concat.payload = ""
    concat.nameregex = concatNameRegex

    macrodict[linenum.name] = linenum
    macrodict[filename.name] = filename
    macrodict[concat.name] = concat
    macrokeys = list(macrodict.keys())
    macrokeys.append(linenum.name)
    macrokeys.append(filename.name)
    macrokeys.append(concat.name)

    return macrokeys
Ejemplo n.º 25
0
def GetDefaultCommandAsMacro(cmd, charIndex, page, slot):
    from macro import Macro, MacroLine

    # Initialize the default macro to None,
    #  in case we don't find the desired command.
    defaultMacro = None

    # Try to get the default command from the local dictionary.
    defaultCommand = DEFAULTCOMMANDS.get(cmd)
    # If it's not one of the default commands here,
    #  check if it's a skill in the skillInfo dictionary
    #  and create a macro from that.
    if not defaultCommand:
        skillInfo = GetSkillInfo(cmd, False)
        if skillInfo:
            defaultMacro = Macro(charIndex, page, slot)
            defaultMacro.name = cmd
            defaultMacro.icon = skillInfo.icon
            if not defaultMacro.icon.startswith('SPELLICON_'):
                defaultMacro.icon = 'icons/%s' % defaultMacro.icon
            defaultMacro.description = skillInfo.name
            defaultMacro.appendMacroLine(MacroLine(command='/skill %s' % cmd))
    else:
        defaultMacro = Macro(charIndex, page, slot)
        defaultMacro.name = defaultCommand.name
        defaultMacro.icon = defaultCommand.icon
        if not defaultMacro.icon.startswith('SPELLICON_'):
            defaultMacro.icon = 'icons/%s' % defaultMacro.icon
        defaultMacro.description = defaultCommand.tooltip
        defaultMacro.appendMacroLine(MacroLine(command=defaultCommand.command))

    # Return the default macro.
    return defaultMacro
Ejemplo n.º 26
0
  if "email" in a:
    return "#   Copyright (c) %(year)s %(name)s <%(email)s>" % a
  else:
    return "#   Copyright (c) %(year)s %(name)s" % a

def countSpaces(line):
  for i in range(len(line)):
    if not line[i].isspace():
      break
  return i

if len(sys.argv) != 3:
  raise Exception("invalid command line syntax: %s" % ' '.join(map(repr, sys.argv)))
(m4File,outFile) = sys.argv[1:]
assert outFile != m4File
m = Macro(m4File, computeSerialNumber=True)
for i in range(len(m.description)):
  para = m.description[i]
  if para[0][0].isspace():
    spaces = min(list(map(countSpaces, para)))
    if spaces > 1:
      m.description[i] = ['  ' + l[spaces:] for l in para]
url = "https://www.gnu.org/software/autoconf-archive/%s.html" % m.name
lineLen = max(len(url) + 2, 75)
m.url = "# %s\n# %s\n# %s" % ('=' * lineLen, (' ' * int((lineLen - len(url)) / 2)) + url, '=' * lineLen)
if m.__dict__.get("obsolete"):
  m.obsolete = "# OBSOLETE MACRO\n#\n" + '\n#\n'.join(map(formatParagraph, m.obsolete)) + "\n#\n"
else:
  m.obsolete = ""
m.synopsis = "\n".join([ "#   %s" % l for l in m.synopsis ])
m.description = '\n#\n'.join(map(formatParagraph, m.description))
Ejemplo n.º 27
0
        return "@smallexample\n%s\n@end smallexample" % quoteTexi(
            '\n'.join(para))
    else:
        return quoteTexi('\n'.join(para))


def formatAuthor(a):
    assert a
    a["year"] = quoteTexi(a["year"])
    a["name"] = quoteTexi(a["name"])
    if "email" in a:
        a["email"] = quoteTexi(a["email"])
        return "Copyright @copyright{} %(year)s %(name)s @email{%(email)s}" % a
    else:
        return "Copyright @copyright{} %(year)s %(name)s" % a


if len(sys.argv) != 3:
    raise Exception("invalid command line syntax: %s" %
                    ' '.join(map(repr, sys.argv)))
(m4File, outFile) = sys.argv[1:]
assert outFile != m4File
m = Macro(m4File)
m.synopsis = "@smallexample\n%s\n@end smallexample" % "\n".join(
    map(quoteTexi, m.synopsis))
m.description = '\n\n'.join(map(formatParagraph, m.description))
m.description = m.description.replace("@end smallexample\n@smallexample", "\n")
m.authors = " @* ".join(["@w{%s}" % formatAuthor(a) for a in m.authors])
m.license = "\n\n".join(map(formatParagraph, m.license))
writeFile(outFile, tmpl % m.__dict__)