Esempio n. 1
0
    def edit_handler(self):
        char = self.character
        target = self.target
        if self.args:
            self.msg(
                "|yYou may specify a description, or use the edit switch, "
                "but not both.|n")
            return
        else:
            obj = char

        def load(obj):
            return obj.db.evmenu_target.db.desc or ''

        def save(obj, buf):
            """
            Save line buffer to the desc prop. This should return True
            if successful and also report its status to the user.
            """
            obj.db.evmenu_target.db.desc = buf
            obj.msg('Saved.')
            return True

        def quit(obj):
            obj.attributes.remove('evmenu_target')
            obj.msg('Exited editor.')

        char.db.evmenu_target = target  # launch the editor
        EvEditor(obj, loadfunc=load, savefunc=save, quitfunc=quit, key='desc')
        return
Esempio n. 2
0
    def func(self):
        """hook function"""

        caller = self.caller
        pycode = self.args

        if "edit" in self.switches:
            caller.db._py_measure_time = "time" in self.switches
            EvEditor(self.caller,
                     loadfunc=_py_load,
                     savefunc=_py_code,
                     quitfunc=_py_quit,
                     key="Python exec: :w  or :!",
                     persistent=True,
                     codefunc=_py_code)
            return

        if not pycode:
            string = "Usage: @py <code>"
            self.msg(string)
            return

        _run_code_snippet(caller,
                          self.args,
                          measure_time="time" in self.switches)
Esempio n. 3
0
    def func(self):
        """hook function"""

        caller = self.caller
        pycode = self.args

        noecho = "noecho" in self.switches

        if "edit" in self.switches:
            caller.db._py_measure_time = "time" in self.switches
            caller.db._py_clientraw = "clientraw" in self.switches
            EvEditor(
                self.caller,
                loadfunc=_py_load,
                savefunc=_py_code,
                quitfunc=_py_quit,
                key="Python exec: :w  or :!",
                persistent=True,
                codefunc=_py_code,
            )
            return

        if not pycode:
            # Run in interactive mode
            console = EvenniaPythonConsole(self.caller)
            banner = (
                "|gEvennia Interactive Python mode{echomode}\n"
                "Python {version} on {platform}".format(
                    echomode=" (no echoing of prompts)" if noecho else "",
                    version=sys.version,
                    platform=sys.platform,
                )
            )
            self.msg(banner)
            line = ""
            main_prompt = "|x[py mode - quit() to exit]|n"
            prompt = main_prompt
            while line.lower() not in ("exit", "exit()"):
                try:
                    line = yield (prompt)
                    if noecho:
                        prompt = "..." if console.push(line) else main_prompt
                    else:
                        prompt = line if console.push(line) else f"{line}\n{main_prompt}"
                except SystemExit:
                    break
            self.msg("|gClosing the Python console.|n")
            return

        _run_code_snippet(
            caller,
            self.args,
            measure_time="time" in self.switches,
            client_raw="clientraw" in self.switches,
        )
Esempio n. 4
0
 def func(self):
     """Open the line editor to edit the description."""
     location = self.caller.location
     self.caller.db.evmenu_target = self.caller.location
     # Launch the editor
     EvEditor(self.caller,
              loadfunc=_desc_load,
              savefunc=_desc_save,
              quitfunc=_desc_quit,
              key="desc",
              persistent=True)
Esempio n. 5
0
    def func(self):
        caller = self.caller
        opts = self.opts

        if opts.loc:
            location = caller.search(opts.loc, global_search=True)
            if not location:
                caller.msg("Destination not found.")
                return
        else:
            location = caller.location

        existing = search_script("EnvScript", obj=location)

        if opts.type == "init":
            if len(existing) > 0:
                caller.msg("An EnvScript already exists.")
                return

            script = create_script(EnvScript, obj=location, key="EnvScript")
        elif len(existing) == 1:
            script = existing[0]
        elif len(existing) == 0:
            caller.msg("No script found.")
            return
        else:
            caller.msg("Error: multiple scripts found.")
            return

        if opts.type == "init" or opts.type == "edit":

            def _env_load(caller):
                return "\n".join(script.db.messages)

            def _env_save(caller, buffer):
                script.db.messages = buffer.splitlines()
                caller.msg("Messages saved.")
                return

            caller.msg("Please place one message on each line.")
            EvEditor(caller,
                     loadfunc=_env_load,
                     savefunc=_env_save,
                     key="Save messages: :w")

        if opts.type == "status":
            caller.msg("The script is operational.")

        if opts.type == "rm":
            script.delete()
            caller.msg("Script deleted.")
