From 90882209deca2ff1b779647831f408bc791e0a46 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 15:26:33 +0000 Subject: [PATCH 1/4] cloud_dataset_browser: filter by published state, add Published column Follows NDI-matlab 3f56952 (cloudDatasetBrowser). The browser gains "Include published" and "Include unpublished" checkboxes (both ticked at first) and a Published (Yes/No) column read from each dataset's isPublished flag; an absent flag counts as unpublished. Published also appears in the details and as a Sort by choice, and the status line says "N of M dataset(s) shown." while a filter hides any. New: filter_entries, count_status_text, set_filter, to_flag, yes_no_text, all_entries. Bridge entry synced to 3f56952. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011v7R5uS1zLb3Jzu5Vu23sb --- CHANGELOG.md | 7 ++ src/ndi/gui/nav/cloud_dataset_browser.py | 116 ++++++++++++++++++-- src/ndi/gui/ndi_matlab_python_bridge.yaml | 10 +- tests/test_gui_nav_cloud_dataset_browser.py | 69 ++++++++++++ 4 files changed, 194 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04822363..02dc590c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **Navigator: filter the cloud dataset browser by published state** + (`ndi.gui.nav.cloud_dataset_browser`, MATLAB VH-Lab/NDI-matlab@3f56952). The + "Browse my Cloud datasets..." window gains a Published (Yes/No) column, read + from each dataset's `isPublished` flag, and "Include published" / "Include + unpublished" checkboxes (both ticked at first). The status line says how + many datasets are shown out of how many while a filter hides any. + - **Navigator: Cloud comparison, Cloud info and a cloud dataset browser** (`ndi.gui.nav`, MATLAB VH-Lab/NDI-matlab#1230 and #1231). A dataset's Cloud menu is now "Cloud info...", "Upload to Cloud" and "Cloud comparison...". diff --git a/src/ndi/gui/nav/cloud_dataset_browser.py b/src/ndi/gui/nav/cloud_dataset_browser.py index c03feb8c..e8afc9da 100644 --- a/src/ndi/gui/nav/cloud_dataset_browser.py +++ b/src/ndi/gui/nav/cloud_dataset_browser.py @@ -4,13 +4,18 @@ (VH-Lab/NDI-matlab#1231) Lists every NDI Cloud dataset in every organization the signed-in user -belongs to, with Name, Organization, Documents, Files, Created and Last -changed. "Created" is when the dataset was created on NDI Cloud, which is +belongs to, with Name, Organization, Documents, Files, Created, Last changed +and Published. "Created" is when the dataset was created on NDI Cloud, which is when its first documents were added; "Last changed" is its last update time. Selecting a row shows the details, including the cloud dataset id with a Copy button; counts or dates the list did not include are then fetched with :func:`ndi.cloud.api.datasets.getDataset`. +"Published" is Yes when the dataset's ``isPublished`` flag is true and No +otherwise (an absent flag counts as unpublished). The "Include published" and +"Include unpublished" boxes show or hide those datasets; both start ticked, +and the status line says how many are shown out of how many there are. + "Sort by" orders the list by any column, either direction; Refresh reloads. OPEN hands the selected dataset to the ``open_fcn`` callback (the navigator @@ -44,7 +49,15 @@ __all__ = ["CloudDatasetBrowser", "COLUMN_NAMES"] #: The table's columns, in order; also the "Sort by" choices. -COLUMN_NAMES = ["Name", "Organization", "Documents", "Files", "Created", "Last changed"] +COLUMN_NAMES = [ + "Name", + "Organization", + "Documents", + "Files", + "Created", + "Last changed", + "Published", +] class CloudDatasetBrowser: @@ -60,6 +73,9 @@ def __init__( ): self.open_fcn = open_fcn self.entries: list[dict[str, Any]] = [] + self.all_entries: list[dict[str, Any]] = [] + self.include_published = True + self.include_unpublished = True self.organizations: list[dict[str, Any]] = [] self.selected_index: int | None = None self.sort_column = "Name" @@ -74,6 +90,8 @@ def __init__( self.delete_button: Any = None self.status_label: Any = None self.sort_dir_button: Any = None + self.published_checkbox: Any = None + self.unpublished_checkbox: Any = None if build: self.build(parent) if load: @@ -96,6 +114,17 @@ def to_count(value: Any) -> float: return math.nan return math.nan + @staticmethod + def to_flag(value: Any) -> bool: + """A true/false record field; absent or unreadable is False.""" + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return not math.isnan(value) and value != 0 + if isinstance(value, str): + return value.strip().lower() in ("true", "1", "yes") + return False + @staticmethod def entry_from_record(record: Any) -> dict[str, Any]: """One dataset record (from listDatasets or getDataset) -> entry.""" @@ -120,6 +149,7 @@ def f(names: list[str]) -> Any: "fileCount": CloudDatasetBrowser.to_count(f(["fileCount", "numberOfFiles"])), "createdAt": str(f(["createdAt", "created"]) or ""), "updatedAt": str(f(["updatedAt", "lastModified", "modifiedAt"]) or ""), + "isPublished": CloudDatasetBrowser.to_flag(f(["isPublished", "published"])), } if not entry["name"]: entry["name"] = entry["id"] @@ -148,8 +178,28 @@ def merge_entry(entry: dict[str, Any], full: dict[str, Any]) -> dict[str, Any]: for key in ("documentCount", "fileCount"): if math.isnan(out.get(key, math.nan)): out[key] = full.get(key, math.nan) + # An absent flag reads as False, so a True from either wins. + out["isPublished"] = bool(out.get("isPublished")) or bool(full.get("isPublished")) return out + @staticmethod + def filter_entries( + entries: list[dict[str, Any]], include_published: bool, include_unpublished: bool + ) -> list[dict[str, Any]]: + """Keep the published and/or unpublished ENTRIES (absent flag = unpublished).""" + return [ + e + for e in entries + if (include_published if e.get("isPublished") else include_unpublished) + ] + + @staticmethod + def count_status_text(n_shown: int, n_all: int) -> str: + """Status line: how many datasets are shown of how many.""" + if n_shown == n_all: + return f"{n_all} dataset(s)." + return f"{n_shown} of {n_all} dataset(s) shown." + @staticmethod def sort_entries( entries: list[dict[str, Any]], column: str, descending: bool = False @@ -164,6 +214,7 @@ def sort_entries( "Last changed": ("updatedAt", False), "Documents": ("documentCount", False), "Files": ("fileCount", False), + "Published": ("isPublished", False), } if column not in keys: raise ValueError(f"Unknown column {column!r}. Use one of: {', '.join(COLUMN_NAMES)}.") @@ -171,6 +222,8 @@ def sort_entries( def missing(e: dict[str, Any]) -> bool: v = e.get(field) + if isinstance(v, bool): + return False return v in (None, "") or (isinstance(v, float) and math.isnan(v)) known = [e for e in entries if not missing(e)] @@ -196,6 +249,7 @@ def entries_to_rows(entries: list[dict[str, Any]]) -> list[list[str]]: b.count_text(e["fileCount"]), b.date_text(e["createdAt"]), b.date_text(e["updatedAt"]), + b.yes_no_text(e.get("isPublished")), ] for e in entries ] @@ -214,6 +268,7 @@ def details_text(entry: dict[str, Any], is_group: bool) -> list[str]: f"Last changed: {b.date_text(entry['updatedAt'])}", f"Documents: {b.count_text(entry['documentCount'])}", f"Files: {b.count_text(entry['fileCount'])}", + f"Published: {b.yes_no_text(entry.get('isPublished'))}", ] @staticmethod @@ -226,6 +281,10 @@ def date_text(value: str) -> str: return f"{value[:10]} {value[11:16]} UTC" return value + @staticmethod + def yes_no_text(flag: Any) -> str: + return "Yes" if flag else "No" + @staticmethod def count_text(n: Any) -> str: if n is None or (isinstance(n, float) and math.isnan(n)): @@ -277,18 +336,41 @@ def is_group_organization(org: Mapping[str, Any] | None) -> bool: # model actions # ------------------------------------------------------------------ def set_entries(self, entries: list[dict[str, Any]]) -> None: - """Show ENTRIES, sorted by the current sort choice.""" - self.entries = self.sort_entries(entries, self.sort_column, self.sort_descending) + """Show ENTRIES, filtered and sorted by the current choices. + + ENTRIES is every listed dataset; the published/unpublished choices + decide which of them are shown. + """ + self.all_entries = list(entries) + shown = self.filter_entries( + self.all_entries, self.include_published, self.include_unpublished + ) + self.entries = self.sort_entries(shown, self.sort_column, self.sort_descending) self._redraw() self.select(None) def set_sort(self, column: str, descending: bool = False) -> None: self.sort_column = column self.sort_descending = bool(descending) - self.set_entries(self.entries) + self.set_entries(self.all_entries) if self.sort_dir_button is not None: self.sort_dir_button.setText("Descending" if descending else "Ascending") + def set_filter(self, include_published: bool, include_unpublished: bool) -> None: + """Choose whether published and unpublished datasets are shown.""" + self.include_published = bool(include_published) + self.include_unpublished = bool(include_unpublished) + for box, value in ( + (self.published_checkbox, self.include_published), + (self.unpublished_checkbox, self.include_unpublished), + ): + if box is not None and box.isChecked() != value: + box.blockSignals(True) + box.setChecked(value) + box.blockSignals(False) + self.set_entries(self.all_entries) + self._set_status(self.count_status_text(len(self.entries), len(self.all_entries))) + def refresh(self) -> None: """Reload the dataset list from NDI Cloud.""" self._set_status("Contacting NDI Cloud...") @@ -306,7 +388,7 @@ def refresh(self) -> None: except Exception: # noqa: BLE001 - only refines the group check self.organizations = [] self.set_entries(self.entries_from_list(answer)) - self._set_status(f"{len(self.entries)} dataset(s).") + self._set_status(self.count_status_text(len(self.entries), len(self.all_entries))) def organization_of(self, entry: dict[str, Any]) -> dict[str, Any]: for org in self.organizations: @@ -332,6 +414,10 @@ def fill_details(self, index: int) -> dict[str, Any]: pass entry["detailed"] = True self.entries[index] = entry + for k, e in enumerate(self.all_entries): + if e["id"] == entry["id"]: + self.all_entries[k] = entry + break self._redraw() return entry @@ -513,6 +599,22 @@ def build(self, parent: Any = None) -> Any: lambda: self.set_sort(self.sort_column, not self.sort_descending) ) sort_row.addWidget(self.sort_dir_button) + self.published_checkbox = QtWidgets.QCheckBox("Include published") + self.published_checkbox.setObjectName("ndiBrowserIncludePublished") + self.published_checkbox.setToolTip("Show datasets that are published on NDI Cloud") + self.published_checkbox.setChecked(self.include_published) + self.published_checkbox.toggled.connect( + lambda v: self.set_filter(v, self.include_unpublished) + ) + sort_row.addWidget(self.published_checkbox) + self.unpublished_checkbox = QtWidgets.QCheckBox("Include unpublished") + self.unpublished_checkbox.setObjectName("ndiBrowserIncludeUnpublished") + self.unpublished_checkbox.setToolTip("Show datasets that are not published on NDI Cloud") + self.unpublished_checkbox.setChecked(self.include_unpublished) + self.unpublished_checkbox.toggled.connect( + lambda v: self.set_filter(self.include_published, v) + ) + sort_row.addWidget(self.unpublished_checkbox) sort_row.addStretch(1) outer.addLayout(sort_row) diff --git a/src/ndi/gui/ndi_matlab_python_bridge.yaml b/src/ndi/gui/ndi_matlab_python_bridge.yaml index 207d3820..6d5287e0 100644 --- a/src/ndi/gui/ndi_matlab_python_bridge.yaml +++ b/src/ndi/gui/ndi_matlab_python_bridge.yaml @@ -938,7 +938,7 @@ ported_late: - name: cloudDatasetBrowser matlab_path: "+ndi/+gui/+nav/cloudDatasetBrowser.m" - matlab_last_sync_hash: "ffee1bc" + matlab_last_sync_hash: "3f56952" python_path: "ndi/gui/nav/cloud_dataset_browser.py" decision_log: > Browse, open and delete the user's NDI Cloud datasets @@ -950,6 +950,14 @@ ported_late: array; unknown counts are NaN as in MATLAB. delete_selected takes the confirmation as a callable for the same testability reason as CloudComparison.run_action. + 2026-11-18: NDI-matlab 3f56952 adds a Published (Yes/No) column from the + record's isPublished flag (absent -> unpublished), "Include published" + / "Include unpublished" checkboxes, and a "N of M dataset(s) shown." + status. Ported 1:1 in snake_case: filterEntries -> filter_entries, + countStatusText -> count_status_text, setFilter -> set_filter, + AllEntries -> all_entries, IncludePublished/IncludeUnpublished -> + include_published/include_unpublished, toFlag -> to_flag (public + static here; private in MATLAB), yesNoText -> yes_no_text. - name: cloudPane matlab_path: "+ndi/+gui/+nav/cloudPane.m" diff --git a/tests/test_gui_nav_cloud_dataset_browser.py b/tests/test_gui_nav_cloud_dataset_browser.py index bfd2df68..9d27cacb 100644 --- a/tests/test_gui_nav_cloud_dataset_browser.py +++ b/tests/test_gui_nav_cloud_dataset_browser.py @@ -131,6 +131,54 @@ def test_details_and_formatting(self): assert "group organization" in text +class TestPublished: + def _entries(self): + return B.entries_from_list( + [ + {"id": "p", "name": "pub", "isPublished": True}, + {"id": "u", "name": "unpub", "isPublished": False}, + {"id": "x", "name": "unknown"}, + ] + ) + + def test_is_published_is_read(self): + f = B.entry_from_record + assert f({"id": "d", "isPublished": True})["isPublished"] is True + assert f({"id": "d", "isPublished": False})["isPublished"] is False + assert f({"id": "d", "isPublished": "true"})["isPublished"] is True + assert f({"id": "d"})["isPublished"] is False # absent -> unpublished + m = B.merge_entry(f({"id": "d"}), f({"id": "d", "isPublished": True})) + assert m["isPublished"] is True + text = "\n".join(B.details_text(f({"id": "d", "isPublished": True}), False)) + assert "Published: Yes" in text + assert B.entries_to_rows([f({"id": "d"})])[0][COLUMN_NAMES.index("Published")] == "No" + + def test_filter_sort_and_status(self): + e = self._entries() + + def kept(p, u): + return [x["id"] for x in B.filter_entries(e, p, u)] + + assert kept(True, True) == ["p", "u", "x"] + assert kept(True, False) == ["p"] + assert kept(False, True) == ["u", "x"] + assert kept(False, False) == [] + assert [x["id"] for x in B.sort_entries(e, "Published", False)] == ["u", "x", "p"] + assert [x["id"] for x in B.sort_entries(e, "Published", True)] == ["p", "u", "x"] + assert B.count_status_text(3, 3) == "3 dataset(s)." + assert B.count_status_text(1, 3) == "1 of 3 dataset(s) shown." + + def test_set_filter_keeps_all_entries(self): + b = CloudDatasetBrowser(build=False) + b.set_entries(self._entries()) + b.set_filter(False, True) + assert [x["id"] for x in b.entries] == ["x", "u"] # by Name: unknown, unpub + b.set_sort("Name", True) # sorting keeps the filter + assert [x["id"] for x in b.entries] == ["u", "x"] + b.set_filter(True, True) + assert len(b.entries) == 3 + + class TestDeleteSelected: def _browser(self, monkeypatch, deleted): from ndi.cloud.api import datasets as datasets_api @@ -204,6 +252,27 @@ def test_selecting_a_row_shows_details_and_enables_delete(self, monkeypatch): assert b.delete_button.isEnabled() assert b.table.item(0, 2).text() == "7" # fetched by getDataset + def test_include_checkboxes_filter_the_table(self): + _qt_or_skip() + b = CloudDatasetBrowser(load=False) + b.set_entries( + B.entries_from_list( + [ + {"id": "p", "name": "a", "isPublished": True}, + {"id": "u", "name": "b", "isPublished": False}, + ] + ) + ) + assert b.table.columnCount() == len(COLUMN_NAMES) + assert b.table.item(0, COLUMN_NAMES.index("Published")).text() == "Yes" + assert b.published_checkbox.isChecked() and b.unpublished_checkbox.isChecked() + b.published_checkbox.setChecked(False) + assert b.table.rowCount() == 1 and b.table.item(0, 0).text() == "b" + assert "1 of 2" in b.status_label.text() + b.set_filter(True, False) + assert b.published_checkbox.isChecked() and not b.unpublished_checkbox.isChecked() + assert b.table.rowCount() == 1 and b.table.item(0, 0).text() == "a" + def test_sort_control_reorders(self): _qt_or_skip() b = CloudDatasetBrowser(load=False) From 80c365529a85ec47fc319b123bcfff0a994c1528 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:30:05 +0000 Subject: [PATCH 2/4] readngrid: read from file objects (sync NDI-matlab e3744121e) The "MATLAB/Python bridge completeness" check flagged readngrid as drifted: NDI-matlab e3744121e (VH-Lab/NDI-matlab#1229) made readngrid accept a did.file.fileobj as well as a path. Ported: - a did.file.Fileobj that is not open is opened 'rb' and closed after; - one already open, or any open binary file object (what database_openbinarydoc returns), is read from its current position and left open for its owner to close; - an object with only fullpathfilename (cloud CachedBinaryFile) is read by that path. From a file object only prod(data_size) elements are read, as MATLAB does. Bridge entry synced to e3744121e; five new tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011v7R5uS1zLb3Jzu5Vu23sb --- src/ndi/fun/data.py | 70 +++++++++++++++++++---- src/ndi/fun/ndi_matlab_python_bridge.yaml | 17 +++++- tests/test_fun_data_ngrid.py | 47 +++++++++++++++ 3 files changed, 121 insertions(+), 13 deletions(-) diff --git a/src/ndi/fun/data.py b/src/ndi/fun/data.py index 20d2b9be..7d9bb51a 100644 --- a/src/ndi/fun/data.py +++ b/src/ndi/fun/data.py @@ -33,17 +33,25 @@ def readngrid( - file_path: str | Path, + file_path: str | Path | Any, data_size: Sequence[int], data_type: str = "double", ) -> np.ndarray: - """Read n-dimensional binary matrix from file. + """Read n-dimensional binary matrix from a file path or a file object. MATLAB equivalent: ndi.fun.data.readngrid Args: - file_path: Path to the binary file. - data_size: Shape tuple, e.g. ``(100, 3)``. + file_path: Path to the binary file, OR a file object: a + :class:`did.file.Fileobj`, or an open binary file such as the one + ``ndi_session.database_openbinarydoc`` returns. A file object that + is already open is read from its current position and left open, + so the caller can close it (e.g. with ``database_closebinarydoc``). + A ``did.file.Fileobj`` that is not open yet is opened read-only + here and closed again after reading. An object that only carries + ``fullpathfilename`` (a cloud ``CachedBinaryFile``) is read by + that path. + data_size: Shape tuple, e.g. ``(100, 3)``; any number of dimensions. data_type: ndi_element type name (``'double'``, ``'int16'``, etc.). Returns: @@ -51,21 +59,22 @@ def readngrid( Raises: ValueError: If data type is unknown or data count mismatches. - FileNotFoundError: If file does not exist. + FileNotFoundError: If the file does not exist or cannot be opened. + TypeError: If ``file_path`` is neither a path nor a file object. """ dtype = _TYPE_MAP.get(data_type) if dtype is None: raise ValueError(f"Unknown data type: '{data_type}'") - p = Path(file_path) - if not p.exists(): - raise FileNotFoundError(f"File not found: {file_path}") - expected = 1 for d in data_size: expected *= d - raw = np.fromfile(str(p), dtype=dtype) + if isinstance(file_path, (str, Path)): + raw = _read_ngrid_path(Path(file_path), dtype) + else: + raw = _read_ngrid_fileobj(file_path, expected, dtype) + if raw.size != expected: raise ValueError(f"ndi_gui_Data count mismatch: expected {expected}, got {raw.size}") # MATLAB's fread/fwrite serialise column-major; readngrid must match so @@ -73,6 +82,47 @@ def readngrid( return raw.reshape(data_size, order="F") +def _read_ngrid_path(p: Path, dtype: np.dtype) -> np.ndarray: + """Every element in the file at P.""" + if not p.exists(): + raise FileNotFoundError(f"File not found: {p}") + return np.fromfile(str(p), dtype=dtype) + + +def _read_ngrid_fileobj(fobj: Any, count: int, dtype: np.dtype) -> np.ndarray: + """COUNT elements from a file object (see :func:`readngrid`). + + MATLAB (readFromFileObj) reads an already-open object as it is and leaves + it open for its owner; reopening would close the caller's handle first. + """ + from did.file import Fileobj + + nbytes = count * dtype.itemsize + if isinstance(fobj, Fileobj): + opened_here = False + if fobj.fid is None: + fobj.fopen("rb") + if fobj.fid is None: + raise FileNotFoundError( + f"Could not open file '{fobj.fullpathfilename}' for reading. " + "Ensure the path is correct and the file exists." + ) + opened_here = True + try: + data = fobj.fid.read(nbytes) + finally: + if opened_here: + fobj.fclose() + elif callable(getattr(fobj, "read", None)): + data = fobj.read(nbytes) + elif getattr(fobj, "fullpathfilename", None): + return _read_ngrid_path(Path(fobj.fullpathfilename), dtype) + else: + raise TypeError(f"readngrid needs a file path or a file object, not {type(fobj).__name__}.") + usable = len(data) - len(data) % dtype.itemsize + return np.frombuffer(data[:usable], dtype=dtype).copy() + + def writengrid( data: np.ndarray, file_path: str | Path, diff --git a/src/ndi/fun/ndi_matlab_python_bridge.yaml b/src/ndi/fun/ndi_matlab_python_bridge.yaml index c4ee940b..8b581a0e 100644 --- a/src/ndi/fun/ndi_matlab_python_bridge.yaml +++ b/src/ndi/fun/ndi_matlab_python_bridge.yaml @@ -178,12 +178,12 @@ functions: - name: readngrid type: function matlab_path: "+ndi/+fun/+data/readngrid.m" - matlab_last_sync_hash: "b33d8ce64" + matlab_last_sync_hash: "e3744121e" python_path: "ndi/fun/data.py" input_arguments: - name: file_path - type_matlab: "char (fileName_or_fileObj)" - type_python: "str | Path" + type_matlab: "char | string | did.file.fileobj (fileName_or_fileObj)" + type_python: "str | Path | did.file.Fileobj | binary file object" - name: data_size type_matlab: "double (vector)" type_python: "Sequence[int]" @@ -216,6 +216,17 @@ functions: byte is not something to infer without a MATLAB to test against; recorded here for whoever has one. + 2026-11-18: synced to NDI-matlab e3744121e (VH-Lab/NDI-matlab#1229), + which accepts a did.file.fileobj as well as a path and reads N-D sizes + by element count then reshapes. Ported: a did.file.Fileobj that is not + open is opened 'rb' and closed after; one already open, or any open + binary file object (what ndi_session.database_openbinarydoc returns), + is read from its current position and left open. An object carrying + only fullpathfilename (cloud CachedBinaryFile) is read by that path. + From a file object only prod(data_size) elements are read, as MATLAB + does; a path still reads the whole file, so a file with extra elements + is refused there (the existing mismatch divergence above). + - name: writengrid type: function matlab_path: "+ndi/+fun/+data/writengrid.m" diff --git a/tests/test_fun_data_ngrid.py b/tests/test_fun_data_ngrid.py index 8ee02116..fe8757d4 100644 --- a/tests/test_fun_data_ngrid.py +++ b/tests/test_fun_data_ngrid.py @@ -101,6 +101,53 @@ def test_a_size_mismatch_is_refused(self, tmp_path): with pytest.raises(ValueError, match="mismatch"): readngrid(f, (5,), "double") + def test_a_did_fileobj_not_yet_open_is_opened_and_closed(self, tmp_path): + """MATLAB counterpart: readngrid's readFromFileObj (NDI-matlab e3744121).""" + from did.file import Fileobj + + data = np.arange(24, dtype=" Date: Wed, 18 Nov 2026 16:32:08 +0000 Subject: [PATCH 3/4] List NDIcalc's speed_tuning_bootstrap as failing ngrid's blank template test_definitions_validate_or_are_listed failed on CI: vision/speed_tuning_bootstrap: DID:Database:ValidationFieldInteger NDIcalc-vis-matlab 93a1fe7 (VH-Lab/NDIcalc-vis-matlab#109, merged 2026-11-13, after main's last green run) made the definition inherit ngrid, whose blank template fails with that identifier (data/ngrid and neuro/reverse_correlation are listed for the same reason). Record it in KNOWN_UNVALIDATABLE_FROM_DEPENDENCIES; the gate still fails if the identifier changes or upstream fixes it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011v7R5uS1zLb3Jzu5Vu23sb --- tests/test_did_integration.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_did_integration.py b/tests/test_did_integration.py index 75a90380..7e525911 100644 --- a/tests/test_did_integration.py +++ b/tests/test_did_integration.py @@ -246,6 +246,10 @@ def test_a_document_that_lies_about_its_class_is_rejected(self): # Inherits ngrid, which its schema omits. "neuro/hartley_reverse_correlation": "DID:Database:ValidationSuperClasses", "neuro/reverse_correlation": "DID:Database:ValidationFieldInteger", + # NDIcalc-vis-matlab 93a1fe7 (merged in VH-Lab/NDIcalc-vis-matlab#109, + # 2026-11-13) made it inherit ngrid to store every bootstrap fit; it + # fails with ngrid's own blank-template error (data/ngrid, above). + "vision/speed_tuning_bootstrap": "DID:Database:ValidationFieldInteger", } #: Files that are not valid JSON and cannot be fixed from this repository. From bd922321bb2b2f7a7ec7d4e1fd574eccbef761db Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:57:27 +0000 Subject: [PATCH 4/4] Navigator: NDI Cloud login indicator in the NDI Cloud pane Follows NDI-matlab 579176c88. The NDI Cloud pane's header gains a small indicator button, left of the reload button: green (check) when NDI_CLOUD_TOKEN holds an unexpired token, yellow (circle) when the current or default profile has an email and stored password (or NDI_CLOUD_USERNAME/NDI_CLOUD_PASSWORD are set), red (cross) when nothing is configured. Hovering explains the state; clicking opens the profile editor. A QTimer parented to the indicator re-checks every 30 s; the state is also re-read when the editor closes, after logout and on refresh. New: describe_login, login_status, duration_text, update_login_indicator; cloud_colors gains alert_red/alertRed. Bridge entries cloudPane and cloudColors synced to 579176c88; CHANGELOG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011v7R5uS1zLb3Jzu5Vu23sb --- CHANGELOG.md | 8 + src/ndi/gui/cloud_colors.py | 7 + src/ndi/gui/nav/cloud_pane.py | 253 +++++++++++++++++++++- src/ndi/gui/ndi_matlab_python_bridge.yaml | 18 +- tests/test_gui_nav_cloud_pane.py | 178 ++++++++++++++- tests/test_gui_nav_pane.py | 2 + tests/test_matlab_name_aliases.py | 1 + 7 files changed, 456 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02dc590c..145f835e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **Navigator: NDI Cloud login indicator** (`ndi.gui.nav.cloud_pane`, MATLAB + VH-Lab/NDI-matlab@579176c88). The NDI Cloud pane gains a small button that is + green when logged in (an unexpired `NDI_CLOUD_TOKEN`), yellow when a profile + with a stored password (or `NDI_CLOUD_USERNAME`/`NDI_CLOUD_PASSWORD`) is ready + to log in, and red when nothing is configured. Hovering explains the state; + clicking opens the profile editor. It re-checks every 30 seconds. + `cloud_colors` gains `alert_red`. + - **Navigator: filter the cloud dataset browser by published state** (`ndi.gui.nav.cloud_dataset_browser`, MATLAB VH-Lab/NDI-matlab@3f56952). The "Browse my Cloud datasets..." window gains a Published (Yes/No) column, read diff --git a/src/ndi/gui/cloud_colors.py b/src/ndi/gui/cloud_colors.py index aac1b91d..19c3107f 100644 --- a/src/ndi/gui/cloud_colors.py +++ b/src/ndi/gui/cloud_colors.py @@ -44,6 +44,9 @@ class CloudColors(NamedTuple): warn_amber: tuple[float, float, float] = (0.9020, 0.6235, 0.1294) #: #8C949E status: not yet / absent (e.g. an un-ingested on-disk session). neutral_grey: tuple[float, float, float] = (0.5490, 0.5804, 0.6196) + #: #CC2626 status: not working / needs setting up (e.g. the navigator's + #: NDI Cloud login indicator when no login is configured). + alert_red: tuple[float, float, float] = (0.8000, 0.1500, 0.1500) # MATLAB-cased aliases, so code written against either convention reads # naturally -- the same dual-naming used across this port. @@ -71,6 +74,10 @@ def warnAmber(self) -> tuple[float, float, float]: # noqa: N802 def neutralGrey(self) -> tuple[float, float, float]: # noqa: N802 return self.neutral_grey + @property + def alertRed(self) -> tuple[float, float, float]: # noqa: N802 + return self.alert_red + _PALETTE = CloudColors() diff --git a/src/ndi/gui/nav/cloud_pane.py b/src/ndi/gui/nav/cloud_pane.py index 8e15549b..701bb307 100644 --- a/src/ndi/gui/nav/cloud_pane.py +++ b/src/ndi/gui/nav/cloud_pane.py @@ -2,8 +2,24 @@ MATLAB counterpart: ``src/ndi/+ndi/+gui/+nav/cloudPane.m`` -A single-row pane with three controls on the right: - +A single-row pane with four controls on the right: + + * a login indicator: a small coloured button saying whether NDI Cloud + access is set up (see :meth:`CloudPane.login_status`): + + - green (check mark): logged in -- ``NDI_CLOUD_TOKEN`` holds a token + that has not expired; + - yellow (circle): ready to log in -- not logged in, but the current + (else default) profile has an email and a stored password, or + ``NDI_CLOUD_USERNAME`` / ``NDI_CLOUD_PASSWORD`` are both set, so the + next NDI Cloud action signs in; + - red (cross): not configured -- no token and nothing to log in with + (no profile, or a profile without a stored password). + + Hovering says which, and for whom; clicking opens the profile editor. + It is re-read every ``LOGIN_REFRESH_SECONDS`` (a token can expire while + the navigator is open), when the profile editor closes, after the + reload button logs out, and on every pane refresh; * a reload button that clears the current NDI Cloud login, so the next cloud action re-authenticates with the default profile. This is the quick recovery when a token has expired and a stale login is otherwise @@ -23,13 +39,18 @@ from __future__ import annotations +import os +from collections.abc import Mapping from typing import Any +from ..cloud_colors import cloud_colors, rgb_to_hex from .datasets_text import cloud_summary_message from .pane import RELOAD_GLYPH, NavPane, reload_icon_file # noqa: F401 - re-exported __all__ = [ "CloudPane", + "LOGIN_WIDTH", + "LOGIN_REFRESH_SECONDS", "RELOAD_WIDTH", "CHECK_WIDTH", "PROFILE_WIDTH", @@ -37,11 +58,20 @@ "reload_icon_file", ] +LOGIN_WIDTH = 26 RELOAD_WIDTH = 26 CHECK_WIDTH = 26 PROFILE_WIDTH = 62 BUTTON_SPACING = 4 +#: How often the login indicator re-reads its state, in seconds. +LOGIN_REFRESH_SECONDS = 30 + +#: Glyphs drawn on the login indicator, so the state does not rest on colour. +LOGIN_GLYPHS = {"loggedin": "\u2713", "ready": "\u25cb", "notconfigured": "\u2715"} + +_CLICK = "Click to view or edit your NDI Cloud profiles." + LOGOUT_MESSAGE = ( "Cleared the current NDI Cloud login. The next NDI Cloud action will " @@ -52,10 +82,13 @@ class CloudPane(NavPane): - """The "NDI Cloud" pane: refresh login, check all, profile.""" + """The "NDI Cloud" pane: login indicator, refresh login, check all, profile.""" def __init__(self, navigator: Any = None): super().__init__(navigator, title="NDI Cloud", collapsible=False) + self.login_indicator: Any = None + self.login_state = "" + self.login_timer: Any = None self.reload_button: Any = None self.check_button: Any = None self.profile_button: Any = None @@ -63,14 +96,195 @@ def __init__(self, navigator: Any = None): self.profile_editor: Any = None def right_width(self) -> float: - """reload (26) + 4 + C (26) + 4 + Profile (62).""" - return RELOAD_WIDTH + BUTTON_SPACING + CHECK_WIDTH + BUTTON_SPACING + PROFILE_WIDTH + """login (26) + 4 + reload (26) + 4 + C (26) + 4 + Profile (62).""" + return ( + LOGIN_WIDTH + + BUTTON_SPACING + + RELOAD_WIDTH + + BUTTON_SPACING + + CHECK_WIDTH + + BUTTON_SPACING + + PROFILE_WIDTH + ) + + # ------------------------------------------------------------------ + # the login indicator -- no Qt + # ------------------------------------------------------------------ + @staticmethod + def duration_text(secs: float) -> str: + """A rough, readable length of time (``'about 3 hours'``).""" + secs = abs(float(secs)) + if secs < 90: + return "less than 2 minutes" + if secs < 90 * 60: + return f"{round(secs / 60)} minutes" + if secs < 36 * 3600: + return f"about {round(secs / 3600)} hours" + return f"about {round(secs / 86400)} days" + + @staticmethod + def describe_login( + seconds_left: float | None, + user_name: str = "", + profile: Any = None, + has_password: bool = False, + env_credentials: bool = False, + ) -> dict[str, Any]: + """Decide the login indicator's state and hover text. + + MATLAB counterpart: ``cloudPane.describeLogin``. Returns a dict with + ``state`` (``'loggedin'``, ``'ready'`` or ``'notconfigured'``), + ``color`` (a palette triplet), ``glyph`` and ``tooltip``. + + SECONDS_LEFT is the token's remaining life (None when there is no + readable token; <= 0 when it has expired). USER_NAME names the account + the token or the environment variables are for. PROFILE is the + current-or-default profile (a ``ProfileEntry`` or a mapping with + ``Nickname`` and ``Email``), or None. HAS_PASSWORD says whether it has + a stored password; ENV_CREDENTIALS whether ``NDI_CLOUD_USERNAME`` and + ``NDI_CLOUD_PASSWORD`` are both set. + """ + c = cloud_colors() + user_name = str(user_name or "") + + def field(name: str) -> str: + if profile is None: + return "" + if isinstance(profile, Mapping): + return str(profile.get(name) or "") + return str(getattr(profile, name, "") or "") + + has_profile = profile is not None + email, nickname = field("Email"), field("Nickname") + expired = "" + if seconds_left is not None and seconds_left <= 0: + expired = f" (The last login expired {CloudPane.duration_text(-seconds_left)} ago.)" + + def status(state: str, color: Any, tooltip: str) -> dict[str, Any]: + return { + "state": state, + "color": color, + "glyph": LOGIN_GLYPHS[state], + "tooltip": tooltip, + } + + if seconds_left is not None and seconds_left > 0: + as_whom = f" as {user_name}" if user_name else "" + return status( + "loggedin", + c.ok_green, + f"Logged in to NDI Cloud{as_whom}. The login expires in " + f"{CloudPane.duration_text(seconds_left)}. {_CLICK}", + ) + if has_profile and email and has_password: + return status( + "ready", + c.warn_amber, + f'Ready to log in to NDI Cloud as {email} (profile "{nickname}"). ' + f"Not logged in yet: the next NDI Cloud action signs in.{expired} {_CLICK}", + ) + if env_credentials: + return status( + "ready", + c.warn_amber, + f"Ready to log in to NDI Cloud as {user_name} (from the " + "NDI_CLOUD_USERNAME and NDI_CLOUD_PASSWORD environment variables). " + f"Not logged in yet: the next NDI Cloud action signs in.{expired} {_CLICK}", + ) + if has_profile: + return status( + "notconfigured", + c.alert_red, + f'NDI Cloud login is not set up: profile "{nickname}" has no stored ' + f"email and password.{expired} Click to open the profile editor and " + "set its password.", + ) + return status( + "notconfigured", + c.alert_red, + f"NDI Cloud login is not set up: there is no NDI Cloud profile.{expired} " + "Click to open the profile editor and add one with your NDI Cloud email " + "and password.", + ) + + @staticmethod + def login_status() -> dict[str, Any]: + """The NDI Cloud login state, read from this process. + + MATLAB counterpart: ``cloudPane.loginStatus``. Gathers the + ``NDI_CLOUD_TOKEN`` token's remaining life, the current (else default) + profile and whether it has a stored password, and the + ``NDI_CLOUD_USERNAME`` / ``NDI_CLOUD_PASSWORD`` variables, and passes + them to :meth:`describe_login`. Never raises: anything it cannot read + counts as absent. + """ + user_name = os.environ.get("NDI_CLOUD_USERNAME", "") + token = os.environ.get("NDI_CLOUD_TOKEN", "") + seconds_left = None + if token: + try: + from ...cloud.auth import decodeJwt, tokenSecondsRemaining + + seconds_left = tokenSecondsRemaining(token) + if not user_name: + user_name = str(decodeJwt(token).get("email") or "") + except Exception: # noqa: BLE001 - an unreadable token is no login + pass + + entry = None + has_password = False + try: + from ...cloud import profile + + entry = profile.get_current() or profile.get_default() + if entry is not None: + has_password = bool(profile.get_password(entry.UID)) + except Exception: # noqa: BLE001 - see docstring + has_password = False + + env_credentials = bool( + os.environ.get("NDI_CLOUD_USERNAME") and os.environ.get("NDI_CLOUD_PASSWORD") + ) + return CloudPane.describe_login( + seconds_left, user_name, entry, has_password, env_credentials + ) + + def refresh(self) -> None: + """Re-read the NDI Cloud login state into the indicator.""" + self.update_login_indicator() + + def update_login_indicator(self) -> dict[str, Any]: + """Show the current login state on the indicator, and return it.""" + status = self.login_status() + self.login_state = status["state"] + btn = self.login_indicator + if btn is not None: + c = cloud_colors() + btn.setText(status["glyph"]) + btn.setToolTip(status["tooltip"]) + btn.setStyleSheet( + f"background-color: {rgb_to_hex(status['color'])}; " + f"color: {rgb_to_hex(c.white)}; font-weight: bold;" + ) + return status # ------------------------------------------------------------------ # Qt # ------------------------------------------------------------------ def build_header_right(self, layout: Any) -> None: - from PySide6 import QtWidgets + from PySide6 import QtCore, QtWidgets + + self.login_indicator = QtWidgets.QPushButton() + self.login_indicator.setObjectName("ndiNavigatorCloudLoginIndicator") + self.login_indicator.setFixedWidth(LOGIN_WIDTH) + self.login_indicator.clicked.connect(self.open_profile_editor) + layout.addWidget(self.login_indicator) + self.update_login_indicator() + # Parented to the indicator, so it goes when the navigator does. + self.login_timer = QtCore.QTimer(self.login_indicator) + self.login_timer.setInterval(LOGIN_REFRESH_SECONDS * 1000) + self.login_timer.timeout.connect(self._on_login_timer) + self.login_timer.start() self.reload_button = self.refresh_button( "Refresh NDI Cloud login (logout)", self.refresh_login @@ -142,6 +356,7 @@ def refresh_login(self) -> bool: except Exception as exc: # noqa: BLE001 self._alert(str(exc), title, success=False) return False + self.update_login_indicator() self._alert(LOGOUT_MESSAGE, title, success=True) return True @@ -159,6 +374,7 @@ def open_profile_editor(self) -> Any: try: if self.profile_editor is None or self.profile_editor.figure is None: self.profile_editor = ProfileEditor() + self._watch_editor_close(self.profile_editor.figure) else: self.profile_editor.refresh() self.profile_editor.show() @@ -170,6 +386,31 @@ def open_profile_editor(self) -> Any: # ------------------------------------------------------------------ # helpers # ------------------------------------------------------------------ + def _on_login_timer(self) -> None: + try: + self.update_login_indicator() + except Exception: # noqa: BLE001 - a failed read must not stop the timer + pass + + def _watch_editor_close(self, figure: Any) -> None: + """Re-read the login state when the profile editor window closes.""" + if figure is None: + return + try: + from PySide6 import QtCore + except ImportError: + return + pane = self + + class _CloseWatcher(QtCore.QObject): + def eventFilter(self, obj: Any, event: Any) -> bool: # noqa: N802 - Qt API + if event.type() == QtCore.QEvent.Type.Close: + pane._on_login_timer() + return False + + watcher = _CloseWatcher(figure) + figure.installEventFilter(watcher) + def _datasets_pane(self) -> Any | None: if self.navigator is None: return None diff --git a/src/ndi/gui/ndi_matlab_python_bridge.yaml b/src/ndi/gui/ndi_matlab_python_bridge.yaml index 6d5287e0..0f62b601 100644 --- a/src/ndi/gui/ndi_matlab_python_bridge.yaml +++ b/src/ndi/gui/ndi_matlab_python_bridge.yaml @@ -961,7 +961,7 @@ ported_late: - name: cloudPane matlab_path: "+ndi/+gui/+nav/cloudPane.m" - matlab_last_sync_hash: "666a0ddfa" + matlab_last_sync_hash: "579176c88" python_path: "ndi/gui/nav/cloud_pane.py" decision_log: > Cloud status and actions pane. Ported in #112. NDI-matlab 293ec411 (VH-Lab/NDI-matlab#1037) @@ -973,6 +973,18 @@ ported_late: follow. 2026-11-12: NDI-matlab 666a0ddfa: the reload button is built by the shared pane.refreshButton; same icon and tooltip. + 2026-11-20: NDI-matlab 579176c88 adds the NDI Cloud login indicator + (green logged in / yellow ready to log in / red not configured, with + hover text; a click opens the profile editor). Ported 1:1 in + snake_case: describeLogin -> describe_login, loginStatus -> + login_status, durationText -> duration_text, updateLoginIndicator -> + update_login_indicator, LoginIndicator/LoginState/LoginTimer -> + login_indicator/login_state/login_timer, LoginRefreshSeconds -> module + constant LOGIN_REFRESH_SECONDS. describe_login returns a dict rather + than a struct and accepts a ProfileEntry or a mapping. MATLAB's timer + is a QTimer parented to the indicator (it goes with the navigator); + MATLAB re-reads on the editor figure's ObjectBeingDestroyed, Python on + the editor window's Close event (the window is hidden, not destroyed). - name: progressPane matlab_path: "+ndi/+gui/+nav/progressPane.m" @@ -1100,7 +1112,7 @@ ported_late: - name: cloudColors matlab_path: "+ndi/+gui/cloudColors.m" - matlab_last_sync_hash: "b9ccf47b" + matlab_last_sync_hash: "579176c88" python_path: "ndi/gui/cloud_colors.py" python_class: "CloudColors" decision_log: > @@ -1109,6 +1121,8 @@ ported_late: NamedTuple's snake_case fields, so both spellings already resolve and an alias would be a third name for one value. That exemption is itself tested, in TestCloudColorsIsExemptForAReason. + 2026-11-20: NDI-matlab 579176c88 adds alertRed (#CC2626) for the login + indicator; mirrored as alert_red with an alertRed property. - name: jrclust matlab_path: "+ndi/+gui/+app/jrclust.m" diff --git a/tests/test_gui_nav_cloud_pane.py b/tests/test_gui_nav_cloud_pane.py index e2d53663..adc703cc 100644 --- a/tests/test_gui_nav_cloud_pane.py +++ b/tests/test_gui_nav_cloud_pane.py @@ -16,6 +16,7 @@ from ndi.gui.nav.cloud_pane import ( BUTTON_SPACING, CHECK_WIDTH, + LOGIN_WIDTH, LOGOUT_MESSAGE, NO_DATASETS_PANE, PROFILE_WIDTH, @@ -69,9 +70,17 @@ def test_it_is_not_elastic(self): assert not nav_layout.is_elastic(CloudPane()) def test_right_width_matches_matlabs_arithmetic(self): - """26 (reload) + 4 + 26 (C) + 4 + 62 (Profile) = 122.""" - assert CloudPane().right_width() == 122 - assert (RELOAD_WIDTH + BUTTON_SPACING + CHECK_WIDTH + BUTTON_SPACING + PROFILE_WIDTH) == 122 + """26 (login) + 4 + 26 (reload) + 4 + 26 (C) + 4 + 62 (Profile) = 152.""" + assert CloudPane().right_width() == 152 + assert ( + LOGIN_WIDTH + + BUTTON_SPACING + + RELOAD_WIDTH + + BUTTON_SPACING + + CHECK_WIDTH + + BUTTON_SPACING + + PROFILE_WIDTH + ) == 152 def test_it_has_no_body(self): assert CloudPane().has_body() is False @@ -93,6 +102,142 @@ def test_it_is_byte_identical_to_matlabs(self): assert reload_icon_file().read_bytes() == matlab.read_bytes() +class TestLoginIndicatorDecision: + """MATLAB counterpart: TestCloudPane's describeLogin tests.""" + + PROFILE = {"UID": "u1", "Nickname": "Lab", "Email": "me@lab.org"} + + def test_green_when_the_token_is_valid(self): + from ndi.gui.cloud_colors import cloud_colors + + s = CloudPane.describe_login(3 * 3600, "me@lab.org") + assert s["state"] == "loggedin" + assert s["color"] == cloud_colors().ok_green + assert "Logged in to NDI Cloud as me@lab.org" in s["tooltip"] + assert "about 3 hours" in s["tooltip"] + + def test_yellow_with_a_ready_profile_or_environment(self): + from ndi.gui.cloud_colors import cloud_colors + + s = CloudPane.describe_login(None, "", self.PROFILE, True) + assert s["state"] == "ready" + assert s["color"] == cloud_colors().warn_amber + assert 'me@lab.org (profile "Lab")' in s["tooltip"] + # An expired token falls back to the profile, and says so. + s = CloudPane.describe_login(-600, "", self.PROFILE, True) + assert s["state"] == "ready" + assert "expired 10 minutes ago" in s["tooltip"] + s = CloudPane.describe_login(None, "env@lab.org", None, False, True) + assert s["state"] == "ready" and "env@lab.org" in s["tooltip"] + + def test_red_when_not_configured(self): + from ndi.cloud.profile import ProfileEntry + from ndi.gui.cloud_colors import cloud_colors + + s = CloudPane.describe_login(None) + assert s["state"] == "notconfigured" + assert s["color"] == cloud_colors().alert_red + assert "there is no NDI Cloud profile" in s["tooltip"] + # A profile without a stored password cannot log in (ProfileEntry too). + entry = ProfileEntry(UID="u1", Nickname="Lab", Email="me@lab.org") + s = CloudPane.describe_login(None, "", entry, False) + assert s["state"] == "notconfigured" and 'profile "Lab"' in s["tooltip"] + + def test_the_three_states_have_distinct_glyphs(self): + glyphs = { + CloudPane.describe_login(60)["glyph"], + CloudPane.describe_login(None, "", self.PROFILE, True)["glyph"], + CloudPane.describe_login(None)["glyph"], + } + assert len(glyphs) == 3 + + def test_duration_text(self): + f = CloudPane.duration_text + assert f(30) == "less than 2 minutes" + assert f(600) == "10 minutes" + assert f(-600) == "10 minutes" + assert f(5 * 3600) == "about 5 hours" + assert f(3 * 86400) == "about 3 days" + + +class TestLoginStatusReadsTheSession: + def _jwt(self, exp, email="tok@lab.org"): + import base64 + import json + + def b64(d): + return base64.urlsafe_b64encode(json.dumps(d).encode()).decode().rstrip("=") + + return f"{b64({'alg': 'none'})}.{b64({'exp': exp, 'email': email})}.sig" + + def _no_profile(self, monkeypatch): + from ndi.cloud import profile + + monkeypatch.setattr(profile, "get_current", lambda: None) + monkeypatch.setattr(profile, "get_default", lambda: None) + + def test_a_valid_token_is_green_and_names_its_user(self, monkeypatch): + import time + + self._no_profile(monkeypatch) + monkeypatch.delenv("NDI_CLOUD_USERNAME", raising=False) + monkeypatch.setenv("NDI_CLOUD_TOKEN", self._jwt(time.time() + 7200)) + s = CloudPane.login_status() + assert s["state"] == "loggedin" and "tok@lab.org" in s["tooltip"] + + def test_an_expired_token_with_nothing_else_is_red(self, monkeypatch): + import time + + self._no_profile(monkeypatch) + for var in ("NDI_CLOUD_USERNAME", "NDI_CLOUD_PASSWORD"): + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("NDI_CLOUD_TOKEN", self._jwt(time.time() - 60)) + assert CloudPane.login_status()["state"] == "notconfigured" + + def test_a_garbage_token_is_not_a_login(self, monkeypatch): + self._no_profile(monkeypatch) + for var in ("NDI_CLOUD_USERNAME", "NDI_CLOUD_PASSWORD"): + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("NDI_CLOUD_TOKEN", "not-a-jwt") + assert CloudPane.login_status()["state"] == "notconfigured" + + def test_a_profile_with_a_password_is_yellow(self, monkeypatch): + from ndi.cloud import profile + from ndi.cloud.profile import ProfileEntry + + entry = ProfileEntry(UID="u1", Nickname="Lab", Email="me@lab.org") + monkeypatch.setattr(profile, "get_current", lambda: None) + monkeypatch.setattr(profile, "get_default", lambda: entry) + monkeypatch.setattr(profile, "get_password", lambda uid: "pw") + monkeypatch.delenv("NDI_CLOUD_TOKEN", raising=False) + assert CloudPane.login_status()["state"] == "ready" + + def test_an_unreadable_secret_counts_as_no_password(self, monkeypatch): + from ndi.cloud import profile + from ndi.cloud.profile import ProfileEntry + + def boom(uid): + raise RuntimeError("cannot decrypt") + + entry = ProfileEntry(UID="u1", Nickname="Lab", Email="me@lab.org") + monkeypatch.setattr(profile, "get_current", lambda: entry) + monkeypatch.setattr(profile, "get_password", boom) + for var in ("NDI_CLOUD_TOKEN", "NDI_CLOUD_USERNAME", "NDI_CLOUD_PASSWORD"): + monkeypatch.delenv(var, raising=False) + assert CloudPane.login_status()["state"] == "notconfigured" + + def test_logout_updates_the_state(self, monkeypatch): + from ndi.cloud import auth + + self._no_profile(monkeypatch) + monkeypatch.setattr(auth, "logout", lambda *a, **k: None) + for var in ("NDI_CLOUD_TOKEN", "NDI_CLOUD_USERNAME", "NDI_CLOUD_PASSWORD"): + monkeypatch.delenv(var, raising=False) + pane = CloudPane(RecordingNavigator()) + pane.refresh_login() + assert pane.login_state == "notconfigured" + + class TestCheckAllCloud: def test_it_reports_the_summary(self): pane = CloudPane(RecordingNavigator(FakeDatasetsPane())) @@ -219,6 +364,33 @@ def test_the_three_buttons_are_built_at_matlabs_widths(self): assert pane.profile_button.text() == "Profile" assert pane.profile_button.width() == PROFILE_WIDTH + def test_the_login_indicator_is_built_coloured_and_timed(self, monkeypatch): + _qt_or_skip() + from ndi.gui.navigator import Navigator + + pane = Navigator().panes[1] + btn = pane.login_indicator + expected = CloudPane.login_status() + assert btn.width() == LOGIN_WIDTH + assert btn.objectName() == "ndiNavigatorCloudLoginIndicator" + assert btn.text() == expected["glyph"] + assert btn.toolTip() == expected["tooltip"] + assert pane.login_timer.isActive() + # Clicking opens the profile editor. + from ndi.gui import profile_editor as pe + + opened = [] + + class FakeEditor: + figure = None + + def show(self): + opened.append(True) + + monkeypatch.setattr(pe, "ProfileEditor", FakeEditor) + btn.click() + assert opened == [True] + def test_the_reload_button_carries_the_icon_not_the_fallback_glyph(self): """The glyph is only for a Qt build with no SVG support; if it shows up here the icon silently failed to load.""" diff --git a/tests/test_gui_nav_pane.py b/tests/test_gui_nav_pane.py index c2ba763e..00c12e74 100644 --- a/tests/test_gui_nav_pane.py +++ b/tests/test_gui_nav_pane.py @@ -54,6 +54,7 @@ def test_channels_are_zero_to_one(self): ("ok_green", "#2e9e47"), ("warn_amber", "#e69f21"), ("neutral_grey", "#8c949e"), + ("alert_red", "#cc2626"), ("white", "#ffffff"), ], ) @@ -80,6 +81,7 @@ def test_matlab_cased_aliases_agree(self): assert c.okGreen == c.ok_green assert c.warnAmber == c.warn_amber assert c.neutralGrey == c.neutral_grey + assert c.alertRed == c.alert_red assert cloudColors is cloud_colors def test_palette_is_a_singleton(self): diff --git a/tests/test_matlab_name_aliases.py b/tests/test_matlab_name_aliases.py index 751959ad..4cf2e719 100644 --- a/tests/test_matlab_name_aliases.py +++ b/tests/test_matlab_name_aliases.py @@ -285,6 +285,7 @@ class TestCloudColorsIsExemptForAReason: ("okGreen", "ok_green"), ("warnAmber", "warn_amber"), ("neutralGrey", "neutral_grey"), + ("alertRed", "alert_red"), ], ) def test_both_spellings_resolve_to_the_same_value(self, camel, snake):