예제 #1
0
파일: evform.py 프로젝트: Aumnren/evennia
    def reload(self, filename=None, form=None, **kwargs):
        """
        Creates the form from a stored file name
        """
        # clean kwargs (these cannot be overridden)
        kwargs.pop("enforce_size", None)
        kwargs.pop("width", None)
        kwargs.pop("height", None)

        if form or self.input_form_dict:
            datadict = form if form else self.input_form_dict
            self.input_form_dict = datadict
        elif filename or self.filename:
            filename = filename if filename else self.filename
            datadict = all_from_module(filename)
            self.filename = filename
        else:
            datadict = {}

        cellchar = to_str(datadict.get("FORMCHAR", "x"))
        self.cellchar = to_str(cellchar[0] if len(cellchar) > 1 else cellchar)
        tablechar = datadict.get("TABLECHAR", "c")
        self.tablechar = tablechar[0] if len(tablechar) > 1 else tablechar

        # split into a list of list of lines. Form can be indexed with form[iy][ix]
        self.raw_form = to_unicode(datadict.get("FORM", "")).split("\n")
        # strip first line
        self.raw_form = self.raw_form[1:] if self.raw_form else self.raw_form

        self.options.update(kwargs)

        # parse and replace
        self.mapping = self._parse_rectangles(self.cellchar, self.tablechar, self.raw_form, **kwargs)
        self.form = self._populate_form(self.raw_form, self.mapping)
예제 #2
0
    def reload(self, filename=None, form=None, **kwargs):
        """
        Creates the form from a stored file name
        """
        # clean kwargs (these cannot be overridden)
        kwargs.pop("enforce_size", None)
        kwargs.pop("width", None)
        kwargs.pop("height", None)

        if form or self.input_form_dict:
            datadict = form if form else self.input_form_dict
            self.input_form_dict = datadict
        elif filename or self.filename:
            filename = filename if filename else self.filename
            datadict = all_from_module(filename)
            self.filename = filename
        else:
            datadict = {}

        cellchar = to_str(datadict.get("FORMCHAR", "x"))
        self.cellchar = to_str(cellchar[0] if len(cellchar) > 1 else cellchar)
        tablechar = datadict.get("TABLECHAR", "c")
        self.tablechar = tablechar[0] if len(tablechar) > 1 else tablechar

        # split into a list of list of lines. Form can be indexed with form[iy][ix]
        self.raw_form = _to_ansi(to_unicode(datadict.get("FORM", "")).split("\n"))
        # strip first line
        self.raw_form = self.raw_form[1:] if self.raw_form else self.raw_form

        self.options.update(kwargs)

        # parse and replace
        self.mapping = self._parse_rectangles(self.cellchar, self.tablechar, self.raw_form, **kwargs)
        self.form = self._populate_form(self.raw_form, self.mapping)
def get_command_docs(directory="commands/default/"):
    """
    Loads all commands from their locations
    """
    directory = SRC + sep + directory
    print "directory set to %s" % directory
    NOUSE = ("muxcommand.py", "syscommands.py", "tests.py")

    cmddict = collections.defaultdict(list)
    for filename in glob.glob(directory + sep + "*.py"):
        fname = filename.split(sep)[-1]

        if fname.startswith("cmdset_") or \
                fname.startswith("_") or fname in NOUSE:
            continue

        print "reading %s ..." % fname

        module = mod_import(filename)
        allist = module.__all__
        props = all_from_module(module)

        for cls in props.values():
            if not callable(cls): continue
            clsname = cls.__name__
            if not clsname in allist: continue
            key = cls.key
            doc = cls.__doc__.strip('\n').strip()
            aliases = cls.__dict__.get("aliases", "<None>")
            locks = cls.__dict__.get("locks", "cmd:all()")
            help_category = cls.__dict__.get("help_category", "General").capitalize()
            extra = ""
            if key.startswith("__"):
                extra = "\n*OBS: This is a [[System Command|Commands]] name - it belongs to a number "
                extra += "of command names the server calls in certain situations or as fallbacks.*"

            cmddict[filename].append({"key":key, "clsname":clsname, "aliases":aliases, "fname":fname,
                                      "locks":locks, "help_category":help_category, "doc":doc,
                                      "extra":extra})
    return cmddict
예제 #4
0
from src.server.models import ServerConfig
from src.server.sessionhandler import SESSIONS
from src.scripts.scripts import Script
from src.utils.create import create_script
from src.utils.dbserialize import dbserialize, dbunserialize, pack_dbobj, unpack_dbobj
from src.utils import logger
from src.utils.utils import all_from_module, make_iter

_SA = object.__setattr__
_GA = object.__getattribute__
_DA = object.__delattr__

# load from plugin module
_OOB_FUNCS = {}
for mod in make_iter(settings.OOB_PLUGIN_MODULES):
    _OOB_FUNCS.update(dict((key.lower(), func) for key, func in all_from_module(mod).items() if isfunction(func)))
