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 at_start(self): """Set up the event system when starting. Note that this hook is called every time the server restarts (including when it's reloaded). This hook performs the following tasks: - Create temporarily stored events. - Generate locals (individual events' namespace). - Load eventfuncs, including user-defined ones. - Re-schedule tasks that aren't set to fire anymore. - Effectively connect the handler to the main script. """ self.ndb.events = {} for typeclass, name, variables, help_text, custom_call, custom_add in EVENTS: self.add_event(typeclass, name, variables, help_text, custom_call, custom_add) # Generate locals self.ndb.current_locals = {} self.ndb.fresh_locals = {} addresses = ["evennia.contrib.ingame_python.eventfuncs"] addresses.extend( getattr(settings, "EVENTFUNCS_LOCATIONS", ["world.eventfuncs"])) for address in addresses: if pypath_to_realpath(address): self.ndb.fresh_locals.update(all_from_module(address)) # Restart the delayed tasks now = datetime.now() for task_id, definition in tuple(self.db.tasks.items()): future, obj, event_name, locals = definition seconds = (future - now).total_seconds() if seconds < 0: seconds = 0 delay(seconds, complete_task, task_id) # Place the script in the CallbackHandler from evennia.contrib.ingame_python import typeclasses CallbackHandler.script = self DefaultObject.callbacks = typeclasses.EventObject.callbacks # Create the channel if non-existent try: self.ndb.channel = ChannelDB.objects.get(db_key="everror") except ChannelDB.DoesNotExist: self.ndb.channel = create_channel( "everror", desc="Event errors", locks="control:false();listen:perm(Builders);send:false()", )
def at_start(self): """Set up the event system when starting. Note that this hook is called every time the server restarts (including when it's reloaded). This hook performs the following tasks: - Create temporarily stored events. - Generate locals (individual events' namespace). - Load eventfuncs, including user-defined ones. - Re-schedule tasks that aren't set to fire anymore. - Effectively connect the handler to the main script. """ self.ndb.events = {} for typeclass, name, variables, help_text, custom_call, custom_add in EVENTS: self.add_event(typeclass, name, variables, help_text, custom_call, custom_add) # Generate locals self.ndb.current_locals = {} self.ndb.fresh_locals = {} addresses = ["evennia.contrib.ingame_python.eventfuncs"] addresses.extend(getattr(settings, "EVENTFUNCS_LOCATIONS", ["world.eventfuncs"])) for address in addresses: if pypath_to_realpath(address): self.ndb.fresh_locals.update(all_from_module(address)) # Restart the delayed tasks now = datetime.now() for task_id, definition in tuple(self.db.tasks.items()): future, obj, event_name, locals = definition seconds = (future - now).total_seconds() if seconds < 0: seconds = 0 delay(seconds, complete_task, task_id) # Place the script in the CallbackHandler from evennia.contrib.ingame_python import typeclasses CallbackHandler.script = self DefaultObject.callbacks = typeclasses.EventObject.callbacks # Create the channel if non-existent try: self.ndb.channel = ChannelDB.objects.get(db_key="everror") except ChannelDB.DoesNotExist: self.ndb.channel = create_channel("everror", desc="Event errors", locks="control:false();listen:perm(Builders);send:false()")
def load_apps(path="auto.apps", errors=None): """Dynamically-load the apps stored in modules.""" errors = errors or [] relpath = path.replace(".", os.path.sep) for content in os.listdir(relpath): if content == "base.py": continue if os.path.isfile(relpath + os.path.sep + content) and content.endswith( ".py") and not content.startswith("_"): # Obviously a module, try to load it try: variables = all_from_module(path + "." + content[:-3]) except Exception as err: errors.append((path + "." + content[:-3], str(err))) else: # Explore the module, looking for a class app = None for var in variables.values(): if issubclass(var, BaseApp) and getattr( var, "app_name", ""): app = var break if not app: errors.append((path + "." + content[:-3], "Could not find the application class")) else: folder = getattr(app, "folder", "app") if folder not in APPS: APPS[folder] = {} folder = APPS[folder] app_name = app.app_name folder[app_name] = app elif os.path.isdir(relpath + os.path.sep + content): # Explore the sub-folder load_apps(path + "." + content, errors) return errors
def load_module_prototypes(): """ This is called by `evennia.__init__` as Evennia initializes. It's important to do this late so as to not interfere with evennia initialization. """ for mod in settings.PROTOTYPE_MODULES: # to remove a default prototype, override it with an empty dict. # internally we store as (key, desc, locks, tags, prototype_dict) prots = [] for variable_name, prot in all_from_module(mod).items(): if isinstance(prot, dict): if "prototype_key" not in prot: prot["prototype_key"] = variable_name.lower() prots.append( (prot["prototype_key"], homogenize_prototype(prot))) # assign module path to each prototype_key for easy reference _MODULE_PROTOTYPE_MODULES.update( {prototype_key.lower(): mod for prototype_key, _ in prots}) # make sure the prototype contains all meta info for prototype_key, prot in prots: actual_prot_key = prot.get("prototype_key", prototype_key).lower() prot.update({ "prototype_key": actual_prot_key, "prototype_desc": prot["prototype_desc"] if "prototype_desc" in prot else mod, "prototype_locks": (prot["prototype_locks"] if "prototype_locks" in prot else "use:all();edit:false()"), "prototype_tags": list( set( list(make_iter(prot.get("prototype_tags", []))) + ["module"])), }) _MODULE_PROTOTYPES[actual_prot_key] = prot
homogenized["prototype_key"] = "prototype-{}".format( hashlib.md5(str(time.time())).hexdigest()[:7]) if "typeclass" not in prototype and "prototype_parent" not in prototype: homogenized["typeclass"] = settings.BASE_OBJECT_TYPECLASS return homogenized # module-based prototypes for mod in settings.PROTOTYPE_MODULES: # to remove a default prototype, override it with an empty dict. # internally we store as (key, desc, locks, tags, prototype_dict) prots = [] for variable_name, prot in all_from_module(mod).items(): if isinstance(prot, dict): if "prototype_key" not in prot: prot['prototype_key'] = variable_name.lower() prots.append((prot['prototype_key'], homogenize_prototype(prot))) # assign module path to each prototype_key for easy reference _MODULE_PROTOTYPE_MODULES.update({prototype_key.lower(): mod for prototype_key, _ in prots}) # make sure the prototype contains all meta info for prototype_key, prot in prots: actual_prot_key = prot.get('prototype_key', prototype_key).lower() prot.update({ "prototype_key": actual_prot_key, "prototype_desc": prot['prototype_desc'] if 'prototype_desc' in prot else mod, "prototype_locks": (prot['prototype_locks'] if 'prototype_locks' in prot else "use:all();edit:false()"), "prototype_tags": list(set(make_iter(prot.get('prototype_tags', [])) + ["module"]))})
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. prototype_parents - a dictionary holding a custom prototype-parent dictionary. Will overload same-named prototypes from 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))) #overload module's protparents with specifically given protparents protparents.update(kwargs.get("prototype_parents", {})) for key, prototype in protparents.items(): _validate_prototype(key, prototype, protparents, []) if "return_prototypes" in kwargs: # only return the parents return copy.deepcopy(protparents) objsparams = [] for prototype in prototypes: _validate_prototype(None, prototype, protparents, []) 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", "") tags = prot.pop("tags", "") # 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.startswith("ndb_"))) # pack for call into _batch_create_object objsparams.append((create_kwargs, permission_string, lock_string, alias_string, nattributes, attributes, tags)) return _batch_create_object(*objsparams)
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)
def spawn(*prototypes, **kwargs): """ Spawn a number of prototyped objects. Args: prototypes (dict): Each argument should be a prototype dictionary. Kwargs: prototype_modules (str or list): 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. prototype_parents (dict): A dictionary holding a custom prototype-parent dictionary. Will overload same-named prototypes from prototype_modules. return_prototypes (bool): 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))) # overload module's protparents with specifically given protparents protparents.update(kwargs.get("prototype_parents", {})) for key, prototype in protparents.items(): _validate_prototype(key, prototype, protparents, []) if "return_prototypes" in kwargs: # only return the parents return copy.deepcopy(protparents) objsparams = [] for prototype in prototypes: _validate_prototype(None, prototype, protparents, []) prot = _get_prototype(prototype, {}, protparents) if not prot: continue # extract the keyword args we need to create the object itself. If we get a callable, # call that to get the value (don't catch errors) create_kwargs = {} keyval = prot.pop("key", "Spawned Object %06i" % randint(1, 100000)) create_kwargs["db_key"] = keyval() if callable(keyval) else keyval locval = prot.pop("location", None) create_kwargs["db_location"] = locval() if callable(locval) else _handle_dbref(locval) homval = prot.pop("home", settings.DEFAULT_HOME) create_kwargs["db_home"] = homval() if callable(homval) else _handle_dbref(homval) destval = prot.pop("destination", None) create_kwargs["db_destination"] = destval() if callable(destval) else _handle_dbref(destval) typval = prot.pop("typeclass", settings.BASE_OBJECT_TYPECLASS) create_kwargs["db_typeclass_path"] = typval() if callable(typval) else typval # extract calls to handlers permval = prot.pop("permissions", []) permission_string = permval() if callable(permval) else permval lockval = prot.pop("locks", "") lock_string = lockval() if callable(lockval) else lockval aliasval = prot.pop("aliases", "") alias_string = aliasval() if callable(aliasval) else aliasval tagval = prot.pop("tags", []) tags = tagval() if callable(tagval) else tagval attrval = prot.pop("attrs", []) attributes = attrval() if callable(tagval) else attrval exval = prot.pop("exec", "") execs = make_iter(exval() if callable(exval) else exval) # 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 simple_attributes = [(key, value()) if callable(value) else (key, value) for key, value in prot.items() if not key.startswith("ndb_")] attributes = attributes + simple_attributes attributes = [tup for tup in attributes if not tup[0] in _CREATE_OBJECT_KWARGS] # pack for call into _batch_create_object objsparams.append((create_kwargs, permission_string, lock_string, alias_string, nattributes, attributes, tags, execs)) return _batch_create_object(*objsparams)
def spawn(*prototypes, **kwargs): """ Spawn a number of prototyped objects. Args: prototypes (dict): Each argument should be a prototype dictionary. Kwargs: prototype_modules (str or list): 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. prototype_parents (dict): A dictionary holding a custom prototype-parent dictionary. Will overload same-named prototypes from prototype_modules. return_prototypes (bool): 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))) # overload module's protparents with specifically given protparents protparents.update(kwargs.get("prototype_parents", {})) for key, prototype in protparents.items(): _validate_prototype(key, prototype, protparents, []) if "return_prototypes" in kwargs: # only return the parents return copy.deepcopy(protparents) objsparams = [] for prototype in prototypes: _validate_prototype(None, prototype, protparents, []) prot = _get_prototype(prototype, {}, protparents) if not prot: continue # extract the keyword args we need to create the object itself. If we get a callable, # call that to get the value (don't catch errors) create_kwargs = {} keyval = prot.pop("key", "Spawned Object %06i" % randint(1, 100000)) create_kwargs["db_key"] = keyval() if callable(keyval) else keyval locval = prot.pop("location", None) create_kwargs["db_location"] = locval() if callable( locval) else _handle_dbref(locval) homval = prot.pop("home", settings.DEFAULT_HOME) create_kwargs["db_home"] = homval() if callable( homval) else _handle_dbref(homval) destval = prot.pop("destination", None) create_kwargs["db_destination"] = destval() if callable( destval) else _handle_dbref(destval) typval = prot.pop("typeclass", settings.BASE_OBJECT_TYPECLASS) create_kwargs["db_typeclass_path"] = typval() if callable( typval) else typval # extract calls to handlers permval = prot.pop("permissions", []) permission_string = permval() if callable(permval) else permval lockval = prot.pop("locks", "") lock_string = lockval() if callable(lockval) else lockval aliasval = prot.pop("aliases", "") alias_string = aliasval() if callable(aliasval) else aliasval tagval = prot.pop("tags", []) tags = tagval() if callable(tagval) else tagval attrval = prot.pop("attrs", []) attributes = attrval() if callable(tagval) else attrval exval = prot.pop("exec", "") execs = make_iter(exval() if callable(exval) else exval) # 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 simple_attributes = [(key, value()) if callable(value) else (key, value) for key, value in prot.items() if not key.startswith("ndb_")] attributes = attributes + simple_attributes attributes = [ tup for tup in attributes if not tup[0] in _CREATE_OBJECT_KWARGS ] # pack for call into _batch_create_object objsparams.append((create_kwargs, permission_string, lock_string, alias_string, nattributes, attributes, tags, execs)) return _batch_create_object(*objsparams)
if key in reserved: homogenized[key] = val else: attrs.append((key, val, None, '')) if attrs: homogenized['attrs'] = attrs return homogenized # module-based prototypes for mod in settings.PROTOTYPE_MODULES: # to remove a default prototype, override it with an empty dict. # internally we store as (key, desc, locks, tags, prototype_dict) prots = [(prototype_key.lower(), homogenize_prototype(prot)) for prototype_key, prot in all_from_module(mod).items() if prot and isinstance(prot, dict)] # assign module path to each prototype_key for easy reference _MODULE_PROTOTYPE_MODULES.update({prototype_key.lower(): mod for prototype_key, _ in prots}) # make sure the prototype contains all meta info for prototype_key, prot in prots: actual_prot_key = prot.get('prototype_key', prototype_key).lower() prot.update({ "prototype_key": actual_prot_key, "prototype_desc": prot['prototype_desc'] if 'prototype_desc' in prot else mod, "prototype_locks": (prot['prototype_locks'] if 'prototype_locks' in prot else "use:all();edit:false()"), "prototype_tags": list(set(make_iter(prot.get('prototype_tags', [])) + ["module"]))}) _MODULE_PROTOTYPES[actual_prot_key] = prot
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. prototype_parents - a dictionary holding a custom prototype-parent dictionary. Will overload same-named prototypes from 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))) #overload module's protparents with specifically given protparents protparents.update(kwargs.get("prototype_parents", {})) for key, prototype in protparents.items(): _validate_prototype(key, prototype, protparents, []) if "return_prototypes" in kwargs: # only return the parents return copy.deepcopy(protparents) objsparams = [] for prototype in prototypes: _validate_prototype(None, prototype, protparents, []) 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)