Пример #1
0
    def __init__(self):
        super().__init__()

        # Create all dialogs
        self.about_dialog = AboutDialog()
        self.tutorial_dialog = HelpDialog()
        self.size_warning = SizeWarning()
        self.source_warning = SourceCodeWarning()
        self.about_dialog.hide()
        self.tutorial_dialog.hide()
        self.size_warning.hide()
        self.source_warning.hide()

        # Read config file to find out if this is first run
        configpath = str(
            Path.home()) + "/.config/codeblock_visual_studio/config"
        configread = configparser.ConfigParser()
        config = configread.read(configpath)
        if len(config) == 0:
            # First Run, open tutorial and autogenerate config
            os.makedirs(os.path.dirname(configpath), exist_ok=True)
            with open(configpath, 'w') as f:
                f.write("")
                self.tutorial_dialog.exec_()

        # Bind buttons to functions and initialize varibales
        self.bind()
        self.classViewFileIndex = {}
        self.lines = []
        self.lint = ()
        self.go_ahead = True
        self.class_list = {}
Пример #2
0
    def show_about_dialog(self, parent=None):
        if not self.__about_dialog:
            self.__about_dialog = AboutDialog()
            self.__about_dialog.connect("destroy",
                                        self.on_about_dialog_destroy)

        self.__about_dialog.set_transient_for(parent)
        self.__about_dialog.present()
Пример #3
0
    def on_about(self):
        about_dialog = AboutDialog(self.root)

        # make window modal
        about_dialog.wait_visibility()
        about_dialog.focus_set()
        about_dialog.grab_set()
        about_dialog.transient(self.root)
Пример #4
0
 def showAbout(self):
     """Run method that loads and starts the plugin"""
     locale = self.locale
     if not locale in ['en', 'de', 'it', 'fr']:
         locale = 'en'
     if self.aboutWidget is None:
         self.aboutWidget = AboutDialog(locale, self.iface.mainWindow())
     self.aboutWidget.show()
     self.aboutWidget.raise_()
Пример #5
0
    def show_about_dialog(self, parent=None):
        if not self.__about_dialog:
            self.__about_dialog = AboutDialog()
            self.__about_dialog.connect("destroy", self.on_about_dialog_destroy)

        self.__about_dialog.set_transient_for(parent)
        self.__about_dialog.present()
class About(object):
    '''
    Main class for the create project widget
    '''


    def __init__(self):
        '''
        Constructor
        '''
        
        self.dlg = AboutDialog()
    
    def run(self):
        '''
        Runs the widget
        '''
        
        self.dlg.show()
Пример #7
0
    def _about_dialog_default(self):
        """ Trait initializer. """

        about_dialog = AboutDialog(
            parent = self.workbench.active_window.control,
            image  = ImageResource('about'),
            additions = ['RadPy version: ' + self.version]
        )

        return about_dialog
Пример #8
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, "i18n",
                                  "openlayers_{}.qm".format(locale))

        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self._olLayerTypeRegistry = WebLayerTypeRegistry(self)
        self.olOverview = OLOverview(iface, self._olLayerTypeRegistry)
        self.dlgAbout = AboutDialog()
