Beispiel #1
0
    def search(self, description):
        if description.help_ref:
            ref = description.help_ref
        else:
            raise KeyError()

        url = QUrl(self.baseurl).resolved(QUrl(ref))
        if url.isLocalFile():
            path = url.toLocalFile()
            fragment = url.fragment()
            if os.path.isfile(path):
                return url
            elif os.path.isfile("{}.html".format(path)):
                url = QUrl.fromLocalFile("{}.html".format(path))
                url.setFragment(fragment)
                return url
            elif os.path.isdir(path) and \
                    os.path.isfile(os.path.join(path, "index.html")):
                url = QUrl.fromLocalFile(os.path.join(path, "index.html"))
                url.setFragment(fragment)
                return url
            else:
                raise KeyError()
        else:
            if url.scheme() in ["http", "https"]:
                path = url.path()
                if not (path.endswith(".html") or path.endswith("/")):
                    url.setPath(path + ".html")
        return url
    def setUpClass(cls):
        """Run before all tests"""
        # Create test layer
        srcpath = os.path.join(TEST_DATA_DIR, 'provider')
        cls.basetestfile = os.path.join(srcpath, 'delimited_wkt.csv')

        url = QUrl.fromLocalFile(cls.basetestfile)
        url.addQueryItem("crs", "epsg:4326")
        url.addQueryItem("type", "csv")
        url.addQueryItem("wktField", "wkt")
        url.addQueryItem("spatialIndex", "no")
        url.addQueryItem("subsetIndex", "no")
        url.addQueryItem("watchFile", "no")

        cls.vl = QgsVectorLayer(url.toString(), u'test', u'delimitedtext')
        assert cls.vl.isValid(), "{} is invalid".format(cls.basetestfile)
        cls.provider = cls.vl.dataProvider()

        cls.basetestpolyfile = os.path.join(srcpath, 'delimited_wkt_poly.csv')

        url = QUrl.fromLocalFile(cls.basetestpolyfile)
        url.addQueryItem("crs", "epsg:4326")
        url.addQueryItem("type", "csv")
        url.addQueryItem("wktField", "wkt")
        url.addQueryItem("spatialIndex", "no")
        url.addQueryItem("subsetIndex", "no")
        url.addQueryItem("watchFile", "no")

        cls.vl_poly = QgsVectorLayer(url.toString(), u'test_polygon',
                                     u'delimitedtext')
        assert cls.vl_poly.isValid(), "{} is invalid".format(
            cls.basetestpolyfile)
        cls.poly_provider = cls.vl_poly.dataProvider()
    def setUpClass(cls):
        """Run before all tests"""
        # Create test layer
        srcpath = os.path.join(TEST_DATA_DIR, 'provider')
        cls.basetestfile = os.path.join(srcpath, 'delimited_wkt.csv')

        url = QUrl.fromLocalFile(cls.basetestfile)
        url.addQueryItem("crs", "epsg:4326")
        url.addQueryItem("type", "csv")
        url.addQueryItem("wktField", "wkt")
        url.addQueryItem("spatialIndex", "no")
        url.addQueryItem("subsetIndex", "no")
        url.addQueryItem("watchFile", "no")

        cls.vl = QgsVectorLayer(url.toString(), u'test', u'delimitedtext')
        assert cls.vl.isValid(), "{} is invalid".format(cls.basetestfile)
        cls.provider = cls.vl.dataProvider()

        cls.basetestpolyfile = os.path.join(srcpath, 'delimited_wkt_poly.csv')

        url = QUrl.fromLocalFile(cls.basetestpolyfile)
        url.addQueryItem("crs", "epsg:4326")
        url.addQueryItem("type", "csv")
        url.addQueryItem("wktField", "wkt")
        url.addQueryItem("spatialIndex", "no")
        url.addQueryItem("subsetIndex", "no")
        url.addQueryItem("watchFile", "no")

        cls.vl_poly = QgsVectorLayer(url.toString(), u'test_polygon', u'delimitedtext')
        assert cls.vl_poly.isValid(), "{} is invalid".format(cls.basetestpolyfile)
        cls.poly_provider = cls.vl_poly.dataProvider()
