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
2 changes: 2 additions & 0 deletions .github/workflows/desktop-builds.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ on:
- "packaging/desktop/**"
- "scripts/desktop/**"
- "eagleplot/utils/runtime.py"
- "eagleplot/utils/host_folders.py"
- "eagleplot/pages/1_Data_Upload.py"
- ".github/workflows/desktop-builds.yml"
workflow_dispatch:

Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
install and no network. Installers are built for every release and need no admin
rights. Settings are kept between sessions. Links open in your web browser. They are
not code-signed yet: the first launch shows a warning (see `packaging/desktop/README.md`).
Loading whole folders is not available in the desktop app yet.
Data Upload → Batch Import reads folders on your computer: type the folder's path as
usual (`C:\Users\you\data`, `~/data`).

### Changed

Expand Down
7 changes: 5 additions & 2 deletions eagleplot/pages/1_Data_Upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
from eagleplot.batch import scan_directory, batch_load_files # noqa: E402
from eagleplot.io import downsample_for_preview # noqa: E402
from eagleplot.utils.access import folder_loading_allowed_here # noqa: E402
from eagleplot.utils.host_folders import local_folder # noqa: E402
from eagleplot.utils.runtime import capabilities, missing_package_message # noqa: E402

_LARGE_FILE_BYTES = 50 * 1024 * 1024 # 50 MB — warn above this
Expand Down Expand Up @@ -351,7 +352,9 @@ def _load_example_cached(path: str):
try:
_exts = _batch_exts if _batch_exts else None
_pat = _batch_pattern.strip() if _batch_pattern.strip() else None
_found = scan_directory(_batch_folder, extensions=_exts, pattern=_pat)
_found = scan_directory(
local_folder(_batch_folder), extensions=_exts, pattern=_pat
)

if not _found:
st.info("No matching files found in that directory.")
Expand Down Expand Up @@ -401,7 +404,7 @@ def _load_example_cached(path: str):
st.error(f"`{_ename}`: {missing_package_message(_emsg)}")

except NotADirectoryError as _e:
st.error(f"Not a valid directory: {_e}")
st.error(str(_e))
except Exception as _e:
st.error(f"Batch import error: {_e}")

Expand Down
7 changes: 6 additions & 1 deletion eagleplot/utils/access.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ def folder_loading_allowed_here(environ: Optional[Mapping[str, str]] = None) ->
""":func:`folder_loading_allowed` for the current Streamlit session.

Always ``False`` where the runtime has no local disk to read (the browser build,
see :mod:`eagleplot.utils.runtime`), whatever :data:`FOLDER_LOAD_ENV` says.
see :mod:`eagleplot.utils.runtime`), whatever :data:`FOLDER_LOAD_ENV` says, and
always ``True`` in the desktop build, which reads the user's own disk.
"""
if environ is None:
env: Mapping[str, str] = os.environ
Expand All @@ -74,6 +75,10 @@ def folder_loading_allowed_here(environ: Optional[Mapping[str, str]] = None) ->
caps = compute_capabilities(sys.platform, env)
if not caps.local_folders:
return False
if sys.platform == "emscripten":
# The desktop build: the app runs on the user's own computer and only they use
# it. There is no server whose disk a visitor could read.
return True
return folder_loading_allowed(folder_load_setting(env), _client_ip())


Expand Down
123 changes: 123 additions & 0 deletions eagleplot/utils/host_folders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""Folders on the user's computer, read from the desktop build (roadmap D5.2).

In the desktop app (packaging/desktop) Python runs on Pyodide in a Node.js worker. Its file
system is Pyodide's own, not the computer's, so a path the user types
(``C:\\Users\\you\\data``, ``/Users/you/data``, ``~/data``) means nothing to it until that
folder is mounted. :func:`local_folder` mounts the typed folder with Emscripten's NODEFS
(the same mechanism @stlite/desktop uses for its ``nodefsMountpoints``) and returns the
path to read. Everywhere else it returns the path unchanged.

Only folders the user names are mounted, one at a time, under :data:`MOUNT_ROOT`.
"""

from __future__ import annotations

import ntpath
import os
import posixpath
from pathlib import Path
from typing import Dict, Optional

from eagleplot.utils import runtime

#: Where the desktop build mounts the folders users type.
MOUNT_ROOT = "/mnt/host"

#: Host folder (as normalised by :func:`host_path`) → its mount point. Mounts last until
#: the app closes; the same folder typed again reuses its mount.
_mounts: Dict[str, str] = {}


def host_path(text: str, platform: str, home: Optional[str]) -> str:
"""The absolute, normalised host path the user typed (pure).

