示例#1
0
 def discover_preferences_configurations(self):
     """
     Discovers the configuration.json files on the directory and subdirectories of the preferences package
     and attempts to load  them.
     """
     preferences = Preferences()
     packages = preferences.get_packages(
         Preferences.PACKAGE_TYPE_DRIVERS, [])
     for package in packages:
         try:
             mod = importlib.import_module(package)
             if mod is not None:
                 self.discover_configurations(
                     os.path.dirname(mod.__file__), mod.__name__)
             else:
                 # Ignore package that could not be initialized.
                 logger.debug(
                     'Failed to import package {}'.format(package))
         except Exception as e:
             # Ignore package that could not be initialized.
             logger.debug('Failed to load package {} error {}'.format(
                 package, str(e)))
def discover_preferences_chemistry_operators():
    """
    Discovers the chemistry operators on the directory and subdirectories of the preferences package
    and attempts to register them. Chem.Operator modules should subclass ChemistryOperator Base class.
    """
    preferences = Preferences()
    packages = preferences.get_packages(Preferences.PACKAGE_TYPE_CHEMISTRY, [])
    for package in packages:
        try:
            mod = importlib.import_module(package)
            if mod is not None:
                _discover_local_chemistry_operators(
                    os.path.dirname(mod.__file__),
                    mod.__name__,
                    names_to_exclude=['__main__'],
                    folders_to_exclude=['__pycache__'])
            else:
                # Ignore package that could not be initialized.
                logger.debug('Failed to import package {}'.format(package))
        except Exception as e:
            # Ignore package that could not be initialized.
            logger.debug('Failed to load package {} error {}'.format(
                package, str(e)))
class PackagesPage(ToolbarView):
    def __init__(self, parent, preferences, **options):
        super(PackagesPage, self).__init__(parent, **options)
        size = font.nametofont('TkHeadingFont').actual('size')
        ttk.Style().configure("PackagesPage.Treeview.Heading",
                              font=(None, size, 'bold'))
        self._tree = ttk.Treeview(self,
                                  style='PackagesPage.Treeview',
                                  selectmode=tk.BROWSE,
                                  height=4,
                                  columns=['value'])
        self._tree.heading('#0', text='Type')
        self._tree.heading('value', text='Name')
        self._tree.column('#0', minwidth=0, width=150, stretch=tk.NO)
        self._tree.column('value', minwidth=0, width=500, stretch=tk.YES)
        self._tree.bind('<<TreeviewSelect>>', self._on_tree_select)
        self._tree.bind('<Button-1>', self._on_tree_edit)
        self.init_widgets(self._tree)

        self._preferences = Preferences()
        self._popup_widget = None
        self.pack(fill=tk.BOTH, expand=tk.TRUE)
        self.populate()
        self.initial_focus = self._tree

    def clear(self):
        if self._popup_widget is not None and self._popup_widget.winfo_exists(
        ):
            self._popup_widget.destroy()

        self._popup_widget = None
        for i in self._tree.get_children():
            self._tree.delete([i])

    def populate(self):
        self.clear()
        packages = self._preferences.get_packages(
            Preferences.PACKAGE_TYPE_DRIVERS, [])
        for package in packages:
            self._populate(Preferences.PACKAGE_TYPE_DRIVERS, package)

        packages = self._preferences.get_packages(
            Preferences.PACKAGE_TYPE_CHEMISTRY, [])
        for package in packages:
            self._populate(Preferences.PACKAGE_TYPE_CHEMISTRY, package)

    def _populate(self, package_type, package):
        package_type = '' if type is None else str(package_type)
        package_type = package_type.replace('\r', '\\r').replace('\n', '\\n')
        package = '' if package is None else str(package)
        package = package.replace('\r', '\\r').replace('\n', '\\n')
        self._tree.insert('', tk.END, text=package_type, values=[package])

    def has_selection(self):
        return self._tree.selection()

    def _on_tree_select(self, event):
        for item in self._tree.selection():
            self.show_remove_button(True)
            return

    def _on_tree_edit(self, event):
        rowid = self._tree.identify_row(event.y)
        if not rowid:
            return

        column = self._tree.identify_column(event.x)
        if column == '#1':
            x, y, width, height = self._tree.bbox(rowid, column)
            pady = height // 2

            item = self._tree.identify("item", event.x, event.y)
            package_type = self._tree.item(item, "text")
            package = self._tree.item(item, 'values')[0]
            self._popup_widget = PackagePopup(self,
                                              package_type,
                                              self._tree,
                                              package,
                                              state=tk.NORMAL)
            self._popup_widget.selectAll()
            self._popup_widget.place(x=x, y=y + pady, anchor=tk.W, width=width)

    def onadd(self):
        dialog = PackageComboDialog(self.master, self)
        dialog.do_init(tk.LEFT)
        dialog.do_modal()
        if dialog.result is not None and self._preferences.add_package(
                dialog.result[0], dialog.result[1]):
            self.populate()
            self.show_remove_button(self.has_selection())

    def onremove(self):
        for item in self._tree.selection():
            package_type = self._tree.item(item, 'text')
            package = self._tree.item(item, 'values')[0]
            if self._preferences.remove_package(package_type, package):
                self.populate()
                self.show_remove_button(self.has_selection())

            break

    def on_package_set(self, package_type, old_package, new_package):
        new_package = new_package.strip()
        if len(new_package) == 0:
            return False

        if self._preferences.change_package(package_type, old_package,
                                            new_package):
            self.populate()
            self.show_remove_button(self.has_selection())
            return True

        return False

    def is_valid(self):
        return True

    def validate(self):
        return True

    def apply(self, preferences):
        changed = False
        packages = self._preferences.get_packages(
            Preferences.PACKAGE_TYPE_DRIVERS, [])
        if packages != preferences.get_packages(
                Preferences.PACKAGE_TYPE_DRIVERS, []):
            preferences.set_packages(Preferences.PACKAGE_TYPE_DRIVERS,
                                     packages)
            changed = True

        packages = self._preferences.get_packages(
            Preferences.PACKAGE_TYPE_CHEMISTRY, [])
        if packages != preferences.get_packages(
                Preferences.PACKAGE_TYPE_CHEMISTRY, []):
            preferences.set_packages(Preferences.PACKAGE_TYPE_CHEMISTRY,
                                     packages)
            changed = True

        if changed:
            preferences.save()
            refresh_operators()
            configuration_mgr = ConfigurationManager()
            configuration_mgr.refresh_drivers()