Exemplo n.º 1
0
    def startWorking(self):
        # Setting override cursor
        qApp.setOverrideCursor(Qt.WaitCursor)

        # Button
        self.btnCompile.setEnabled(False)
        self.txtBtn = self.btnCompile.text()
        self.btnCompile.setText(self.tr("Working..."))
Exemplo n.º 2
0
    def convert(self, src, args, outputfile=None):
        args = [self.cmd] + args

        if outputfile:
            args.append("--output={}".format(outputfile))

        for name, col, var in [
            ("Title", 0, "title"),
            ("Subtitle", 1, "subtitle"),
            ("Serie", 2, ""),
            ("Volume", 3, ""),
            ("Genre", 4, ""),
            ("License", 5, ""),
            ("Author", 6, "author"),
            ("Email", 7, ""),
            ]:
            item = mainWindow().mdlFlatData.item(0, col)
            if var and item and item.text().strip():
                args.append("--variable={}:{}".format(var, item.text().strip()))

        # Add title metatadata required for pandoc >= 2.x
        args.append("--metadata=title:{}".format(mainWindow().mdlFlatData.item(0, 0).text().strip()))

        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        p = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

        if not type(src) == bytes:
            src = src.encode("utf-8")  # assumes utf-8

        stdout, stderr = p.communicate(src)

        qApp.restoreOverrideCursor()

        if stderr or p.returncode != 0:
            err = "ERROR on export" + "\n" \
                + "Return code" + ": %d\n" % (p.returncode) \
                + "Command and parameters" + ":\n%s\n" % (p.args) \
                + "Stderr content" + ":\n" + stderr.decode("utf-8") 
            print(err)
            QMessageBox.critical(mainWindow().dialog, qApp.translate("Export", "Error"), err)
            return None

        return stdout.decode("utf-8")
Exemplo n.º 3
0
    def mouseMoveEvent(self, event):
        textEditView.mouseMoveEvent(self, event)

        onRef = [r for r in self.refRects if r.contains(event.pos())]

        if not onRef:
            qApp.restoreOverrideCursor()
            QToolTip.hideText()
            return

        cursor = self.cursorForPosition(event.pos())
        ref = self.refUnderCursor(cursor)
        if ref:
            if not qApp.overrideCursor():
                qApp.setOverrideCursor(Qt.PointingHandCursor)
            QToolTip.showText(self.mapToGlobal(event.pos()), Ref.tooltip(ref))
Exemplo n.º 4
0
    def convert(self, src, args, outputfile=None):
        args = [self.cmd] + args

        if outputfile:
            args.append("--output={}".format(outputfile))

        for name, col, var in [
            ("Title", 0, "title"),
            ("Subtitle", 1, "subtitle"),
            ("Serie", 2, ""),
            ("Volume", 3, ""),
            ("Genre", 4, ""),
            ("License", 5, ""),
            ("Author", 6, "author"),
            ("Email", 7, ""),
            ]:
            item = mainWindow().mdlFlatData.item(0, col)
            if var and item and item.text().strip():
                args.append("--variable={}:{}".format(var, item.text().strip()))

        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        p = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

        if not type(src) == bytes:
            src = src.encode("utf-8")  # assumes utf-8

        stdout, stderr = p.communicate(src)

        qApp.restoreOverrideCursor()

        if stderr:
            err = stderr.decode("utf-8")
            print(err)
            QMessageBox.critical(mainWindow().dialog, qApp.translate("Export", "Error"), err)
            return None

        return stdout.decode("utf-8")