Parameters
----------
text : str
What the user typed. Surrounding whitespace and quotes (from "Copy as path" on
Windows) are ignored; a leading ``~`` is the user's home folder.
platform : str
Node's ``process.platform`` on the host: ``win32``, ``darwin`` or ``linux``.
home : str or None
The user's home folder on the host.

Raises
------
NotADirectoryError
If the path is empty or relative: there is no working directory to resolve it
against that the user would recognise.
"""
flavour = ntpath if platform == "win32" else posixpath
path = text.strip().strip("\"'").strip()
if path == "~" or path.startswith(("~/", "~\\")):
if not home:
raise NotADirectoryError("Can't tell where your home folder is: type the full path.")
path = home + path[1:]
if not path or not flavour.isabs(path):
example = "C:\\Users\\you\\data" if platform == "win32" else "/Users/you/data"
raise NotADirectoryError(
f"Type the folder's full path, for example {example} (got {text.strip()!r})."
)
return flavour.normpath(path)


def _host() -> tuple:
"""``(platform, home)`` of the computer the desktop app runs on."""
import js # type: ignore[import-not-found] # only exists under Pyodide

env = js.process.env
home = getattr(env, "HOME", None) or getattr(env, "USERPROFILE", None)
return str(js.process.platform), (str(home) if home else None)


def _mount(host: str, mountpoint: str) -> None:
"""Mount host folder *host* at *mountpoint* (NODEFS), or raise ``NotADirectoryError``."""
import pyodide_js # type: ignore[import-not-found] # only exists under Pyodide
from js import Object # type: ignore[import-not-found]
from pyodide.ffi import to_js # type: ignore[import-not-found]

fs = pyodide_js.FS
os.makedirs(mountpoint, exist_ok=True)
mounted = False
try:
options = to_js({"root": host}, dict_converter=Object.fromEntries)
fs.mount(fs.filesystems.NODEFS, options, mountpoint)
mounted = True
if not os.path.isdir(mountpoint):
raise OSError("not a folder")
os.listdir(mountpoint) # a file, a missing folder or no permission fails here
except Exception: # noqa: BLE001 - FS errors arrive as JS objects, not OSError
if mounted:
try:
fs.unmount(mountpoint)
except Exception: # noqa: BLE001
pass
try:
os.rmdir(mountpoint)
except OSError:
pass
raise NotADirectoryError(f"Not a folder EaglePlot can open: {host}") from None


def local_folder(text: str) -> Path:
"""The folder named by *text*, as a path this process can read.

On a server this is just ``Path(text)``. In the desktop build the host folder is
mounted first (see the module docstring). The browser build has no local folders
(:attr:`~eagleplot.utils.runtime.Capabilities.local_folders`) and never gets here.

