Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 28 additions & 13 deletions raptor/gui/ui/chart_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from PySide6.QtGui import (
QColor, QFont, QFontMetrics, QPainter, QPainterPath, QPen, QPolygonF,
)
from PySide6.QtWidgets import QApplication, QFileDialog, QMenu, QToolTip, QWidget
from PySide6.QtWidgets import QApplication, QMenu, QToolTip, QWidget

from raptor.api.insight.attribution import CAUSE_LABELS
from raptor.api.insight.axes import (
Expand Down Expand Up @@ -1482,30 +1482,45 @@ def _menu(self, position) -> None:
menu.exec(self.mapToGlobal(position))

def _ask_png(self) -> None:
path, _ = QFileDialog.getSaveFileName(self, "Save chart", "",
"PNG image (*.png)")
if path:
if path := ask_chart_path(self, "Save chart", "", "PNG image", ".png"):
self.save_png(path)

def _ask_svg(self) -> None:
path, _ = QFileDialog.getSaveFileName(self, "Save chart", "",
"SVG image (*.svg)")
if path:
if path := ask_chart_path(self, "Save chart", "", "SVG image", ".svg"):
self.save_svg(path)

def _ask_pdf(self) -> None:
path, _ = QFileDialog.getSaveFileName(self, "Save chart", "",
"PDF document (*.pdf)")
if path:
if path := ask_chart_path(self, "Save chart", "", "PDF document", ".pdf"):
self.save_pdf(path)

def _ask_csv(self) -> None:
path, _ = QFileDialog.getSaveFileName(self, "Save chart data", "",
"CSV (*.csv)")
if path:
if path := ask_chart_path(self, "Save chart data", "", "CSV", ".csv"):
self.save_csv(path)


def ask_chart_path(parent, caption: str, stem: str, label: str, ext: str) -> str:
"""Where to save a chart, always with `ext` on the end ("" if cancelled).

The save dialog returns the name as typed, and "outage" saved as PNG
wrote nothing at all: the image format comes from the extension. A
name without it gets it added; as the dialog did not check that name,
replacing a file of that name is asked here."""
import os
from raptor.gui.ui.filedialogs import getSaveFileName
path, _ = getSaveFileName(parent, caption, stem, f"{label} (*{ext})")
if not path:
return ""
if os.path.splitext(path)[1].lower() != ext:
path += ext
if os.path.exists(path):
from raptor.gui.ui import dialogs
if not dialogs.question_box(
parent, caption, f"{os.path.basename(path)} already exists. Replace it?",
yes_text="Replace", no_text="Cancel"):
return ""
return path


def ribbon_reading(rows: Sequence[dict], index: int, t: float) -> str:
"""U17: what the run-to-run chart says at time `t` on row `index`:
the run, whether it is up or in an outage (with its start, end and
Expand Down
17 changes: 8 additions & 9 deletions raptor/gui/ui/charts_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QAction, QActionGroup, QColor, QFont
from PySide6.QtWidgets import (
QComboBox, QFileDialog, QHBoxLayout, QLabel, QMenu, QPushButton, QSpinBox,
QComboBox, QHBoxLayout, QLabel, QMenu, QPushButton, QSpinBox,
QSplitter, QStackedWidget, QToolButton, QTreeWidget, QTreeWidgetItem,
QVBoxLayout, QWidget,
)
Expand Down Expand Up @@ -764,25 +764,24 @@ def save_pdf(self, path: str) -> None:
def save_csv(self, path: str) -> None:
self.chart.save_csv(path)

def _ask(self, caption: str, filters: str) -> str:
stem = (self.selected_key() or "chart")
path, _ = QFileDialog.getSaveFileName(self, caption, stem, filters)
return path
def _ask(self, caption: str, label: str, ext: str) -> str:
from raptor.gui.ui.chart_widget import ask_chart_path
return ask_chart_path(self, caption, self.selected_key() or "chart", label, ext)

def _ask_svg(self) -> None:
if path := self._ask("Save chart", "SVG image (*.svg)"):
if path := self._ask("Save chart", "SVG image", ".svg"):
self.save_svg(path)

def _ask_png(self) -> None:
if path := self._ask("Save chart", "PNG image (*.png)"):
if path := self._ask("Save chart", "PNG image", ".png"):
self.save_png(path)

def _ask_pdf(self) -> None:
if path := self._ask("Save chart", "PDF document (*.pdf)"):
if path := self._ask("Save chart", "PDF document", ".pdf"):
self.save_pdf(path)

def _ask_csv(self) -> None:
if path := self._ask("Save chart data", "CSV (*.csv)"):
if path := self._ask("Save chart data", "CSV", ".csv"):
self.save_csv(path)

def _ask_raw(self) -> None:
Expand Down
7 changes: 4 additions & 3 deletions raptor/gui/ui/library_dock.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@
from PySide6.QtCore import QEvent, QMimeData, QObject, Qt
from PySide6.QtGui import QDrag
from PySide6.QtWidgets import (
QAbstractItemView, QComboBox, QDialog, QDialogButtonBox, QFileDialog, QFormLayout,
QAbstractItemView, QComboBox, QDialog, QDialogButtonBox, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, QMenu, QMessageBox, QPushButton,
QRadioButton, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout,
QWidget,
)

from raptor.gui.ui import filedialogs as fdg
from raptor.api.library.assembly import (
ASSEMBLY, add_local_part, adapted_buffer, assembly_from_buffer, describe,
renamed_buffer,
Expand Down Expand Up @@ -600,7 +601,7 @@ def detach_selected(self) -> None:
self.status.setText(f"Detached {changed} element(s); values kept.")

def add_library(self) -> None:
path, _ = QFileDialog.getOpenFileName(
path, _ = fdg.getOpenFileName(
self, "Open part library", "", "Part libraries (*.rbdlib *.json)")
if path:
self.open_library(path)
Expand All @@ -625,7 +626,7 @@ def export_library(self) -> None:
if not parts:
self.status.setText("The model holds no parts to export.")
return
path, _ = QFileDialog.getSaveFileName(
path, _ = fdg.getSaveFileName(
self, "Export parts to a library", "", "Part library (*.rbdlib)")
if not path:
return
Expand Down
56 changes: 56 additions & 0 deletions tests/unit/test_chart_export_extension.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""A chart saved under a name with no extension gets the type's own: a
PNG named "outage" wrote nothing at all, as the format comes from it."""
from __future__ import annotations

import os

import pytest

os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")


@pytest.fixture
def chart():
from PySide6.QtWidgets import QApplication

from raptor.api.insight import charts
from raptor.gui.ui.chart_widget import ChartWidget
QApplication.instance() or QApplication([])
widget = ChartWidget()
widget.set_spec(charts.ecdf([{"availability": v} for v in (0.95, 0.97, 0.99)]))
return widget


def _answer(monkeypatch, path):
from raptor.gui.ui import filedialogs
monkeypatch.setattr(filedialogs, "getSaveFileName", lambda *a, **k: (str(path), ""))


@pytest.mark.parametrize("ask, ext, magic", [
("_ask_png", ".png", b"\x89PNG"), ("_ask_svg", ".svg", b"<"),
("_ask_pdf", ".pdf", b"%PDF"), ("_ask_csv", ".csv", b"")])
def test_a_name_without_an_extension_gets_one(chart, monkeypatch, tmp_path, ask, ext, magic):
_answer(monkeypatch, tmp_path / "outage")
getattr(chart, ask)()
saved = tmp_path / f"outage{ext}"
assert saved.is_file() and saved.read_bytes().lstrip().startswith(magic)
assert not (tmp_path / "outage").exists()


def test_an_existing_file_is_only_replaced_when_asked(chart, monkeypatch, tmp_path):
from raptor.gui.ui import dialogs
(tmp_path / "outage.png").write_bytes(b"keep")
_answer(monkeypatch, tmp_path / "outage")
monkeypatch.setattr(dialogs, "question_box", lambda *a, **k: False)
chart._ask_png()
assert (tmp_path / "outage.png").read_bytes() == b"keep"


def test_the_charts_page_menu_adds_it_too(monkeypatch, tmp_path):
from PySide6.QtWidgets import QApplication

from raptor.gui.ui.charts_page import ChartsPage
QApplication.instance() or QApplication([])
page = ChartsPage()
_answer(monkeypatch, tmp_path / "chart")
assert page._ask("Save chart", "PNG image", ".png") == str(tmp_path / "chart.png")
15 changes: 15 additions & 0 deletions tests/unit/test_file_dialog_icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,18 @@ def test_stock_toolbar_glyphs_are_replaced_with_theme_icons(qapp):
for name, tb in buttons.items():
assert not tb.icon().isNull(), name
assert not tb.icon().pixmap(18, 18).isNull(), name


def test_no_static_qt_file_dialog_helpers_in_the_gui():
"""`QFileDialog.getSaveFileName(...)` and friends build their own dialog
with the desktop's icon provider, out of reach of `plain_icons`: the
chart and part-library dialogs logged the asciidoctor.svg line from
them. Call the wrappers in `filedialogs` instead."""
import re
from pathlib import Path
root = Path(filedialogs.__file__).resolve().parents[1]
pattern = re.compile(r"QFileDialog\.get(Open|Save|Existing)\w*\(")
found = [f"{path.name}:{n + 1}" for path in root.rglob("*.py")
for n, line in enumerate(path.read_text().splitlines())
if pattern.search(line) and path.name != "filedialogs.py"]
assert found == []