def load_images(self, *directories): """Find all formatted SVG images in directories""" imagepack = [] for path in directories: for root, _, files in os.walk(path): svg_files = [ os.path.join(root, name) for name in files if name.endswith('.svg') ] # check if images formatted correctly for file_ in svg_files: try: temp_data = self._load_image_data(None, file_) if (temp_data.bg is None or any([ item is None for item in temp_data.colors ]) or any([item is None for item in temp_data.shift])): raise Exception("Missed tag parameter") imagepack.append(file_) except Exception: logger.exception("Broken image file:\n%s" % file_) logger.debug("%s image files was found." % len(imagepack)) if not imagepack: logger.warning("No image was found.\nLoad test sample.") imagepack.append(self._testimage) self.image_list = sorted(imagepack)
def get_current(): """ Try to find current version of package. Use git output, package file or fallback variable in the designated order. """ version = _FALLBACK_VERSION try: cwd_ = os.path.dirname(os.path.abspath(__file__)) output = subprocess.check_output(["git", "describe", "--tags", "--long"], stderr=subprocess.PIPE, cwd=cwd_) describe = str(output, "utf-8").strip() output = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], stderr=subprocess.PIPE, cwd=cwd_) branch = str(output, "utf-8").strip() v, n, commit = describe.split('-') if branch == _MASTER_BRANCH or n == "0": # TODO: does it possible to proper count commit on master branch? version = v elif branch == _DEVELOPMENT_BRANCH: version = "%.1f.dev%s-%s" % (float(v) + 0.1, n, commit) else: version = "%s-%s-%s" % (v, branch, commit) except Exception as e: logger.debug("Can't read git output:\n%s", e) if os.path.isfile(_version_file): with open(_version_file, 'r') as file_: version = file_.read() logger.debug("Set version from package file: %s", version) return version
def _on_color_activated(self, tree, path, column): """GUI handler""" treeiter = self.color_store.get_iter(path) color_dialog = Gtk.ColorChooserDialog("Choose Color", self._app.mainwin.gui["window"], use_alpha=False) color_dialog.set_rgba( rgba_from_hex( self.color_store[treeiter][self.color_view_data.index.HEX])) response = color_dialog.run() if response == Gtk.ResponseType.OK: color_index = self.color_store[treeiter][ self.color_view_data.index.INDEX] hex_color = hex_from_rgba(color_dialog.get_rgba()) logger.debug("New color %s in line %s", hex_color, color_index) self.color_store[treeiter][ self.color_view_data.index.HEX] = hex_color self.color_store[treeiter][ self.color_view_data.index.COLOR] = pixbuf_from_hex( hex_color, width=self.PIXBUF_PATTERN_WIDTH) self._parser.current.change_color(hex_color, color_index) self._color_changes_apply() color_dialog.destroy()
def save_color_to_clipboard(self, *args): """Save text representation of selected color to system clipboard""" model, sel = self.gui["color-list-selection"].get_selected() if sel is not None: color = model[sel][self.color_view_data.index.HEX] logger.debug("Copy to clipboard: %s", color) self.clipboard.set_text(color, -1)
def export_colors(self, file_): """Export colors to ini file""" bg = dict(background=self.bg) colors = {"color" + str(i): c for i, c in enumerate(self.colors)} palette = {**bg, **colors} logger.debug("Exporting colors: %s", str(palette)) config = ConfigParser() config["colors"] = palette with open(file_, "w") as configfile: config.write(configfile)
def _on_palette_export(self, *args): """Action handler""" is_ok, _, filename = self.palette_export_dialog.run( name_suggest="scheme") if is_ok: if not filename.endswith(".%s" % self.palette_extension): filename += ".%s" % self.palette_extension logger.debug("New palette export settings: %s" % filename) self._parser.current.export_colors(filename) else: logger.debug("Palette export canceled")
def export_image(self): """GUI handler""" type_ = self._app.settings.get_string("export-type") file_ = os.path.join(self._app.settings.get_string("export-path"), self.current.name + "." + type_) width = self._app.settings.get_string("export-width") height = self._app.settings.get_string("export-height") logger.debug("Exporting image: %s at size %sx%s", file_, width, height) pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale( self.temporary.name, int(width), int(height), False) pixbuf.savev(file_, type_, [], [])
def _on_palette_import(self, *args): """Action handler""" is_ok, _, filename = self.palette_import_dialog.run() if is_ok: logger.debug("New palette import request: %s", filename) self._parser.current.import_colors(filename) self._parser.apply_changes() self.update_color_list() self.update_preview() self._set_subtitle(True) else: logger.debug("Palette import canceled")
def import_colors(self, file_): """Import colors from ini file""" try: config = ConfigParser() config.read(file_) self.bg = config["colors"]["background"] for i, color in enumerate(self.colors): tag = "color" + str(i) if tag in config["colors"]: self.colors[i] = config["colors"][tag] logger.debug("Updated color scheme: %s, %s", self.bg, str(self.colors)) except Exception: logger.exception("Fail to load palette from file: %s", file_)
def _on_export_as_button_clicked(self, *args): """GUI handler""" is_ok, path, filename = self.export_dialog.run( self._app.settings.get_string("export-path"), self._parser.current.name) if is_ok: name = os.path.splitext(os.path.basename(filename))[0] self._app.settings.set_string("export-path", path) self._parser.current.name = name self._parser.export_image() logger.debug("New image export settings: [path: %s], [name: %s]" % (path, name)) else: logger.debug("Image export canceled")
def _set_artists(self): credits_ = [] for path in self._app.settings.get_strv("images-location-list"): file_ = os.path.join(path, "credits") if os.path.isfile(file_): with open(file_, "r") as credits_file: # TODO: is it possible to add raw string without link formatting? credits_ += [ line for line in credits_file.read().split("\n") if line ] logger.debug("Artist credits for current images:\n%s", credits_) if credits_: self.about_dialog.add_credit_section("Wallpaper artists", credits_)
def _load_resources(self): """Initialize resources""" logger.info("Loading resources...") # Set data files locations self.path = dict(data=os.path.join( os.path.abspath(os.path.dirname(__file__)), "data"), ) if logger.is_debug(): logger.debug("Data files location:\n%s", "\n".join(k + ": " + v for k, v in self.path.items())) # init resources resource_path = os.path.join(self.path["data"], "aniwall.gresource") resource = Gio.Resource.load(resource_path) # noinspection PyProtectedMember resource._register() if logger.is_debug(): ui_resource_path = self.resource_path + "ui/" resource_files = "\n".join( resource.enumerate_children(ui_resource_path, Gio.ResourceLookupFlags.NONE)) logger.debug("List of loaded resources files:\n%s" % resource_files) # init settings if self.is_local: schema_source = Gio.SettingsSchemaSource.new_from_directory( self.path["data"], Gio.SettingsSchemaSource.get_default(), False, ) schema = schema_source.lookup("com.github.worron.aniwall", False) self.settings = Gio.Settings.new_full(schema, None, None) # FIXME: get child for local settings def get_local_child(inst, name): child_schema = inst.get_property("schema") + "." + name return Gio.Settings.new_full( schema_source.lookup(child_schema, False), None, None) # noinspection PyArgumentList self.settings.get_child = types.MethodType(get_local_child, self.settings) else: self.settings = Gio.Settings.new("com.github.worron.aniwall") # set initial settings on first run if not self.settings.get_string("export-path"): self.settings.set_string("export-path", os.path.expanduser("~")) if logger.is_debug(): schema = self.settings.get_property("settings-schema") settings_list = "\n".join(k + ": " + str(self.settings.get_value(k)) for k in schema.list_keys()) logger.debug("Current settings:\n%s", settings_list) logger.info("Loading resources completed")
def rebuild(self, file_=None): """Apply image changes""" if file_ is None: file_ = self.file if not os.access(file_, os.W_OK): logger.warning("Permission denied to change %s", file_) return transform_data = (self.shift[0], self.shift[1], self.scale) self.tags["transform"].set( "transform", "translate(%s,%s) scale(%s)" % transform_data) self.tags["background"].set("fill", self.bg) for i, color in enumerate(self.colors, start=1): self.tags["color" + str(i)].set("fill", color) self.tree.write(file_, pretty_print=True) if logger.is_debug: tag_info = "Current image parameters " for name, tag in self.tags.items(): attr = "transform" if name == "transform" else "fill" tag_info += "[%s: %s], " % (name, tag.get(attr)) logger.debug(tag_info)
def save_gui_state(self): """Save some GUI parameters across sessions""" image_column_width = self.image_column.get_width() settings_ui = self._app.settings.get_child("ui") settings_ui.set_uint("image-column-width", image_column_width) logger.debug("image-column-width: %d", image_column_width)