Raises
------
NotADirectoryError
In the desktop build, if *text* isn't the full path of a folder that can be read.
"""
if not runtime.IS_DESKTOP:
return Path(text)
platform, home = _host()
host = host_path(text, platform, home)
key = host.lower() if platform in ("win32", "darwin") else host # case-insensitive
if key not in _mounts:
mountpoint = f"{MOUNT_ROOT}/{len(_mounts) + 1}"
_mount(host, mountpoint)
_mounts[key] = mountpoint
return Path(_mounts[key])
8 changes: 4 additions & 4 deletions eagleplot/utils/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* **browser**: stlite, i.e. Streamlit on Pyodide/WebAssembly (``sys.platform ==
"emscripten"``), served as a static web app;
* **desktop**: the same stlite build inside Electron, which sets
``EAGLEPLOT_DESKTOP=1``.
``EAGLEPLOT_DESKTOP=1`` (or is recognised from Electron, see ``_running_in_electron``).

Pages should branch on *what is possible* (:class:`Capabilities`), never on *which
build this is*, so a capability can change in one build without touching the pages.
Expand Down Expand Up @@ -104,9 +104,9 @@ def compute_capabilities(platform: str, environ: Mapping[str, str]) -> Capabilit
)
if desktop:
return Capabilities(
# Folder import needs the user's typed paths (C:\Users\…) mapped onto the
# folders the desktop build mounts: roadmap D5.2. Off until then.
local_folders=False,
# A typed folder is mounted from the host when it's read
# (eagleplot.utils.host_folders, roadmap D5.2).
local_folders=True,
# Python runs in a Node.js worker, where Pyodide's requests support (built on
# the browser's XMLHttpRequest) doesn't work; NIST links out instead.
outbound_http=False,
Expand Down
11 changes: 7 additions & 4 deletions packaging/desktop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,16 @@ The app recognises the desktop build from Electron (`eagleplot.utils.runtime`),
`https://stlite.invalid`, where they fail. Prepared downloads go through Python and work.
Streamlit still checks each download button's URL at that origin once; the request
can't resolve (`.invalid` is reserved) and nothing depends on it.
- **Folders on the computer** (Data Upload → Batch Import): the folder the user types
(`C:\Users\you\data`, `/Users/you/data`, `~/data`, with or without quotes) is mounted
into the app when it's read (`eagleplot.utils.host_folders`, Emscripten's NODEFS). Only
folders the user names are mounted. On macOS the system may first ask to let EaglePlot
open Documents, Desktop or Downloads.
- **Python runs in a Node.js worker** (`nodeJsWorker`), which is needed to mount host
folders. It runs only EaglePlot's own code; keep it that way (no pickle loading, no
user-supplied Python).
- **Not yet:** loading a whole folder (Batch Import, Batch Analysis) needs the paths users
type (`C:\Users\…`) mapped onto mounted folders: roadmap D5.2. Fetching from NIST is off
(Pyodide's `requests` support needs the browser's XMLHttpRequest, which Node lacks); the
page links to NIST instead.
- **Not available:** fetching from NIST (Pyodide's `requests` support needs the browser's
XMLHttpRequest, which Node lacks); the page links to NIST instead.

## Unsigned builds: what users see the first time

Expand Down
29 changes: 29 additions & 0 deletions scripts/desktop/smoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
// Checks, with a fresh user-data folder:
// - the app starts and shows Home, with no exception and no page error;
// - it runs as the desktop build (Settings: no theme form, settings persist);
// - Batch Import reads a folder on the computer (a typed path, mounted on demand);
// - one click from Home's example gives a plot;
// - settings saved in one run are there after a restart;
// - an https link goes to the system browser (shell.openExternal), not nowhere;
Expand Down Expand Up @@ -151,6 +152,34 @@ const check = (ok, what) => { console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); if
}
check((await page.locator('[data-testid="stSidebar"]').count()) > 0, 'the app is still running after the download');
check((await page.locator('[data-testid="stException"]').count()) === 0, 'no Streamlit exception');

// Batch Import from a folder on the computer (roadmap D5.2). After Home's example:
// Home only offers the examples while no data is loaded.
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eagleplot-folder-'));
for (const [name, k] of [['smoke_a.csv', 2], ['smoke_b.csv', 3]]) {
fs.writeFileSync(path.join(dataDir, name), 'x,y\n' + [1, 2, 3, 4].map((x) => `${x},${k * x}`).join('\n') + '\n');
}
fs.writeFileSync(path.join(dataDir, 'notes.txt'), 'not data');
await nav(page, 'data-upload');
await page.getByRole('tab', { name: 'Batch Import' }).click();
await page.waitForTimeout(800);
await page.getByRole('textbox', { name: 'Folder path' }).fill(dataDir);
await page.getByRole('textbox', { name: 'Folder path' }).press('Enter');
await page.waitForTimeout(1000);
await page.getByRole('button', { name: 'Load All Files' }).click();
await waitForText(page, '3 dataset(s) loaded');
t = await mainText(page);
// One dataset from Home's example, two from the folder (notes.txt isn't data).
check(t.includes('3 dataset(s) loaded'), `Batch Import loads a folder on the computer (${dataDir})`);
await page.getByRole('tab', { name: 'Batch Import' }).click();
await page.getByRole('textbox', { name: 'Folder path' }).fill(path.join(dataDir, 'missing'));
await page.getByRole('textbox', { name: 'Folder path' }).press('Enter');
await page.waitForTimeout(1000);
await page.getByRole('button', { name: 'Scan Directory' }).click();
await waitForText(page, 'can open');
check((await mainText(page)).includes('Not a folder EaglePlot can open'), 'Batch Import: a missing folder gets a clear message');
await page.screenshot({ path: path.join(out, 'batch-import.png') });

await app.close();

// ── Restart: settings persist ──
Expand Down
88 changes: 88 additions & 0 deletions tests/test_host_folders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""eagleplot.utils.host_folders: typed folders in the desktop build (roadmap D5.2)."""

from pathlib import Path

import pytest

from eagleplot.utils import host_folders, runtime


class TestHostPath:
@pytest.mark.parametrize(
"typed, expected",
[
("C:\\Users\\ana\\data", "C:\\Users\\ana\\data"),
("C:/Users/ana/data/", "C:\\Users\\ana\\data"), # forward slashes work too
(' "C:\\Users\\ana\\my data" ', "C:\\Users\\ana\\my data"), # Copy as path
("~\\data", "C:\\Users\\ana\\data"),
("~/data", "C:\\Users\\ana\\data"),
("D:\\runs\\..\\spectra", "D:\\spectra"),
],
)
def test_windows(self, typed, expected):
assert host_folders.host_path(typed, "win32", "C:\\Users\\ana") == expected

