Skip to content

Commit

Permalink
refactor(interactive.imagetool): show error message in GUI when openi…
Browse files Browse the repository at this point in the history
…ng file
  • Loading branch information
kmnhan committed Jul 1, 2024
1 parent e3615c4 commit 287a7e8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
33 changes: 28 additions & 5 deletions src/erlab/interactive/imagetool/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
__all__ = ["ImageTool", "itool"]

import gc
import os
import pickle
import sys
from typing import TYPE_CHECKING, Any, Literal, cast
Expand Down Expand Up @@ -279,6 +280,7 @@ def __init__(
self.slicer_area.sigHistoryChanged.connect(self.refreshEditMenus)

self._recent_name_filter: str | None = None
self._recent_directory: str | None = None

@property
def array_slicer(self) -> ArraySlicer:
Expand Down Expand Up @@ -513,7 +515,9 @@ def _copy_cursor_idx(self):
copy_to_clipboard(str(self.slicer_area.array_slicer._indices))

@QtCore.Slot()
def _open_file(self, *, name_filter: str | None = None):
def _open_file(
self, *, name_filter: str | None = None, directory: str | None = None
):
valid_loaders: dict[str, tuple[Callable, dict]] = {
"xarray HDF5 Files (*.h5)": (erlab.io.load_hdf5, {}),
"NetCDF Files (*.nc *.nc4 *.cdf)": (xr.load_dataarray, {}),
Expand All @@ -531,15 +535,34 @@ def _open_file(self, *, name_filter: str | None = None):

if name_filter is not None:
dialog.selectNameFilter(name_filter)

if directory is None:
directory = self._recent_directory

if directory is not None:
dialog.setDirectory(directory)

# dialog.setOption(QtWidgets.QFileDialog.Option.DontUseNativeDialog)

if dialog.exec():
files = dialog.selectedFiles()
fname = dialog.selectedFiles()[0]
self._recent_name_filter = dialog.selectedNameFilter()
self._recent_directory = os.path.dirname(fname)
fn, kargs = valid_loaders[self._recent_name_filter]
# !TODO: handle ambiguous datasets
self.slicer_area.set_data(fn(files[0], **kargs))
self.slicer_area.view_all()

try:
self.slicer_area.set_data(fn(fname, **kargs))
except Exception as e:
QtWidgets.QMessageBox.critical(
self,
"Error",
f"An error occurred while loading the file: {e}"
"\n\nTry again with a different loader.",
QtWidgets.QMessageBox.StandardButton.Ok,
)
self._open_file()
else:
self.slicer_area.view_all()

def _export_file(self):
if self.slicer_area._data is None:
Expand Down
5 changes: 4 additions & 1 deletion src/erlab/interactive/imagetool/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,10 @@ def set_data(

if not isinstance(data, xr.DataArray):
if isinstance(data, xr.Dataset):
data = cast(xr.DataArray, data[next(iter(data.data_vars.keys()))])
try:
data = cast(xr.DataArray, data[next(iter(data.data_vars.keys()))])
except StopIteration as e:
raise ValueError("No data variables found in Dataset") from e
else:
data = xr.DataArray(np.asarray(data))
if hasattr(data.data, "flags"):
Expand Down
8 changes: 6 additions & 2 deletions src/erlab/interactive/imagetool/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,9 @@ def __init__(self: ImageToolManagerGUI):
# Temporary directory for storing archived data
self._tmp_dir = tempfile.TemporaryDirectory()

# Store most recent name filter for new windows
# Store most recent name filter and directory for new windows
self._recent_name_filter: str | None = None
self._recent_directory: str | None = None

self.setCentralWidget(self.options)
self.sigLinkersChanged.connect(self.changed)
Expand Down Expand Up @@ -324,8 +325,11 @@ def add_new(self):
tool = ImageTool(np.zeros((2, 2)))
self.add_tool(tool, activate=True)

tool.mnb._open_file(name_filter=self._recent_name_filter)
tool.mnb._open_file(
name_filter=self._recent_name_filter, directory=self._recent_directory
)
self._recent_name_filter = tool.mnb._recent_name_filter
self._recent_directory = tool.mnb._recent_directory

def color_for_linker(self, linker: SlicerLinkProxy) -> QtGui.QColor:
idx = self.linkers.index(linker)
Expand Down

0 comments on commit 287a7e8

Please sign in to comment.