Exemple #1
0
    def configure_colors(self):
        # Get colors from GTKrc file
        if not resource_exists(__name__, self.get_assets_path("gtk-2.0", "gtkrc")):
            raise ValueError("GTK theme does not exist")

        gtkrc_file_path = resource_filename(__name__, self.get_assets_path("gtk-2.0", "gtkrc"))
        with open(gtkrc_file_path) as f:
            lines = f.readlines()

        for line in lines:
            if re.match("\s*gtk_color_scheme", line):
                color = re.findall(r'"(.*?)"', line)
                color = color[0]
                color = color.split(':')
                self.colors[color[0].upper()] = color[1]
                self.gtk_colors[color[0].upper()] = gtk.gdk.Color(color[1])

        # Get color definitions
        color_file_path = resource_filename(__name__, self.get_assets_path(filename="colors.json"))
        try:
            colors = storage_utils.load_objects_from_json(color_file_path)
        except IOError:
            raise ValueError("No color definitions found")

        # replace unicode strings with str strings
        colors = {str(key): str(value) for key, value in colors.iteritems()}
        gtk_colors = {str(key): gtk.gdk.Color(str(value)) for key, value in colors.iteritems()}
        self.gtk_colors.update(gtk_colors)
        self.colors.update(colors)
Exemple #2
0
    def configure_colors(self):
        from gi.repository import Gdk
        dark_theme = self.get_config_value('THEME_DARK_VARIANT', True)
        css_filename = "gtk-dark.css" if dark_theme else "gtk.css"
        # Get colors from GTKrc file
        if not resource_exists(__name__,
                               self.get_assets_path("gtk-3.0", css_filename)):
            raise ValueError("GTK theme does not exist")

        # Provide black as fallback color if theme is not found instead of crashing
        self.colors = defaultdict(lambda: "#FFFFFF")
        self.gtk_colors = defaultdict(lambda: Gdk.RGBA(0, 0, 0).to_color())

        gtkrc_file_path = resource_filename(
            __name__, self.get_assets_path("gtk-3.0", css_filename))
        with open(gtkrc_file_path) as f:
            lines = f.readlines()

        for line in lines:
            match = re.match("\s*@define-color (\w*) (#[\w]{3,6})", line)
            if match:
                color_name = match.group(1).upper()
                color_code = match.group(2)
                self.colors[color_name] = color_code
                gtk_color = Gdk.RGBA()
                if gtk_color.parse(color_code):
                    self.gtk_colors[color_name] = gtk_color.to_color()
                else:
                    self.logger.warning(
                        "Could not parse color with name '{}' and code '{}'".
                        format(color_name, color_code))

        # Get color definitions
        colors_filename = "colors-dark.json" if dark_theme else "colors.json"
        color_file_path = resource_filename(
            __name__, self.get_assets_path(filename=colors_filename))
        try:
            colors = storage_utils.load_objects_from_json(color_file_path)
        except IOError:
            raise ValueError("No color definitions found")

        for color_name, color_code in colors.items():
            # replace unicode strings with str strings
            color_name = str(color_name)
            color_code = str(color_code)
            if color_code.startswith("#"):
                color = Gdk.Color.parse(color_code)[1]
            elif color_code in self.colors:
                color = self.gtk_colors[color_code]
                color_code = self.gtk_colors[color_code]
            else:
                self.logger.warning(
                    "Undefined color alias '{}' for color name '{}'".format(
                        color_code, color_name))
                continue
            self.gtk_colors[color_name] = color
            self.colors[color_name] = color_code
Exemple #3
0
    def configure_gtk(self):
        if not resource_exists(__name__, self.get_assets_path("gtk-2.0", "gtkrc")):
            raise ValueError("GTK theme does not exist")
        gtkrc_file_path = resource_filename(__name__, self.get_assets_path("gtk-2.0", "gtkrc"))
        filename = resource_filename(__name__, self.get_assets_path(
            "icons", "RAFCON_figurative_mark_negative.svg", for_theme=False))
        gtk.window_set_default_icon_from_file(filename)

        # wait for all gtk events being processed before parsing the gtkrc file
        wait_for_gui()
        gtk.rc_parse(gtkrc_file_path)
Exemple #4
0
    def configure_gtk(self):
        if not resource_exists(__name__, self.get_assets_path()):
            raise ValueError("GTK theme 'RAFCON' does not exist")

        theme_name = "RAFCON"
        dark_theme = self.get_config_value('THEME_DARK_VARIANT', True)

        data_dir = resource_filename(__name__,
                                     self.get_assets_path(for_theme=False))
        os.environ['GTK_DATA_PREFIX'] = data_dir
        os.environ['GTK_THEME'] = "{}{}".format(theme_name,
                                                ":dark" if dark_theme else "")

        # The env vars GTK_DATA_PREFIX and GTK_THEME must be set before Gtk is imported first to prevent GTK warnings
        # from other themes
        try:
            from gi.repository import Gtk
            settings = Gtk.Settings.get_default()
            if settings:
                settings.set_property("gtk-theme-name", theme_name)
                settings.set_property("gtk-application-prefer-dark-theme",
                                      dark_theme)

            Gtk.Window.set_default_icon_name(
                "rafcon" if dark_theme else "rafcon-light")
        except ImportError:
            pass