@pytest.mark.parametrize(
"typed, expected",
[
("/Users/ana/data", "/Users/ana/data"),
("/Users/ana/data/", "/Users/ana/data"),
("'/Users/ana/my data'", "/Users/ana/my data"),
("~", "/Users/ana"),
("~/data", "/Users/ana/data"),
("/Volumes/USB/runs", "/Volumes/USB/runs"),
],
)
def test_macos_and_linux(self, typed, expected):
assert host_folders.host_path(typed, "darwin", "/Users/ana") == expected

@pytest.mark.parametrize("typed", ["", " ", "data", "./data", "..\\data"])
@pytest.mark.parametrize("platform", ["win32", "darwin", "linux"])
def test_relative_paths_ask_for_the_full_path(self, typed, platform):
with pytest.raises(NotADirectoryError, match="full path"):
host_folders.host_path(typed, platform, "/home/ana")

def test_a_posix_path_is_not_a_full_windows_path(self):
with pytest.raises(NotADirectoryError, match=r"C:\\Users\\you\\data"):
host_folders.host_path("Users\\ana", "win32", "C:\\Users\\ana")

def test_home_unknown(self):
with pytest.raises(NotADirectoryError, match="home folder"):
host_folders.host_path("~/data", "linux", None)


class TestLocalFolder:
def test_server_paths_are_used_as_typed(self, tmp_path):
assert runtime.IS_DESKTOP is False
assert host_folders.local_folder(str(tmp_path)) == Path(str(tmp_path))

@pytest.fixture
def desktop(self, monkeypatch):
"""A fake desktop build that records mounts instead of making them."""
mounts = []
monkeypatch.setattr(runtime, "IS_DESKTOP", True)
monkeypatch.setattr(host_folders, "_mounts", {})
monkeypatch.setattr(host_folders, "_host", lambda: ("win32", "C:\\Users\\ana"))
monkeypatch.setattr(host_folders, "_mount", lambda host, mp: mounts.append((host, mp)))
return mounts

def test_desktop_mounts_the_typed_folder(self, desktop):
assert host_folders.local_folder("~\\data") == Path("/mnt/host/1")
assert desktop == [("C:\\Users\\ana\\data", "/mnt/host/1")]

def test_the_same_folder_is_mounted_once(self, desktop):
first = host_folders.local_folder("C:\\Users\\ana\\data")
again = host_folders.local_folder('"c:/users/ana/data/"') # Windows ignores case
other = host_folders.local_folder("D:\\spectra")
assert first == again == Path("/mnt/host/1")
assert other == Path("/mnt/host/2")
assert [host for host, _ in desktop] == ["C:\\Users\\ana\\data", "D:\\spectra"]

def test_a_failed_mount_is_not_remembered(self, desktop, monkeypatch):
def refuse(host, mp):
raise NotADirectoryError(f"Not a folder EaglePlot can open: {host}")

monkeypatch.setattr(host_folders, "_mount", refuse)
with pytest.raises(NotADirectoryError, match="can open"):
host_folders.local_folder("C:\\nope")
assert host_folders._mounts == {}
13 changes: 6 additions & 7 deletions tests/test_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ def test_browser(self):
)

def test_desktop(self):
# Folder import comes with D5.2 (path mapping); NIST needs browser XHR, not in Node.
# Typed folders are mounted from the host (D5.2); NIST needs browser XHR, not Node.
assert DESKTOP == runtime.Capabilities(
local_folders=False,
local_folders=True,
outbound_http=False,
persistent_storage=True,
native_speed=False,
Expand Down Expand Up @@ -93,12 +93,11 @@ def test_browser_ignores_the_legacy_variable_too(self, monkeypatch):
self._with_platform(monkeypatch, "emscripten")
assert access.folder_loading_allowed_here({"PLOTTLE_ALLOW_FOLDER_LOAD": "1"}) is False

def test_desktop_does_not_load_folders_yet(self, monkeypatch):
"""Until D5.2 maps the user's paths onto the mounted folders."""
def test_desktop_loads_folders(self, monkeypatch):
"""The desktop app reads the user's own disk (D5.2): no server, no IP check."""
self._with_platform(monkeypatch, "emscripten")
assert access.folder_loading_allowed_here({"EAGLEPLOT_DESKTOP": "1"}) is False
env = {"EAGLEPLOT_DESKTOP": "1", "EAGLEPLOT_ALLOW_FOLDER_LOAD": "1"}
assert access.folder_loading_allowed_here(env) is False
monkeypatch.setattr(access, "_client_ip", lambda: "203.0.113.5")
assert access.folder_loading_allowed_here({"EAGLEPLOT_DESKTOP": "1"}) is True

def test_server_follows_the_usual_rules(self, monkeypatch):
self._with_platform(monkeypatch, "linux")
Expand Down
Loading