_OOB_ERROR = _OOB_FUNCS.get("oob_error", None)


class TrackerHandler(object):
    """
    This object is dynamically assigned to objects whenever one of its fields
    are to be tracked. It holds an internal dictionary mapping to the fields
    on that object. Each field can be tracked by any number of trackers (each
    tied to a different callback).
    """
    def __init__(self, obj):
        """
        This is initiated and stored on the object as a
        property _trackerhandler.
        """
예제 #5
0
    return time.strftime(strformat)


def you(text, *args, **kwargs):
    "Inserts your name"
    name = "You"
    sess = kwargs.get("session")
    if sess and sess.puppet:
        name = sess.puppet.key
    return name


# load functions from module (including this one, if using default settings)
_INLINE_FUNCS = {}
for module in utils.make_iter(settings.INLINEFUNC_MODULES):
    _INLINE_FUNCS.update(utils.all_from_module(module))
_INLINE_FUNCS.pop("inline_func_parse", None)

# dynamically build regexes for found functions
_RE_FUNCFULL = r"\{%s\((.*?)\)(.*?){/%s"
_RE_FUNCFULL_SINGLE = r"\{%s\((.*?)\)"
_RE_FUNCSTART = r"\{((?:%s))"
_RE_FUNCEND = r"\{/((?:%s))"
_RE_FUNCSPLIT = r"(\{/*(?:%s)(?:\(.*?\))*)"
_RE_FUNCCLEAN = r"\{%s\(.*?\)|\{/%s"

_INLINE_FUNCS = dict(
    (key, (func,
           re.compile(_RE_FUNCFULL % (key, key), re.DOTALL & re.MULTILINE),
           re.compile(_RE_FUNCFULL_SINGLE % key, re.DOTALL & re.MULTILINE)))
    for key, func in _INLINE_FUNCS.items() if callable(func))
예제 #6
0
def spawn(*prototypes, **kwargs):
    """
    Spawn a number of prototyped objects. Each argument should be a
    prototype dictionary.

    keyword args:
        prototype_modules - a python-path to a
            prototype module, or a list of such paths. These will be used
            to build the global protparents dictionary accessible by the
            input prototypes. If not given, it will instead look for modules
            defined by settings.PROTOTYPE_MODULES.
        return_prototypes - only return a list of the prototype-parents
                            (no object creation happens)
    """

    protparents = {}
    protmodules = make_iter(kwargs.get("prototype_modules", []))
    if not protmodules and hasattr(settings, "PROTOTYPE_MODULES"):
        protmodules = make_iter(settings.PROTOTYPE_MODULES)
    for prototype_module in protmodules:
        protparents.update(
            dict((key, val)
                 for key, val in all_from_module(prototype_module).items()
                 if isinstance(val, dict)))

    if "return_prototypes" in kwargs:
        # only return the parents
        return protparents

    objsparams = []
    for prototype in prototypes:

        prot = _get_prototype(prototype, {}, protparents, [])
        if not prot:
            continue

        # extract the keyword args we need to create the object itself
        create_kwargs = {}
        create_kwargs["db_key"] = prot.pop(
            "key", "Spawned Object %06i" % randint(1, 100000))
        create_kwargs["db_location"] = _handle_dbref(prot.pop(
            "location", None))
        create_kwargs["db_home"] = _handle_dbref(
            prot.pop("home", settings.DEFAULT_HOME))
        create_kwargs["db_destination"] = _handle_dbref(
            prot.pop("destination", None))
        create_kwargs["db_typeclass_path"] = prot.pop(
            "typeclass", settings.BASE_OBJECT_TYPECLASS)

        # extract calls to handlers
        permission_string = prot.pop("permissions", "")
        lock_string = prot.pop("locks", "")
        alias_string = prot.pop("aliases", "")

        # extract ndb assignments
        nattributes = dict(
            (key.split("_", 1)[1], value if callable(value) else value)
            for key, value in prot.items() if key.startswith("ndb_"))

        # the rest are attributes
        attributes = dict(
            (key, value() if callable(value) else value)
            for key, value in prot.items()
            if not (key in _CREATE_OBJECT_KWARGS or key in nattributes))

        # pack for call into _batch_create_object
        objsparams.append((create_kwargs, permission_string, lock_string,
                           alias_string, nattributes, attributes))

    return _batch_create_object(*objsparams)
예제 #7
0
        strformat = str(args[0])
    return time.strftime(strformat)

def you(text, *args, **kwargs):
    "Inserts your name"
    name = "You"
    sess = kwargs.get("session")
    if sess and sess.puppet:
        name = sess.puppet.key
    return name


# load functions from module (including this one, if using default settings)
_INLINE_FUNCS = {}
for module in utils.make_iter(settings.INLINEFUNC_MODULES):
    _INLINE_FUNCS.update(utils.all_from_module(module))