Пример #9
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__).decode(
            sys.getfilesystemencoding())

        # initialize locale
        self.translator = QTranslator()

        self.locale = Locale.get_locale()
        locale_path = os.path.join(
            self.plugin_dir, 'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.info_dlg = AboutDialog()

        # Check Contrib and User dirs
        try:
            ExtraSources.check_extra_dirs()
        except:
            error_message = self.tr(
                'Extra dirs for %s can\'t be created: %s %s') % (
                    PluginSettings.product_name(), sys.exc_type, sys.exc_value)
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None
Пример #10
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        self.translator = QTranslator()

        self.locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir, 'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.settings_dlg = SettingsDialog()
        self.info_dlg = AboutDialog()

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None

        # TileLayer assets
        self.crs3857 = None
        self.downloadTimeout = 30  # TODO: settings
        self.navigationMessagesEnabled = Qt.Checked  # TODO: settings
        self.pluginName = 'QuickMapServices'
Пример #11
0
 def show_about_dialog(self, *args):
     d = AboutDialog(self,
                     window_title='About Binary Code Translator',
                     about_title='Binary Code Translator',
                     content='Developed and written by:\n'
                     '\tDenniel Luis Saway Sadian '
                     '(https://denniel-sadian.github.io)\n\n'
                     'Date of creation:\n'
                     '\tMarch 10, 2018\n\n'
                     'Description:\n'
                     '\tThis app can translate text to binary and '
                     'binary to text.',
                     image='binary.png')
     d.wm_iconbitmap('binary.ico')
     d.mainloop()
     return args
Пример #12
0
 def f1(self, *args):
     AboutDialog(self.master,
                 window_title='About Gaseous',
                 about_title='Gaseous',
                 content='Developed and written by:\n'
                 '\tDenniel Luis Saway Sadian '
                 '(https://denniel-sadian.github.io)\n\n'
                 'Date of creation:\n'
                 '\tJanuary 21, 2018\n\n'
                 'Description:\n'
                 '\tThis application is written for quicker solving '
                 'of gas problems. When using this application,'
                 ' make sure that all the givens are compatible '
                 'with each other. For example, if the initial '
                 'volume is in liters, the final volume must be in '
                 'liters as well. The desired unit for temperature '
                 'is kelvin. This app has a built-in unit converter, '
                 'so conversion is easy.\n'
                 '\tThis application is written completely in Python '
                 'Programming Language. It uses Tkinter as the GUI '
                 'Framework.',
                 image='gas.png').mainloop()
     return args
Пример #13
0
 def show_about(self, *args):
     window = AboutDialog(
         self,
         window_title='About Tailoring Management System',
         about_title='Tailoring Management System',
         content='Developed and written by:\n'
         '\tDenniel Luis Saway Sadian '
         '(https://denniel-sadian.github.io)\n\n'
         'Date of creation:\n'
         '\tJuly ‎15, ‎2018\n\n'
         'Description:\n'
         "\tThis application's purpose is to be used in shops that "
         "stitch clothes. They don't have to use papers to write down "
         "their clients' information",
         image='tms.png')
     window.wm_iconbitmap('tms.ico')
     window.mainloop()
     return args
 def show_about(self, *args):
     window = AboutDialog(
         self,
         window_title='About LyricsManager',
         about_title='Lyrics Manager',
         content='Developed and written by:\n'
         '\tDenniel Luis Saway Sadian '
         '(https://denniel-sadian.github.io)\n\n'
         'Date of creation:\n'
         '\tJanuary 9, 2018\n\n'
         'Description:\n'
         '\tThis application lets you store, create and view '
         'your favorite lyrics. It is written completely in '
         'Python Programming Language and uses Tkinter as '
         'its GUI framework.',
         image='lm.png')
     window.wm_iconbitmap('ic.ico')
     window.mainloop()
     return args
Пример #15
0
class Application():
    def __init__(self):
        self.__unsaved_indices = []
        self.windows = set()
        self.__about_dialog = None
        self.__page_setup = None
        self.__print_settings = None

        config_folder = global_settings.config_dir
        if not os.path.exists(config_folder):
            os.makedirs(config_folder)

        state_location = os.path.join(config_folder, 'reinteract.state')
        self.state = ApplicationState(state_location)

    def get_notebook_infos(self):
        paths = []

        recent = self.state.get_recent_notebooks()
        notebooks_dir = global_settings.notebooks_dir
        recent_paths = [os.path.abspath(r.path) for r in recent]
        folder_paths = [os.path.join(notebooks_dir, f) for f in os.listdir(notebooks_dir)]
        paths = recent_paths + folder_paths

        example_state = self.state.get_notebook_state(global_settings.examples_dir)
        if example_state.get_last_opened() == -1:
            paths.append(global_settings.examples_dir)
        paths = [p for p in paths if os.path.isdir(p)]
        paths = list(set((os.path.normpath(path) for path in paths)))

        return [NotebookInfo(p) for p in paths]

    def __make_notebook_window(self, notebook):
        if global_settings.mini_mode:
            global MiniWindow
            from mini_window import MiniWindow
            return MiniWindow(notebook)
        else:
            global NotebookWindow
            from notebook_window import NotebookWindow
            return NotebookWindow(notebook)

    def open_notebook(self, path):
        for window in self.windows:
            if window.path == path:
                window.window.present()
                return window

        notebook = Notebook(path)
        window = self.__make_notebook_window(notebook)
        window.show()
        self.windows.add(window)

        self.state.notebook_opened(path)

        return window

    def find_notebook_path(self, path):
        # Given a path, possibly inside a notebook, find the notebook and the relative
        # path of the notebook inside the file
        relative = None
        tmp = path
        while True:
            if os.path.isdir(tmp):
                if os.path.exists(os.path.join(tmp, "index.rnb")):
                    return tmp, relative
            parent, basename = os.path.split(tmp)
            if parent == tmp: # At the root
                # As a transition thing, for now allow specifying a folder without
                # an index.rnb as a folder
                if os.path.isdir(path):
                    return path, None
                else:
                    return None, None

            tmp = parent
            if relative is None:
                relative = basename
            else:
                relative = os.path.join(basename, relative)

        return tmp, relative

    def open_path(self, path):
        """Figure out what path points to, and open it appropriately"""

        absolute = os.path.abspath(path)
        basename, dirname = os.path.split(absolute)

        if basename.lower() == "index.rnb":
            notebook_path, relative = dirname, None
        else:
            notebook_path, relative = self.find_notebook_path(absolute)

        if notebook_path:
            window = self.open_notebook(notebook_path)
            if relative and relative in window.notebook.files:
                window.open_file(window.notebook.files[relative])
        else:
            global EditorWindow
            from editor_window import EditorWindow

            window = EditorWindow()
            if not window.load(absolute):
                window.window.destroy()
                return False

            window.show()
            self.windows.add(window)

        return True

    def create_notebook(self, path, description=None):
        os.makedirs(path)
        notebook = Notebook(path)
        if description is not None:
            notebook.info.description = description
        window = self.__make_notebook_window(notebook)
        window.show()
        self.windows.add(window)

        self.state.notebook_opened(path)

        return window

    def create_notebook_dialog(self, parent=None):
        return new_notebook.run(parent)

    def open_notebook_dialog(self, parent=None):
        import open_notebook
        return open_notebook.run(parent)

    def on_about_dialog_destroy(self, dialog):
        self.__about_dialog = None

    def show_about_dialog(self, parent=None):
        if not self.__about_dialog:
            self.__about_dialog = AboutDialog()
            self.__about_dialog.connect("destroy", self.on_about_dialog_destroy)

        self.__about_dialog.set_transient_for(parent)
        self.__about_dialog.present()

    def show_uri(self, uri):
        if sys.platform=='win32':
            os.startfile(uri)
        elif sys.platform == 'darwin':
            os.spawnl(os.P_NOWAIT, '/usr/bin/open', uri)
        else:
            gtk.show_uri(gtk.gdk.screen_get_default(),
                         uri,
                         gtk.get_current_event_time())

    def quit(self, from_window_close=False):
        for window in self.windows:
            if not window.confirm_discard(before_quit=not from_window_close):
                return

        self.state.flush()
        gtk.main_quit()

    def close_all_windows(self, confirm_discard=True, wait_for_execution=True):
        windows = list(self.windows)
        for window in windows:
            window.close(confirm_discard=confirm_discard, wait_for_execution=wait_for_execution)

    def window_closed(self, window):
        self.windows.remove(window)
        if not global_settings.main_menu_mode and len(self.windows) == 0 and gtk.main_level() > 0:
            self.quit()

    def allocate_unsaved_index(self):
        """Allocate an index to be used when displaying an unsaved object ("Unsaved Worksheet 1")"""

        for i in xrange(0, len(self.__unsaved_indices)):
            if not self.__unsaved_indices[i]:
                self.__unsaved_indices[i] = True
                return i + 1
        self.__unsaved_indices.append(True)
        return len(self.__unsaved_indices)

    def free_unsaved_index(self, index):
        """Free an index previously returned by allocate_unsaved_index()"""

        self.__unsaved_indices[index - 1] = False

    def __get_page_setup_filename(self):
        return os.path.join(global_settings.config_dir, "page_setup.ini")

    def get_page_setup(self):
        if not self.__page_setup:
            self.__page_setup = gtk.PageSetup()
            try:
                filename = self.__get_page_setup_filename()
                self.__page_setup.load_file(filename)
            except glib.GError:
                pass

        return self.__page_setup

    def save_page_setup(self, page_setup):
        self.__page_setup = page_setup

        filename = self.__get_page_setup_filename()
        page_setup.to_file(filename)

    # We currently don't persist print permanently settings - it seems
    # like the stuff that you don't want to persist (number of copies,
    # etc), is at least as much as the stuff you want to persist
    # (printer output tray, perhaps) - instead we just keep them
    # around until quit.

    def get_print_settings(self):
        if self.__print_settings is None:
            self.__print_settings = gtk.PrintSettings()

        return self.__print_settings

    def save_print_settings(self, settings):
        self.__print_settings = settings

    def free_caches(self):
        self.__page_setup = None
        self.__print_settings = None
Пример #16
0
 def show_about(self):
     dlg = AboutDialog(self.context, self)
     dlg.exec_()
Пример #17
0
 def show_about(self):
     self.init_window_flags(allow_top=False)
     AboutDialog().exec()
     self.init_window_flags(allow_top=True)
     self.show()
Пример #18
0
 def __init__(self):
     '''
     Constructor
     '''
     
     self.dlg = AboutDialog()
Пример #19
0
    def _onActionAboutTriggered(self):

        dialog = AboutDialog(self)
        dialog.exec_()
Пример #20
0
 def about(self):
     ad = AboutDialog()
     ad.display()
Пример #21
0
class Main(MainWindow):
    def __init__(self):
        super().__init__()

        # Create all dialogs
        self.about_dialog = AboutDialog()
        self.tutorial_dialog = HelpDialog()
        self.size_warning = SizeWarning()
        self.source_warning = SourceCodeWarning()
        self.about_dialog.hide()
        self.tutorial_dialog.hide()
        self.size_warning.hide()
        self.source_warning.hide()

        # Read config file to find out if this is first run
        configpath = str(
            Path.home()) + "/.config/codeblock_visual_studio/config"
        configread = configparser.ConfigParser()
        config = configread.read(configpath)
        if len(config) == 0:
            # First Run, open tutorial and autogenerate config
            os.makedirs(os.path.dirname(configpath), exist_ok=True)
            with open(configpath, 'w') as f:
                f.write("")
                self.tutorial_dialog.exec_()

        # Bind buttons to functions and initialize varibales
        self.bind()
        self.classViewFileIndex = {}
        self.lines = []
        self.lint = ()
        self.go_ahead = True
        self.class_list = {}

    def bind(self):
        self.actionOpen.triggered.connect(self.open_file)
        self.actionAbout.triggered.connect(self.about_dialog.show)
        self.actionTutorial.triggered.connect(self.tutorial_dialog.show)
        self.classView.itemDoubleClicked.connect(self.classview_openclass)
        self.size_warning.buttonBox.accepted.connect(self.size_warning.hide)
        self.size_warning.buttonBox.rejected.connect(self.check_size)

    def check_size(self):
        self.size_warning.hide()
        self.go_ahead = False

    def classview_openclass(self):
        # Get the selected class (should be first one selected)
        try:
            selected_item = self.classView.selectedItems()[0].parent().text(0)
        except AttributeError:
            return 0

        # Figure out whether to use package naming or module naming
        if selected_item.split(".")[-1] in ["py", "so"]:
            # Select module naming
            inspect_typed = selected_item.split(".")[0]
        else:
            # Select package naming
            inspect_typed = selected_item

        # Read entire file into self.lines
        try:
            with open(self.class_list[2][inspect_typed]) as f:
                self.lines = []
                for l in f:
                    self.lines.append(l.lstrip())
        except UnicodeDecodeError:
            self.source_warning.show()
            return 0

        if len(self.lines) > 2000:
            self.size_warning.exec_()
            if self.go_ahead == False:
                self.go_ahead = True
                return 0

        # Get output from linter and use the read code to generate the code blocks
        self.lint = error_catcher.get_lint(self.class_list[2][inspect_typed])
        self.create_blocks(
            self.class_list[0][self.class_list[2][inspect_typed]][
                self.classView.selectedItems()[0].text(0)])

    def open_file(self):
        filename = QFileDialog.getOpenFileName(self, 'Open file for reading',
                                               '', "Python files (*.py)")[0]
        self.regenerate_classview(filename)

    def regenerate_classview(self, file):
        try:
            # Get everything in format (classes, lint, imports)
            # classes is in format {file: {class: {functions: {list_of_source}}}}
            # Lint is in format {file: [list_of_lint_warns]}
            # Imports is in format {module: file}
            self.class_list = interpreter.get_classes_all(file)
        except:
            self.class_list = ({}, {}, {})
        class_list_sorted = {}
        for k, v in self.class_list[0].items():
            # Get name of modules
            try:
                filename = list(self.class_list[2].keys())[list(
                    self.class_list[2].values()).index(k)]
            except ValueError:
                filename = file.split("/")[-1]
            if len(filename.split(".")) < 2:
                # Use module-style naming (.py or .so extension)
                filename = filename + "." + k.split(".")[-1]

            class_list_sorted[filename] = {}
            for i, j in v.items():
                class_list_sorted[filename][i] = None
            # for i, j in self.class_list[0].items():
            #     if len(filename.split(".")) > 2:
            #         filecompare = filename
            #     else:
            #         filecompare = filename.split(".")[0]
            #     if filecompare in str(j):
            #         class_list_sorted[filename][i] = j
        class_tree_index = {}
        self.classView.clear()
        ind0 = 0
        # class_list_sorted should be in the format {module_name: {class_name:[arbitrary val]}}
        for k2, v2 in class_list_sorted.items():
            class_tree_index[ind0] = QTreeWidgetItem(self.classView)
            class_tree_index[ind0].setText(0, k2)
            for k3, v3 in v2.items():
                class_tree_index[v3] = QTreeWidgetItem(class_tree_index[ind0])
                class_tree_index[v3].setText(0, k3)
            ind0 = ind0 + 1

    def create_blocks(self, funcs):
        for child in self.codeArea.children():
            child.deleteLater()
        self.codeArea.setUpdatesEnabled(True)
        self.function_blocks = self.generate_function_blocks(funcs)
        self.code_blocks = self.generate_code_blocks(funcs)
        for k, v in self.function_blocks.items():
            v.attach_child(self.code_blocks[k][0])
            v.raiseEvent()
            self.code_blocks[k].append(v)

        # svgWidget = HatBlock("test", self.code_blocks['test'][-1], self.codeArea)
        # self.function_blocks.append(svgWidget)
        # svgWidget.show()
        for c, i in enumerate(self.function_blocks.values()):
            i.move_recurse(sum(self.code_blocks['func-widths'][0:c]),
                           i.geometry().y())
            i.raiseEvent()

        for bar in self.code_blocks['ctrlbar']:
            bar.adjust_bar()
            bar.show()
            bar.raise_()

        for comment in self.code_blocks['comments']:
            comment.adjust()
            comment.show()

    def generate_function_blocks(self, funcs):
        f = 0
        retblocks = {}
        for func, func_def in funcs.items():
            if func != "":
                if func_def[0].startswith("@"):
                    retblocks[func] = CapBlock(func_def[1].strip(),
                                               parent=self.codeArea)
                else:
                    retblocks[func] = CapBlock(func_def[0].strip(),
                                               parent=self.codeArea)
            f = f + 1
        return retblocks

    def generate_code_blocks(self, funcs_list):
        f = 0
        retblocks = {}
        # We need a fresh copy of funcs_list due to mutations that occur during function run
        funcs = copy.deepcopy(funcs_list)
        retblocks['comments'] = []
        retblocks['ctrlbar'] = []
        retblocks['func-widths'] = []
        ctrl_bar_count = 0
        for func, code in funcs.items():
            f = 0
            maxwidth = 0
            retblocks[func] = []
            control_block_map = {}
            not_done = True
            for line in code:
                if code.index(line) == 0:
                    # Skip first line (which, by spec, contains function header)
                    continue
                if func != "":
                    if line.lstrip().startswith("#"):
                        self.lint[2][line.lstrip()] = self.lines.index(
                            line.lstrip()) + 1
                    line_leading_whitespace = len(line) - len(line.lstrip())
                    if line_leading_whitespace in control_block_map.keys():
                        # CtrlBottom detected (must be before ifblock)
                        sorted_keys = list(control_block_map.keys())
                        sorted_keys.sort()
                        if not line_leading_whitespace == \
                                sorted_keys[-1]:
                            line = line.lstrip()
                            for l in range(sorted_keys[-1]):
                                line = " " + line
                        retblocks[func].append(
                            CtrlBottom(line.lstrip(), parent=self.codeArea))
                        code.insert(f + 1, line)
                        retblocks['ctrlbar'].append(
                            CtrlBar(parent=self.codeArea))
                        retblocks['ctrlbar'][ctrl_bar_count].attach_top(
                            control_block_map[len(line) - len(line.lstrip())])
                        retblocks['ctrlbar'][ctrl_bar_count].attach_bottom(
                            retblocks[func][f])
                        ctrl_bar_count = ctrl_bar_count + 1
                        del control_block_map[len(line) - len(line.lstrip())]
                    elif line.strip(
                    )[-1] == ':' and not line.lstrip().startswith("#"):
                        # Indented Block - use CtrlTop block
                        retblocks[func].append(
                            CtrlTop(line.lstrip(), parent=self.codeArea))
                        # Store [whitespace, satisfied] values for ctrltop
                        control_block_map[
                            len(line) -
                            len(line.lstrip())] = retblocks[func][f]
                    else:
                        # Just a regular CodeBlock
                        try:
                            if self.lines.index(
                                    line.lstrip()) + 1 in self.lint[0].values(
                                    ):
                                color = "red"
                                lintline = list(self.lint[0].keys())[list(
                                    self.lint[0].values()).index(
                                        self.lines.index(line.lstrip()) + 1)]
                            elif self.lines.index(
                                    line.lstrip()) + 1 in self.lint[1].values(
                                    ):
                                color = "#FFBB33"
                                lintline = list(self.lint[1].keys())[list(
                                    self.lint[1].values()).index(
                                        self.lines.index(line.lstrip()) + 1)]
                            else:
                                color = "#496BD3"
                                lintline = None
                        except ValueError as v:
                            color = "#496BD3"
                            lintline = None
                        retblocks[func].append(
                            CodeBlock(line.lstrip(),
                                      color,
                                      parent=self.codeArea))
                        if lintline is not None:
                            retblocks['comments'].append(
                                CommentBubble(lintline,
                                              retblocks[func][f],
                                              parent=self.codeArea))
                    if f != 0:
                        retblocks[func][f - 1].attach_child(retblocks[func][f])
                if retblocks[func][f].geometry().width() > maxwidth:
                    maxwidth = retblocks[func][f].geometry().width()
                f = f + 1
                if f == len(code) - 1 and len(
                        control_block_map) > 0 and not_done:
                    # CtrlBottom detected (must be before ifblock)
                    sorted_keys = list(control_block_map.keys())
                    sorted_keys.sort()
                    if not line_leading_whitespace == \
                            sorted_keys[-1]:
                        line = line.lstrip()
                        for l in range(sorted_keys[-1]):
                            line = " " + line

                    retblocks[func].append(
                        CtrlBottom(line, parent=self.codeArea))
                    code.insert(f + 1, line)
                    retblocks['ctrlbar'].append(CtrlBar(parent=self.codeArea))
                    retblocks['ctrlbar'][ctrl_bar_count].attach_top(
                        control_block_map[len(line) - len(line.lstrip())])
                    retblocks['ctrlbar'][ctrl_bar_count].attach_bottom(
                        retblocks[func][f])
                    ctrl_bar_count = ctrl_bar_count + 1
                    del control_block_map[len(line) - len(line.lstrip())]
                    not_done = False
            retblocks['func-widths'].append(maxwidth)

        return retblocks

    def get_imports(self, file):
        finder = ModuleFinder()
        finder.run_script(file)
        im = []
        for name, mod in finder.modules.items():
            im.append(name)
        return im

    def get_functions(self, file, class_name):
        spec = importlib.util.spec_from_file_location("foo", file)
        foo = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(foo)
        dirvar = getattr(foo, class_name)
        functions = {}
        for i in dir(dirvar):
            if inspect.isroutine(getattr(dirvar, i)):
                try:
                    functions[i] = list(
                        filter(
                            None,
                            inspect.getsource(getattr(dirvar,
                                                      i)).splitlines()))
                except TypeError:
                    pass
        return functions

    def get_classes(self, file):
        classes = {}
        try:
            sys.path.append("/".join(file.split("/")[:-1]))
            spec = importlib.util.spec_from_file_location(
                file.split("/")[-1], file)
            foo = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(foo)
            for name, obj in inspect.getmembers(foo):
                if inspect.isclass(obj):
                    classes[name] = obj
                    try:
                        self.classViewFileIndex[str(classes[name]).split(
                            "'")[1::2][0]] = inspect.getfile(obj)
                    except TypeError:
                        self.classViewFileIndex[str(
                            classes[name]).split("'")[1::2][0].replace(
                                ".py", "")] = file
        except FileNotFoundError:
            pass
            # do stuff
        return classes

    def get_vars(self, file):
        defined = []
        try:
            importvar = __import__(file)
            dirvar = importvar
            returnvar = dir(dirvar)
        except ImportError:
            importvar = __import__(file.split(".")[0])
            dirvar = getattr(importvar, file.split(".")[1])
            returnvar = dir(dirvar)
        for attr in returnvar:
            if not callable(getattr(dirvar, attr)):
                defined.append(attr)
        returnvar = defined
        return returnvar
Пример #22
0
    def menuAboutClick(self):
        """Slot used when the "About" menu item is clicked.

        """
        about_dialog = AboutDialog(self)
        about_dialog.exec_()
Пример #23
0
class OpenlayersPlugin:
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        localePath = os.path.join(self.plugin_dir, "i18n",
                                  "openlayers_{}.qm".format(locale))

        if os.path.exists(localePath):
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self._olLayerTypeRegistry = WebLayerTypeRegistry(self)
        self.olOverview = OLOverview(iface, self._olLayerTypeRegistry)
        self.dlgAbout = AboutDialog()

    def initGui(self):
        self._olMenu = QMenu("OpenLayers plugin")
        self._olMenu.setIcon(QIcon(":/plugins/openlayers/openlayers.png"))

        # Overview
        self.overviewAddAction = QAction(
            QApplication.translate("OpenlayersPlugin", "OpenLayers Overview"),
            self.iface.mainWindow())
        self.overviewAddAction.setCheckable(True)
        self.overviewAddAction.setChecked(False)
        QObject.connect(self.overviewAddAction, SIGNAL("toggled(bool)"),
                        self.olOverview.setVisible)
        self._olMenu.addAction(self.overviewAddAction)

        self._actionAbout = QAction("Terms of Service / About",
                                    self.iface.mainWindow())
        self._actionAbout.triggered.connect(self.dlgAbout.show)
        self._olMenu.addAction(self._actionAbout)
        self.dlgAbout.finished.connect(self._publicationInfoClosed)

        self._olLayerTypeRegistry.register(OlGooglePhysicalLayer())
        self._olLayerTypeRegistry.register(OlGoogleStreetsLayer())
        self._olLayerTypeRegistry.register(OlGoogleHybridLayer())
        self._olLayerTypeRegistry.register(OlGoogleSatelliteLayer())

        self._olLayerTypeRegistry.register(OlOpenStreetMapLayer())
        self._olLayerTypeRegistry.register(OlOpenCycleMapLayer())
        self._olLayerTypeRegistry.register(OlOCMLandscapeLayer())
        self._olLayerTypeRegistry.register(OlOCMPublicTransportLayer())

        # ID 8-10 was Yahoo
        self._olLayerTypeRegistry.register(OlOSMHumanitarianDataModelLayer())

        self._olLayerTypeRegistry.register(OlOCMOutdoorstLayer())
        self._olLayerTypeRegistry.register(OlOCMTransportDarkLayer())

        self._olLayerTypeRegistry.register(OlBingRoadLayer())
        self._olLayerTypeRegistry.register(OlBingAerialLayer())
        self._olLayerTypeRegistry.register(OlBingAerialLabelledLayer())

        # Order from here on is free. Layers 0-14 should keep order for
        # compatibility with OL Plugin < 2.3

        self._olLayerTypeRegistry.register(OlOCMSpinalMapLayer())
        self._olLayerTypeRegistry.register(OlOCMPioneerLayer())
        self._olLayerTypeRegistry.register(OlOCMMobileAtlasLayer())
        self._olLayerTypeRegistry.register(OlOCMNeighbourhoodLayer())

        self._olLayerTypeRegistry.register(OlOSMStamenTonerLayer())
        self._olLayerTypeRegistry.register(OlOSMStamenTonerLiteLayer())
        self._olLayerTypeRegistry.register(OlOSMStamenWatercolorLayer())
        self._olLayerTypeRegistry.register(OlOSMStamenTerrainLayer())

        self._olLayerTypeRegistry.register(OlAppleiPhotoMapLayer())

        self._olLayerTypeRegistry.register(WikimediaLabelledLayer())
        self._olLayerTypeRegistry.register(WikimediaUnLabelledLayer())

        for group in self._olLayerTypeRegistry.groups():
            groupMenu = group.menu()
            for layer in self._olLayerTypeRegistry.groupLayerTypes(group):
                layer.addMenuEntry(groupMenu, self.iface.mainWindow())
            self._olMenu.addMenu(groupMenu)

        # add action for API key dialogs
        for action in self._olMenu.actions():
            if action.text() == "Google Maps":
                self._actionGoogleMapsApiKey = QAction("Set API key",
                                                       self.iface.mainWindow())
                self._actionGoogleMapsApiKey.triggered.connect(
                    self.showGoogleMapsApiKeyDialog)
                action.menu().addAction(self._actionGoogleMapsApiKey)
            if action.text() == "OSM/Thunderforest":
                self._actionThunderforestApiKey = QAction(
                    "Set API key", self.iface.mainWindow())
                self._actionThunderforestApiKey.triggered.connect(
                    self.showThunderforestApiKeyDialog)
                action.menu().addAction(self._actionThunderforestApiKey)

        #Create Web menu, if it doesn't exist yet
        self.iface.addPluginToWebMenu("_tmp", self._actionAbout)
        self._menu = self.iface.webMenu()
        self._menu.addMenu(self._olMenu)
        self.iface.removePluginWebMenu("_tmp", self._actionAbout)

        # Register plugin layer type
        self.pluginLayerType = OpenlayersPluginLayerType(
            self.iface, self.setReferenceLayer, self._olLayerTypeRegistry)
        QgsPluginLayerRegistry.instance().addPluginLayerType(
            self.pluginLayerType)

        QObject.connect(QgsProject.instance(),
                        SIGNAL("readProject(const QDomDocument &)"),
                        self.projectLoaded)
        QgsProject.instance().projectSaved.connect(self.projectSaved)

        self.setGDALProxy()

    def unload(self):
        self.iface.webMenu().removeAction(self._olMenu.menuAction())

        self.olOverview.setVisible(False)
        del self.olOverview

        # Unregister plugin layer type
        QgsPluginLayerRegistry.instance().removePluginLayerType(
            OpenlayersLayer.LAYER_TYPE)

        QObject.disconnect(QgsProject.instance(),
                           SIGNAL("readProject(const QDomDocument &)"),
                           self.projectLoaded)
        QgsProject.instance().projectSaved.disconnect(self.projectSaved)

    def addLayer(self, layerType):
        if layerType.hasGdalTMS():
            # create GDAL TMS layer
            layer = self.createGdalTmsLayer(layerType, layerType.displayName)
        else:
            # create OpenlayersLayer
            layer = OpenlayersLayer(self.iface, self._olLayerTypeRegistry)
            layer.setLayerName(layerType.displayName)
            layer.setLayerType(layerType)

        if layer.isValid():
            coordRefSys = layerType.coordRefSys(self.canvasCrs())
            self.setMapCrs(coordRefSys)
            QgsMapLayerRegistry.instance().addMapLayer(layer)

            # last added layer is new reference
            self.setReferenceLayer(layer)

            if not layerType.hasGdalTMS():
                msg = "Printing and rotating of Javascript API " \
                      "based layers is currently not supported!"
                self.iface.messageBar().pushMessage(
                    "OpenLayers Plugin",
                    msg,
                    level=QgsMessageBar.WARNING,
                    duration=5)

    def setReferenceLayer(self, layer):
        self.layer = layer

    def removeLayer(self, layerId):
        if self.layer is not None:
            if QGis.QGIS_VERSION_INT >= 10900:
                if self.layer.id() == layerId:
                    self.layer = None
            else:
                if self.layer.getLayerID() == layerId:
                    self.layer = None
            # TODO: switch to next available OpenLayers layer?

    def canvasCrs(self):
        mapCanvas = self.iface.mapCanvas()
        if QGis.QGIS_VERSION_INT >= 20300:
            #crs = mapCanvas.mapRenderer().destinationCrs()
            crs = mapCanvas.mapSettings().destinationCrs()
        elif QGis.QGIS_VERSION_INT >= 10900:
            crs = mapCanvas.mapRenderer().destinationCrs()
        else:
            crs = mapCanvas.mapRenderer().destinationSrs()
        return crs

    def setMapCrs(self, coordRefSys):
        mapCanvas = self.iface.mapCanvas()
        # On the fly
        if QGis.QGIS_VERSION_INT >= 20300:
            mapCanvas.setCrsTransformEnabled(True)
        else:
            mapCanvas.mapRenderer().setProjectionsEnabled(True)
        canvasCrs = self.canvasCrs()
        if canvasCrs != coordRefSys:
            coordTrans = QgsCoordinateTransform(canvasCrs, coordRefSys)
            extMap = mapCanvas.extent()
            extMap = coordTrans.transform(
                extMap, QgsCoordinateTransform.ForwardTransform)
            if QGis.QGIS_VERSION_INT >= 20300:
                mapCanvas.setDestinationCrs(coordRefSys)
            elif QGis.QGIS_VERSION_INT >= 10900:
                mapCanvas.mapRenderer().setDestinationCrs(coordRefSys)
            else:
                mapCanvas.mapRenderer().setDestinationSrs(coordRefSys)
            mapCanvas.freeze(False)
            mapCanvas.setMapUnits(coordRefSys.mapUnits())
            mapCanvas.setExtent(extMap)

    def projectLoaded(self):
        # replace old OpenlayersLayer with GDAL TMS (OL plugin <= 1.3.6)
        rootGroup = self.iface.layerTreeView().layerTreeModel().rootGroup()
        for layer in QgsMapLayerRegistry.instance().mapLayers().values():
            if layer.type(
            ) == QgsMapLayer.PluginLayer and layer.pluginLayerType(
            ) == OpenlayersLayer.LAYER_TYPE:
                if layer.layerType.hasGdalTMS():
                    # replace layer
                    gdalTMSLayer = self.createGdalTmsLayer(
                        layer.layerType, layer.name())
                    if gdalTMSLayer.isValid():
                        self.replaceLayer(rootGroup, layer, gdalTMSLayer)

    def _hasOlLayer(self):
        for layer in QgsMapLayerRegistry.instance().mapLayers().values():
            if layer.customProperty('ol_layer_type'):
                return True
        return False

    def _publicationInfo(self):
        cloud_info_off = QSettings().value("Plugin-OpenLayers/cloud_info_off",
                                           defaultValue=False,
                                           type=bool)
        day = 3600 * 24
        now = time.time()
        lastInfo = QSettings().value("Plugin-OpenLayers/cloud_info_ts",
                                     defaultValue=0.0,
                                     type=float)
        if lastInfo == 0.0:
            lastInfo = now - 20 * day  # Show first time after 10 days
            QSettings().setValue("Plugin-OpenLayers/cloud_info_ts", lastInfo)
        days = (now - lastInfo) / day
        if days >= 30 and not cloud_info_off:
            self.dlgAbout.tabWidget.setCurrentWidget(
                self.dlgAbout.tab_publishing)
            self.dlgAbout.show()
            QSettings().setValue("Plugin-OpenLayers/cloud_info_ts", now)

    def _publicationInfoClosed(self):
        QSettings().setValue("Plugin-OpenLayers/cloud_info_off",
                             self.dlgAbout.cb_publishing.isChecked())

    def projectSaved(self):
        if self._hasOlLayer():
            self._publicationInfo()

    def createGdalTmsLayer(self, layerType, name):
        # create GDAL TMS layer with XML string as datasource
        layer = QgsRasterLayer(layerType.gdalTMSConfig(), name)
        layer.setCustomProperty('ol_layer_type', layerType.layerTypeName)
        return layer

    def replaceLayer(self, group, oldLayer, newLayer):
        index = 0
        for child in group.children():
            if QgsLayerTree.isLayer(child):
                if child.layerId() == oldLayer.id():
                    # insert new layer
                    QgsMapLayerRegistry.instance().addMapLayer(newLayer, False)
                    newLayerNode = group.insertLayer(index, newLayer)
                    newLayerNode.setVisible(child.isVisible())

                    # remove old layer
                    QgsMapLayerRegistry.instance().removeMapLayer(
                        oldLayer.id())

                    msg = "Updated layer '%s' from old OpenLayers Plugin version" % newLayer.name(
                    )
                    self.iface.messageBar().pushMessage(
                        "OpenLayers Plugin", msg, level=QgsMessageBar.INFO)
                    QgsMessageLog.logMessage(msg, "OpenLayers Plugin",
                                             QgsMessageLog.INFO)

                    # layer replaced
                    return True
            else:
                if self.replaceLayer(child, oldLayer, newLayer):
                    # layer replaced in child group
                    return True

            index += 1

        # layer not in this group
        return False

    def setGDALProxy(self):
        proxy = getProxy()

        httpProxyTypes = [
            QNetworkProxy.DefaultProxy, QNetworkProxy.Socks5Proxy,
            QNetworkProxy.HttpProxy
        ]
        if QT_VERSION >= 0X040400:
            httpProxyTypes.append(QNetworkProxy.HttpCachingProxy)

        if proxy is not None and proxy.type() in httpProxyTypes:
            # set HTTP proxy for GDAL
            gdalHttpProxy = proxy.hostName()
            port = proxy.port()
            if port != 0:
                gdalHttpProxy += ":%i" % port
            os.environ["GDAL_HTTP_PROXY"] = gdalHttpProxy

            if proxy.user():
                gdalHttpProxyuserpwd = "%s:%s" % (proxy.user(),
                                                  proxy.password())
                os.environ["GDAL_HTTP_PROXYUSERPWD"] = gdalHttpProxyuserpwd
        else:
            # disable proxy
            os.environ["GDAL_HTTP_PROXY"] = ''
            os.environ["GDAL_HTTP_PROXYUSERPWD"] = ''

    def showGoogleMapsApiKeyDialog(self):
        apiKey = QSettings().value("Plugin-OpenLayers/googleMapsApiKey")
        newApiKey, ok = QInputDialog.getText(self.iface.mainWindow(),
                                             "API key",
                                             "Enter your Google Maps API key",
                                             QLineEdit.Normal, apiKey)
        if ok:
            QSettings().setValue("Plugin-OpenLayers/googleMapsApiKey",
                                 newApiKey)

    def showThunderforestApiKeyDialog(self):
        apiKey = QSettings().value("Plugin-OpenLayers/thunderforestApiKey")
        newApiKey, ok = QInputDialog.getText(
            self.iface.mainWindow(), "API key",
            "Enter your API key (<a href=\"https://thunderforest.com/pricing/\">https://thunderforest.com</a>)",
            QLineEdit.Normal, apiKey)
        if ok:
            QSettings().setValue("Plugin-OpenLayers/thunderforestApiKey",
                                 newApiKey)
Пример #24
0
 def show_about(self):
     d = AboutDialog(self.root)
     self.root.wait_window(d.top)
Пример #25
0
class Application():
    def __init__(self):
        self.__unsaved_indices = []
        self.windows = set()
        self.__about_dialog = None
        self.__page_setup = None
        self.__print_settings = None

        config_folder = global_settings.config_dir
        if not os.path.exists(config_folder):
            os.makedirs(config_folder)

        state_location = os.path.join(config_folder, 'reinteract.state')
        self.state = ApplicationState(state_location)

    def get_notebook_infos(self):
        paths = []

        recent = self.state.get_recent_notebooks()
        notebooks_dir = global_settings.notebooks_dir
        recent_paths = [os.path.abspath(r.path) for r in recent]
        folder_paths = [
            os.path.join(notebooks_dir, f) for f in os.listdir(notebooks_dir)
        ]
        paths = recent_paths + folder_paths

        example_state = self.state.get_notebook_state(
            global_settings.examples_dir)
        if example_state.get_last_opened() == -1:
            paths.append(global_settings.examples_dir)
        paths = [p for p in paths if os.path.isdir(p)]
        paths = list(set((os.path.normpath(path) for path in paths)))

        return [NotebookInfo(p) for p in paths]

    def __make_notebook_window(self, notebook):
        if global_settings.mini_mode:
            global MiniWindow
            from mini_window import MiniWindow
            return MiniWindow(notebook)
        else:
            global NotebookWindow
            from notebook_window import NotebookWindow
            return NotebookWindow(notebook)

    def open_notebook(self, path):
        for window in self.windows:
            if window.path == path:
                window.window.present()
                return window

        notebook = Notebook(path)
        window = self.__make_notebook_window(notebook)
        window.show()
        self.windows.add(window)

        self.state.notebook_opened(path)

        return window

    def find_notebook_path(self, path):
        # Given a path, possibly inside a notebook, find the notebook and the relative
        # path of the notebook inside the file
        relative = None
        tmp = path
        while True:
            if os.path.isdir(tmp):
                if os.path.exists(os.path.join(tmp, "index.rnb")):
                    return tmp, relative
            parent, basename = os.path.split(tmp)
            if parent == tmp:  # At the root
                # As a transition thing, for now allow specifying a folder without
                # an index.rnb as a folder
                if os.path.isdir(path):
                    return path, None
                else:
                    return None, None

            tmp = parent
            if relative is None:
                relative = basename
            else:
                relative = os.path.join(basename, relative)

        return tmp, relative

    def open_path(self, path):
        """Figure out what path points to, and open it appropriately"""

        absolute = os.path.abspath(path)
        basename, dirname = os.path.split(absolute)

        if basename.lower() == "index.rnb":
            notebook_path, relative = dirname, None
        else:
            notebook_path, relative = self.find_notebook_path(absolute)

        if notebook_path:
            window = self.open_notebook(notebook_path)
            if relative and relative in window.notebook.files:
                window.open_file(window.notebook.files[relative])
        else:
            global EditorWindow
            from editor_window import EditorWindow

            window = EditorWindow()
            if not window.load(absolute):
                window.window.destroy()
                return False

            window.show()
            self.windows.add(window)

        return True

    def create_notebook(self, path, description=None):
        os.makedirs(path)
        notebook = Notebook(path)
        if description is not None:
            notebook.info.description = description
        window = self.__make_notebook_window(notebook)
        window.show()
        self.windows.add(window)

        self.state.notebook_opened(path)

        return window

    def create_notebook_dialog(self, parent=None):
        return new_notebook.run(parent)

    def open_notebook_dialog(self, parent=None):
        import open_notebook
        return open_notebook.run(parent)

    def on_about_dialog_destroy(self, dialog):
        self.__about_dialog = None

    def show_about_dialog(self, parent=None):
        if not self.__about_dialog:
            self.__about_dialog = AboutDialog()
            self.__about_dialog.connect("destroy",
                                        self.on_about_dialog_destroy)

        self.__about_dialog.set_transient_for(parent)
        self.__about_dialog.present()

    def show_uri(self, uri):
        if sys.platform == 'win32':
            os.startfile(uri)
        elif sys.platform == 'darwin':
            os.spawnl(os.P_NOWAIT, '/usr/bin/open', uri)
        else:
            gtk.show_uri(gtk.gdk.screen_get_default(), uri,
                         gtk.get_current_event_time())

    def quit(self, from_window_close=False):
        for window in self.windows:
            if not window.confirm_discard(before_quit=not from_window_close):
                return

        self.state.flush()
        gtk.main_quit()

    def close_all_windows(self, confirm_discard=True, wait_for_execution=True):
        windows = list(self.windows)
        for window in windows:
            window.close(confirm_discard=confirm_discard,
                         wait_for_execution=wait_for_execution)

    def window_closed(self, window):
        self.windows.remove(window)
        if not global_settings.main_menu_mode and len(
                self.windows) == 0 and gtk.main_level() > 0:
            self.quit()

    def allocate_unsaved_index(self):
        """Allocate an index to be used when displaying an unsaved object ("Unsaved Worksheet 1")"""

        for i in xrange(0, len(self.__unsaved_indices)):
            if not self.__unsaved_indices[i]:
                self.__unsaved_indices[i] = True
                return i + 1
        self.__unsaved_indices.append(True)
        return len(self.__unsaved_indices)

    def free_unsaved_index(self, index):
        """Free an index previously returned by allocate_unsaved_index()"""

        self.__unsaved_indices[index - 1] = False

    def __get_page_setup_filename(self):
        return os.path.join(global_settings.config_dir, "page_setup.ini")

    def get_page_setup(self):
        if not self.__page_setup:
            self.__page_setup = gtk.PageSetup()
            try:
                filename = self.__get_page_setup_filename()
                self.__page_setup.load_file(filename)
            except glib.GError:
                pass

        return self.__page_setup

    def save_page_setup(self, page_setup):
        self.__page_setup = page_setup

        filename = self.__get_page_setup_filename()
        page_setup.to_file(filename)

    # We currently don't persist print permanently settings - it seems
    # like the stuff that you don't want to persist (number of copies,
    # etc), is at least as much as the stuff you want to persist
    # (printer output tray, perhaps) - instead we just keep them
    # around until quit.

    def get_print_settings(self):
        if self.__print_settings is None:
            self.__print_settings = gtk.PrintSettings()

        return self.__print_settings

    def save_print_settings(self, settings):
        self.__print_settings = settings

    def free_caches(self):
        self.__page_setup = None
        self.__print_settings = None
Пример #26
0
 def _on_about(self, event):
     dlg = AboutDialog()
     dlg.ShowModal()
     dlg.Destroy()
Пример #27
0
class Application():
    def __init__(self):
        self.__unsaved_indices = []
        self.windows = set()
        self.__about_dialog = None

        config_folder = self.get_config_folder()
        if not os.path.exists(config_folder):
            os.makedirs(config_folder)

        state_location = os.path.join(config_folder, 'reinteract.state')
        self.state = ApplicationState(state_location)

    def get_notebook_infos(self):
        paths = []

        recent = self.state.get_recent_notebooks()
        notebooks_folder = self.get_notebooks_folder()
        recent_paths = [os.path.abspath(r.path) for r in recent]
        folder_paths = [os.path.join(notebooks_folder, f) for f in os.listdir(notebooks_folder)]
        paths = recent_paths + folder_paths

        example_state = self.state.get_notebook_state(global_settings.examples_dir)
        if example_state.get_last_opened() == -1:
            paths.append(global_settings.examples_dir)
        paths = [p for p in paths if os.path.isdir(p)]
        paths = list(set((os.path.normpath(path) for path in paths)))

        return [NotebookInfo(p) for p in paths]

    def get_config_folder(self):
        if sys.platform == 'win32':
            return os.path.join(os.getenv('APPDATA'), 'Reinteract')
        else:
            return os.path.expanduser("~/.reinteract")

    def get_notebooks_folder(self):
        # In a shocking example of cross-platform convergence, ~/Documents
        # is the documents directory on OS X, Windows, and Linux
        return os.path.expanduser("~/Documents/Reinteract")

    def validate_name(self, name):
        # Remove surrounding whitespace
        name = name.strip()
        if name == "":
            raise ValueError("Name cannot be empty")

        # Replace series of whitespace with a single space
        name = name.replace("\s+", " ")

        bad_chars = set()
        for c in name:
            if not _VALID_CHAR.match(c):
                bad_chars.add(c)

        bad = ", ".join(("'" + c + "'" for c in bad_chars))

        if len(bad_chars) == 1:
            raise ValueError("Name contains invalid character: %s" % bad)
        elif len(bad_chars) > 0:
            raise ValueError("Name contains invalid characters: %s" % bad)

        return name

    def __make_notebook_window(self, notebook):
        if global_settings.mini_mode:
            global MiniWindow
            from mini_window import MiniWindow
            return MiniWindow(notebook)
        else:
            global NotebookWindow
            from notebook_window import NotebookWindow
            return NotebookWindow(notebook)

    def open_notebook(self, path):
        for window in self.windows:
            if window.path == path:
                window.window.present()
                return window

        notebook = Notebook(path)
        window = self.__make_notebook_window(notebook)
        window.show()
        self.windows.add(window)

        self.state.notebook_opened(path)

        return window

    def find_notebook_path(self, path):
        # Given a path, possibly inside a notebook, find the notebook and the relative
        # path of the notebook inside the file
        relative = None
        tmp = path
        while True:
            if os.path.isdir(tmp):
                if os.path.exists(os.path.join(tmp, "index.rnb")):
                    return tmp, relative
            parent, basename = os.path.split(tmp)
            if parent == tmp: # At the root
                # As a transition thing, for now allow specifying a folder without
                # an index.rnb as a folder
                if os.path.isdir(path):
                    return path, None
                else:
                    return None, None

            tmp = parent
            if relative == None:
                relative = basename
            else:
                relative = os.path.join(basename, relative)

        return tmp, relative

    def open_path(self, path):
        """Figure out what path points to, and open it appropriately"""

        absolute = os.path.abspath(path)
        basename, dirname = os.path.split(absolute)

        if basename.lower() == "index.rnb":
            notebook_path, relative = dirname, None
        else:
            notebook_path, relative = self.find_notebook_path(absolute)

        if notebook_path:
            window = self.open_notebook(notebook_path)
            if relative and relative in window.notebook.files:
                window.open_file(window.notebook.files[relative])
        else:
            global EditorWindow
            from editor_window import EditorWindow

            window = EditorWindow()
            if not window.load(absolute):
                window.window.destroy()
                return False

            window.show()
            self.windows.add(window)

        return True

    def create_notebook(self, path, description=None):
        os.makedirs(path)
        notebook = Notebook(path)
        if description != None:
            notebook.info.description = description
        window = self.__make_notebook_window(notebook)
        window.show()
        self.windows.add(window)

        self.state.notebook_opened(path)

        return window

    def create_notebook_dialog(self, parent=None):
        return new_notebook.run(parent)

    def open_notebook_dialog(self, parent=None):
        return open_notebook.run(parent)

    def on_about_dialog_destroy(self, dialog):
        self.__about_dialog = None

    def show_about_dialog(self, parent=None):
        if not self.__about_dialog:
            self.__about_dialog = AboutDialog()
            self.__about_dialog.connect("destroy", self.on_about_dialog_destroy)

        self.__about_dialog.set_transient_for(parent)
        self.__about_dialog.present()

    def quit(self):
        for window in self.windows:
            if not window.confirm_discard():
                return

        self.state.flush()
        gtk.main_quit()

    def window_closed(self, window):
        self.windows.remove(window)
        if not global_settings.main_menu_mode and len(self.windows) == 0:
            self.quit()

    def allocate_unsaved_index(self):
        """Allocate an index to be used when displaying an unsaved object ("Unsaved Worksheet 1")"""

        for i in xrange(0, len(self.__unsaved_indices)):
            if not self.__unsaved_indices[i]:
                self.__unsaved_indices[i] = True
                return i + 1
        self.__unsaved_indices.append(True)
        return len(self.__unsaved_indices)

    def free_unsaved_index(self, index):
        """Free an index previously returned by allocate_unsaved_index()"""

        self.__unsaved_indices[index - 1] = False
Пример #28
0
class UserManual:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        self.locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'UserManual_{}.qm'.format(self.locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.helpWidget = None
        self.aboutWidget = None
        self.helpAction = None
        self.aboutAction = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('UserManual', message)

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        self.helpAction = self.iface.findAction("mActionHelp")
        if not self.helpAction and self.iface.helpToolBar():
            self.helpAction = QAction(QIcon(":/plugins/UserManual/icon.png"), self.tr("Help"), self.iface.helpToolBar())
            self.iface.helpToolBar().addAction(self.helpAction)
        if self.helpAction:
            self.helpAction.triggered.connect(self.showHelp)

        self.aboutAction = self.iface.findAction("mActionAbout")
        if not self.aboutAction and self.iface.helpToolBar():
            self.aboutAction = QAction(QIcon(":/plugins/UserManual/about.png"), self.tr("About"), self.iface.helpToolBar())
            self.iface.helpToolBar().addAction(self.aboutAction)
        if self.aboutAction:
            self.aboutAction.triggered.connect(self.showAbout)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        if self.iface.helpToolBar():
            self.iface.helpToolBar().removeAction(self.helpAction)
        if self.helpAction:
            self.helpAction.triggered.disconnect(self.showHelp)
        if self.iface.helpToolBar():
            self.iface.helpToolBar().removeAction(self.aboutAction)
        if self.aboutAction:
            self.aboutAction.triggered.disconnect(self.showAbout)
        self.helpWidget = None
        self.helpAction = None
        self.aboutAction = None

    def showHelp(self):
        """Run method that loads and starts the plugin"""
        docdir = os.path.join(self.plugin_dir, "html")
        if os.path.isdir(os.path.join(docdir, self.locale)):
            lang = self.locale
        else:
            lang = 'en'
        url = QUrl("file:///{dir}/{lang}/index.html".format(
                  dir=docdir, lang=lang))

        if not HAVE_WEBKIT:
          QDesktopServices.openUrl(url)
        else:
          if self.helpWidget is None:
              # Create the widget (after translation) and keep reference
              self.helpWidget = QWebEngineView()
              self.helpWidget.setWindowTitle(self.tr('User Manual'))
              self.helpWidget.resize(800, 600)
              self.helpWidget.load(url)

          self.helpWidget.show()
          self.helpWidget.raise_()

    def showAbout(self):
        """Run method that loads and starts the plugin"""
        locale = self.locale
        if not locale in ['en', 'de', 'it', 'fr']:
            locale = 'en'
        if self.aboutWidget is None:
            self.aboutWidget = AboutDialog(locale, self.iface.mainWindow())
        self.aboutWidget.show()
        self.aboutWidget.raise_()
Пример #29
0
 def open_about(self):
     about_dialog = AboutDialog(self)
     about_dialog.exec()
Пример #30
0
    def __init__(self, iface, parentMnu):
        # Save reference to the QGIS interface
        self.iface = iface
        self.parentMnu = parentMnu
        # initialize plugin directory
        # self.plugin_dir = os.path.dirname(__file__)
        # # initialize locale
        # locale = QSettings().value("locale/userLocale")[0:2]
        # localePath = os.path.join(self.plugin_dir, "i18n", "openlayers_{}.qm".format(locale))
        #
        # if os.path.exists(localePath):
        #     self.translator = QTranslator()
        #     self.translator.load(localePath)
        #
        #     if qVersion() > '4.3.3':
        #         QCoreApplication.installTranslator(self.translator)

        self._olLayerTypeRegistry = WebLayerTypeRegistry(self)
        self.olOverview = OLOverview(iface, self._olLayerTypeRegistry)
        self.dlgAbout = AboutDialog()

        # def initGui(self):
        self._olMenu = self.parentMnu.addMenu("OpenLayers")
        # self._olMenu.setIcon(QIcon(":/plugins/openlayers/openlayers.png"))

        # Overview
        self.overviewAddAction = QAction("OpenLayers Overview", self.iface)
        self.overviewAddAction.setCheckable(True)
        self.overviewAddAction.setChecked(False)
        QObject.connect(self.overviewAddAction, SIGNAL("toggled(bool)"),
                        self.olOverview.setVisible)
        self._olMenu.addAction(self.overviewAddAction)

        self._actionAbout = QAction("Terms of Service / About", self.iface)
        QObject.connect(self._actionAbout, SIGNAL("triggered()"),
                        self.dlgAbout, SLOT("show()"))
        #? self._actionAbout.triggered.connect(self.dlgAbout, SLOT("show()"))
        self._olMenu.addAction(self._actionAbout)

        self._olLayerTypeRegistry.register(OlGooglePhysicalLayer())
        self._olLayerTypeRegistry.register(OlGoogleStreetsLayer())
        self._olLayerTypeRegistry.register(OlGoogleHybridLayer())
        self._olLayerTypeRegistry.register(OlGoogleSatelliteLayer())

        self._olLayerTypeRegistry.register(OlOpenStreetMapLayer())
        self._olLayerTypeRegistry.register(OlOpenCycleMapLayer())
        self._olLayerTypeRegistry.register(OlOCMLandscapeLayer())
        self._olLayerTypeRegistry.register(OlOCMPublicTransportLayer())
        self._olLayerTypeRegistry.register(OlOSMHumanitarianDataModelLayer())

        self._olLayerTypeRegistry.register(OlBingRoadLayer())
        self._olLayerTypeRegistry.register(OlBingAerialLayer())
        self._olLayerTypeRegistry.register(OlBingAerialLabelledLayer())

        self._olLayerTypeRegistry.register(OlOSMStamenTonerLayer())
        self._olLayerTypeRegistry.register(OlOSMStamenTonerLiteLayer())
        self._olLayerTypeRegistry.register(OlOSMStamenWatercolorLayer())
        self._olLayerTypeRegistry.register(OlOSMStamenTerrainLayer())

        self._olLayerTypeRegistry.register(OlMapQuestOSMLayer())
        self._olLayerTypeRegistry.register(OlMapQuestOpenAerialLayer())

        self._olLayerTypeRegistry.register(OlAppleiPhotoMapLayer())

        for group in self._olLayerTypeRegistry.groups():
            groupMenu = group.menu()
            for layer in self._olLayerTypeRegistry.groupLayerTypes(group):
                layer.addMenuEntry(groupMenu, self.iface)
            self._olMenu.addMenu(groupMenu)

        #Create Web menu, if it doesn't exist yet
        # self.iface.addPluginToWebMenu("_tmp", self._actionAbout)
        # self._menu = self.iface.menuBar()
        # self.parentMnu.addMenu(self._olMenu)
        # self.iface.removePluginWebMenu("_tmp", self._actionAbout)

        # Register plugin layer type
        self.pluginLayerType = OpenlayersPluginLayerType(
            self.iface, self.setReferenceLayer, self._olLayerTypeRegistry)
        QgsPluginLayerRegistry.instance().addPluginLayerType(
            self.pluginLayerType)

        QObject.connect(QgsProject.instance(),
                        SIGNAL("readProject(const QDomDocument &)"),
                        self.projectLoaded)

        self.setGDALProxy()
Пример #31
0
 def about(self):
     print("about")
     ad = AboutDialog()
     ad.display()
Пример #32
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # setup locale
        pluginDir = os.path.dirname(__file__)
        localePath = ""
        locale = QSettings().value("locale/userLocale")[0:2]
        if QFileInfo(pluginDir).exists():
            localePath = pluginDir + "/i18n/openlayers_" + locale + ".qm"
        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Layers
        self.olLayerTypeRegistry = OlLayerTypeRegistry()
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Google Physical', 'google_icon.png',
                        'google_physical.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Google Streets', 'google_icon.png',
                        'google_streets.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Google Hybrid', 'google_icon.png',
                        'google_hybrid.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Google Satellite', 'google_icon.png',
                        'google_satellite.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'OpenStreetMap', 'osm_icon.png', 'osm.html',
                        True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'OpenCycleMap', 'osm_icon.png', 'ocm.html',
                        True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'OCM Landscape', 'osm_icon.png',
                        'ocm_landscape.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'OCM Public Transport', 'osm_icon.png',
                        'ocm_transport.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Yahoo Street', 'yahoo_icon.png',
                        'yahoo_street.html'))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Yahoo Hybrid', 'yahoo_icon.png',
                        'yahoo_hybrid.html'))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Yahoo Satellite', 'yahoo_icon.png',
                        'yahoo_satellite.html'))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Bing Road', 'bing_icon.png', 'bing_road.html',
                        True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Bing Aerial', 'bing_icon.png',
                        'bing_aerial.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Bing Aerial with labels', 'bing_icon.png',
                        'bing_aerial-labels.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Apple iPhoto map', 'apple_icon.png',
                        'apple.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Stamen Toner/OSM', 'stamen_icon.png',
                        'stamen_toner.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Stamen Watercolor/OSM', 'stamen_icon.png',
                        'stamen_watercolor.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'Stamen Terrain-USA/OSM', 'stamen_icon.png',
                        'stamen_terrain.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis wig 500k', 'hgis_icon.png',
                        'hgis_wig500k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis wig 300k', 'hgis_icon.png',
                        'hgis_wig300k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis wig 100k', 'hgis_icon.png',
                        'hgis_wig100k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis wig 25k', 'hgis_icon.png',
                        'hgis_wig25k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis mb 25k', 'hgis_icon.png',
                        'hgis_mb25k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis ukvme 300k', 'hgis_icon.png',
                        'hgis_ukvme300k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis kdr 100k', 'hgis_icon.png',
                        'hgis_kdr100k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis kdwr 100k', 'hgis_icon.png',
                        'hgis_kdwr100k.html', True))
        self.olLayerTypeRegistry.add(
            OlLayerType(self, 'hgis kdr_gb 100k', 'hgis_icon.png',
                        'hgis_kdr_gb100k.html', True))
        # Overview
        self.olOverview = OLOverview(iface, self.olLayerTypeRegistry)
        self.dlgAbout = AboutDialog(iface)
Пример #33
0
 def about(self):
     print("about")
     ad = AboutDialog()
     ad.display()