def test_new(self): path = request_new_filename(prompt = "Save booty as:", filename = "treasure", suffix = ".dat") if path: alert("You chose %r." % path) else: alert("Cancelled.")
def test_lookfor(self): path = look_for_file_or_directory(prompt = "Please find 'Vera.ttf'", target = "Vera.ttf") if path: alert("You chose %r." % path) else: alert("Cancelled.")
def tryImport(name): try: return __import__(name) except Exception, e: print traceback.format_exc() alert(_(u"Exception while importing filter module {}. See console for details.\n\n{}").format(name, e)) return object()
def update(self): client = self.client dir = client.directory def filter(name): path = os.path.join(dir, name) return os.path.isdir(path) or self.client.filter(path) try: content = os.walk(dir) for a, dirnames, filenames in content: dirnames.sort() filenames.sort() break try: self.names = [unicode(name, 'utf-8') for name in dirnames + filenames if filter(name)] except: self.names = [name for name in dirnames + filenames if filter(name)] except EnvironmentError as e: alert(u"%s: %s" % (dir, e)) self.names = [] self.rows = [Row([Image(self.icons[os.path.isdir(os.path.join(dir, a))]), Label(a, margin=0)], margin=0, spacing=2) for a in self.names] self.selected_item_index = None self.scroll_to_item(0)
def downloadSkin(username, cache = None, cape = False): host = "skins.minecraft.net" if cache == None else "textures.minecraft.net" conn = HTTPConnection(host, timeout = 10000) path = ("/Minecraft" + ("Cloak" if cape else "Skin") + "s/" + username + ".png") if cache == None else cache[29:] conn.request("GET", path) response = conn.getresponse() if cache == None and response.status == 301: location = response.getheader("Location", "non-cache") if location != "non-cache": return downloadSkin(username, location, cape) if cape and response.status != 200: return None if response.status != 200 and response.status != 403: conn.close() alert("Couldn't connect to " + host + path) if response.status == 403: alert("Not a premium user.") if response.status == 200: data = response.read() conn.close() reader = png.Reader(bytes = data) (width, height, pixels, metadata) = reader.asRGBA8() return (width, height, list(pixels), metadata) else: return None
def reload(self): for i in list(self.subwidgets): self.remove(i) tool = self.tool if len(tool.filterModules) is 0: self.add(Label("No filter modules found!")) self.shrink_wrap() return if self.selectedFilterName is None or self.selectedFilterName not in tool.filterNames: self.selectedFilterName = tool.filterNames[0] self.filterOptionsPanel = None while self.filterOptionsPanel is None: module = self.tool.filterModules[self.selectedFilterName] try: self.filterOptionsPanel = FilterModuleOptions(self.tool, module) except Exception, e: alert(_("Error creating filter inputs for {0}: {1}").format(module, e)) traceback.print_exc() self.tool.filterModules.pop(self.selectedFilterName) self.selectedFilterName = tool.filterNames[0] if len(tool.filterNames) == 0: raise ValueError("No filters loaded!")
def tryImport_new(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False, notify=True): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: # This work fine with custom filters, but the choice buttons are broken for the stock ones... if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) if os.path.exists(trn_path): albow.translate.buildTranslation(config.settings.langCode.get(), extend=True, langPath=trn_path) # module.trn = albow.translate module.displayName = _(module.displayName) module.trn = albow.translate return module except Exception as e: traceback.print_exc() if notify: alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def update(self): client = self.client dir = client.directory def filter(name): path = os.path.join(dir, name) return os.path.isdir(path) or self.client.filter(path) try: content = os.walk(dir) for a, dirnames, filenames in content: dirnames.sort() filenames.sort() break try: self.names = [ unicode(name, 'utf-8') for name in dirnames + filenames if filter(name) ] except: self.names = [ name for name in dirnames + filenames if filter(name) ] except EnvironmentError, e: alert(u"%s: %s" % (dir, e)) self.names = []
def _func(*args, **kw): try: func(*args, **kw) except Exception, e: print traceback.format_exc() alert( _(u"Exception during filter operation. See console for details.\n\n{0}" ).format(e))
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if recordUndo: self.undoLevel = self.extractUndo(self.level, self.box) self.filter.perform(self.level, BoundingBox(self.box), self.options) pass
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if recordUndo: self.undoLevel = self.extractUndo(self.level, self._box) for o, f in zip(self.options, self.filters): f.perform(self.level, BoundingBox(self._box), o) self.canUndo = True
def tryImport_old(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec(source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] from albow import translate as trn if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) module.trn = trn if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n import albow.translate albow.translate.lang = org_lang return module except Exception as e: traceback.print_exc() alert( _(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def tryImport(_root, name, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec(source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: # -- Note by Rubisk 20-06-2015: # I have no idea what this does, and left it as much alone as I could. # If anyone wants to explain it and/or modify this to work w/o modifying sys stuff, # that would be great. if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, module_name) module.trn = translate if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n return module except Exception as e: traceback.print_exc() alert( _(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def update(self): client = self.client dir = client.directory suffixes = client.suffixes def filter(name): path = os.path.join(dir, name) return os.path.isdir(path) or self.client.filter(path) try: names = [name for name in os.listdir(dir) if not name.startswith(".") and filter(name)] except EnvironmentError, e: alert("%s: %s" % (dir, e)) names = []
def tryImport_old(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False, notify=True): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, "displayName")): module.displayName = module_name # Python is awesome if not stock: if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] from albow import translate as trn if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) module.trn = trn if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n import albow.translate albow.translate.lang = org_lang return module except Exception as e: traceback.print_exc() if notify: alert( _(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format( name, e ) ) return None
def tryImport(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: #-# WIP. Following commented lines can be removed once we're sure we don't need them any more. # if "trn" in sys.modules.keys(): # del sys.modules["trn"] # if "albow.translate" in sys.modules.keys(): # del sys.modules["albow.translate"] # from albow import translate as trn if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) # module.trn = trn if os.path.exists(trn_path): # module.trn.setLangPath(trn_path) # module.trn.buildTranslation(config.settings.langCode.get()) albow.translate.buildTranslation(config.settings.langCode.get(), extend=True, langPath=trn_path) # n = module.displayName # if hasattr(module, "trn"): # n = module.trn._(module.displayName) # if n == module.displayName: # n = _(module.displayName) # module.displayName = n module.displayName = _(module.displayName) # import albow.translate # albow.translate.lang = org_lang return module except Exception as e: traceback.print_exc() alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def update(self): client = self.client dir = client.directory def filter(name): path = os.path.join(dir, name) return os.path.isdir(path) or self.client.filter(path) try: names = [name for name in os.listdir(dir) if filter(name)] #if not name.startswith(".") and filter(name)] except EnvironmentError, e: alert(u"%s: %s" % (dir, e)) names = []
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if recordUndo: self.undoLevel = self.extractUndo(self.level, self.box) # Inject the defs for blocks/entities in the module # Need to reimport the defs and ids to get the 'fresh' ones from pymclevel import MCEDIT_DEFS, MCEDIT_IDS self.filter.MCEDIT_DEFS = MCEDIT_DEFS self.filter.MCEDIT_IDS = MCEDIT_IDS self.filter.perform(self.level, BoundingBox(self.box), self.options) self.canUndo = True
def perform(level, box, options): global world, y, material, width world = level y = box.miny material = options[inputMaterial] width = options[inputWidth] majorDirection = False if box.width > box.length: majorDirection = True major = box.width minor = box.length else: major = box.length minor = box.width stepCount = floorFibonacci(major) while stepCount > 0: base = fibonacci(stepCount) extension = fibonacci(stepCount - 1) if extension + base <= major and base <= minor: break stepCount = stepCount - 1 if stepCount <= 0: alert("Not enought room.") return if fibonacci(stepCount) < width / 2: alert("The path is too wide for selection, decrease width or enlarge selection.") return x, z, direction = box.minx, box.minz, WEST if majorDirection else NORTH print direction step = stepCount while step > 0: size = fibonacci(step) quarterCircle(x, z, direction, size) step = step - 1 nextSize = fibonacci(step) if nextSize < width / 2: break if direction == NORTH: x = x + size - nextSize z = z + size elif direction == SOUTH: z = z - nextSize elif direction == EAST: x = x - nextSize z = z + size - nextSize else: x = x + size direction = rotateClockwise[direction]
def tryImport(_root, name, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: # -- Note by Rubisk 20-06-2015: # I have no idea what this does, and left it as much alone as I could. # If anyone wants to explain it and/or modify this to work w/o modifying sys stuff, # that would be great. if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, module_name) module.trn = translate if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n return module except Exception as e: traceback.print_exc() alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return # Override 'recordUndo' with filter RECORD_UNDO. # Some filters, like Find does not need to record undo stuff, since they're not changing anything recordUndo = getattr(self.filter, 'RECORD_UNDO', recordUndo) if recordUndo: self.undoLevel = self.extractUndo(self.level, self.box) # Inject the defs for blocks/entities in the module # Need to reimport the defs and ids to get the 'fresh' ones # from pymclevel import MCEDIT_DEFS, MCEDIT_IDS self.filter.MCEDIT_DEFS = self.level.defsIds.mcedit_defs self.filter.MCEDIT_IDS = self.level.defsIds.mcedit_ids self.filter.perform(self.level, BoundingBox(self.box), self.options) self.canUndo = True
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return # Override 'recordUndo' with filter RECORD_UNDO. # Some filters, like Find does not need to record undo stuff, since they're not changing anything recordUndo = getattr(self.filter, 'RECORD_UNDO', recordUndo) if recordUndo: self.undoLevel = self.extractUndo(self.level, self.box) # Inject the defs for blocks/entities in the module # Need to reimport the defs and ids to get the 'fresh' ones from pymclevel import MCEDIT_DEFS, MCEDIT_IDS self.filter.MCEDIT_DEFS = MCEDIT_DEFS self.filter.MCEDIT_IDS = MCEDIT_IDS self.filter.perform(self.level, BoundingBox(self.box), self.options) self.canUndo = True
def add_item_to(self, parent, xxx_todo_changeme): (name, item) = xxx_todo_changeme if parent is None: tp = 'dict' parent = self.data else: tp = parent[7].__name__ parent = parent[9] if not name: i = 0 name = 'Item %03d' % i for name in list(self.data.keys()): i += 1 name = 'Item %03d' % i meth = getattr(self, 'add_item_to_%s' % tp, None) if meth: meth(parent, name, item) self.build_layout() else: alert(_("No function implemented to add items to %s type.") % type(parent).__name__, doNotTranslate=True)
def update(self): client = self.client dir = client.directory def filter(name): path = os.path.join(dir, name) return os.path.isdir(path) or self.client.filter(path) try: content = os.walk(dir) for a, dirnames, filenames in content: dirnames.sort() filenames.sort() break try: self.names = [unicode(name, "utf-8") for name in dirnames + filenames if filter(name)] except: self.names = [name for name in dirnames + filenames if filter(name)] except EnvironmentError, e: alert(u"%s: %s" % (dir, e)) self.names = []
def reload(self): for i in list(self.subwidgets): self.remove(i) tool = self.tool if len(tool.filterModules) is 0: self.add(Label("No filter modules found!")) self.shrink_wrap() return if self.selectedFilterName is None or self.selectedFilterName not in tool.filterNames: self.selectedFilterName = tool.filterNames[0] self.filterSelect = ChoiceButton(tool.filterNames, choose=self.filterChanged) self.filterSelect.selectedChoice = self.selectedFilterName filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir()) filterLabel.tooltipText = "Click to open filters folder" self.filterSelectRow = filterSelectRow = Row((filterLabel, self.filterSelect)) self.confirmButton = Button("Filter", action=self.tool.confirm) self.filterOptionsPanel = None while self.filterOptionsPanel is None: module = self.tool.filterModules[self.selectedFilterName] try: self.filterOptionsPanel = FilterModuleOptions(self.tool, module, _parent=self) except Exception, e: alert(_("Error creating filter inputs for {0}: {1}").format(module, e)) traceback.print_exc() self.tool.filterModules.pop(self.selectedFilterName) self.selectedFilterName = tool.filterNames[0] if len(tool.filterNames) == 0: raise ValueError("No filters loaded!")
class Tree(Column): """...""" rows = [] row_margin = 2 column_margin = 2 bullet_size = ThemeProperty('bullet_size') bullet_color_active = ThemeProperty('bullet_color_active') bullet_color_inactive = ThemeProperty('bullet_color_inactive') def __init__(self, *args, **kwargs): self.menu = [("Add", "add_item"), ("Delete", "delete_item"), ("New child", "add_child"), ("Rename", "rename_item"), ("", ""), ("Cut", "cut_item"), ("Copy", "copy_item"), ("Paste", "paste_item"), ("Paste as child", "paste_child"), ] if not hasattr(self, 'map_types_item'): global map_types_item self.map_types_item = setup_map_types_item() self.selected_item_index = None self.selected_item = None self.clicked_item = None self.copyBuffer = kwargs.pop('copyBuffer', None) self._parent = kwargs.pop('_parent', None) self.styles = kwargs.pop('styles', {}) self.compound_types = [dict,] + kwargs.pop('compound_types', []) self.item_types = self.compound_types + kwargs.pop('item_types', [a[0] for a in self.map_types_item.values()] or [int, float, unicode, bool]) for t in self.item_types: if 'create_%s'%t.__name__ in globals().keys(): setattr(self, 'create_%s'%t.__name__, globals()['create_%s'%t.__name__]) self.show_fields = kwargs.pop('show_fields', False) self.deployed = [] self.data = data = kwargs.pop("data", {}) self.draw_zebra = draw_zebra = kwargs.pop('draw_zebra', True) # self.inner_width = kwargs.pop('inner_width', 'auto') self.inner_width = kwargs.pop('inner_width', 500) self.__num_rows = len(data.keys()) self.build_layout() # row_height = self.font.size(' ')[1] row_height = self.font.get_linesize() self.treeRow = treeRow = TreeRow((self.inner_width, row_height), 10, draw_zebra=draw_zebra) Column.__init__(self, [treeRow,], **kwargs) def dispatch_key(self, name, evt): if not hasattr(evt, 'key'): return if name == "key_down": keyname = self.root.getKey(evt) if keyname == "Up" and self.selected_item_index > 0: if self.selected_item_index == None: self.selected_item_index = -1 self.selected_item_index = max(self.selected_item_index - 1, 0) elif keyname == "Down" and self.selected_item_index < len(self.rows) - 1: if self.selected_item_index == None: self.selected_item_index = -1 self.selected_item_index += 1 elif keyname == 'Page down': if self.selected_item_index == None: self.selected_item_index = -1 self.selected_item_index = min(len(self.rows) - 1, self.selected_item_index + self.treeRow.num_rows()) elif keyname == 'Page up': if self.selected_item_index == None: self.selected_item_index = -1 self.selected_item_index = max(0, self.selected_item_index - self.treeRow.num_rows()) if self.treeRow.cell_to_item_no(0, 0) != None and (self.treeRow.cell_to_item_no(0, 0) + self.treeRow.num_rows() -1 > self.selected_item_index or self.treeRow.cell_to_item_no(0, 0) + self.treeRow.num_rows() -1 < self.selected_item_index): self.treeRow.scroll_to_item(self.selected_item_index) if keyname == 'Return' and self.selected_item_index != None: self.select_item(self.selected_item_index) if self.selected_item[7] in self.compound_types: self.deploy(self.selected_item[6]) def cut_item(self): self.copyBuffer = ([] + self.selected_item, 1) self.delete_item() def copy_item(self): self.copyBuffer = ([] + self.selected_item, 0) def paste_item(self): parent = self.get_item_parent(self.selected_item) name = self.copyBuffer[0][3] old_name = u"%s"%self.copyBuffer[0][3] if self.copyBuffer[1] == 0: name = input_text_buttons("Choose a name", 300, self.copyBuffer[0][3]) else: old_name = "" if name and type(name) in (str, unicode) and name != old_name: new_item = copy.deepcopy(self.copyBuffer[0][9]) if hasattr(new_item, 'name'): new_item.name = name self.add_item_to(parent, (name, new_item)) def paste_child(self): name = self.copyBuffer[0][3] old_name = u"%s"%self.copyBuffer[0][3] names = [] children = self.get_item_children(self.selected_item) if children: names = [a[3] for a in children] if name in names: name = input_text_buttons("Choose a name", 300, self.copyBuffer[0][3]) else: old_name = "" if name and type(name) in (str, unicode) and name != old_name: new_item = copy.deepcopy(self.copyBuffer[0][9]) if hasattr(new_item, 'name'): new_item.name = name self.add_item_to(self.selected_item, (name, new_item)) @staticmethod def add_item_to_dict(parent, name, item): parent[name] = item def add_item_to(self, parent, (name, item)): if parent is None: tp = 'dict' parent = self.data else: tp = parent[7].__name__ parent = parent[9] if not name: i = 0 name = 'Item %03d'%i while name in self.data.keys(): i += 1 name = 'Item %03d'%i meth = getattr(self, 'add_item_to_%s'%tp, None) if meth: meth(parent, name, item) self.build_layout() else: alert(_("No function implemented to add items to %s type.")%type(parent).__name__, doNotTranslate=True)
def test_old(self): path = request_old_filename() if path: alert("You chose %r." % path) else: alert("Cancelled.")
def _func(*args, **kw): try: func(*args, **kw) except Exception, e: print traceback.format_exc() alert(_(u"Exception during filter operation. See console for details.\n\n{0}").format(e))
class FilterTool(EditorTool): tooltipText = "Filter" toolIconName = "filter" def __init__(self, editor): EditorTool.__init__(self, editor) self.filterModules = {} self.panel = FilterToolPanel(self) @property def statusText(self): return "Choose a filter, then click Filter or press ENTER to apply it." def toolEnabled(self): return not (self.selectionBox() is None) def toolSelected(self): self.showPanel() @alertException def showPanel(self): if self.panel.parent: self.editor.remove(self.panel) self.reloadFilters() # self.panel = FilterToolPanel(self) self.panel.reload() self.panel.midleft = self.editor.midleft self.editor.add(self.panel) self.updatePanel = Panel() updateButton = Button("Update Filters", action=self.updateFilters) self.updatePanel.add(updateButton) self.updatePanel.shrink_wrap() self.updatePanel.bottomleft = self.editor.viewportContainer.bottomleft self.editor.add(self.updatePanel) def hidePanel(self): self.panel.saveOptions() if self.panel.parent: self.panel.parent.remove(self.panel) self.updatePanel.parent.remove(self.updatePanel) def updateFilters(self): totalFilters = 0 updatedFilters = 0 try: os.mkdir(mcplatform.filtersDir + "/updates") except OSError: pass for module in self.filterModules.values(): totalFilters = totalFilters + 1 if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"): if isinstance(module.UPDATE_URL, (str, unicode)) and isinstance(module.VERSION, (str, unicode)): versionJSON = json.loads(urllib2.urlopen(module.UPDATE_URL).read()) if module.VERSION != versionJSON["Version"]: urllib.urlretrieve(versionJSON["Download-URL"], mcplatform.filtersDir + "/updates/" + versionJSON["Name"]) updatedFilters = updatedFilters + 1 for f in os.listdir(mcplatform.filtersDir + "/updates"): shutil.copy(mcplatform.filtersDir + "/updates/" + f, mcplatform.filtersDir) shutil.rmtree(mcplatform.filtersDir + "/updates/") self.finishedUpdatingWidget = Widget() lbl = Label("Updated " + str(updatedFilters) + " filter(s) out of " + str(totalFilters)) closeBTN = Button("Close this message", action=self.closeFinishedUpdatingWidget) col = Column((lbl, closeBTN)) self.finishedUpdatingWidget.bg_color = (0.0, 0.0, 0.6) self.finishedUpdatingWidget.add(col) self.finishedUpdatingWidget.shrink_wrap() self.finishedUpdatingWidget.present() def closeFinishedUpdatingWidget(self): self.finishedUpdatingWidget.dismiss() def reloadFilters(self): filterDir = mcplatform.filtersDir filterFiles = os.listdir(filterDir) filterPyfiles = filter(lambda x: x.endswith(".py"), filterFiles) def tryImport(name): try: return __import__(name) except Exception, e: print traceback.format_exc() alert(_(u"Exception while importing filter module {}. See console for details.\n\n{}").format(name, e)) return object() filterModules = (tryImport(x[:-3]) for x in filterPyfiles) filterModules = filter(lambda module: hasattr(module, "perform"), filterModules) self.filterModules = collections.OrderedDict(sorted((self.moduleDisplayName(x), x) for x in filterModules)) for m in self.filterModules.itervalues(): try: reload(m) except Exception, e: print traceback.format_exc() alert( _(u"Exception while reloading filter module {}. Using previously loaded module. See console for details.\n\n{}").format( m.__file__, e))
class FilterTool(EditorTool): tooltipText = "Filter" toolIconName = "filter" def __init__(self, editor): EditorTool.__init__(self, editor) self.filterModules = {} self.panel = FilterToolPanel(self) @property def statusText(self): return "Choose a filter, then click Filter or press ENTER to apply it." def toolEnabled(self): return not (self.selectionBox() is None) def toolSelected(self): self.showPanel() @alertException def showPanel(self): if self.panel.parent: self.editor.remove(self.panel) self.reloadFilters() #self.panel = FilterToolPanel(self) self.panel.reload() self.panel.left = self.editor.left self.panel.centery = self.editor.centery self.editor.add(self.panel) def hidePanel(self): self.panel.saveOptions() if self.panel.parent: self.panel.parent.remove(self.panel) def reloadFilters(self): filterDir = mcplatform.filtersDir filterFiles = os.listdir(filterDir) filterPyfiles = filter(lambda x: x.endswith(".py"), filterFiles) def tryImport(name): try: return __import__(name) except Exception, e: print traceback.format_exc() alert( u"Exception while importing filter module {}. See console for details.\n\n{}" .format(name, e)) return object() filterModules = (tryImport(x[:-3]) for x in filterPyfiles) filterModules = filter(lambda module: hasattr(module, "perform"), filterModules) self.filterModules = collections.OrderedDict( sorted((self.moduleDisplayName(x), x) for x in filterModules)) for m in self.filterModules.itervalues(): try: reload(m) except Exception, e: print traceback.format_exc() alert( u"Exception while reloading filter module {}. Using previously loaded module. See console for details.\n\n{}" .format(m.__file__, e))
def test_ask(self): response = ask("Do you like mustard and avocado ice cream?", ["Yes", "No", "Undecided"]) alert("You chose %r." % response)
def reload(self): for i in list(self.subwidgets): self.remove(i) tool = self.tool # Display "No filter modules found" if there are no filters if len(tool.filterModules) is 0: self.add(Label("No filter modules found!")) self.shrink_wrap() return names_list = sorted( [n for n in tool.filterNames if not n.startswith("[")]) # We get a list of names like ["[foo] bar", "[test] thing"] # The to sort on is created by splitting on "[": "[foo", " bar" and then # removing the first char: "foo", "bar" subfolder_names_list = sorted( [n for n in tool.filterNames if n.startswith("[")], key=lambda x: x.split("]")[0][1:]) names_list.extend(subfolder_names_list) names_list.extend( [macro for macro in self.filter_json["Macros"].keys()]) if self.selectedName is None or self.selectedName not in names_list: self.selectedName = names_list[0] # Remove any keybindings that don't have a filter for (i, j) in config.config.items("Filter Keys"): if i == "__name__": continue if not any([i == m.lower() for m in names_list]): config.config.remove_option("Filter Keys", i) self.filterSelect.choices = names_list name = self.selectedName.lower() names = [k for (k, v) in config.config.items("Filter Keys")] btn_name = config.config.get("Filter Keys", name) if name in names else "*" self.binding_button.set_text(btn_name) self.filterOptionsPanel = None while self.filterOptionsPanel is None: module = self.tool.filterModules.get(self.selectedName, None) if module is not None: try: self.filterOptionsPanel = FilterModuleOptions(self.tool, module, _parent=self) except Exception as e: alert( _("Error creating filter inputs for {0}: {1}").format( module, e)) traceback.print_exc() self.tool.filterModules.pop(self.selectedName) self.selectedName = tool.filterNames[0] if len(tool.filterNames) == 0: raise ValueError("No filters loaded!") if not self._recording: self.confirmButton.set_text("Filter") else: # We verified it was an existing macro already macro_data = self.filter_json["Macros"][self.selectedName] self.filterOptionsPanel = MacroModuleOptions(macro_data) self.confirmButton.set_text("Run Macro") # This has to be recreated every time in case a macro has a longer name then everything else. self.filterSelect = ChoiceButton(names_list, choose=self.filterChanged, doNotTranslate=True) self.filterSelect.selectedChoice = self.selectedName self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.add( Column((self.filterSelectRow, self.filterOptionsPanel, self.confirmButton))) self.shrink_wrap() if self.parent: height = self.parent.mainViewport.height - self.parent.toolbar.height self.centery = height / 2 + self.parent.subwidgets[0].height if self.selectedName in self.tool.savedOptions: self.filterOptionsPanel.options = self.tool.savedOptions[ self.selectedName]
def reload(self): for i in list(self.subwidgets): self.remove(i) tool = self.tool # Display "No filter modules found" if there are no filters if len(tool.filterModules) is 0: self.add(Label("No filter modules found!")) self.shrink_wrap() return names_list = sorted([n for n in tool.filterNames if not n.startswith("[")]) # We get a list of names like ["[foo] bar", "[test] thing"] # The to sort on is created by splitting on "[": "[foo", " bar" and then # removing the first char: "foo", "bar" subfolder_names_list = sorted([n for n in tool.filterNames if n.startswith("[")], key=lambda x: x.split("]")[0][1:]) names_list.extend(subfolder_names_list) names_list.extend([macro for macro in self.filter_json["Macros"].keys()]) if self.selectedName is None or self.selectedName not in names_list: self.selectedName = names_list[0] # Remove any keybindings that don't have a filter for (i, j) in config.config.items("Filter Keys"): if i == "__name__": continue if not any([i == m.lower() for m in names_list]): config.config.remove_option("Filter Keys", i) self.filterSelect.choices = names_list name = self.selectedName.lower() names = [k for (k, v) in config.config.items("Filter Keys")] btn_name = config.config.get("Filter Keys", name) if name in names else "*" self.binding_button.set_text(btn_name) self.filterOptionsPanel = None while self.filterOptionsPanel is None: module = self.tool.filterModules.get(self.selectedName, None) if module is not None: try: self.filterOptionsPanel = FilterModuleOptions(self.tool, module, _parent=self) except Exception as e: alert(_("Error creating filter inputs for {0}: {1}").format(module, e)) traceback.print_exc() self.tool.filterModules.pop(self.selectedName) self.selectedName = tool.filterNames[0] if len(tool.filterNames) == 0: raise ValueError("No filters loaded!") if not self._recording: self.confirmButton.set_text("Filter") else: # We verified it was an existing macro already macro_data = self.filter_json["Macros"][self.selectedName] self.filterOptionsPanel = MacroModuleOptions(macro_data) self.confirmButton.set_text("Run Macro") # This has to be recreated every time in case a macro has a longer name then everything else. self.filterSelect = ChoiceButton(names_list, choose=self.filterChanged, doNotTranslate=True) self.filterSelect.selectedChoice = self.selectedName self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.add(Column((self.filterSelectRow, self.filterOptionsPanel, self.confirmButton))) self.shrink_wrap() if self.parent: height = self.parent.mainViewport.height - self.parent.toolbar.height self.centery = height / 2 + self.parent.subwidgets[0].height if self.selectedName in self.tool.savedOptions: self.filterOptionsPanel.options = self.tool.savedOptions[self.selectedName]