Exemple #1
0
    def search(self):
        self.result.clear()
        self.result.setCurrentRow(0)

        searchText = self.searchTextInput.text()
        if len(searchText) > 0:
            searchRegex = self.prepareRegex(searchText)
            results = []

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

            for model, modelName in [
                (mainWindow().mdlOutline, Model.Outline),
                (mainWindow().mdlCharacter, Model.Character),
                (flatDataModelWrapper(mainWindow().mdlFlatData),
                 Model.FlatData), (mainWindow().mdlWorld, Model.World),
                (mainWindow().mdlPlots, Model.Plot)
            ]:
                filteredColumns = self.searchMenu.columns(modelName)

                # Searching
                if len(filteredColumns):
                    results += model.searchOccurrences(searchRegex,
                                                       filteredColumns)

            # Showing results
            self.generateResultsLists(results)

            # Remove override cursor
            qApp.restoreOverrideCursor()
Exemple #2
0
    def onSubprocessExecuteResult(self, success, status, detail, is_owner):
        qApp.restoreOverrideCursor()
        if not success:
            self.resetUI(status, detail)
            return

        if not is_owner or self.curator_mode:
            self.resetUI(status, detail)
            return

        # prompt for save/complete/discard
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setWindowTitle("Confirm Action")
        msg.setText("How would you like to proceed?")
        msg.setInformativeText(
            "Select \"Save Progress\" to save your progress and upload the output to the server.\n\n"
            "Select \"Complete\" to upload the output to the server and mark this task as completed.\n\n"
            "Select \"Discard\" to abort the process and leave the task state unchanged."
        )
        saveButton = msg.addButton("Save Progress", QMessageBox.ActionRole)
        completeButton = msg.addButton("Complete", QMessageBox.ActionRole)
        discardButton = msg.addButton("Discard", QMessageBox.RejectRole)
        msg.exec_()
        if msg.clickedButton() == discardButton:
            self.resetUI("Aborted.")
            return
        update_state = None
        if msg.clickedButton() == saveButton:
            update_state = ("incomplete", "analysis in progress")
        elif msg.clickedButton() == completeButton:
            update_state = ("complete", "analysis complete")

        self.uploadAnalysisResult(update_state)
Exemple #3
0
    def setContent(self, theText, timeStamp):
        """Set the content, either from text or list of text.
        """
        if isinstance(theText, list):
            theText = "".join(theText)

        self.buildTime = timeStamp
        sPos = self.verticalScrollBar().value()
        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))

        theText = theText.replace("\t", "!!tab!!")
        theText = theText.replace(
            "<del>", "<span style='text-decoration: line-through;'>")
        theText = theText.replace("</del>", "</span>")
        self.setHtml(theText)
        qApp.processEvents()

        while self.find("!!tab!!"):
            theCursor = self.textCursor()
            theCursor.insertText("\t")

        self.verticalScrollBar().setValue(sPos)
        self._updateBuildAge()

        # 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.qDocument.markContentsDirty(0, self.qDocument.characterCount())
        qApp.restoreOverrideCursor()

        return
Exemple #4
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.video, self.devmode = '', False
     self.parse_cmdline()
     self.init_logger()
     self.init_settings()
     self.init_scale()
     self.init_cutter()
     self.setWindowTitle('%s' % qApp.applicationName())
     self.setContentsMargins(0, 0, 0, 0)
     self.statusBar().showMessage('Ready')
     self.statusBar().setStyleSheet('border: none; padding: 0; margin: 0;')
     self.setAcceptDrops(True)
     self.show()
     self.console.setGeometry(int(self.x() - (self.width() / 2)), self.y() + int(self.height() / 3), 750, 300)
     try:
         if len(self.video):
             if QFileInfo(self.video).suffix() == 'vcp':
                 self.cutter.openProject(project_file=self.video)
             else:
                 self.cutter.loadMedia(self.video)
     except (FileNotFoundError, PermissionError) as e:
         QMessageBox.critical(self, 'Error loading file', sys.exc_info()[0])
         logging.exception('Error loading file')
         qApp.restoreOverrideCursor()
         self.restart()
     if not self.cutter.ffmpeg_check():
         qApp.exit(1)
