def loadMovementsFromConfigFile(self, config_file): """Load movements from config file. Args: config_file: String Returns: Boolean """ if (not os.path.isfile(config_file + '.py') and not os.path.isfile(config_file + '.pyc')): tf.err('Could not find file: %s [.py or .pyc]' % config_file) return False path, basename = os.path.split(config_file) movements = self.loadMovementsListFromConfigFile(path, basename) if not isinstance(movements, list): tf.err('The FILE attribute is not a list.') return False self.fixMovements(movements) self.loadMovementsFromDictList(movements) tf.eval('/say -d"party" -b -c"green" -- Loaded run from config: %s' % basename) self._name = basename self._path = config_file return True
def load(self, path): if not os.path.isfile(path): tf.err('Could not find file: %s' % path) return False try: fh = open(path, 'r') except IOError, e: tf.err('IOError: %s' % e) return False
def addGroup(self, effect_group): """Add an effect group. Args: effect_group: """ if effect_group.key in self._effects: tf.err('effect.group.key is an effect: %s' % effect_group.key) return self._effect_groups[effect_group.key] = effect_group
def loadMovementsListFromConfigFile(path, basename): sys_path = sys.path try: sys.path = [path] try: module = reload(__import__(basename)) except ImportError, e: tf.err('ImportError: %s' % e) return False except NameError, e: tf.err('NameError: %s' % e) return False
def add(self, effect): """Add an effect. Args: effect: Boolean """ if effect.key in self._effect_groups: tf.err('effect.key is an effect group: %s' % effect.key) return self._effects[effect.key] = effect if not effect.groups: return for group in effect.groups: if group not in self._effect_groups: tf.err('effect.groups does not exist: %s' % group) continue self._effect_groups[group].add(effect)
def upload(argstr): # # argument parsing is much larger than actual logic! # if not argstr: return help() args = argstr.split() # check for raw flag if "-r" in args: raw = True args.remove("-r") else: raw = False # lines per second and progress lps, prog = LINES_PER_SECOND, 0 args2 = [] for i, arg in enumerate(args): # progress if arg.startswith("-p"): prog = 100 if len(arg) > 2: try: prog = int(arg[2:]) except ValueError: return help() # no waiting elif arg in ('-S', '-0'): lps = 0 # fractional seconds elif arg.startswith("-"): try: lps = float(arg[1:]) if lps < 0: lps = abs(lps) if lps < 1: lps = 1 / lps except ValueError: pass else: args2.append(arg) # what's left? args = args2 if len(args) != 3: return help() # which type if args[0] == 'muf': editor = up_muf elif args[0] == 'lsedit': editor = up_lsedit else: tf.err("* diffedit.upload: known editors are 'muf' and 'lsedit'") return -1 # Check for the file if not os.path.isfile(args[2]): tf.err("* diffedit.upload: file %s not found" % args[2]) return -1 # # Okay, here's we we actually do some work # # Create the object editor = editor(args[1], args[2], raw) # Check to make sure we're not already running if editor.keyname in INPROGRESS: tf.err("* diffedit.upload: upload for '%s:%s' already running." % (editor.world, editor.remote)) tf.err( "* use '/python_call diffedit.abort' to reset if this is wrong." ) return # find the diffs diffs = editor.find_diffs() # only do the rest if we need to if diffs: # generate the editor commands cmds = editor.generate_commands(editor.massage_opcodes(diffs)) # upload them editor.upload_commands(lps, prog, cmds) else: # all done editor.lines_sent = 0 editor.done()
def execute(self, announce_only=False): if self._current is None: tf.err('There is no movement to execute.') return self._current.execute(announce_only=announce_only)
def add(self, group, stat, force=False): if group not in self._groups: tf.err('The group (%s) does not exist.' % group) return self._groups[group].add(stat, force=force)
def display(self, group, command): if group not in self._groups: tf.err('The group (%s) does not exist.' % group) return self._groups[group].display(command)
def resetAll(self, group): if group not in self._groups: tf.err('The group (%s) does not exist.' % group) return self._groups[group].resetAll()
def save(self, path): try: fh = open(path, 'w') except IOError, e: tf.err('IOError: %s' % e) return False
class Run(object): def __init__(self, first=None): """ """ self._first = first self._current = first self._name = None self._path = None def loadMovements(self, first): self._first = first self._current = first def loadMovementsFromDictList(self, movement_dicts): previous = None first = None for movement_dict in movement_dicts: movement = Movement(**movement_dict) if first is None: first = movement movement.setPrevious(previous) previous = movement self.loadMovements(first) def getPrefix(self, line): """Get the prefix for the current line.""" for char in (':', ','): if char in line: return line.split(char, 1)[0] return line def fixMovements(self, movements): """Fix movements by updating the name and announce attributes.""" if not movements: return previous = None for index, current in enumerate(movements): current['index'] = index if previous is not None: if 'name' in current and 'announce' in previous: if current['name'] == '__announce__': if 'announce' in current: current['name'] = self.getPrefix( current['announce']) else: current['name'] = 'Unknown' previous['announce'] = '%s, next %s' % ( previous['announce'], current['name']) previous = current @staticmethod def loadMovementsListFromConfigFile(path, basename): sys_path = sys.path try: sys.path = [path] try: module = reload(__import__(basename)) except ImportError, e: tf.err('ImportError: %s' % e) return False except NameError, e: tf.err('NameError: %s' % e) return False except SyntaxError, e: tf.err('Syntax error on line %d: %s' % (e.lineno, e.filename)) return False
def update(self, group, key, amount): if group not in self._groups: tf.err('The group (%s) does not exist.' % group) return self._groups[group].update(key, amount)
class StatGroup(object): def __init__(self, key, name): self._stats = {} self._key = key self._name = name self._totals = {} def __iter__(self): return iter(sorted(self._stats.values())) @property def key(self): return self._key @property def name(self): return self._name @property def session(self): return sum(t.session for t in self if not t.special) @property def total(self): return sum(t.total for t in self if not t.special) @property def totals(self): totals = {} for key, stat in self._stats.iteritems(): totals[key] = stat.total self._totals.update(totals) return self._totals def add(self, stat, force=False): if not force and stat.key in self._stats: return self._stats[stat.key] = stat total = self._totals.get(stat.key, 0) stat.set(0, total) def update(self, key, amount): if key not in self._stats: tf.err('The key (%s) does not exist.' % key) return self._stats[key].update(amount) def reset(self): for stat in self: stat.reset() def resetAll(self): for stat in self: stat.set(0, 0) self._totals = {} def display(self, command): session = self.session total = self.total output = [ '.-----------------------------------------------------------------------------.', '| %s |' % self._name.center(75), '|-------------------------------.----------------------.----------------------|', '| | SESSION | TOTAL |', '|-------------------------------+----------------------+----------------------|', ] special = [] found = False for stat in self: if stat.hide: continue if stat.special: special.append( '| %-29s | %10s (%6.2f%%%%) | %10s (%6.2f%%%%) |' % (stat.name, util.formatNumber(stat.session), stat.session * 100.0 / (session or 1), util.formatNumber( stat.total), stat.total * 100.0 / (total or 1))) continue found = True output.append('| %-29s | %10s (%6.2f%%%%) | %10s (%6.2f%%%%) |' % (stat.name, util.formatNumber( stat.session), stat.session * 100.0 / (session or 1), util.formatNumber( stat.total), stat.total * 100.0 / (total or 1))) if found: output.append( '|-------------------------------+----------------------+----------------------|' ) if special: special.append( '|-------------------------------+----------------------+----------------------|' ) output.extend(special) output.append('| | %20s | %20s |' % (util.formatNumber(session), util.formatNumber(total))) output.append( "'-------------------------------'----------------------'----------------------'" ) for line in output: tf.eval('%s %s' % (command, line)) def load(self, path): if not os.path.isfile(path): tf.err('Could not find file: %s' % path) return False try: fh = open(path, 'r') except IOError, e: tf.err('IOError: %s' % e) return False try: totals = pickle.load(fh) for key, total in totals.iteritems(): if key not in self._stats: continue self._stats[key].set(0, total) self._totals = totals except IOError, e: tf.err('IOError: %s' % e) return False
def purge(self, group): if group not in self._groups: tf.err('The group (%s) does not exist.' % group) return self._groups[group].purge()
def clean(self, group): if group not in self._groups: tf.err('The group (%s) does not exist.' % group) return self._groups[group].clean()
def save(self, group, path): if group not in self._groups: tf.err('The group (%s) does not exist.' % group) return self._groups[group].save(path)
tf.err('IOError: %s' % e) return False finally: fh.close() return True def save(self, path): try: fh = open(path, 'w') except IOError, e: tf.err('IOError: %s' % e) return False try: pickle.dump(self.totals, fh, pickle.HIGHEST_PROTOCOL) except IOError, e: tf.err('IOError: %s' % e) return False finally: fh.close() return True def clean(self): for key in self._totals: if key not in self._stats: del self._totals[key] def purge(self): self.totals self._stats = {}
def update(self, key, amount): if key not in self._stats: tf.err('The key (%s) does not exist.' % key) return self._stats[key].update(amount)
def _worlds(stdscr): # get dictionary of current worlds wdict = tfutil.listworlds(asdict=True) cols, lines = tfutil.screensize() colors = curses.can_change_color() # Draw the border and create a world window stdscr.clear() stdscr.border() stdscr.addstr(0, 4, "| TinyFugue Worlds |", curses.A_BOLD) wpos, lastwpos = 0, 9999 worldwin, scrollwin = _worldwin(stdscr, lines - 4, cols - 4, 2, 2) #worldwin, scrollwin = _worldwin( stdscr, 15, cols-4, 2, 2 ) worldwin.refresh() # start an undo stack undo, redo = [], [] global SAVED # now loop message, lastmessage = None, "dummy" while True: # sort by name wlist = sorted(wdict.values()) # draw the list, get a command _drawworlds(wlist, scrollwin, wpos, lastwpos) lastwpos = wpos # # parse keys # c = scrollwin.getkey() # Movement if c in ('i', 'KEY_UP', '\x10'): if wpos > 0: wpos -= 1 elif c in ('j', 'KEY_DOWN', '\x0e'): if (wpos + 1) < len(wlist): wpos += 1 # actual editing elif wlist and c in ('d', 'KEY_DC'): message = 'Deleted world %s' % wlist[wpos].name _new_undo(undo, wdict, message, SAVED) del wdict[wlist[wpos].name] wpos = min(wpos, len(wdict) - 1) SAVED, lastwpos = False, 9999 elif wlist and c in ('c', ): w = wlist[wpos] for i in range(2, 99): newname = '%s(%d)' % (w.name, i) if not newname in wdict: message = 'Copied world %s' % newname _new_undo(undo, wdict, message, SAVED) newworld = tfutil.World(w) newworld.name = newname wdict[newname] = newworld SAVED, lastwpos = False, 9999 break elif c in ('a', 'KEY_INS'): w = _editworld(worldwin, wdict.keys(), None) if w: message = 'Added world %s' % w.name _new_undo(undo, wdict, message, SAVED) wdict[w.name] = w SAVED = False lastwpos = 9999 _worldwin_redraw(worldwin) elif wlist and c in ('e', ): oldname = wlist[wpos].name w = _editworld(worldwin, wdict.keys(), tfutil.World(wlist[wpos])) if w: message = 'Edited world %s' % w.name _new_undo(undo, wdict, message, SAVED) if oldname != w.name: del wdict[oldname] wdict[w.name] = w SAVED = False lastwpos = 9999 _worldwin_redraw(worldwin) # undo/redo elif c == 'u': if undo: message, wdict2, SAVED2 = undo.pop() _new_undo(redo, wdict, message, SAVED) wdict, SAVED = wdict2, SAVED2 message = "Undid: " + message lastwpos = 9999 else: message = 'Nothing to undo' elif c == 'r': if redo: message, wdict2, SAVED2 = redo.pop() _new_undo(undo, wdict, message, SAVED) wdict, SAVED = wdict2, SAVED2 message = "Redid: " + message lastwpos = 9999 else: message = 'Nothing to redo' # Anything that terminates us elif wlist and c in ('\n', 'KEY_ENTER', 'Q'): if undo: _change_worlds(undo[0][1], wdict) if c != 'Q': tf.eval("/connect %s" % wlist[wpos].name) if not SAVED: tf.err("* Warning: your /worlds haven't been saved yet") break elif c == 'S': if undo: _change_worlds(undo[0][1], wdict) if not SAVED: SAVED, message = _save_worlds(wdict) if SAVED: break elif c == 'A': if not SAVED: tf.err("* all /worlds changes aborted") SAVED = False break message, lastmessage = _show_message(stdscr, message, lastmessage)