Esempio n. 6
0
def menu_edit(caller, choice, obj):
    """
    Open the EvEditor to edit a specified field.

    Args:
        caller (Account or Object): the caller.
        choice (Choice): the choice object.
        obj (Object): the object to edit.

    """
    attr = choice.attr
    caller.db._building_menu_to_edit = (obj, attr)
    caller.cmdset.remove(BuildingMenuCmdSet)
    EvEditor(caller,
             loadfunc=_menu_loadfunc,
             savefunc=_menu_savefunc,
             quitfunc=_menu_quitfunc,
             key="editor",
             persistent=True)
Esempio n. 7
0
    def func(self):
        """hook function"""

        caller = self.caller
        pycode = self.args

        if "edit" in self.switches:
            caller.db._py_measure_time = "time" in self.switches
            caller.db._py_clientraw = "clientraw" in self.switches
            EvEditor(
                self.caller,
                loadfunc=_py_load,
                savefunc=_py_code,
                quitfunc=_py_quit,
                key="Python exec: :w  or :!",
                persistent=True,
                codefunc=_py_code,
            )
            return

        if not pycode:
            # Run in interactive mode
            console = EvenniaPythonConsole(self.caller)
            banner = (
                f"|gPython {sys.version} on {sys.platform}\n"
                "Evennia interactive console mode - type 'exit()' to leave.|n")
            self.msg(banner)
            line = ""
            prompt = ">>>"
            while line.lower() not in ("exit", "exit()"):
                line = yield (prompt)
                prompt = "..." if console.push(line) else ">>>"
            self.msg("|gClosing the Python console.|n")
            return

        _run_code_snippet(
            caller,
            self.args,
            measure_time="time" in self.switches,
            client_raw="clientraw" in self.switches,
        )
Esempio n. 8
0
    def add_callback(self):
        """Add a callback."""
        obj = self.obj
        callback_name = self.callback_name
        types = self.handler.get_events(obj)

        # Check that the callback exists
        if not callback_name.startswith(
                "chain_") and not callback_name in types:
            self.msg("The callback name {} can't be found in {} of " \
                    "typeclass {}.".format(callback_name, obj, type(obj)))
            return

        definition = types.get(callback_name, (None, "Chained event."))
        description = definition[1]
        self.msg(raw(description.strip("\n")))

        # Open the editor
        callback = self.handler.add_callback(obj,
                                             callback_name,
                                             "",
                                             self.caller,
                                             False,
                                             parameters=self.parameters)

        # Lock this callback right away
        self.handler.db.locked.append((obj, callback_name, callback["number"]))

        # Open the editor for this callback
        self.caller.db._callback = callback
        EvEditor(self.caller,
                 loadfunc=_ev_load,
                 savefunc=_ev_save,
                 quitfunc=_ev_quit,
                 key="Callback {} of {}".format(callback_name, obj),
                 persistent=True,
                 codefunc=_ev_save)
