Beispiel #1
0
def test_qt_viewer_clipboard_without_flash(make_napari_viewer):
    viewer = make_napari_viewer()
    # make sure clipboard is empty
    QGuiApplication.clipboard().clear()
    clipboard_image = QGuiApplication.clipboard().image()
    assert clipboard_image.isNull()

    # capture screenshot
    with pytest.warns(FutureWarning):
        viewer.window.qt_viewer.clipboard(flash=False)

    viewer.window.clipboard(flash=False, canvas_only=True)

    clipboard_image = QGuiApplication.clipboard().image()
    assert not clipboard_image.isNull()

    # ensure the flash effect is not applied
    assert viewer.window._qt_viewer._canvas_overlay.graphicsEffect() is None
    assert not hasattr(viewer.window._qt_viewer._canvas_overlay,
                       "_flash_animation")

    # clear clipboard and grab image from application view
    QGuiApplication.clipboard().clear()
    clipboard_image = QGuiApplication.clipboard().image()
    assert clipboard_image.isNull()

    # capture screenshot of the entire window
    viewer.window.clipboard(flash=False)
    clipboard_image = QGuiApplication.clipboard().image()
    assert not clipboard_image.isNull()

    # ensure the flash effect is not applied
    assert viewer.window._qt_window.graphicsEffect() is None
    assert not hasattr(viewer.window._qt_window, "_flash_animation")