Exemple #5
0
    def load(self, config_file=None, path=None):
        using_default_config = False
        if config_file is None:
            if path is None:
                using_default_config = True
                path, config_file = os.path.split(
                    resource_filename(__name__, CONFIG_FILE))
            else:
                config_file = CONFIG_FILE
        super(GuiConfig, self).load(config_file, path)

        self.configure_gtk()
        self.configure_colors()

        # fill up shortcuts
        if not using_default_config:
            default_gui_config = yaml.load(
                self.default_config) if self.default_config else {}
            shortcuts_dict = self.get_config_value('SHORTCUTS')
            for shortcut_name, shortcuts_list in default_gui_config.get(
                    'SHORTCUTS', {}).items():
                if shortcut_name not in shortcuts_dict:
                    self.logger.info(
                        "Shortcut for '{0}' is {1}, now, and was taken from default config."
                        "".format(shortcut_name, shortcuts_list))
                    shortcuts_dict[
                        shortcut_name] = shortcuts_list if isinstance(
                            shortcuts_list, list) else [shortcuts_list]
Exemple #6
0
    def load(self, config_file=None, path=None):
        """Loads the configuration from a specific file

        :param config_file: the name of the config file
        :param path: the path to the config file
        """
        if config_file is None:
            if path is None:
                path, config_file = split(
                    resource_filename(__name__, CONFIG_FILE))
            else:
                config_file = CONFIG_FILE
        super(Config, self).load(config_file, path)
Exemple #7
0
def setup_l10n():
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error as e:
        logger.warning("Cannot setup translations: {}".format(e))

    localedir = resource_filename('rafcon', 'locale')

    # Install gettext globally: Allows to use _("my string") without further imports
    gettext.install('rafcon', localedir)

    # Required for glade and the GtkBuilder
    locale.bindtextdomain('rafcon', localedir)
    locale.textdomain('rafcon')
Exemple #8
0
    def rotate_image(self, random_=True):
        images = []
        for image_filename in resource_listdir(rafcon.gui.__name__, "assets/splashscreens"):
            images.append(resource_filename(rafcon.gui.__name__, "assets/splashscreens/" + image_filename))

        # if random mode is specified, choose a picture out of the target folder. Else switch through the pictures
        if random_:
            image_path = images[int(random.uniform(0.0, len(images)))]
        else:
            if self.image_index >= len(images):
                self.image_index = 0
            image_path = images[self.image_index]
            self.image_index += 1

        self.load_image(image_path)
Exemple #9
0
    def apply_clicked(self, button):
        """Triggered when the Apply button in the source editor is clicked.

        """
        if isinstance(self.model.state, LibraryState):
            logger.warn("It is not allowed to modify libraries.")
            self.view.set_text("")
            return

        # Ugly workaround to give user at least some feedback about the parser
        # Without the loop, this function would block the GTK main loop and the log message would appear after the
        # function has finished
        # TODO: run parser in separate thread
        while gtk.events_pending():
            gtk.main_iteration_do()

        # get script
        current_text = self.view.get_text()

        # Directly apply script if linter was deactivated
        if not self.view['pylint_check_button'].get_active():
            self.set_script_text(current_text)
            return

        logger.debug("Parsing execute script...")
        with open(self.tmp_file, "w") as text_file:
            text_file.write(current_text)

        # clear astroid module cache, see http://stackoverflow.com/questions/22241435/pylint-discard-cached-file-state
        MANAGER.astroid_cache.clear()
        lint_config_file = resource_filename(rafcon.__name__, "pylintrc")
        args = ["--rcfile={}".format(lint_config_file)]  # put your own here
        with contextlib.closing(StringIO()) as dummy_buffer:
            json_report = JSONReporter(dummy_buffer)
            try:
                lint.Run([self.tmp_file] + args,
                         reporter=json_report,
                         exit=False)
            except:
                logger.exception("Could not run linter to check script")
        os.remove(self.tmp_file)

        if json_report.messages:

            def on_message_dialog_response_signal(widget, response_id):
                if response_id == 1:
                    self.set_script_text(current_text)
                else:
                    logger.debug("The script was not saved")
                widget.destroy()

            message_string = "Are you sure that you want to save this file?\n\nThe following errors were found:"

            line = None
            for message in json_report.messages:
                (error_string, line) = self.format_error_string(message)
                message_string += "\n\n" + error_string

            # focus line of error
            if line:
                tbuffer = self.view.get_buffer()
                start_iter = tbuffer.get_start_iter()
                start_iter.set_line(int(line) - 1)
                tbuffer.place_cursor(start_iter)
                message_string += "\n\nThe line was focused in the source editor."
                self.view.scroll_to_cursor_onscreen()

            # select state to show source editor
            sm_m = state_machine_manager_model.get_state_machine_model(
                self.model)
            if sm_m.selection.get_selected_state() is not self.model:
                sm_m.selection.set(self.model)

            RAFCONButtonDialog(message_string,
                               ["Save with errors", "Do not save"],
                               on_message_dialog_response_signal,
                               message_type=gtk.MESSAGE_WARNING,
                               parent=self.get_root_window())
        else:
            self.set_script_text(current_text)
Exemple #10
0
def get_glade_path(glade_file):
    return resource_filename(__name__, glade_file)