Exemple #5
0
    def __execute_and_update(self, cmd, out_dir=None, out_file=sys.stdout):
        """Execute the given command and update the progress bar"""

        # TODO: kill this when done...
        fds_pid = util.execute(cmd=cmd, cwd=out_dir, out_file=out_file)

        t_end = float(self._fds.sim_time())

        # Make progress bar visible
        self._progress_bar.show()

        # We need to give WFDS some time to create the proper .out so that we may
        # read from it and update the progress bar.
        # Since everyone has different hardware, this seems to be the most sensible solution.
        # Could get caught in an infinite while loop if .out is never made, but we expect this file to be present
        # as part of WFDS' 'interface'

        wait = True
        while wait:

            try:
                out_file = osp.join(out_dir, self._fds.job() + '.out')
                for line in follow(open(out_file, 'r')):

                    line = line.replace(' ', '').replace('\n', '')

                    # Break if we hit STOP because simulation is over
                    if line.startswith('STOP'):
                        break

                    if line.startswith('Timestep'):
                        timestep_kv, sim_time_kv = line.split(',')

                        # Not currently used, could be later?
                        timestep_int = timestep_kv.split(':')[1]
                        sim_time_float = float(sim_time_kv.split(':')[1].replace('s', ''))

                        # Figure out percentage and update progress bar
                        loading = (sim_time_float / t_end) * 100
                        self._progress_bar.setValue(loading)
                wait = False

            except FileNotFoundError:
                logger.log(logger.INFO, 'Sleep')
                qApp.processEvents()  # Helps keep gui responsive
                time.sleep(0.1)

        # TODO: could get pid from popen and check it or something here.
        # May also be useful to get pid for things such as killing if FireScape Rx is
        # terminated prematurely

        # If we reach here, simulation should be done.
        logger.log(logger.INFO, "Simulation complete")

        self._progress_bar.setValue(100)

        qApp.restoreOverrideCursor()
        QMessageBox.information(self, 'Simulation Complete', 'Simulation completed.')

        self.__hide_and_reset_progress()
Exemple #6
0
    def convert(self, src, args, outputfile=None):
        args = [self.cmd] + args

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

        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")
Exemple #7
0
    def stopWorking(self):
        # Removing override cursor
        qApp.restoreOverrideCursor()

        # Button
        self.btnCompile.setEnabled(True)
        self.btnCompile.setText(self.txtBtn)
Exemple #8
0
    def mouseMoveEvent(self, event):
        """
        When mouse moves, we show tooltip when appropriate.
        """
        textEditView.mouseMoveEvent(self, event)

        onRect = [r for r in self.clickRects if r.rect.contains(event.pos())]

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

        ct = onRect[0]
        if not qApp.overrideCursor():
            qApp.setOverrideCursor(Qt.PointingHandCursor)

        if ct.regex == self.automaticLinkRegex:
            tooltip = ct.texts[2] or ct.texts[4]

        elif ct.regex == self.imageRegex:
            tt = ("<p><b>" + ct.texts[1] + "</b></p>" +
                  "<p><img src='data:image/png;base64,{}'></p>")
            tooltip = None
            pos = event.pos() + QPoint(0, ct.rect.height())
            ImageTooltip.fromUrl(ct.texts[2], pos, self)

        elif ct.regex == self.inlineLinkRegex:
            tooltip = ct.texts[1] or ct.texts[2]

        if tooltip:
            tooltip = self.tr("{} (CTRL+Click to open)").format(tooltip)
            QToolTip.showText(self.mapToGlobal(event.pos()), tooltip)