Beispiel #4
0
 def setup(self, parent=None, caption=str("Sélectionnez")) :
     self.setFileMode(self.ExistingFiles)
     icon = QtGui.QIcon()
     icon.addPixmap(QtGui.QPixmap(_fromUtf8("resources/PL128.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
     self.setWindowIcon(icon)
     mydir = str(os.environ['USERPROFILE'])
     thedir = QDir("C:/")
     self.setDirectory(thedir)
     url = []
     url.append(QUrl.fromLocalFile(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)))
     url.append(QUrl.fromLocalFile(QDesktopServices.storageLocation(QDesktopServices.DesktopLocation)))
     url.append(QUrl.fromLocalFile(QDesktopServices.storageLocation(QDesktopServices.HomeLocation)))
     url.append(QUrl('file:'))
     self.setSidebarUrls(url)
     # self.setDirectory(mydir)
     self.setWindowModality(QtCore.Qt.ApplicationModal)
     MyFileDialog.setNameFilter(self, "Epub (*.epub)")
     self.setLabelText(self.LookIn, "Regarder dans :")
     self.setLabelText(self.FileName, "Fichier")
     self.setLabelText(self.FileType, "Type de fichier")
     self.setLabelText(self.Accept, "Ouvrir")
     self.setLabelText(self.Reject, "Annuler")
     self.setWindowTitle("Sélectionnez un ou plusieurs fichiers")
     self.setOption(self.DontUseNativeDialog, False)
     # self.setOption(self.DontResolveSymlinks, True)
     self.setOption(self.ShowDirsOnly, False)
     self.tree = self.findChild(QtGui.QTreeView)
     self.init_ui()
     self.filesSelected.connect(self.cur_change)
     self.filesSelected.connect(self.choose_file)
Beispiel #5
0
def startmain():
    import optparse
    optparse._ = _ # let optparse use our translations
    parser = optparse.OptionParser(
        usage = _("{appname} [options] file ...").format(appname=info.name),
        version = "{0} {1}".format(info.appname, info.version),
        description = _("A LilyPond Music Editor"))
    parser.add_option('-e', '--encoding', metavar=_("ENC"),
        help=_("Encoding to use"))
    parser.add_option('-l', '--line', type="int", metavar=_("NUM"),
        help=_("Line number to go to, starting at 1"))
    parser.add_option('-c', '--column', type="int", metavar=_("NUM"),
        help=_("Column to go to, starting at 0"), default=0)
    parser.add_option('--start', metavar=_("NAME"),
        help=_("Session to start ('{none}' for empty session)").format(none="none"),
        dest="session")

    args = QApplication.arguments()
    if os.name == 'nt' and args and 'python' in os.path.basename(args[0]).lower():
        args = args[2:]
    else:
        args = args[1:]
    options, files = parser.parse_args(args)

    # load specified session
    doc = None
    if options.session and options.session != "none":
        doc = sessions.loadSession(options.session)
        
    # Just create one MainWindow
    win = mainwindow.MainWindow()
    win.show()
    
    if files:
        # make urls
        for arg in files:
            if re.match(r'^(https?|s?ftp)://', arg):
                url = QUrl(arg)
            elif arg.startswith('file://'):
                url = QUrl.fromLocalFile(arg[7:])
            elif arg.startswith('file:'):
                url = QUrl.fromLocalFile(os.path.abspath(arg[5:]))
            else:
                url = QUrl.fromLocalFile(os.path.abspath(arg))
            doc = win.openUrl(url, options.encoding)
    elif not options.session:
        # no docs, load default session
        doc = sessions.loadDefaultSession()
    win.setCurrentDocument(doc or document.Document())
    if files and options.line is not None:
        # set the last loaded document active and apply navigation if requested
        pos = doc.findBlockByNumber(options.line - 1).position() + options.column
        cursor = QTextCursor(doc)
        cursor.setPosition(pos)
        win.currentView().setTextCursor(cursor)
        win.currentView().centerCursor()
    def test_refLayers2(self):
        l1 = QgsVectorLayer(QUrl.fromLocalFile(os.path.join(self.testDataDir, "delimitedtext/test.csv")).toString() + "?type=csv&geomType=none&subsetIndex=no&watchFile=no", "test", "delimitedtext", False)
        self.assertEqual(l1.isValid(), True)
        QgsMapLayerRegistry.instance().addMapLayer(l1)

        # referenced layers cannot be stored !
        tmp = QUrl.fromLocalFile(os.path.join(tempfile.gettempdir(), "t.sqlite")).toString()
        l2 = QgsVectorLayer("%s?layer_ref=%s" % (tmp, l1.id()), "tt", "virtual", False)
        self.assertEqual(l2.isValid(), False)
        self.assertEqual("Cannot store referenced layers" in l2.dataProvider().error().message(), True)
Beispiel #7
0
def url(arg):
    """Converts a filename-like argument to a QUrl."""
    if re.match(r'^(https?|s?ftp)://', arg):
        return QUrl(arg)
    elif arg.startswith('file://'):
        return QUrl.fromLocalFile(os.path.abspath(arg[7:]))
    elif arg.startswith('file:'):
        return QUrl.fromLocalFile(os.path.abspath(arg[5:]))
    else:
        return QUrl.fromLocalFile(os.path.abspath(arg))
Beispiel #8
0
def url(arg):
    """Converts a filename-like argument to a QUrl."""
    if re.match(r'^(https?|s?ftp)://', arg):
        return QUrl(arg)
    elif arg.startswith('file://'):
        return QUrl.fromLocalFile(os.path.abspath(arg[7:]))
    elif arg.startswith('file:'):
        return QUrl.fromLocalFile(os.path.abspath(arg[5:]))
    else:
        return QUrl.fromLocalFile(os.path.abspath(arg))
    def test_resolve_path(self):
        """Test resolving the path works correctly."""
        collection_path = test_data_path('collections', 'test_collection')
        search_paths = []

        # Test case 1: local path
        img_path = test_data_path('collections', 'test_collection', 'svg',
                                  'blastoise.svg')
        fixed_path = resolve_path(img_path, collection_path, search_paths)
        self.assertEqual(img_path, fixed_path)

        # Test case 2: local url
        img_path = test_data_path('collections', 'test_collection', 'svg',
                                  'blastoise.svg')
        img_url = QUrl.fromLocalFile(img_path)
        fixed_path = resolve_path(img_url.toString(), collection_path,
                                  search_paths)
        self.assertEqual(fixed_path, img_path)

        # Test case 3:  http url
        img_path = 'http://qgis.org/test/image.svg'
        img_url = QUrl.fromLocalFile(img_path)
        fixed_path = resolve_path(img_url.toString(), collection_path,
                                  search_paths)
        self.assertEqual(fixed_path, img_path)

        # Test case 4: checking in the svg local collection path
        img_path = '/you/would/not/find/this/charizard.svg'
        fixed_path = resolve_path(img_path, collection_path, search_paths)
        expected_path = test_data_path('collections', 'test_collection', 'svg',
                                       'charizard.svg')
        self.assertEqual(fixed_path, expected_path)

        # Test case 5: checking in the image local collection path
        img_path = '/you/would/not/find/this/pikachu.png'
        fixed_path = resolve_path(img_path, collection_path, search_paths)
        expected_path = test_data_path('collections', 'test_collection',
                                       'image', 'pikachu.png')
        self.assertEqual(fixed_path, expected_path)

        # Test case 6: checking in the search paths
        search_paths = [
            test_data_path('collections', 'test_collection', 'preview')
        ]
        img_path = 'prev_1.png'
        fixed_path = resolve_path(img_path, collection_path, search_paths)
        expected_path = test_data_path('collections', 'test_collection',
                                       'preview', 'prev_1.png')
        self.assertEqual(fixed_path, expected_path)

        # Test case 7: not finding anywhere (return the original path)
        img_path = '/you/would/not/find/this/anywhere.png'
        fixed_path = resolve_path(img_path, collection_path, search_paths)
        self.assertEqual(fixed_path, img_path)
    def _addAlgorithm(self,name,operationNumber,xpos,ypos):
        print "python local method adding: ",name, " at location (",xpos,",",ypos,")"
        engine = self._savedViewObject.engine()
        print "engine: ", engine
        newalgo_comp = QtDeclarative.QDeclarativeComponent(engine)
          
        for case in switch(name):
           if case("Lagrange"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/Lagrange.qml"));
            break;
           if case("OpenModeller"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/OpenModeller.qml"));
            break;
           if case("DataIntegrator"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/DataIntegrator.qml"));
            break;
           if case("FitContinuous"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/FitContinuous.qml"));
            break;
           if case("FitDiscrete"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/FitDiscrete.qml"));
            break;
           if case("TreeFromFile"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/TreeFromFile.qml"));
            break;
           if case("OpenTreeOfLife"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/OpenTreeOfLife.qml"));
            break;
           if case("CharacterMatrix"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/CharacterMatrix.qml"));
            break;
           if case("TreeTransform"):
            newalgo_comp = QtDeclarative.QDeclarativeComponent(engine,QUrl.fromLocalFile("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt/Declarations/operations/TreeTransform.qml"));
            break;

           if case():
              document.write("Sorry, we are out of " + name + ".<br>");
                  
        # instantiate the component to create a new instance
        newalgo_item = newalgo_comp.create()
        # assign a unique object name to the workstep instance
        newalgo_item.setObjectName("operation_"+str(operationNumber))
        # store the algorithm in the list of operations saved by the workflow manager.  The type of the operation
        # is stored in a parallel list so we can reference this to find pixel offsets later depending on the
        # type of the operation
        self._operations.append(newalgo_item)
        # build a dictionary indexed by object name that returns the object type.  Keeping local and global one just 
        # because the Segment class needs access to this cross reference, as well. 
        self._operationsType[newalgo_item.objectName()] = name
        operationsType[newalgo_item.objectName()] = name
        #print "newalgo_item=", newalgo_item
        print "new objname is: ",newalgo_item.objectName()
        # set the visual position of the icon and add it to the visual scene so it displays. The 
        # position it is added to the scene needs to be fixed, but this doesn't affect operation, just
        # aesthetics.  We need to translate from screen to workspace rectangle coordinates to get it right. 
        newalgo_item.setPos(float(xpos),float(ypos))
        self._savedViewObject.scene().addItem(newalgo_item)
        newalgo_item.setParentItem(self._workspaceObject)
Beispiel #11
0
def select_git_directory():
    settings = QSettings("majerti", "gitbuster")
    settings.beginGroup("Last run")

    filepath = '/'
    last_directory = settings.value("directory", QVariant(QDir.homePath()))
    dirs_list = settings.value("recent directories",
                               QStringList()).toStringList()
    custom_entries = settings.value("custom entries",
                                    QStringList()).toStringList()

    recent_dirs_urls = [QUrl.fromLocalFile(dir) for dir in dirs_list]
    home_url = QUrl.fromLocalFile(QDir.homePath())
    custom_entries_urls = [QUrl.fromLocalFile(dir) for dir in custom_entries]

    while not is_top_git_directory(unicode(filepath)):
        file_dialog = QFileDialog(None, "Open git repository",
                                  last_directory.toString())
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOptions(QFileDialog.ShowDirsOnly)
        if recent_dirs_urls:
            file_dialog.setSidebarUrls(
                [home_url,] +
                custom_entries_urls +
                recent_dirs_urls[-6:]
            )
        ret = file_dialog.exec_()

        custom_entries = QStringList()
        custom_entries_urls = []
        for url in file_dialog.sidebarUrls():
            if url not in recent_dirs_urls and url != home_url:
                custom_entries.append(QString(url.path()))
                custom_entries_urls.append(url)
        settings.setValue("custom entries", custom_entries)

        if ret:
            filepath = file_dialog.selectedFiles()[0]
        else:
            return ret

        if not filepath:
            return filepath

    if not dirs_list.contains(filepath):
        dirs_list.append(filepath)
        settings.setValue("recent directories", dirs_list)

    settings.setValue("directory", filepath)
    settings.endGroup()
    settings.sync()

    return unicode(filepath)
Beispiel #12
0
    def compute(self):
        """ compute() -> None
        Render the XML tree and display it on the spreadsheet
        """
        xml = self.getInputFromPort('XML').name
        xsl = self.getInputFromPort('XSL').name

        query = QXmlQuery(QXmlQuery.XSLT20)
        query.setFocus(QUrl.fromLocalFile(os.path.join(os.getcwd(), xml)))
        query.setQuery(QUrl.fromLocalFile(os.path.join(os.getcwd(), xsl)))
        html = query.evaluateToString()

        self.cellWidget = self.displayAndWait(RichTextCellWidget, (html,))
Beispiel #13
0
    def createDocument(self, filename, contents):
        """Create a new document using the specified filename and contents.

        Make it the current document in our mainwindow.

        """
        while os.path.exists(filename) or app.findDocument(QUrl.fromLocalFile(filename)):
            filename = util.next_file(filename)
        doc = app.openUrl(QUrl())
        doc.setPlainText(contents)
        doc.setUrl(QUrl.fromLocalFile(filename))
        doc.setModified(True)
        self.mainwindow().setCurrentDocument(doc)
        return doc
Beispiel #14
0
    def compute(self):
        """ compute() -> None
        Render the XML tree and display it on the spreadsheet
        """
        xml = self.get_input('XML').name
        xsl = self.get_input('XSL').name

        query = QXmlQuery(QXmlQuery.XSLT20)
        query.setFocus(QUrl.fromLocalFile(os.path.join(os.getcwd(), xml)))
        query.setQuery(QUrl.fromLocalFile(os.path.join(os.getcwd(), xsl)))
        html = query.evaluateToString() # gets a unicode object
        if html is None:
            raise ModuleError(self, "Error applying XSL")

        self.displayAndWait(RichTextCellWidget, (html,))
Beispiel #15
0
    def createDocument(self, filename, contents):
        """Create a new document using the specified filename and contents.

        Make it the current document in our mainwindow.

        """
        while os.path.exists(filename) or app.findDocument(
                QUrl.fromLocalFile(filename)):
            filename = util.next_file(filename)
        doc = app.openUrl(QUrl())
        doc.setPlainText(contents)
        doc.setUrl(QUrl.fromLocalFile(filename))
        doc.setModified(True)
        self.mainwindow().setCurrentDocument(doc)
        return doc
Beispiel #16
0
    def compute(self):
        """ compute() -> None
        Render the XML tree and display it on the spreadsheet
        """
        xml = self.get_input('XML').name
        xsl = self.get_input('XSL').name

        query = QXmlQuery(QXmlQuery.XSLT20)
        query.setFocus(QUrl.fromLocalFile(os.path.join(os.getcwd(), xml)))
        query.setQuery(QUrl.fromLocalFile(os.path.join(os.getcwd(), xsl)))
        html = query.evaluateToString()  # gets a unicode object
        if html is None:
            raise ModuleError(self, "Error applying XSL")

        self.displayAndWait(RichTextCellWidget, (html, ))
Beispiel #17
0
    def xmlbuffer(self):
        queryimpl = QXmlQuery(QXmlQuery.XQuery10)
        #merge params from xquerynames and query path arguments
        params = copy.deepcopy(self.xquerynames)
        for name,value in self._queryparams.iteritems():
          params.append([name,value])
        #push values into external variable names in xquery
        for item in params:
            if len(item)==3 : # item has namespace
                (name,value,namespace) = item
                qname = QXmlName(queryimpl.namePool(), name, namespace)
            else:
                (name,value) = item
                qname = QXmlName(queryimpl.namePool(), name)
            qvalue = QXmlItem(value)
            queryimpl.bindVariable(qname,qvalue)
        #bind focus if available
        if(self.focuspath != None):
            queryimpl.setFocus(QUrl.fromLocalFile(self.focuspath))
        queryimpl.setQuery(self.querysource)

        buf = QBuffer()
        buf.open(QBuffer.ReadWrite)
        queryimpl.evaluateTo(buf)
        buf.close()
        data = buf.data()
        return data
Beispiel #18
0
 def onHelp(self):
     helpPath = Utils.getHelpPath()
     if helpPath == '':
         url = QUrl("http://www.gdal.org/" + self.helpFileName)
     else:
         url = QUrl.fromLocalFile(helpPath + '/' + self.helpFileName)
     QDesktopServices.openUrl(url)
Beispiel #19
0
 def openformfolder(self, url):
     """
     Open the form folder using the OS file manager.
     :param url:
     :return:
     """
     QDesktopServices.openUrl(QUrl.fromLocalFile(self.form.folder))
Beispiel #20
0
def _ask_for_CMakeLists_location_and_try_open(start_dir_to_show, cur_doc_dir):
    selected_dir = KUrlRequesterDialog.getUrl(
        start_dir_to_show
      , kate.mainInterfaceWindow().window()
      , i18nc('@title:window', '<filename>CMakeLists.txt</filename> location')
      )
    kate.kDebug('CMakeHelper: selected_dir={}'.format(selected_dir))

    if selected_dir.isEmpty():
        return                                              # User pressed 'Cancel'

    selected_dir = selected_dir.toLocalFile()               # Get selected path
    # Is it relative?
    if not os.path.isabs(selected_dir):
        # Yep, join w/ a path of the current doc
        selected_dir = os.path.abspath(os.path.join(cur_doc_dir, selected_dir))

    # Check if there CMakeLists.txt present
    cmakelists = os.path.join(selected_dir, _CMAKE_LISTS)
    if _is_there_CMakeLists(selected_dir):
        # Open it!
        _openDocumentNoCheck(QUrl.fromLocalFile(cmakelists))
    else:
        kate.ui.popup(
            i18nc('@title:window', 'Error')
          , i18nc('@info:tooltip', 'No such file <filename>%1</filename>', cmakelists)
          , 'dialog-error'
          )
Beispiel #21
0
def csv_vector_layer(csv_path, **kwargs):
    """
    Create a vector layer from a CSV file.
    :param csv_path: Path of the CSV file.
    :type csv_path: str
    :param kwargs:
    :return: Returns a QGIS memory layer containing the CSV data.
    :rtype: QgsVectorLayer
    """
    # Get file name
    csv_fi = QFileInfo(csv_path)
    layer_name = csv_fi.completeBaseName()

    delimiter = kwargs.pop('delimiter', ',')

    # Construct URL with CSV provider query items
    url = QUrl.fromLocalFile(csv_path)
    url.addQueryItem('type', 'csv')
    url.addQueryItem('delimiter', delimiter)
    url.addQueryItem('geomType', 'none')
    url.addQueryItem('subsetIndex', 'no')
    url.addQueryItem('watchFile', 'no')

    uri = url.toEncoded().data()
    csv_vl = QgsVectorLayer(uri, layer_name, 'delimitedtext')
    fields = csv_vl.fields()

    return csv_vl
Beispiel #22
0
 def __init__(self):
     super(TweetWindow, self).__init__()
     self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
                         | Qt.Popup | Qt.Tool)
     self.setAttribute(Qt.WA_TranslucentBackground, True)
     self.resize(550, 520)
     point = Utils.getDesktopCenterPoint(self)
     self.move(point["x"], point["y"])
     self.webview = QWebView(self)
     self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled,
                                          True)
     self.webview.settings().setAttribute(
         QWebSettings.DeveloperExtrasEnabled, True)
     self.webview.settings().setAttribute(
         QWebSettings.LocalContentCanAccessRemoteUrls, True)
     self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled,
                                          True)
     self.webview.settings().setLocalStoragePath(AppProperty.HomeDir +
                                                 "/data")
     #self.webview.setContextMenuPolicy(Qt.NoContextMenu)
     self.webview.settings().setDefaultTextEncoding("utf-8")
     self.webview.setGeometry(1, 1, self.width() - 2, self.height() - 2)
     self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(
         self.setJavaScriptObject)
     self.webview.setStyleSheet(
         "QWebView{background-color: rgba(255, 193, 245, 0%); }")
     self.webview.page().networkAccessManager().setCookieJar(
         AppProperty.CookieJar)
     self.webview.load(
         QUrl.fromLocalFile(AppProperty.HomeDir + "/html/tweetWindow.html"))
Beispiel #23
0
	def initializeUi(self):
		"""
		Initializes the Component ui.

		:return: Method success.
		:rtype: bool
		"""

		LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__))

		self.Zoom_In_pushButton.setIcon(QIcon(os.path.join(self.__uiResourcesDirectory, self.__uiZoomInImage)))
		self.Zoom_Out_pushButton.setIcon(QIcon(os.path.join(self.__uiResourcesDirectory, self.__uiZoomOutImage)))

		self.Map_Type_comboBox.addItems([foundations.common.getFirstItem(mapType) for mapType in self.__mapTypeIds])

		self.__map = Map_QWebView()
		self.__map.setMinimumSize(self.__gpsMapBaseSize)
		self.__map.load(QUrl.fromLocalFile(os.path.normpath(os.path.join(self.__uiResourcesDirectory,
																		self.__gpsMapHtmlFile))))
		self.__map.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
		self.__map.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
		self.Map_scrollAreaWidgetContents_gridLayout.addWidget(self.__map)

		# Signals / Slots.
		for view in self.__iblSetsOutliner.views:
			view.selectionModel().selectionChanged.connect(
			self.__iblSetsOutliner_view_selectionModel__selectionChanged)
		self.__map.loadFinished.connect(self.__map__loadFinished)
		self.Map_Type_comboBox.activated.connect(self.__Map_Type_comboBox__activated)
		self.Zoom_In_pushButton.clicked.connect(self.__Zoom_In_pushButton__clicked)
		self.Zoom_Out_pushButton.clicked.connect(self.__Zoom_Out_pushButton__clicked)

		self.initializedUi = True
		return True
Beispiel #24
0
 def openformfolder(self, url):
     """
     Open the form folder using the OS file manager.
     :param url:
     :return:
     """
     QDesktopServices.openUrl(QUrl.fromLocalFile(self.form.folder))
Beispiel #25
0
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.ui.lineEdit.selectAll()

        self.ui.lineEdit.setFocus()

        self.ui.comboBox.setCurrentIndex(0)

        self.ui.checkBox.setChecked(False)

        self.dictionaries = [
            str("TLFi").decode("utf-8", "strict"),
            str("Académie 9e Ed.").decode("utf-8", "strict"),
            str("Académie 8e Ed.").decode("utf-8", "strict"),
            str("Académie 4e Ed.").decode("utf-8", "strict"),
        ]
        self.ui.comboBox_2.addItems(self.dictionaries)

        self.clipboard = QApplication.clipboard()

        self.ui.lineEdit.returnPressed.connect(self.update_ui)

        self.ui.comboBox.activated.connect(self.on_combo_change)

        self.ui.webView.settings().setUserStyleSheetUrl(
            QUrl.fromLocalFile(':/lexi.css'))

        self.ui.listView.clicked.connect(self.on_row_clicked)

        self.clipboard.dataChanged.connect(self.get_from_clipboard)
Beispiel #26
0
 def on_help(self):
     app.g_pwd = os.getcwd()
     if not (QtGui.QDesktopServices.openUrl(
             QUrl.fromLocalFile(app.g_pwd + os.sep + 'image' + os.sep +
                                'help.pdf'))):
         print app.g_pwd + os.sep + '/image/help.pdf'
         QMessageBox.critical(None, "Failure", "Cannot open help manual")
Beispiel #27
0
 def reset(self):
     self.setFixedWidth(0)
     self.setVisible(False)
     self.setUrl(QUrl.fromLocalFile(Resources.get_path("leftpane.html")))
     self._teams=[]
     self.page().currentFrame().addToJavaScriptWindowObject("leftPane", self)
     self.page().currentFrame().evaluateJavaScript(self.js)
Beispiel #28
0
    def help(self):
        localDoc = None
        html = self.grass7Name + '.html'
        if system.isWindows():
            # For MS-Windows, use the configured GRASS7 path
            localPath = os.path.join(Grass7Utils.grassPath(), 'docs/html', html)
            if os.path.exists(localPath):
                localDoc = os.path.abspath(localPath)
        elif system.isMac():
            # For MacOSX official package
            localPath = os.path.join('/Applications/GRASS-7.0.app/Contents/MacOS/docs/html', html)
            if os.path.exists(localPath):
                localDoc = os.path.abspath(localPath)
        else:
            # For GNU/Linux distributions
            searchPaths = ['/usr/share/doc/grass-doc/html', '/opt/grass/docs/html',
                           '/usr/share/doc/grass/docs/html']
            for path in searchPaths:
                localPath = os.path.join(path, html)
                if os.path.exists(localPath):
                    localDoc = os.path.abspath(localPath)

        # Found the local documentation
        if localDoc:
            localDoc = QUrl.fromLocalFile(localDoc).toString()
            return False, localDoc

        # Return the URL if local doc is not found
        return False, 'http://grass.osgeo.org/grass70/manuals/' + self.grass7Name + '.html'
 def __init__(self):
     super(NotificationPresenter, self).__init__()
     rect = QApplication.desktop().availableGeometry()
     self.setGeometry(QRect(rect.width() - 300, 0, 300, rect.height()))
     self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
                         | Qt.Popup | Qt.Tool)
     self.setAttribute(Qt.WA_TranslucentBackground, True)
     self.webview = QWebView(self)
     self.webview.settings().setAttribute(QWebSettings.JavascriptEnabled,
                                          True)
     self.webview.settings().setAttribute(
         QWebSettings.DeveloperExtrasEnabled, True)
     self.webview.settings().setAttribute(
         QWebSettings.LocalContentCanAccessRemoteUrls, True)
     self.webview.settings().setAttribute(QWebSettings.LocalStorageEnabled,
                                          True)
     self.webview.settings().setLocalStoragePath(AppProperty.HomeDir +
                                                 "/data")
     self.webview.setContextMenuPolicy(Qt.NoContextMenu)
     self.webview.settings().setDefaultTextEncoding("utf-8")
     self.webview.setGeometry(0, 0, self.width(), self.height())
     self.webview.setStyleSheet(
         "QWebView{background-color: rgba(255, 193, 245, 0%); }")
     self.webview.load(
         QUrl.fromLocalFile(AppProperty.HomeDir +
                            "/html/notification.html"))
     self.webview.page().linkClicked.connect(self.linkClicked)
     self.webview.page().mainFrame().javaScriptWindowObjectCleared.connect(
         self.setJavaScriptObject)
     self.webview.page().setLinkDelegationPolicy(
         self.webview.page().DelegateAllLinks)
Beispiel #30
0
 def test_source_escaping(self):
     # the source contains ':'
     source = QUrl.fromLocalFile(os.path.join(self.testDataDir, "delimitedtext/test.csv")).toString() + "?type=csv&geomType=none&subsetIndex=no&watchFile=no"
     d = QgsVirtualLayerDefinition()
     d.addSource("t", source, "delimitedtext")
     l = QgsVectorLayer(d.toString(), "vtab", "virtual", False)
     self.assertEqual(l.isValid(), True)
def open_file_at_cursor(cursor, mainwin):
    """Opens the filename mentioned at the text cursor."""
    # take either the selection or the include-args found by ly.parse
    if cursor.hasSelection():
        fnames = [cursor.selection().toPlainText()]
    else:
        fnames = list(ly.parse.includeargs(iter(tokeniter.tokens(cursor.block()))))
    
    # detemine search path: doc dir and other include path names
    filename = cursor.document().url().toLocalFile()
    if filename:
        path = [os.path.dirname(filename)]
    else:
        path = []
    path.extend(documentinfo.info(cursor.document()).includepath())
    
    # load all docs, trying all include paths
    d = None
    for f in fnames:
        for p in path:
            name = os.path.normpath(os.path.join(p, f))
            if os.access(name, os.R_OK):
                d = mainwin.openUrl(QUrl.fromLocalFile(name))
                break
    if d:
        mainwin.setCurrentDocument(d, True)
Beispiel #32
0
def create_html_provider(entry_point):
    locations = entry_point.load()
    replacements = _replacements_for_dist(entry_point.dist)

    formatter = string.Formatter()

    for target in locations:
        # Extract all format fields
        format_iter = formatter.parse(target)
        fields = {name for _, name, _, _ in format_iter if name}

        if not set(fields) <= set(replacements.keys()):
            log.warning("Invalid replacement fields %s",
                        set(fields) - set(replacements.keys()))
            continue
        target = formatter.format(target, **replacements)

        targeturl = qurl_from_path(target)
        if not targeturl.isValid():
            continue

        if targeturl.isLocalFile():
            if not os.path.exists(target):
                log.info("Local doc root '%s' does not exist.", target)
                continue

        if target:
            return provider.SimpleHelpProvider(
                baseurl=QUrl.fromLocalFile(target))

    return None
Beispiel #33
0
    def accept(self):
        """Do merging two impact layers."""
        # Store the current state to configuration file
        self.save_state()

        # Prepare all the input from dialog, validate, and store it
        try:
            self.prepare_input()
        except (InvalidLayerError, EmptyDirectoryError,
                FileNotFoundError) as ex:
            # noinspection PyCallByClass,PyTypeChecker, PyArgumentList
            QMessageBox.information(
                self, self.tr("InaSAFE Merge Impact Tool Information"),
                str(ex))
            return
        except CanceledImportDialogError:
            return

        # Validate all the layers logically
        try:
            self.validate_all_layers()
        except (NoKeywordsFoundError, KeywordNotFoundError,
                InvalidLayerError) as ex:
            # noinspection PyCallByClass,PyTypeChecker, PyArgumentList
            QMessageBox.information(
                self, self.tr("InaSAFE Merge Impact Tools Information"),
                str(ex))
            return

        # The input is valid, do the merging
        # Set cursor to wait cursor
        QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
        # pylint: disable=W0703
        try:
            self.merge()
        except Exception as ex:
            # End wait cursor
            QtGui.qApp.restoreOverrideCursor()
            # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
            QMessageBox.warning(self,
                                self.tr("InaSAFE Merge Impact Tools Error"),
                                str(ex))
            return
            # pylint: enable=W0703

        # Finish doing it. End wait cursor
        QtGui.qApp.restoreOverrideCursor()

        # Give user successful information!
        # noinspection PyCallByClass,PyTypeChecker, PyArgumentList
        QMessageBox.information(
            self, self.tr('InaSAFE Merge Impact Tool Information'),
            self.tr('Report from merging two impact layers was generated '
                    'successfully.'))

        # Open output directory on file explorer
        # noinspection PyArgumentList
        output_directory_url = QUrl.fromLocalFile(self.out_dir)
        # noinspection PyTypeChecker,PyCallByClass,PyArgumentList
        QDesktopServices.openUrl(output_directory_url)
Beispiel #34
0
def create_html_provider(entry_point):
    locations = entry_point.load()
    replacements = _replacements_for_dist(entry_point.dist)

    formatter = string.Formatter()

    for target in locations:
        # Extract all format fields
        format_iter = formatter.parse(target)
        fields = {name for _, name, _, _ in format_iter if name}

        if not set(fields) <= set(replacements.keys()):
            log.warning("Invalid replacement fields %s",
                        set(fields) - set(replacements.keys()))
            continue
        target = formatter.format(target, **replacements)

        targeturl = qurl_from_path(target)
        if not targeturl.isValid():
            continue

        if targeturl.isLocalFile():
            if not os.path.exists(target):
                log.info("Local doc root '%s' does not exist.", target)
                continue

        if target:
            return provider.SimpleHelpProvider(
                baseurl=QUrl.fromLocalFile(target))

    return None
def open_file_at_cursor(cursor, mainwin):
    """Open the filename(s) mentioned at the text cursor."""
    d = None
    for name in filenames_at_cursor(cursor):
        d = mainwin.openUrl(QUrl.fromLocalFile(name))
    if d:
        mainwin.setCurrentDocument(d, True)
Beispiel #36
0
 def onHelp(self):
     helpPath = Utils.getHelpPath()
     if helpPath == '':
         url = QUrl("http://www.gdal.org/" + self.helpFileName)
     else:
         url = QUrl.fromLocalFile(helpPath + '/' + self.helpFileName)
     QDesktopServices.openUrl(url)
Beispiel #37
0
 def resetDocx(self, e):
     print 'Resetting document...'
     if len(self.docxFile) > 0:
         content = self.document.getMainPage()
         baseUrl = QUrl.fromLocalFile(os.path.join(os.getcwd(),
                                                   '../import'))
         self.ui.documentView.setHtml(content, baseUrl)
Beispiel #38
0
 def printMusic(self):
     doc = self.actionCollection.music_document_select.currentDocument()
     if doc and doc.document():
         ### temporarily disable printing on Mac OS X
         import sys
         if sys.platform.startswith('darwin'):
             from PyQt4.QtCore import QUrl
             from PyQt4.QtGui import QMessageBox
             result =  QMessageBox.warning(self.mainwindow(),
                 _("Print Music"), _(
                 "Unfortunately, this version of Frescobaldi is unable to print "
                 "PDF documents on Mac OS X due to various technical reasons.\n\n"
                 "Do you want to open the file in the default viewer for printing instead? "
                 "(remember to close it again to avoid access problems)\n\n"
                 "Choose Yes if you want that, No if you want to try the built-in "
                 "printing functionality anyway, or Cancel to cancel printing."),
                 QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
             if result == QMessageBox.Yes:
                 import helpers
                 helpers.openUrl(QUrl.fromLocalFile(doc.filename()), "pdf")
                 return
             elif result == QMessageBox.Cancel:
                 return
         ### end temporarily disable printing on Mac OS X
         import popplerprint
         popplerprint.printDocument(doc, self)
Beispiel #39
0
 def printMusic(self):
     doc = self.actionCollection.music_document_select.currentDocument()
     if doc and doc.document():
         ### temporarily disable printing on Mac OS X
         import sys
         if sys.platform.startswith('darwin'):
             from PyQt4.QtCore import QUrl
             from PyQt4.QtGui import QMessageBox
             result = QMessageBox.warning(
                 self.mainwindow(), _("Print Music"),
                 _("Unfortunately, this version of Frescobaldi is unable to print "
                   "PDF documents on Mac OS X due to various technical reasons.\n\n"
                   "Do you want to open the file in the default viewer for printing instead? "
                   "(remember to close it again to avoid access problems)\n\n"
                   "Choose Yes if you want that, No if you want to try the built-in "
                   "printing functionality anyway, or Cancel to cancel printing."
                   ), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
             if result == QMessageBox.Yes:
                 import helpers
                 helpers.openUrl(QUrl.fromLocalFile(doc.filename()), "pdf")
                 return
             elif result == QMessageBox.Cancel:
                 return
         ### end temporarily disable printing on Mac OS X
         import popplerprint
         popplerprint.printDocument(doc, self)
 def help(self):
    self.help = QWidget()
    self.help.setWindowTitle('Lifemapper Help')
    self.help.resize(600, 400)
    self.help.setMinimumSize(600,400)
    self.help.setMaximumSize(1000,1000)
    layout = QVBoxLayout()
    helpDialog = QTextBrowser()
    helpDialog.setOpenExternalLinks(True)
    #helpDialog.setSearchPaths(['documents'])
    helppath = os.path.dirname(os.path.realpath(__file__))+'/documents/help.html'
    helpDialog.setSource(QUrl.fromLocalFile(helppath))
    helpDialog.scrollToAnchor('randomizePAM')
    layout.addWidget(helpDialog)
    self.help.setLayout(layout)
    if self.isModal():
       self.setModal(False)
    self.help.show()       
    
    
    
    
    
    
    
    
    
    
    
    
def delimitedTextData(testname, filename, requests, verbose, **params):
    # Create a layer for the specified file and query parameters
    # and return the data for the layer (fields, data)

    filepath = os.path.join(unitTestDataPath("delimitedtext"), filename)
    url = QUrl.fromLocalFile(filepath)
    if not requests:
        requests = [{}]
    for k in params.keys():
        url.addQueryItem(k, params[k])
    urlstr = url.toString()
    log = []
    with MessageLogger('DelimitedText') as logger:
        if verbose:
            print testname
        layer = QgsVectorLayer(urlstr, 'test', 'delimitedtext')
        uri = unicode(layer.dataProvider().dataSourceUri())
        if verbose:
            print uri
        basename = os.path.basename(filepath)
        if not basename.startswith('test'):
            basename = 'file'
        uri = re.sub(r'^file\:\/\/[^\?]*', 'file://' + basename, uri)
        fields = []
        fieldTypes = []
        data = {}
        if layer.isValid():
            for nr, r in enumerate(requests):
                if verbose:
                    print "Processing request", nr + 1, repr(r)
                if callable(r):
                    r(layer)
                    if verbose:
                        print "Request function executed"
                if callable(r):
                    continue
                rfields, rtypes, rdata = layerData(layer, r, nr * 1000)
                if len(rfields) > len(fields):
                    fields = rfields
                    fieldTypes = rtypes
                data.update(rdata)
                if not rdata:
                    log.append("Request " + str(nr) +
                               " did not return any data")
                if verbose:
                    print "Request returned", len(rdata.keys()), "features"
        for msg in logger.messages():
            filelogname = 'temp_file' if 'tmp' in filename.lower(
            ) else filename
            msg = re.sub(r'file\s+.*' + re.escape(filename),
                         'file ' + filelogname, msg)
            msg = msg.replace(filepath, filelogname)
            log.append(msg)
        return dict(fields=fields,
                    fieldTypes=fieldTypes,
                    data=data,
                    log=log,
                    uri=uri,
                    geometryType=layer.geometryType())
Beispiel #42
0
 def loadPreviewFile(self, file):
     """
     Loads a web based preview from a local file path
     """
     self.previewUrl = QUrl.fromLocalFile(file)
     if self.preview:
         self.preview.settings().clearMemoryCaches()
         self.preview.setUrl(self.previewUrl)
Beispiel #43
0
def goto_target(mainwindow, target):
    """Switch to the document and location where the node target is."""
    filename = target.document.filename
    doc = app.openUrl(QUrl.fromLocalFile(filename))
    cursor = QTextCursor(doc)
    cursor.setPosition(target.position)
    browseriface.get(mainwindow).setTextCursor(cursor)
    mainwindow.currentView().centerCursor()
Beispiel #44
0
 def openScriptFileExtEditor(self):
     tabWidget = self.tabEditorWidget.currentWidget()
     path = tabWidget.path
     import subprocess
     try:
         subprocess.Popen([os.environ['EDITOR'], path])
     except KeyError:
         QDesktopServices.openUrl(QUrl.fromLocalFile(path))
Beispiel #45
0
def goto_target(mainwindow, target):
    """Switch to the document and location where the node target is."""
    filename = target.document.filename
    doc = app.openUrl(QUrl.fromLocalFile(filename))
    cursor = QTextCursor(doc)
    cursor.setPosition(target.position)
    browseriface.get(mainwindow).setTextCursor(cursor)
    mainwindow.currentView().centerCursor()
Beispiel #46
0
 def _setHtml(self, filePath, html):
     """Set HTML to the view and restore scroll bars position.
     Called by the thread
     """
     self._saveScrollPos()
     self._visiblePath = filePath
     self._widget.webView.page().mainFrame().contentsSizeChanged.connect(self._restoreScrollPos)
     self._widget.webView.setHtml(html,baseUrl=QUrl.fromLocalFile(filePath))
Beispiel #47
0
 def openLilyPondDatadir(self):
     """Menu action Open LilyPond Data Directory."""
     from . import command
     info = command.info(self.mainwindow().currentDocument())
     datadir = info.datadir()
     if datadir:
         import helpers
         helpers.openUrl(QUrl.fromLocalFile(datadir))
Beispiel #48
0
 def openScriptFileExtEditor(self):
     tabWidget = self.tabEditorWidget.currentWidget()
     path = tabWidget.path
     import subprocess
     try:
         subprocess.Popen([os.environ['EDITOR'], path])
     except KeyError:
         QDesktopServices.openUrl(QUrl.fromLocalFile(path))
Beispiel #49
0
 def openLilyPondDatadir(self):
     """Menu action Open LilyPond Data Directory."""
     from . import command
     info = command.info(self.mainwindow().currentDocument())
     datadir = info.datadir()
     if datadir:
         import helpers
         helpers.openUrl(QUrl.fromLocalFile(datadir))
def fileChanged(filename):
    """Called whenever the global filesystem watcher detects a change."""
    url = QUrl.fromLocalFile(filename)
    doc = app.findDocument(url)
    if doc:
        w = DocumentWatcher.instance(doc)
        if not w.changed:
            w.changed = True
            documentChangedOnDisk(doc)
Beispiel #51
0
    def test_CsvNoGeometry(self):
        l1 = QgsVectorLayer(QUrl.fromLocalFile(os.path.join(self.testDataDir, "delimitedtext/test.csv")).toString() + "?type=csv&geomType=none&subsetIndex=no&watchFile=no", "test", "delimitedtext", False)
        self.assertEqual(l1.isValid(), True)
        QgsMapLayerRegistry.instance().addMapLayer(l1)

        l2 = QgsVectorLayer("?layer_ref=" + l1.id(), "vtab", "virtual", False)
        self.assertEqual(l2.isValid(), True)

        QgsMapLayerRegistry.instance().removeMapLayer(l1.id())
Beispiel #52
0
def fileChanged(filename):
    """Called whenever the global filesystem watcher detects a change."""
    url = QUrl.fromLocalFile(filename)
    doc = app.findDocument(url)
    if doc:
        w = DocumentWatcher.instance(doc)
        if not w.changed:
            w.changed = True
            documentChangedOnDisk(doc)
    def showhelp2(self):
		"""
        def showHTMLReport(title, html, data={}, parent=None):
            dialog = HtmlViewerDialog(title)
            dialog.showHTML(html, data)
            dialog.exec_()

        showHTMLReport("Help",contentHelp)"""
		QDesktopServices.openUrl(QUrl.fromLocalFile(self.pathHelp))
Beispiel #54
0
 def _ref_js(self, js_source):
     js_file = u"_" + os.path.basename(js_source)
     try:
         if not os.path.exists(js_file):
             urlretrieve(js_source, js_file)
         _script_src = QUrl.fromLocalFile(QDir.current().filePath(js_file)).toString()
     except Exception as exc:
         print('Download %s failed, using CDN: %s' % (js_source, exc))
         _script_src = js_source
     return u"""<script src='""" + _script_src + u"""'></script>"""
Beispiel #55
0
def dragFile(widget, filename, icon=None, dropactions=Qt.CopyAction):
    """Starts dragging the given local file from the widget."""
    if icon is None or icon.isNull():
        icon = QFileIconProvider().icon(QFileInfo(filename))
    drag = QDrag(widget)
    data = QMimeData()
    data.setUrls([QUrl.fromLocalFile(filename)])
    drag.setMimeData(data)
    drag.setPixmap(icon.pixmap(32))
    drag.exec_(dropactions)
Beispiel #56
0
 def _setHtml(self, filePath, html):
     """Set HTML to the view and restore scroll bars position.
     Called by the thread
     """
     self._saveScrollPos()
     self._visiblePath = filePath
     self._widget.webView.page().mainFrame().contentsSizeChanged.connect(
         self._restoreScrollPos)
     self._widget.webView.setHtml(html,
                                  baseUrl=QUrl.fromLocalFile(filePath))
Beispiel #57
0
def file_open():
    filetypes = app.filetypes('.ly')
    caption = app.caption(_("dialog title", "Open File"))
    directory = app.basedir()
    files = QFileDialog.getOpenFileNames(None, caption, directory, filetypes)
    if files:
        w = mainwindow()
        docs = [w.openUrl(QUrl.fromLocalFile(f)) for f in files]
        if docs:
            w.setCurrentDocument(docs[-1])
Beispiel #58
0
def file_open():
    filetypes = app.filetypes('.ly')
    caption = app.caption(_("dialog title", "Open File"))
    directory = app.basedir()
    files = QFileDialog.getOpenFileNames(None, caption, directory, filetypes)
    if files:
        w = mainwindow()
        w.openUrls([QUrl.fromLocalFile(f) for f in files])
        if not app.documents:
            w.cleanStart()
Beispiel #59
0
 def openDocument(self):
     """ Displays an open dialog to open one or more documents. """
     ext = os.path.splitext(self.currentDocument().url().path())[1]
     filetypes = app.filetypes(ext)
     caption = app.caption(_("dialog title", "Open File"))
     directory = os.path.dirname(
         self.currentDocument().url().toLocalFile()) or app.basedir()
     files = QFileDialog.getOpenFileNames(self, caption, directory,
                                          filetypes)
     urls = [QUrl.fromLocalFile(filename) for filename in files]
     self.openDocuments(urls)