Exemplo n.º 5
0
    def convert(self,
                src,
                _from="markdown",
                to="html",
                args=None,
                outputfile=None):
        if not self.isValid:
            print("ERROR: pandocConverter is called but not valid.")
            return ""

        cmd = [self.runCmd()]

        cmd += ["--from={}".format(_from)]
        cmd += ["--to={}".format(to)]

        if args:
            cmd += args

        if outputfile:
            cmd.append("--output={}".format(outputfile))

        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        p = subprocess.Popen(cmd,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

        if not type(src) == bytes:
            src = src.encode("utf-8")  # assumes utf-8

        stdout, stderr = p.communicate(src)

        qApp.restoreOverrideCursor()

        if stderr:
            err = stderr.decode("utf-8")
            print(err)
            QMessageBox.critical(mainWindow().dialog,
                                 qApp.translate("Export", "Error"), err)
            return None

        return stdout.decode("utf-8")
Exemplo n.º 6
0
 def login(self):
     if not (self.auth_url and
             (self.auth_url.host() and self.auth_url.scheme())):
         logging.error(
             "Missing or invalid hostname parameter in configuration.")
         return
     logging.info("Authenticating with host: %s" % self.auth_url.toString())
     qApp.setOverrideCursor(Qt.WaitCursor)
     self._cleanup()
     self.setHtml(DEFAULT_HTML)
     self.authn_session_page = \
         QWebEnginePage(QWebEngineProfile(self), self) if not self.cookie_persistence else QWebEnginePage(self)
     self.authn_session_page.loadProgress.connect(self._onLoadProgress)
     self.authn_session_page.loadFinished.connect(self._onLoadFinished)
     self.authn_session_page.profile().cookieStore().cookieAdded.connect(
         self._onCookieAdded)
     self.authn_session_page.profile().cookieStore().cookieRemoved.connect(
         self._onCookieRemoved)
     self.authn_session_page.setUrl(
         QUrl(self.auth_url.toString() + "/authn/preauth"))
Exemplo n.º 7
0
    def __export_dem(self):

        user_settings = UserSettings()
        file_filter = 'Ascii file (*' + AsciiParser.FILE_EXT + ')'
        file, filt = QFileDialog.getSaveFileName(self, 'Save File',
                                                 user_settings.working_dir,
                                                 file_filter)

        if file:

            qApp.setOverrideCursor(Qt.WaitCursor)

            if not file.endswith(AsciiParser.FILE_EXT):
                file += AsciiParser.FILE_EXT

            self._ign_pt_editor.save(file)
            qApp.restoreOverrideCursor()
            QMessageBox.information(
                self, "Export successful",
                "Digital elevation model successfully exported")
Exemplo n.º 8
0
 def cutVideo(self) -> bool:
     clips = len(self.clipTimes)
     filename, filelist = '', []
     source = self.mediaPlayer.currentMedia().canonicalUrl().toLocalFile()
     _, sourceext = os.path.splitext(source)
     if clips > 0:
         self.finalFilename, _ = QFileDialog.getSaveFileName(
             self.parent, 'Save video', source,
             'Video files (*%s)' % sourceext)
         if self.finalFilename == '':
             return False
         qApp.setOverrideCursor(Qt.BusyCursor)
         self.saveAction.setDisabled(True)
         self.showProgress(clips)
         file, ext = os.path.splitext(self.finalFilename)
         index = 1
         self.progress.setLabelText('Cutting media files...')
         qApp.processEvents()
         for clip in self.clipTimes:
             duration = self.deltaToQTime(clip[0].msecsTo(
                 clip[1])).toString(self.timeformat)
             filename = '%s_%s%s' % (file, '{0:0>2}'.format(index), ext)
             filelist.append(filename)
             self.videoService.cut(source, filename,
                                   clip[0].toString(self.timeformat),
                                   duration)
             index += 1
         if len(filelist) > 1:
             self.joinVideos(filelist, self.finalFilename)
         else:
             QFile.remove(self.finalFilename)
             QFile.rename(filename, self.finalFilename)
         self.progress.setLabelText('Complete...')
         self.progress.setValue(100)
         qApp.processEvents()
         self.progress.close()
         self.progress.deleteLater()
         qApp.restoreOverrideCursor()
         self.complete()
         return True
     return False
Exemplo n.º 9
0
    def __import_dem(self):

        user_settings = UserSettings()
        file_filter = 'Ascii file (*' + AsciiParser.FILE_EXT + ')'
        file, filt = QFileDialog.getOpenFileName(self, 'Open File', user_settings.working_dir, file_filter)

        if file:

            qApp.setOverrideCursor(Qt.WaitCursor)

            if self._ign_pt_editor:
                self._ign_pt_editor.deleteLater()

            self._ign_pt_editor = IgnitionPointViewer(self, file)
            self._ign_pt_editor.setEnabled(True)

            self._setup_ign_pt_map_lgnd()

            # Enable relevant widgets
            self.action_export_dem.setEnabled(True)

            # This means that a fuel map has already been loaded,
            # so the user can now convert to FDS file
            if self._fl_map_editor:
                self.__init_sim_settings()
                self.action_create_environment.setEnabled(True)

                if self._visualization:
                    self._visualization.deleteLater()

                self._visualization = Visualization(self._fl_map_editor.parser(), self._ign_pt_editor.parser(), self)
                self._visualization.setEnabled(True)
                self._visualization.hide()

            # Set current tab to fuel type legend
            self._tab_widget.setCurrentIndex(2)

            self._dem_title_label.setText("DEM Title: " + util.get_filename(file))

            self._ign_pt_editor.show()
            qApp.restoreOverrideCursor()
Exemplo n.º 10
0
    def spellCheckDocument(self):
        """Rerun the highlighter to update spell checking status of the
        currently loaded text. The fastest way to do this, at least as
        of Qt 5.13, is to clear the text and put it back.
        """

        logger.verbose("Running spell checker")
        if self.spellCheck:
            bfTime = time()
            qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
            if self.bigDoc:
                theText = self.getText()
                self.setPlainText(theText)
            else:
                self.hLight.rehighlight()
            qApp.restoreOverrideCursor()
            afTime = time()
            logger.debug("Document re-highlighted in %.3f milliseconds" %
                         (1000 * (afTime - bfTime)))

        return True
Exemplo n.º 11
0
 def getOptions(parent):
     uploader = parent.uploader
     dialog = OptionsDialog(parent)
     ret = dialog.exec_()
     if QDialog.Accepted == ret:
         debug = dialog.debugCheckBox.isChecked()
         logging.getLogger().setLevel(
             logging.DEBUG if debug else logging.INFO)
         setServers = getattr(uploader, "setServers", None)
         if callable(setServers):
             setServers(dialog.getServers())
         current_server = dialog.serverComboBox.currentData(Qt.UserRole)
         if current_server != uploader.server:
             parent.onServerChanged(current_server)
             return
         if dialog.reconfigure:
             qApp.setOverrideCursor(Qt.WaitCursor)
             uploader.initialize(cleanup=False)
             qApp.restoreOverrideCursor()
             parent.checkVersion()
     del dialog
Exemplo n.º 12
0
    def checkLatest(self):
        """Check for latest release.
        """
        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        urlReq = Request(
            "https://api.github.com/repos/vkbo/novelwriter/releases/latest")
        urlReq.add_header("User-Agent",
                          "Mozilla/5.0 (compatible; novelWriter (Python))")
        urlReq.add_header("Accept", "application/vnd.github.v3+json")

        rawData = {}
        try:
            urlData = urlopen(urlReq, timeout=10)
            rawData = json.loads(urlData.read().decode())
        except Exception:
            logger.error("Failed to contact GitHub API")
            logException()

        relVersion = rawData.get("tag_name", "Unknown")
        relDate = rawData.get("created_at", None)

        try:
            relDate = datetime.strptime(relDate[:10],
                                        "%Y-%m-%d").strftime("%x")
        except Exception:
            relDate = "Unknown"
            logException()

        self.latestValue.setText(
            self.tr("novelWriter {0} released on {1}").format(
                relVersion, relDate))

        self.latestLink.setText(
            self.tr("Download: {0}").format(
                f'<a href="{novelwriter.__url__}">{novelwriter.__url__}</a>'))

        qApp.restoreOverrideCursor()

        return
Exemplo n.º 13
0
    def search(self):
        text = self.text.text()

        # Chosing the right columns
        lstColumns = [
            ("Title", Outline.title.value),
            ("Text", Outline.text.value),
            ("Summary", Outline.summarySentence.value),
            ("Summary", Outline.summaryFull.value),
            ("Notes", Outline.notes.value),
            ("POV", Outline.POV.value),
            ("Status", Outline.status.value),
            ("Label", Outline.label.value),
        ]
        columns = [
            c[1] for c in lstColumns
            if self.options[c[0]] or self.options["All"]
        ]

        # Setting override cursor
        qApp.setOverrideCursor(Qt.WaitCursor)

        # Searching
        model = mainWindow().mdlOutline
        results = model.findItemsContaining(text, columns, self.options["CS"])

        # Showing results
        self.result.clear()
        for r in results:
            index = model.getIndexByID(r)
            if not index.isValid():
                continue
            item = index.internalPointer()
            i = QListWidgetItem(item.title(), self.result)
            i.setData(Qt.UserRole, r)
            i.setData(Qt.UserRole + 1, item.path())
            self.result.addItem(i)

        # Removing override cursor
        qApp.restoreOverrideCursor()
Exemplo n.º 14
0
    def uploadAnalysisResult(self, update_state):
        qApp.setOverrideCursor(Qt.WaitCursor)
        # generate hatrac upload params
        basename = "ROI_%s" % self.ui.workList.getCurrentTableItemTextByName(
            "RID")
        match = r"%s_.*\.csv$" % basename
        output_files = [
            f for f in os.listdir(self.tempdir)
            if os.path.isfile(os.path.join(self.tempdir, f))
            and re.match(match, f)
        ]
        if not output_files:
            self.resetUI(
                "Could not locate output file from viewer subprocess -- aborting."
            )
            return
        seg_mode = self.ui.workList.getCurrentTableItemTextByName(
            "Segmentation Mode")
        if seg_mode == "synaptic":
            extension = "_synaptic_only.csv"
        elif seg_mode == "nucleic":
            extension = "_nucleic_only.csv"
        else:
            self.updateStatus("Unknown segmentation mode \"%s\" -- aborting." %
                              seg_mode)
            return
        file_name = basename + extension
        hatrac_path = HATRAC_UPDATE_URL_TEMPLATE % \
            (self.ui.workList.getCurrentTableItemTextByName("Subject"), file_name)
        file_path = os.path.abspath(os.path.join(self.tempdir, file_name))

        # upload to object store
        self.updateStatus("Uploading file %s to server..." % file_name)
        self.progress_update_signal.connect(self.updateProgress)
        uploadTask = FileUploadTask(self.store)
        uploadTask.status_update_signal.connect(self.onUploadFileResult)
        uploadTask.upload(hatrac_path,
                          file_path,
                          update_state,
                          callback=self.uploadCallback)
Exemplo n.º 15
0
    def convert(self, src, _from="markdown", to="html", args=None, outputfile=None):
        if not self.isValid:
            print("ERROR: pandocConverter is called but not valid.")
            return ""

        cmd = [self.runCmd()]

        cmd += ["--from={}".format(_from)]
        cmd += ["--to={}".format(to)]

        if args:
            cmd += args

        if outputfile:
            cmd.append("--output={}".format(outputfile))

        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        p = subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

        if not type(src) == bytes:
            src = src.encode("utf-8")  # assumes utf-8

        stdout, stderr = p.communicate(src)

        qApp.restoreOverrideCursor()

        if stderr:
            err = stderr.decode("utf-8")
            print(err)
            QMessageBox.critical(mainWindow().dialog,
                                 qApp.translate("Export", "Error"), err)
            return None

        return stdout.decode("utf-8")
Exemplo n.º 16
0
    def mouseMoveEvent(self, event):
        """
        When mouse moves, we show tooltip when appropriate.
        """
        self.beginTooltipMoveEvent()
        MDEditView.mouseMoveEvent(self, event)
        self.endTooltipMoveEvent()

        onRef = [r for r in self.refRects if r.contains(event.pos())]

        if not onRef:
            qApp.restoreOverrideCursor()
            self.hideTooltip()
            return

        cursor = self.cursorForPosition(event.pos())
        ref = self.refUnderCursor(cursor)
        if ref:
            if not qApp.overrideCursor():
                qApp.setOverrideCursor(Qt.PointingHandCursor)

            self.showTooltip(self.mapToGlobal(event.pos()), Ref.tooltip(ref))
Exemplo n.º 17
0
    def login(self):
        if not (self.auth_url and (self.auth_url.host() and self.auth_url.scheme())):
            logging.error("Missing or invalid hostname parameter in configuration.")
            return
        logging.info("Authenticating with host: %s" % self.auth_url.toString())
        qApp.setOverrideCursor(Qt.WaitCursor)
        self._cleanup()
        self.authn_session_page = QWebEnginePage(self.private_profile, self.parent) \
            if not self.cookie_persistence else QWebEnginePage(self.default_profile, self.parent)
        self.authn_session_page.profile().setPersistentCookiesPolicy(
            QWebEngineProfile.ForcePersistentCookies if self.cookie_persistence else
            QWebEngineProfile.NoPersistentCookies)
        if self.cookie_persistence:
            logging.debug("QTWebEngine persistent storage located at: %s" %
                          self.authn_session_page.profile().persistentStoragePath())
        self.authn_session_page.profile().cookieStore().cookieAdded.connect(self._onCookieAdded)
        self.authn_session_page.profile().cookieStore().cookieRemoved.connect(self._onCookieRemoved)
        self.authn_session_page.loadProgress.connect(self._onLoadProgress)
        self.authn_session_page.loadFinished.connect(self._onLoadFinished)

        self.authn_session_page.setUrl(QUrl(self.auth_url.toString() + "/authn/preauth"))
        self.setPage(self.authn_session_page)
Exemplo n.º 18
0
    def __init__(self,
                 uploader,
                 config_file=None,
                 credential_file=None,
                 hostname=None,
                 window_title=None,
                 cookie_persistence=True):
        super(UploadWindow, self).__init__()
        qApp.aboutToQuit.connect(self.quitEvent)

        self.ui = UploadWindowUI(self)
        self.ui.title = window_title if window_title else "Deriva Upload Utility %s" % uploader.getVersion(
        )
        self.setWindowTitle(self.ui.title)

        self.config_file = config_file
        self.credential_file = credential_file
        self.cookie_persistence = cookie_persistence

        self.show()
        qApp.setOverrideCursor(Qt.WaitCursor)
        self.configure(uploader, hostname)
        qApp.restoreOverrideCursor()
Exemplo n.º 19
0
    def search(self):
        text = self.text.text()

        # Chosing the right columns
        lstColumns = [
            ("Title", Outline.title.value),
            ("Text", Outline.text.value),
            ("Summary", Outline.summarySentance.value),
            ("Summary", Outline.summaryFull.value),
            ("Notes", Outline.notes.value),
            ("POV", Outline.POV.value),
            ("Status", Outline.status.value),
            ("Label", Outline.label.value),
        ]
        columns = [c[1] for c in lstColumns if self.options[c[0]] or self.options["All"]]

        # Setting override cursor
        qApp.setOverrideCursor(Qt.WaitCursor)

        # Searching
        model = mainWindow().mdlOutline
        results = model.findItemsContaining(text, columns, self.options["CS"])

        # Showing results
        self.result.clear()
        for r in results:
            index = model.getIndexByID(r)
            if not index.isValid():
                continue
            item = index.internalPointer()
            i = QListWidgetItem(item.title(), self.result)
            i.setData(Qt.UserRole, r)
            i.setData(Qt.UserRole + 1, item.path())
            self.result.addItem(i)

        # Removing override cursor
        qApp.restoreOverrideCursor()
Exemplo n.º 20
0
    def __import_fuel_map(self):

        user_settings = UserSettings()
        file_filter = 'Ascii file (*' + AsciiParser.FILE_EXT + ')'
        file, filt = QFileDialog.getOpenFileName(self, 'Open File',
                                                 user_settings.working_dir,
                                                 file_filter)

        if file:
            # FIXME: increase SIZE when there are lots of cells in fuel map and ignition

            qApp.setOverrideCursor(Qt.WaitCursor)

            try:
                new_editor = FuelMapViewer(self, file)

            except IndexError:

                qApp.restoreOverrideCursor()
                QMessageBox.information(
                    self, "Invalid file",
                    "A problem occurred while loading the fuel map. Please "
                    "verify that the fuel map does not contain non-integer "
                    "numbers")
                return

            if self._fl_map_editor:
                self._fl_map_editor.deleteLater()

            self._fl_map_editor = new_editor

            self._fl_map_editor.setEnabled(True)

            self.__setup_fl_map_lgnd()

            # Enable relevant widgets
            self.action_export_fuel_map.setEnabled(True)

            # This means that a DEM has already been loaded,
            # so the user can now convert to FDS file
            if self._ign_pt_editor:
                self.__init_sim_settings()
                self.action_create_environment.setEnabled(True)

                if self._visualization:
                    self._visualization.deleteLater()

                self._visualization = Visualization(
                    self._fl_map_editor.parser(), self._ign_pt_editor.parser(),
                    self)
                self._visualization.setEnabled(True)
                self._visualization.hide()

            # Set current tab to fuel type legend
            self._tab_widget.setCurrentIndex(1)

            self._fm_title_label.setText("Fuel Map Title: " +
                                         util.get_filename(file))

            # Tab index might not change, so __tab_changed will never get called
            self._fl_map_editor.show()
            qApp.restoreOverrideCursor()
Exemplo n.º 21
0
 def getSession(self):
     qApp.setOverrideCursor(Qt.WaitCursor)
     logging.debug("Validating session: %s" % self.uploader.server["host"])
     queryTask = SessionQueryTask(self.uploader)
     queryTask.status_update_signal.connect(self.onSessionResult)
     queryTask.query()
Exemplo n.º 22
0
 def updateConfig(self):
     qApp.setOverrideCursor(Qt.WaitCursor)
     configUpdateTask = ConfigUpdateTask(self.uploader)
     configUpdateTask.status_update_signal.connect(self.onUpdateConfigResult)
     configUpdateTask.update_config()
Exemplo n.º 23
0
 def download_link(self, link: str) -> None:
     if len(self.realdebrid_api_token) > 0 and 'real-debrid.com' not in link \
         and 'rdeb.io' not in link:
         qApp.setOverrideCursor(Qt.BusyCursor)
         self.unrestrict_link(link, True)
     else:
         if self.download_manager == 'aria2':
             self.aria2 = Aria2Thread(settings=self.settings, link_url=link)
             self.aria2.aria2Confirmation.connect(self.aria2_confirmation)
             self.aria2.start()
             self.hosters_win.close()
         elif self.download_manager == 'pyload':
             self.pyload_conn = PyloadConnection(self.pyload_host,
                                                 self.pyload_username,
                                                 self.pyload_password)
             pid = self.pyload_conn.addPackage(name='TVLinker',
                                               links=[link])
             qApp.restoreOverrideCursor()
             self.hosters_win.close()
             if sys.platform.startswith('linux'):
                 self.notify(title='Download added to %s' %
                             self.download_manager,
                             icon=self.NotifyIcon.SUCCESS)
             else:
                 QMessageBox.information(
                     self, self.download_manager,
                     'Your link has been queued in %s.' %
                     self.download_manager, QMessageBox.Ok)
             # open_pyload = msgbox.addButton('Open pyLoad', QMessageBox.AcceptRole)
             # open_pyload.clicked.connect(self.open_pyload)
         elif self.download_manager in ('kget', 'persepolis'):
             provider = self.kget_cmd if self.download_manager == 'kget' else self.persepolis_cmd
             cmd = '{0} "{1}"'.format(provider, link)
             if self.cmdexec(cmd):
                 qApp.restoreOverrideCursor()
                 self.hosters_win.close()
                 if sys.platform.startswith('linux'):
                     self.notify(title='Download added to %s' %
                                 self.download_manager,
                                 icon=self.NotifyIcon.SUCCESS)
                 else:
                     QMessageBox.information(
                         self, self.download_manager,
                         'Your link has been queued in %s.' %
                         self.download_manager, QMessageBox.Ok)
         elif self.download_manager == 'idm':
             cmd = '"%s" /n /d "%s"' % (self.idm_exe_path, link)
             if self.cmdexec(cmd):
                 qApp.restoreOverrideCursor()
                 self.hosters_win.close()
                 QMessageBox.information(
                     self, 'Internet Download Manager',
                     'Your link has been queued in IDM.')
             else:
                 print('IDM QProcess error = %s' %
                       self.ProcError(self.idm.error()).name)
                 qApp.restoreOverrideCursor()
                 self.hosters_win.close()
                 QMessageBox.critical(
                     self, 'Internet Download Manager',
                     '<p>Could not connect to your local IDM application instance. '
                     +
                     'Please check your settings and ensure the IDM executable path is correct '
                     +
                     'according to your installation.</p><p>Error Code: %s</p>'
                     % self.ProcError(self.idm.error()).name,
                     QMessageBox.Ok)
         else:
             dlpath, _ = QFileDialog.getSaveFileName(
                 self, 'Save File',
                 link.split('/')[-1])
             if dlpath != '':
                 self.directdl_win = DirectDownload(parent=self)
                 self.directdl = DownloadThread(link_url=link,
                                                dl_path=dlpath)
                 self.directdl.dlComplete.connect(
                     self.directdl_win.download_complete)
                 if sys.platform.startswith('linux'):
                     self.directdl.dlComplete.connect(
                         lambda: self.notify(qApp.applicationName(
                         ), 'Download complete', self.NotifyIcon.SUCCESS))
                 else:
                     self.directdl.dlComplete.connect(
                         lambda: QMessageBox.information(
                             self, qApp.applicationName(),
                             'Download complete', QMessageBox.Ok))
                 self.directdl.dlProgressTxt.connect(
                     self.directdl_win.update_progress_label)
                 self.directdl.dlProgress.connect(
                     self.directdl_win.update_progress)
                 self.directdl_win.cancelDownload.connect(
                     self.cancel_download)
                 self.directdl.start()
                 self.hosters_win.close()
Exemplo n.º 24
0
 def getSession(self):
     qApp.setOverrideCursor(Qt.WaitCursor)
     self.updateStatus("Validating session.")
     queryTask = SessionQueryTask(self.catalog)
     queryTask.status_update_signal.connect(self.onSessionResult)
     queryTask.query()
Exemplo n.º 25
0
    def loadText(self, tHandle, updateHistory=True):
        """Load text into the viewer from an item handle.
        """
        if not self.theProject.tree.checkType(tHandle, nwItemType.FILE):
            logger.warning("Item not found")
            return False

        logger.debug("Generating preview for item '%s'", tHandle)
        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        sPos = self.verticalScrollBar().value()
        aDoc = ToHtml(self.theProject)
        aDoc.setPreview(self.mainConf.viewComments, self.mainConf.viewSynopsis)
        aDoc.setLinkHeaders(True)

        # Be extra careful here to prevent crashes when first opening a
        # project as a crash here leaves no way of recovering.
        # See issue #298
        try:
            aDoc.setText(tHandle)
            aDoc.doPreProcessing()
            aDoc.tokenizeText()
            aDoc.doConvert()
            aDoc.doPostProcessing()
        except Exception:
            logger.error("Failed to generate preview for document with handle '%s'", tHandle)
            logException()
            self.setText(self.tr("An error occurred while generating the preview."))
            qApp.restoreOverrideCursor()
            return False

        # Refresh the tab stops
        if self.mainConf.verQtValue >= 51000:
            self.setTabStopDistance(self.mainConf.getTabWidth())
        else:
            self.setTabStopWidth(self.mainConf.getTabWidth())

        # Must be before setHtml
        if updateHistory:
            self.docHistory.append(tHandle)

        self.setHtml(aDoc.theResult.replace("\t", "!!tab!!"))
        self.setDocumentTitle(tHandle)

        # Loop through the text and put back in the tabs. Tabs are removed by
        # the setHtml function, so the ToHtml class puts in a placeholder.
        while self.find("!!tab!!"):
            theCursor = self.textCursor()
            theCursor.insertText("\t")

        if self._docHandle == tHandle:
            # This is a refresh, so we set the scrollbar back to where it was
            self.verticalScrollBar().setValue(sPos)

        self._docHandle = tHandle
        self.theProject.setLastViewed(tHandle)
        self.docHeader.setTitleFromHandle(self._docHandle)
        self.updateDocMargins()

        # Make sure the main GUI knows we changed the content
        self.mainGui.viewMeta.refreshReferences(tHandle)

        # Since we change the content while it may still be rendering, we mark
        # the document dirty again to make sure it's re-rendered properly.
        self.redrawText()
        qApp.restoreOverrideCursor()

        return True
Exemplo n.º 26
0
 def showKeyframes(self):
     qApp.setOverrideCursor(Qt.WaitCursor)
     keyframes = self.parent.videoService.getKeyframes(self.media,
                                                       formatted_time=True)
     kframes = KeyframesDialog(keyframes, self)
     kframes.show()