Exemple #9
0
 def eventFilter(self, obj: QObject, event: QEvent) -> bool:
     if event.type() == QEvent.Enter:
         qApp.setOverrideCursor(Qt.PointingHandCursor)
     elif event.type() == QEvent.Leave:
         qApp.restoreOverrideCursor()
     return super(ClipErrorsDialog.VCToolBox,
                  self).eventFilter(obj, event)
Exemple #10
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.edl, self.video = '', ''
     self.parse_cmdline()
     self.init_logger()
     self.init_cutter()
     self.setWindowTitle('%s' % qApp.applicationName())
     self.setContentsMargins(0, 0, 0, 0)
     self.statusBar().showMessage('Ready')
     statuslogo = QLabel(pixmap=QPixmap(':/images/vidcutter-emboss.png'),
                         objectName='logowidget')
     self.statusBar().addPermanentWidget(statuslogo)
     self.statusBar().setStyleSheet('border:none;')
     self.setAcceptDrops(True)
     self.setMinimumSize(900, 640)
     self.show()
     try:
         if len(self.video):
             self.cutter.loadMedia(self.video)
         if len(self.edl):
             self.cutter.openEDL(edlfile=self.edl)
     except (FileNotFoundError, PermissionError) as e:
         QMessageBox.critical(self, 'Error loading file', sys.exc_info()[0])
         logging.exception('Error loading file')
         qApp.restoreOverrideCursor()
         self.cutter.startNew()
     if not self.cutter.ffmpeg_check():
         self.close()
         sys.exit(1)
Exemple #11
0
    def onUpdateConfigResult(self, success, status, detail, result):
        qApp.restoreOverrideCursor()
        if not success:
            self.resetUI(status, detail)
            return
        if not result:
            return
        confirm_updates = stob(
            self.uploader.server.get("confirm_updates", False))
        if confirm_updates:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle("Updated Configuration Available")
            msg.setText("Apply updated configuration?")
            msg.setInformativeText(
                "Selecting \"Yes\" will apply the latest configuration from the server and overwrite the existing "
                "default configuration file.\n\nSelecting \"No\" will ignore these updates and continue to use the "
                "existing configuration.\n\nYou should always apply the latest configuration changes from the server "
                "unless you understand the risk involved with using a potentially out-of-date configuration."
            )

            msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            ret = msg.exec_()
            if ret == QMessageBox.No:
                return

        write_config(self.uploader.getDeployedConfigFilePath(), result)
        self.uploader.initialize(cleanup=False)
        if not self.checkVersion():
            return
        self.on_actionRescan_triggered()
Exemple #12
0
    def convert(self, src, args, outputfile=None):
        if self.isValid() == 2:
            run = self.cmd
        elif self.isValid() == 1:
            run = self.customPath
        else:
            LOGGER.error("No command for pandoc.")
            return None
        args = [run] + 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 metadata required for pandoc >= 2.x
        title = "Untitled"
        if mainWindow().mdlFlatData.item(0, 0):
            title = mainWindow().mdlFlatData.item(0, 0).text().strip()
        args.append("--metadata=title:{}".format(title))

        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") 
            LOGGER.error(err)
            QMessageBox.critical(mainWindow().dialog, qApp.translate("Export", "Error"), err)
            return None

        return stdout.decode("utf-8")