Esempio n. 9
0
    def func(self):
        """Implement the function"""

        switches = self.switches
        lhslist = self.lhslist

        if not self.args:
            self.msg(
                "Usage: @sethelp[/switches] <topic>[;alias;alias][,category[,locks,..] = <text>"
            )
            return

        nlist = len(lhslist)
        topicstr = lhslist[0] if nlist > 0 else ""
        if not topicstr:
            self.msg("You have to define a topic!")
            return
        topicstrlist = topicstr.split(";")
        topicstr, aliases = topicstrlist[0], topicstrlist[1:] if len(
            topicstr) > 1 else []
        aliastxt = ("(aliases: %s)" % ", ".join(aliases)) if aliases else ""
        old_entry = None

        # check if we have an old entry with the same name
        try:
            for querystr in topicstrlist:
                old_entry = HelpEntry.objects.find_topicmatch(
                    querystr)  # also search by alias
                if old_entry:
                    old_entry = list(old_entry)[0]
                    break
            category = lhslist[1] if nlist > 1 else old_entry.help_category
            lockstring = ",".join(
                lhslist[2:]) if nlist > 2 else old_entry.locks.get()
        except Exception:
            old_entry = None
            category = lhslist[1] if nlist > 1 else "General"
            lockstring = ",".join(lhslist[2:]) if nlist > 2 else "view:all()"
        category = category.lower()

        if 'edit' in switches:
            # open the line editor to edit the helptext. No = is needed.
            if old_entry:
                topicstr = old_entry.key
                if self.rhs:
                    # we assume append here.
                    old_entry.entrytext += "\n%s" % self.rhs
                helpentry = old_entry
            else:
                helpentry = create.create_help_entry(topicstr,
                                                     self.rhs,
                                                     category=category,
                                                     locks=lockstring,
                                                     aliases=aliases)
            self.caller.db._editing_help = helpentry

            EvEditor(self.caller,
                     loadfunc=_loadhelp,
                     savefunc=_savehelp,
                     quitfunc=_quithelp,
                     key="topic {}".format(topicstr),
                     persistent=True)
            return

        if 'append' in switches or "merge" in switches or "extend" in switches:
            # merge/append operations
            if not old_entry:
                self.msg(
                    "Could not find topic '%s'. You must give an exact name." %
                    topicstr)
                return
            if not self.rhs:
                self.msg("You must supply text to append/merge.")
                return
            if 'merge' in switches:
                old_entry.entrytext += " " + self.rhs
            else:
                old_entry.entrytext += "\n%s" % self.rhs
            old_entry.aliases.add(aliases)
            self.msg("Entry updated:\n%s%s" % (old_entry.entrytext, aliastxt))
            return
        if 'delete' in switches or 'del' in switches:
            # delete the help entry
            if not old_entry:
                self.msg("Could not find topic '%s'%s." % (topicstr, aliastxt))
                return
            old_entry.delete()
            self.msg("Deleted help entry '%s'%s." % (topicstr, aliastxt))
            return

        # at this point it means we want to add a new help entry.
        if not self.rhs:
            self.msg("You must supply a help text to add.")
            return
        if old_entry:
            if 'replace' in switches:
                # overwrite old entry
                old_entry.key = topicstr
                old_entry.entrytext = self.rhs
                old_entry.help_category = category
                old_entry.locks.clear()
                old_entry.locks.add(lockstring)
                old_entry.aliases.add(aliases)
                old_entry.save()
                self.msg("Overwrote the old topic '%s'%s." %
                         (topicstr, aliastxt))
            else:
                self.msg(
                    "Topic '%s'%s already exists. Use /replace to overwrite "
                    "or /append or /merge to add text to it." %
                    (topicstr, aliastxt))
        else:
            # no old entry. Create a new one.
            new_entry = create.create_help_entry(topicstr,
                                                 self.rhs,
                                                 category=category,
                                                 locks=lockstring,
                                                 aliases=aliases)
            if new_entry:
                self.msg("Topic '%s'%s was successfully created." %
                         (topicstr, aliastxt))
                if 'edit' in switches:
                    # open the line editor to edit the helptext
                    self.caller.db._editing_help = new_entry
                    EvEditor(self.caller,
                             loadfunc=_loadhelp,
                             savefunc=_savehelp,
                             quitfunc=_quithelp,
                             key="topic {}".format(new_entry.key),
                             persistent=True)
                    return
            else:
                self.msg(
                    "Error when creating topic '%s'%s! Contact an admin." %
                    (topicstr, aliastxt))