Beispiel #2
0
    def save_result(self):
        if self.settings.image_path is not None and QMessageBox.Yes == QMessageBox.question(
                self, "Copy", "Copy name to clipboard?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes):
            clipboard = QGuiApplication.clipboard()
            clipboard.setText(
                os.path.splitext(os.path.basename(
                    self.settings.image_path))[0])

        if self.settings.roi is None or len(self.settings.sizes) == 1:
            QMessageBox.warning(self, "No components", "No components to save")
            return
        dial = PSaveDialog(
            io_functions.save_components_dict,
            system_widget=False,
            settings=self.settings,
            file_mode=PSaveDialog.Directory,
            path="io.save_components_directory",
        )
        dial.selectFile(
            os.path.splitext(os.path.basename(self.settings.image_path))[0])
        if not dial.exec_():
            return
        res = dial.get_result()
        potential_names = self.settings.get_file_names_for_save_result(
            res.save_destination)
        conflict = []
        for el in potential_names:
            if os.path.exists(el):
                conflict.append(el)
        if len(conflict) > 0:
            # TODO modify because of long lists
            conflict_str = "\n".join(conflict)
            if QMessageBox.No == QMessageBox.warning(
                    self,
                    "Overwrite",
                    f"Overwrite files:\n {conflict_str}",
                    QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No,
            ):
                self.save_result()

        def exception_hook(exception):
            QMessageBox.critical(
                self, "Save error",
                f"Error on disc operation. Text: {exception}", QMessageBox.Ok)

        dial = ExecuteFunctionDialog(
            res.save_class.save,
            [
                res.save_destination,
                self.settings.get_project_info(), res.parameters
            ],
            text="Save components",
            exception_hook=exception_hook,
        )
        dial.exec_()
    def pasteShape(self):
        from qtpy.QtGui import QGuiApplication

        clipboard = QGuiApplication.clipboard()
        if not clipboard.ownsClipboard():
            return
        shapes_json = clipboard.text()
        added_shapes = self.canvas.pasteShapes(shapes_json)
        self.labelList.clearSelection()
        for shape in added_shapes:
            self.addLabel(shape)
        self.setDirty()
Beispiel #4
0
    def clipboard(self, flash=True):
        """Take a screenshot of the currently displayed screen and copy the
        image to the clipboard.

        Parameters
        ----------
        flash : bool
            Flag to indicate whether flash animation should be shown after
            the screenshot was captured.
        """
        cb = QGuiApplication.clipboard()
        cb.setImage(self._screenshot(flash))
def test_error_reporter(qtbot, monkeypatch):
    """test that QtPluginErrReporter shows any instantiated PluginErrors."""

    monkeypatch.setattr(
        qt_plugin_report,
        'standard_metadata',
        lambda x: {'url': 'https://github.com/example/example'},
    )

    error_message = 'my special error'
    try:
        # we need to raise to make sure a __traceback__ is attached to the error.
        raise PluginError(error_message,
                          plugin_name='test_plugin',
                          plugin="mock")
    except PluginError:
        pass
    report_widget = qt_plugin_report.QtPluginErrReporter()
    qtbot.addWidget(report_widget)

    # the null option plus the one we created
    assert report_widget.plugin_combo.count() >= 2

    # the message should appear somewhere in the text area
    report_widget.set_plugin('test_plugin')
    assert error_message in report_widget.text_area.toPlainText()

    # mock_webbrowser_open
    def mock_webbrowser_open(url, new=0):
        assert new == 2
        assert "Errors for plugin 'test_plugin'" in url
        assert "Traceback from napari" in url

    monkeypatch.setattr(webbrowser, 'open', mock_webbrowser_open)

    qtbot.mouseClick(report_widget.github_button, Qt.LeftButton)

    # make sure we can copy traceback to clipboard
    report_widget.copyToClipboard()
    clipboard_text = QGuiApplication.clipboard().text()
    assert "Errors for plugin 'test_plugin'" in clipboard_text

    # plugins without errors raise an error
    with pytest.raises(ValueError):
        report_widget.set_plugin('non_existent')

    report_widget.set_plugin(None)
    assert not report_widget.text_area.toPlainText()
Beispiel #6
0
    def clipboard(self, flash=True):
        """Take a screenshot of the currently displayed screen and copy the
        image to the clipboard.

        Parameters
        ----------
        flash : bool
            Flag to indicate whether flash animation should be shown after
            the screenshot was captured.
        """
        import warnings

        warnings.warn(
            trans.
            _("'window.qt_viewer.screenshot' is deprecated and will be removed in v0.4.14.  Please use 'window.screenshot(canvas_only=True)' instead"
              ),
            FutureWarning,
            stacklevel=2,
        )
        cb = QGuiApplication.clipboard()
        cb.setImage(self._screenshot(flash))
Beispiel #7
0
def test_qt_viewer_clipboard_with_flash(make_napari_viewer, qtbot):
    viewer = make_napari_viewer()
    # make sure clipboard is empty
    QGuiApplication.clipboard().clear()
    clipboard_image = QGuiApplication.clipboard().image()
    assert clipboard_image.isNull()

    # capture screenshot
    viewer.window.qt_viewer.clipboard(flash=True)
    clipboard_image = QGuiApplication.clipboard().image()
    assert not clipboard_image.isNull()

    # ensure the flash effect is applied
    assert viewer.window.qt_viewer._canvas_overlay.graphicsEffect() is not None
    assert hasattr(viewer.window.qt_viewer._canvas_overlay, "_flash_animation")
    qtbot.wait(500)  # wait for the animation to finish
    assert viewer.window.qt_viewer._canvas_overlay.graphicsEffect() is None
    assert not hasattr(viewer.window.qt_viewer._canvas_overlay,
                       "_flash_animation")

    # clear clipboard and grab image from application view
    QGuiApplication.clipboard().clear()
    clipboard_image = QGuiApplication.clipboard().image()
    assert clipboard_image.isNull()

    # capture screenshot of the entire window
    viewer.window.clipboard(flash=True)
    clipboard_image = QGuiApplication.clipboard().image()
    assert not clipboard_image.isNull()

    # ensure the flash effect is applied
    assert viewer.window._qt_window.graphicsEffect() is not None
    assert hasattr(viewer.window._qt_window, "_flash_animation")
    qtbot.wait(500)  # wait for the animation to finish
    assert viewer.window._qt_window.graphicsEffect() is None
    assert not hasattr(viewer.window._qt_window, "_flash_animation")
Beispiel #8
0
 def __init__(self, parent, history):
     super().__init__(parent=parent)
     self.setWindowTitle("History")
     layout = QVBoxLayout()
     text = QPlainTextEdit()
     font = QFont()
     font.setFamily("monospace")
     font.setStyleHint(QFont.Monospace)
     text.setFont(font)
     highlighter = PythonHighlighter(text.document())  # noqa: F841
     text.setReadOnly(True)
     text.setPlainText(history)
     layout.addWidget(text)
     buttonbox = QDialogButtonBox(QDialogButtonBox.Ok)
     clipboardbutton = QPushButton("Copy to clipboard")
     buttonbox.addButton(clipboardbutton, QDialogButtonBox.ActionRole)
     clipboard = QGuiApplication.clipboard()
     clipboardbutton.clicked.connect(
         lambda: clipboard.setText(history + "\n"))
     layout.addWidget(buttonbox)
     self.setLayout(layout)
     buttonbox.accepted.connect(self.accept)
     self.resize(700, 500)
Beispiel #9
0
 def copyToClipboard(self) -> None:
     """Copy current plugin traceback info to clipboard as plain text."""
     plugin = self.plugin_combo.currentText()
     err_string = format_exceptions(plugin, as_html=False)
     cb = QGuiApplication.clipboard()
     cb.setText(err_string)
Beispiel #10
0
 def __to_clipboard(widget):
     QGuiApplication.clipboard().setText('\n'.join([widget.item(i).text() for i in range(widget.count())]))
Beispiel #11
0
    def copySelectedShape(self):
        from qtpy.QtGui import QGuiApplication

        shapes_json = self.canvas.copySelectedShapes()
        clipboard = QGuiApplication.clipboard()
        clipboard.setText(shapes_json)