Exemple #13
0
    def __run_wfds(self):
        """This function runs wfds with the currently loaded environment"""

        qApp.setOverrideCursor(Qt.WaitCursor)

        # Get user's output directory
        user_settings = UserSettings()
        out_dir = osp.abspath(user_settings.output_dir)

        # Get path to current fds file
        fds_filepath = self._fds.fds_file
        fds_fname = util.get_filename(fds_filepath)

        # Create a unique directory with same name as simulation
        out_dir = osp.join(out_dir, fds_fname)
        out_dir = util.make_unique_directory(out_dir)

        os.mkdir(out_dir)

        fds_exec = user_settings.wfds_exec

        if not fds_exec:
            QMessageBox.information(
                self, "No executable found",
                "No WFDS executable found! please specify one in "
                "the User Settings menu")
            return
        #TODO: Determine alternate save method or remove export fds file
        # Save the input file that was used to run the simulation
        #save_fname = osp.join(out_dir, fds_fname + Fds.file_ext())
        #self._fds.save(save_fname)

        logger.log(logger.INFO, 'Running simulation')

        # Clean up the output directory that was made if exception occurs
        try:

            self.__execute_and_update(cmd=[fds_exec, fds_filepath],
                                      out_dir=out_dir)

        except Exception as e:
            logger.log(logger.ERROR, str(e))
            logger.log(logger.INFO, 'Cleaning up...')

            qApp.restoreOverrideCursor()

            QMessageBox.warning(
                self, 'A problem occurred',
                'There was a problem while running the simulation(s), please try again'
            )

            # Remove files from directory
            for file in os.listdir(out_dir):
                os.remove(osp.join(out_dir, file))

            os.rmdir(out_dir)

            # Hide and reset progress bar
            self.__hide_and_reset_progress()
Exemple #14
0
 def onUploadResult(self, success, status, detail, result):
     qApp.restoreOverrideCursor()
     self.uploading = False
     self.displayUploads(self.uploader.getFileStatusAsArray())
     if success:
         self.resetUI("Ready.")
     else:
         self.resetUI(status, detail, success)
Exemple #15
0
 def resize_me(self):
     qApp.setOverrideCursor(Qt.WaitCursor)
     w = QFontMetrics(self.font()).widthChar("0") + 2
     for i in range(10):
         self.setColumnWidth(i, 3 * w)
     for i in range(10, self.model().col_count):
         self.setColumnWidth(i, w * (len(str(i + 1)) + 1))
     qApp.restoreOverrideCursor()
 def populateGUI(self):
     """Populate list box with data from the log file.
     """
     qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
     self._loadLogFile()
     self._updateListBox()
     qApp.restoreOverrideCursor()
     return
Exemple #17
0
 def _doPrintPreview(self, thePrinter):
     """Connect the print preview painter to the document viewer.
     """
     qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
     thePrinter.setOrientation(QPrinter.Portrait)
     self.docView.qDocument.print(thePrinter)
     qApp.restoreOverrideCursor()
     return
 def mouseReleaseEvent(self, event):
     textEditView.mouseReleaseEvent(self, event)
     onRef = [r for r in self.refRects if r.contains(event.pos())]
     if onRef:
         cursor = self.cursorForPosition(event.pos())
         ref = self.refUnderCursor(cursor)
         if ref:
             Ref.open(ref)
             qApp.restoreOverrideCursor()
Exemple #19
0
 def onCatalogUpdateResult(self, success, status, detail, result):
     if not success:
         self.resetUI(status, detail)
         self.serverProblemMessageBox(
             "Unable to update catalog data",
             "The catalog state was not updated successfully.")
         return
     qApp.restoreOverrideCursor()
     self.on_actionRefresh_triggered()
Exemple #20
0
 def mouseReleaseEvent(self, event):
     MDEditView.mouseReleaseEvent(self, event)
     onRef = [r for r in self.refRects if r.contains(event.pos())]
     if onRef:
         cursor = self.cursorForPosition(event.pos())
         ref = self.refUnderCursor(cursor)
         if ref:
             Ref.open(ref)
             qApp.restoreOverrideCursor()
Exemple #21
0
 def onScanResult(self, success, status, detail, result):
     qApp.restoreOverrideCursor()
     if success:
         self.displayUploads(self.uploader.getFileStatusAsArray())
         self.ui.actionUpload.setEnabled(self.canUpload())
         self.resetUI("Ready...")
         if self.uploading:
             self.on_actionUpload_triggered()
     else:
         self.resetUI(status, detail, success)
Exemple #22
0
 def eventFilter(self, obj: QObject, event: QEvent) -> bool:
     if event.type() == QEvent.ToolTip:
         return True
     elif event.type() == QEvent.Enter and obj.isEnabled():
         qApp.setOverrideCursor(Qt.PointingHandCursor)
     elif event.type() == QEvent.Leave:
         qApp.restoreOverrideCursor()
     elif event.type() == QEvent.StatusTip and not obj.isEnabled():
         return True
     return super(VideoToolBar, self).eventFilter(obj, event)