Esempio n. 10
0
    def func(self):
        """
        Implements the multidescer.  We will use `db.desc` for the
        description in use and `db.multidesc` to store all descriptions.
        """

        caller = self.caller
        args = self.args.strip()
        switches = self.switches

        try:
            if "list" in switches or "all" in switches:
                # list all stored descriptions, either in full or cropped.
                # Note that we list starting from 1, not from 0.
                _update_store(caller)
                do_crop = not "full" in switches
                if do_crop:
                    outtext = [
                        "|w%s:|n %s" % (key, crop(desc))
                        for key, desc in caller.db.multidesc
                    ]
                else:
                    outtext = [
                        "\n|w%s:|n|n\n%s\n%s" % (key, "-" *
                                                 (len(key) + 1), desc)
                        for key, desc in caller.db.multidesc
                    ]

                caller.msg("|wStored descs:|n\n" + "\n".join(outtext))
                return

            elif "edit" in switches:
                # Use the eveditor to edit/create the named description
                if not args:
                    caller.msg("Usage: %s/edit key" % self.key)
                    return

                # this is used by the editor to know what to edit; it's deleted automatically
                caller.db._multidesc_editkey = args
                # start the editor
                EvEditor(caller,
                         loadfunc=_load_editor,
                         savefunc=_save_editor,
                         quitfunc=_quit_editor,
                         key="multidesc editor",
                         persistent=True)

            elif "delete" in switches or "del" in switches:
                # delete a multidesc entry.
                if not args:
                    caller.msg("Usage: %s/delete key" % self.key)
                    return
                _update_store(caller, args, delete=True)
                caller.msg("Deleted description with key '%s'." % args)

            elif "swap" in switches or "switch" in switches or "reorder" in switches:
                # Reorder list by swapping two entries. We expect numbers starting from 1
                keys = [arg for arg in args.split("-", 1)]
                if not len(keys) == 2:
                    caller.msg("Usage: %s/swap key1-key2" % self.key)
                    return
                key1, key2 = keys
                # perform the swap
                _update_store(caller, key1, swapkey=key2)
                caller.msg("Swapped descs '%s' and '%s'." % (key1, key2))

            elif "set" in switches:
                # switches one (or more) of the multidescs to be the "active" description
                _update_store(caller)
                if not args:
                    caller.msg("Usage: %s/set key [+ key2 + key3 + ...]" %
                               self.key)
                    return
                new_desc = []
                multidesc = caller.db.multidesc
                for key in args.split("+"):
                    notfound = True
                    lokey = key.strip().lower()
                    for mkey, desc in multidesc:
                        if lokey == mkey:
                            new_desc.append(desc)
                            notfound = False
                            continue
                    if notfound:
                        # if we get here, there is no desc match, we add it as a normal string
                        new_desc.append(key)
                new_desc = "".join(new_desc)
                caller.db.desc = new_desc
                caller.msg(
                    "%s\n\n|wThe above was set as the current description.|n" %
                    new_desc)

            elif self.rhs or "add" in switches:
                # add text directly to a new entry or an existing one.
                if not (self.lhs and self.rhs):
                    caller.msg("Usage: %s/add key = description" % self.key)
                    return
                key, desc = self.lhs, self.rhs
                _update_store(caller, key, desc)
                caller.msg("Stored description '%s': \"%s\"" %
                           (key, crop(desc)))

            else:
                # display the current description or a numbered description
                _update_store(caller)
                if args:
                    key = args.lower()
                    multidesc = caller.db.multidesc
                    for mkey, desc in multidesc:
                        if key == mkey:
                            caller.msg("|wDecsription %s:|n\n%s" % (key, desc))
                            return
                    caller.msg("Description key '%s' not found." % key)
                else:
                    caller.msg("|wCurrent desc:|n\n%s" % caller.db.desc)

        except DescValidateError, err:
            # This is triggered by _key_to_index
            caller.msg(err)
Esempio n. 11
0
    def edit_callback(self):
        """Edit a callback."""
        obj = self.obj
        callback_name = self.callback_name
        parameters = self.parameters
        callbacks = self.handler.get_callbacks(obj)
        types = self.handler.get_events(obj)

        # If no callback name is specified, display the list of callbacks
        if not callback_name:
            self.list_callbacks()
            return

        # Check that the callback exists
        if not callback_name in callbacks:
            self.msg("The callback name {} can't be found in {}.".format(
                callback_name, obj))
            return

        # If there's only one callback, just edit it
        if len(callbacks[callback_name]) == 1:
            number = 0
            callback = callbacks[callback_name][0]
        else:
            if not parameters:
                self.msg(
                    "Which callback do you wish to edit?  Specify a number.")
                self.list_callbacks()
                return

            # Check that the parameter points to an existing callback
            try:
                number = int(parameters) - 1
                assert number >= 0
                callback = callbacks[callback_name][number]
            except (ValueError, AssertionError, IndexError):
                self.msg("The callback {} {} cannot be found in {}.".format(
                    callback_name, parameters, obj))
                return

        # If caller can't edit without validation, forbid editing
        # others' works
        if not self.autovalid and callback["author"] is not self.caller:
            self.msg("You cannot edit this callback created by someone else.")
            return

        # If the callback is locked (edited by someone else)
        if (obj, callback_name, number) in self.handler.db.locked:
            self.msg("This callback is locked, you cannot edit it.")
            return

        self.handler.db.locked.append((obj, callback_name, number))

        # Check the definition of the callback
        definition = types.get(callback_name, (None, "Chained event."))
        description = definition[1]
        self.msg(raw(description.strip("\n")))

        # Open the editor
        callback = dict(callback)
        self.caller.db._callback = callback
        EvEditor(self.caller,
                 loadfunc=_ev_load,
                 savefunc=_ev_save,
                 quitfunc=_ev_quit,
                 key="Callback {} of {}".format(callback_name, obj),
                 persistent=True,
                 codefunc=_ev_save)