_INLINE_FUNCS.pop("inline_func_parse", None)


# dynamically build regexes for found functions
_RE_FUNCFULL = r"\{%s\((.*?)\)(.*?){/%s"
_RE_FUNCFULL_SINGLE = r"\{%s\((.*?)\)"
_RE_FUNCSTART = r"\{((?:%s))"
_RE_FUNCEND = r"\{/((?:%s))"
_RE_FUNCSPLIT = r"(\{/*(?:%s)(?:\(.*?\))*)"
_RE_FUNCCLEAN = r"\{%s\(.*?\)|\{/%s"

_INLINE_FUNCS = dict((key, (func, re.compile(_RE_FUNCFULL % (key, key), re.DOTALL &  re.MULTILINE),
                                  re.compile(_RE_FUNCFULL_SINGLE % key, re.DOTALL & re.MULTILINE)))
                          for key, func in _INLINE_FUNCS.items() if callable(func))
_FUNCSPLIT_REGEX = re.compile(_RE_FUNCSPLIT % r"|".join([key for key in _INLINE_FUNCS]), re.DOTALL & re.MULTILINE)
예제 #8
0
def spawn(*prototypes, **kwargs):
    """
    Spawn a number of prototyped objects. Each argument should be a
    prototype dictionary.

    keyword args:
        prototype_modules - a python-path to a
            prototype module, or a list of such paths. These will be used
            to build the global protparents dictionary accessible by the
            input prototypes. If not given, it will instead look for modules
            defined by settings.PROTOTYPE_MODULES.
        return_prototypes - only return a list of the prototype-parents
                            (no object creation happens)
    """

    protparents = {}
    protmodules = make_iter(kwargs.get("prototype_modules", []))
    if not protmodules and hasattr(settings, "PROTOTYPE_MODULES"):
        protmodules = make_iter(settings.PROTOTYPE_MODULES)
    for prototype_module in protmodules:
        protparents.update(dict((key, val)
                for key, val in all_from_module(prototype_module).items() if isinstance(val, dict)))

    if "return_prototypes" in kwargs:
        # only return the parents
        return protparents

    objsparams = []
    for prototype in prototypes:

        prot = _get_prototype(prototype, {}, protparents, [])
        if not prot:
            continue

        # extract the keyword args we need to create the object itself
        create_kwargs = {}
        create_kwargs["db_key"] = prot.pop("key", "Spawned Object %06i" % randint(1,100000))
        create_kwargs["db_location"] = _handle_dbref(prot.pop("location", None))
        create_kwargs["db_home"] = _handle_dbref(prot.pop("home", settings.DEFAULT_HOME))
        create_kwargs["db_destination"] = _handle_dbref(prot.pop("destination", None))
        create_kwargs["db_typeclass_path"] = prot.pop("typeclass", settings.BASE_OBJECT_TYPECLASS)

        # extract calls to handlers
        permission_string = prot.pop("permissions", "")
        lock_string = prot.pop("locks", "")
        alias_string = prot.pop("aliases", "")

        # extract ndb assignments
        nattributes = dict((key.split("_", 1)[1], value if callable(value) else value)
                            for key, value in prot.items() if key.startswith("ndb_"))

        # the rest are attributes
        attributes = dict((key, value() if callable(value) else value)
                           for key, value in prot.items()
                           if not (key in _CREATE_OBJECT_KWARGS or key in nattributes))

        # pack for call into _batch_create_object
        objsparams.append( (create_kwargs, permission_string, lock_string,
                            alias_string, nattributes, attributes) )

    return _batch_create_object(*objsparams)
예제 #9
0
#from src.scripts.scripts import Script
#from src.utils.create import create_script
from src.scripts.tickerhandler import Ticker, TickerPool, TickerHandler
from src.utils.dbserialize import dbserialize, dbunserialize, pack_dbobj, unpack_dbobj
from src.utils import logger
from src.utils.utils import all_from_module, make_iter, to_str

_SA = object.__setattr__
_GA = object.__getattribute__
_DA = object.__delattr__

# load resources from plugin module
_OOB_FUNCS = {}
for mod in make_iter(settings.OOB_PLUGIN_MODULES):
    _OOB_FUNCS.update(
        dict((key.lower(), func) for key, func in all_from_module(mod).items()
             if isfunction(func)))

# get custom error method or use the default
_OOB_ERROR = _OOB_FUNCS.get("oob_error", None)
if not _OOB_ERROR:
    # create default oob error message function
    def oob_error(oobhandler, session, errmsg, *args, **kwargs):
        "Error wrapper"
        session.msg(oob=("err", ("ERROR ", errmsg)))

    _OOB_ERROR = oob_error

#
# TrackerHandler is assigned to objects that should notify themselves to
# the OOB system when some property changes. This is never assigned manually