Exemple #23
0
 def populateGUI(self):
     """Populate tabs with text.
     """
     qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
     self._setStyleSheet()
     self._fillAboutPage()
     self._fillNotesPage()
     self._fillLicensePage()
     qApp.restoreOverrideCursor()
     return
Exemple #24
0
 def copy_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, False)
     else:
         clip = qApp.clipboard()
         clip.setText(link)
         self.hosters_win.close()
         qApp.restoreOverrideCursor()
Exemple #25
0
 def lock_gui(self, locked: bool = True) -> None:
     if locked:
         qApp.setOverrideCursor(Qt.WaitCursor)
         self.cutter.cliplist.setEnabled(False)
         self.setEnabled(False)
     else:
         self.setEnabled(True)
         self.cutter.cliplist.setEnabled(True)
         qApp.restoreOverrideCursor()
     qApp.processEvents()
Exemple #26
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()
Exemple #27
0
 def startNew(self) -> None:
     qApp.restoreOverrideCursor()
     self.clearList()
     self.seekSlider.setValue(0)
     self.seekSlider.setRange(0, 0)
     self.mediaPlayer.setMedia(QMediaContent())
     self.initNoVideo()
     self.videoLayout.replaceWidget(self.videoplayerWidget,
                                    self.novideoWidget)
     self.initMediaControls(False)
     self.parent.setWindowTitle('%s' % qApp.applicationName())
Exemple #28
0
 def handleError(self, error: QMediaPlayer.Error) -> None:
     qApp.restoreOverrideCursor()
     self.startNew()
     if error == QMediaPlayer.ResourceError:
         QMessageBox.critical(
             self.parent, 'INVALID MEDIA',
             'Invalid media file detected at:<br/><br/><b>%s</b><br/><br/>%s'
             % (self.movieFilename, self.mediaPlayer.errorString()))
     else:
         QMessageBox.critical(self.parent, 'ERROR NOTIFICATION',
                              self.mediaPlayer.errorString())
Exemple #29
0
 def lockGUI(self, locked: bool) -> None:
     if locked:
         qApp.setOverrideCursor(Qt.WaitCursor)
         self.parent.cliplist.setEnabled(False)
         self.parent.parent.setEnabled(False)
         self.blockSignals(True)
     else:
         self.blockSignals(False)
         self.parent.parent.setEnabled(True)
         self.parent.cliplist.setEnabled(True)
         qApp.restoreOverrideCursor()
Exemple #30
0
 def lockGUI(self, locked: bool) -> None:
     if locked:
         qApp.setOverrideCursor(Qt.WaitCursor)
         self.parent.cliplist.setEnabled(False)
         self.parent.parent.setEnabled(False)
         self.blockSignals(True)
         self.parent.parent.layout().setSizeConstraint(QLayout.SetFixedSize)
     else:
         self.blockSignals(False)
         self.parent.parent.setEnabled(True)
         self.parent.cliplist.setEnabled(True)
         qApp.restoreOverrideCursor()
         self.parent.parent.layout().setSizeConstraint(QLayout.SetNoConstraint)
Exemple #31
0
 def _onLoadFinished(self, result):
     qApp.restoreOverrideCursor()
     if not result:
         logging.debug("Page load error: %s" %
                       self.authn_session_page.url().toDisplayString())
         self.setPage(self.authn_session_page)
         return
     if self.authn_session_page.url().path() == "/authn/preauth":
         self.authn_session_page.toPlainText(self._onPreAuthContent)
     elif self.authn_session_page.url().path() == "/authn/session":
         self.authn_session_page.toPlainText(self._onSessionContent)
     else:
         self.setPage(self.authn_session_page)
Exemple #32
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")
    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))
    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")
Exemple #35
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()