Skip to content

fix(uri): preserve non-ASCII URI hosts across sanitization - #2072

Merged
l0gicgate merged 1 commit into
lgse:mainfrom
kantv-linux:kan-v0.3.1
Nov 6, 2026
Merged

l0gicgate merged 1 commit into
lgse:mainfrom
kantv-linux:kan-v0.3.1

Conversation

@zhouwg

@zhouwg zhouwg commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Description

GVfs locations whose host contains non-ASCII characters never resolve properly in Strata.

Example: an MTP phone named "OnePlus 一加 Ace 5 Pro" mounts fine (gio info mtp://OnePlus_%E4%B8%80%E5%8A%A0_Ace_5_Pro_9d231cfe/ works), but Strata reports "The location is not mounted" on open.

Cause

sanitize_uri_credentials re-serializes every URI through glib::Uri (Uri::parse → to_str / build_with_user). GUri applies IDNA encoding to non-ASCII hosts when re-serializing, so the location string becomes mtp://xn--oneplus__ace_5_pro_9d231cfe-ir76bb67e/. The gvfs backend matches its device name verbatim and can never resolve the punycoded host, so every directory load fails with G_IO_ERROR_NOT_MOUNTED.

Fix

Keep GUri's normalization (path percent-encoding, credential stripping) but restore the host text from the original input: to_str_preserving_host re-splices the input's host into the normalized string. Applied at both output sites of sanitize_uri_credentials (with and without credentials).

Non-ASCII hosts affect any backend URI (MTP device names, IDN hosts), so this is not MTP-specific.

Visual evidence

Before fix:

screenshot-2026-11-06_17-03-23-921 screenshot-2026-11-06_17-04-44-040

Expected result(after fix):
screenshot-2026-11-06_17-12-11-372
screenshot-2026-11-06_17-12-26-993

How to test

  1. launch Strata via below method
RUST_LOG=debug /usr/bin/strata 2>&1 | tee /tmp/log.txt

  1. connect Android phone in MTP mode to the laptop running Kan-Linux v0.3.1, click the sidebar and observer the output of /tmp/log.txt

Related issue

N/A

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Yes, Paired with MiMoCode + MiMo-V2.6-Pro, use MiMo-V2.6-Pro to generate the fix, then reviewed/tested manually.

@github-actions github-actions Bot added the fix label Nov 6, 2026
@l0gicgate

Copy link
Copy Markdown
Contributor

Review and cleanup

Not pushed. This PR comes from an organization-owned fork with maintainerCanModify: false, so I can't push to kan-linux:kan-v0.3.1. Requested changes are below, with a ready-to-apply patch. main needed no merge: the branch is already based on 86975bf1.

The diagnosis is correct, and I confirmed it against real GVfs: mtp://xn--… and mtp://OnePlus_%E4… are different files to g_file_equal. The change does not fix the bug completely, though.

Requested changes (blocking)

  1. Going up from a subfolder still breaks. Location::parent() has its own DNS-mode parse, so mtp://Phone_%E4%B8%80%E5%8A%A0/DCIM/Camera gets the parent mtp://xn--phone_-gn7iw92a/DCIM. That path feeds the Up action and breadcrumbs (Location::parent, reveal_in_parent), so it should fail as not mounted again. display_path shows the same xn-- name, and so does a typed sftp://h%C3%A9/x?q.
  2. Some device names still can't open. The sanitizer parses with DNS flags before splicing, so GLib rejects any host that fails IDNA with Illegal internationalized hostname, and sanitize_uri_credentials returns InvalidUri. Examples are a long name like mtp://Xiaomi_%E5%B0%8F%E7%B1%B3_Redmi_Note_12_Turbo_0123456789abcdef0123456789abcdef/ and a name with a no-break space, mtp://Phone%C2%A0X/.
  3. Splicing the input's host back can change the location. Locations compare as text, and host_text disagrees with GLib's parser:
    • sftp://a@b@c/x is host b@c to GLib, but the PR rewrites it to sftp://a@c/x, which targets a different host.
    • smb://MY SERVER/share loses its %20.
    • mtp://OnePlus_一加_Ace/ stays raw, while GVfs reports mtp://OnePlus_%E4%B8%80%E5%8A%A0_Ace/.
    • replacen replaces the first match anywhere in the string, so a username equal to the host's xn-- form gets rewritten instead of the host.

The fix in the patch. GLib already has a flag for this: NON_DNS, which uri_leaf_name used. Adding it to GIO_URI_PARSE_FLAGS fixes every parse, and with ENCODED it also keeps the host percent-encoded, which is how GVfs spells it. That replaces host_text and to_str_preserving_host, so no URI is parsed by hand. The flags move to a new src/model/uri.rs.

parent() also stops decoding hosts, which fixes an existing bug: gphoto2://Canon%20EOS/DCIM/a had the parent gphoto2://Canon EOS/DCIM, with a raw space.

Tests. non_ascii_hosts_are_preserved_verbatim moves into the existing sanitized_uris_keep_gio_percent_encoding table, and its narrating comment goes away. The patch adds regression rows to the existing tables for sanitizing, credentials, parent(), display_path and typed addresses. On this PR's code, 4 of those tests failed with the rows added; all of them pass with the patch.

Validation (patch applied on a423f2ea)

  • ./scripts/test-headless.py -- model:: services::file_source app::browser::tests::location_input adapters::bookmarks adapters::gio_location ui::browser::location tabs_session camera gphoto mount_lanes navigation_history file_manager1 app::browser::remote undo::renames mount_profile ui::thumbnail::tests app::navigation::tests::monitor ui::window::tests::sidebar: 343 passed, 0 failed
  • ./scripts/quality.sh fmt, ./scripts/quality.sh clippy: clean
  • scripts/code-health.sh: src/model/mod.rs 7.49 → 7.52, src/model/uri.rs 10.0, no file lower
  • GVfs URI spelling checked with Gio.File on a private D-Bus session
  • Not run: a real MTP device, because I don't have one. @zhouwg, please retest on the OnePlus, including opening a subfolder and going back up with Up and the breadcrumbs. qa.sh was also not run: no scenario covers these hosts.
  • The full Rust suite was not run locally on the patch. CI will cover it once the patch is on this branch.

CI. I approved the waiting fork run. It is green on a423f2ea, the PR as submitted, not on the patch. The QA job is dispatch-only, so it was skipped.

Follow-ups outside this PR

  • Real internationalized DNS names now reach backends in percent-encoded Unicode instead of punycode, as they do with this PR's approach. münchen.de resolved here without punycode, but that depends on the system resolver. An sftp:// or smb:// host on a resolver without IDN support could stop resolving; if that gets reported, limit NON_DNS by scheme. I did not test a real connection.
  • GVfs spells some camera hosts with literal brackets (gphoto2://[usb:001,002]/), and GLib can't parse that form on main or with this patch.
  • mount_lanes::authority still parses with DNS semantics. It's only a lane key, but a rejected name falls back to the scheme alone, so such devices share one lane.
  • location_input doesn't accept typed mtp:// addresses, so editing the path bar on a phone is still rejected.

No PR comments or reviews existed before this one. The PR has no linked issue, which AGENTS.md expects, though the metadata policy check passes.

Patch: save as review.diff, then run git apply review.diff on a423f2ea
diff --git a/src/app/browser/location_input.rs b/src/app/browser/location_input.rs
index 6ed7aa507..5614127d4 100644
--- a/src/app/browser/location_input.rs
+++ b/src/app/browser/location_input.rs
@@ -3,7 +3,9 @@
 use std::path::{Path, PathBuf};
 
 use crate::{
-    model::{GIO_URI_BUILD_FLAGS, GIO_URI_PARSE_FLAGS, Location, lexically_normalized},
+    model::{
+        GIO_URI_BUILD_FLAGS, GIO_URI_PARSE_FLAGS, Location, gio_uri_text, lexically_normalized,
+    },
     services::{LocationValidationError, validate_uri_credentials},
 };
 
@@ -69,7 +71,7 @@ fn without_query_or_fragment(uri: String) -> String {
     if parsed.query().is_none() && parsed.fragment().is_none() {
         return uri;
     }
-    glib::Uri::build_with_user(
+    gio_uri_text(&glib::Uri::build_with_user(
         GIO_URI_BUILD_FLAGS,
         &parsed.scheme(),
         parsed.user().as_deref(),
@@ -80,9 +82,7 @@ fn without_query_or_fragment(uri: String) -> String {
         &parsed.path(),
         None,
         None,
-    )
-    .to_str()
-    .to_string()
+    ))
 }
 
 /// GIO's spelling of the roots of schemes without a host, which it also reads from
diff --git a/src/app/browser/tests/location_input.rs b/src/app/browser/tests/location_input.rs
index b8d20b5cd..62b81653f 100644
--- a/src/app/browser/tests/location_input.rs
+++ b/src/app/browser/tests/location_input.rs
@@ -275,6 +275,7 @@ fn typed_remote_addresses_drop_the_query_and_fragment_gvfs_would_mount() {
         ),
         ("smb://host/my share#frag", "smb://host/my%20share"),
         ("ftp://host/pub/a%2Fb?x=%FF", "ftp://host/pub/a%2Fb"),
+        ("sftp://h%C3%A9/served?tok=QTOKEN", "sftp://h%C3%A9/served"),
     ] {
         browser.navigate(Location::local("/fixture"));
         assert_eq!(browser.navigate_input(input), Ok(()), "{input}");
diff --git a/src/model/mod.rs b/src/model/mod.rs
index b476d7f61..a9e074554 100644
--- a/src/model/mod.rs
+++ b/src/model/mod.rs
@@ -10,8 +10,12 @@ use std::{
 
 use gio::prelude::*;
 
+use uri::GIO_URI_ENCODED_FLAGS;
+pub(crate) use uri::{GIO_URI_BUILD_FLAGS, GIO_URI_PARSE_FLAGS, gio_uri_text};
+
 pub mod action;
 pub mod hidden_names;
+mod uri;
 
 pub use action::{
     ACTION_SCHEMA_VERSION, ActionConditions, ActionDefinition, ActionError, ActionInput,
@@ -79,19 +83,6 @@ pub(crate) fn transfer_file_name(file: &gio::File) -> Option<OsString> {
     Some(OsStr::from_bytes(bytes).to_os_string())
 }
 
-/// GIO hands out percent-encoded URIs; keep path, query and fragment encoded so names that are
-/// not valid UTF-8 parse, while userinfo is still decoded for credential detection.
-pub(crate) const GIO_URI_PARSE_FLAGS: gio::glib::UriFlags = gio::glib::UriFlags::HAS_PASSWORD
-    .union(gio::glib::UriFlags::HAS_AUTH_PARAMS)
-    .union(gio::glib::UriFlags::ENCODED_PATH)
-    .union(gio::glib::UriFlags::ENCODED_QUERY)
-    .union(gio::glib::UriFlags::ENCODED_FRAGMENT);
-
-/// Build flags matching `GIO_URI_PARSE_FLAGS`, so already-encoded components are not re-escaped.
-pub(crate) const GIO_URI_BUILD_FLAGS: gio::glib::UriFlags = gio::glib::UriFlags::ENCODED_PATH
-    .union(gio::glib::UriFlags::ENCODED_QUERY)
-    .union(gio::glib::UriFlags::ENCODED_FRAGMENT);
-
 /// Removes user-info (including an SMB domain), query, and fragment from a URI for logs.
 pub fn diagnostic_uri(uri: &str) -> String {
     parse_display_uri(uri)
@@ -119,7 +110,9 @@ fn parse_display_uri(uri: &str) -> Result<gio::glib::Uri, gio::glib::Error> {
     }
     gio::glib::Uri::parse(
         uri,
-        gio::glib::UriFlags::HAS_PASSWORD | gio::glib::UriFlags::HAS_AUTH_PARAMS,
+        gio::glib::UriFlags::HAS_PASSWORD
+            | gio::glib::UriFlags::HAS_AUTH_PARAMS
+            | gio::glib::UriFlags::NON_DNS,
     )
     .or(encoded)
 }
@@ -133,11 +126,9 @@ fn uri_display_name(uri: &str, file_name: Option<OsString>) -> String {
         .unwrap_or_else(|| uri_leaf_name(uri))
 }
 
-/// The decoded last path segment, or the host at a server root. `NON_DNS` keeps a non-ASCII
-/// host as typed instead of converting it to punycode.
+/// The decoded last path segment, or the host at a server root.
 fn uri_leaf_name(uri: &str) -> String {
-    let flags = GIO_URI_PARSE_FLAGS.union(gio::glib::UriFlags::NON_DNS);
-    let Ok(parsed) = gio::glib::Uri::parse(uri, flags) else {
+    let Ok(parsed) = gio::glib::Uri::parse(uri, GIO_URI_PARSE_FLAGS) else {
         return uri
             .trim_end_matches('/')
             .rsplit('/')
@@ -292,13 +283,7 @@ impl Location {
             LocationKind::Uri(uri) => {
                 // Walk the URI path. GVfs File::parent() can SIGSEGV on gphoto2
                 // and similar backends when many tests call it concurrently.
-                let parsed = gio::glib::Uri::parse(
-                    uri,
-                    gio::glib::UriFlags::HAS_PASSWORD
-                        | gio::glib::UriFlags::HAS_AUTH_PARAMS
-                        | gio::glib::UriFlags::ENCODED,
-                )
-                .ok()?;
+                let parsed = gio::glib::Uri::parse(uri, GIO_URI_ENCODED_FLAGS).ok()?;
                 let path = parsed.path();
                 let trimmed = path.trim_end_matches('/');
                 if trimmed.is_empty() {
diff --git a/src/model/tests.rs b/src/model/tests.rs
index 3884a311d..e2427410d 100644
--- a/src/model/tests.rs
+++ b/src/model/tests.rs
@@ -228,6 +228,11 @@ fn remote_locations_keep_uri_parents_and_breadcrumbs() {
         ("sftp://host/share/a%2Fb/child", "sftp://host/share/a%2Fb"),
         ("sftp://host/share/100%25/child", "sftp://host/share/100%25"),
         ("trash:///caf%E9.txt", "trash:///"),
+        (
+            "mtp://Phone_%E4%B8%80%E5%8A%A0/DCIM/Camera",
+            "mtp://Phone_%E4%B8%80%E5%8A%A0/DCIM",
+        ),
+        ("gphoto2://Canon%20EOS/DCIM/a", "gphoto2://Canon%20EOS/DCIM"),
     ] {
         assert_eq!(Location::uri(uri).parent(), Some(Location::uri(parent)));
     }
@@ -389,6 +394,10 @@ fn display_paths_hide_remote_credentials_but_preserve_usernames() {
         ("smb://alice:secret@host/caf%E9", "smb://host/caf%E9"),
         ("sftp://host/share/a%2Fb", "sftp://host/share/a%2Fb"),
         ("sftp://host/share/a%2fb", "sftp://host/share/a%2Fb"),
+        (
+            "mtp://Phone_%E4%B8%80%E5%8A%A0/DCIM",
+            "mtp://Phone_一加/DCIM",
+        ),
     ] {
         assert_eq!(Location::uri(uri).display_path(), displayed, "{uri}");
     }
diff --git a/src/model/uri.rs b/src/model/uri.rs
new file mode 100644
index 000000000..acf7a0926
--- /dev/null
+++ b/src/model/uri.rs
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: MIT
+
+/// GIO hands out percent-encoded URIs; keep path, query and fragment encoded so names that are
+/// not valid UTF-8 parse, while userinfo is still decoded for credential detection. `NON_DNS`
+/// keeps GUri from converting a GVfs host, such as an MTP device name, to punycode or rejecting
+/// it as an invalid DNS name.
+pub(crate) const GIO_URI_PARSE_FLAGS: glib::UriFlags = glib::UriFlags::HAS_PASSWORD
+    .union(glib::UriFlags::HAS_AUTH_PARAMS)
+    .union(glib::UriFlags::ENCODED_PATH)
+    .union(glib::UriFlags::ENCODED_QUERY)
+    .union(glib::UriFlags::ENCODED_FRAGMENT)
+    .union(glib::UriFlags::NON_DNS);
+
+/// With `NON_DNS`, `ENCODED` also leaves the host percent-encoded.
+pub(super) const GIO_URI_ENCODED_FLAGS: glib::UriFlags = glib::UriFlags::HAS_PASSWORD
+    .union(glib::UriFlags::HAS_AUTH_PARAMS)
+    .union(glib::UriFlags::ENCODED)
+    .union(glib::UriFlags::NON_DNS);
+
+/// Build flags matching `GIO_URI_PARSE_FLAGS`, so already-encoded components are not re-escaped.
+pub(crate) const GIO_URI_BUILD_FLAGS: glib::UriFlags = glib::UriFlags::ENCODED_PATH
+    .union(glib::UriFlags::ENCODED_QUERY)
+    .union(glib::UriFlags::ENCODED_FRAGMENT);
+
+/// GUri writes a non-DNS host as raw UTF-8 where GVfs percent-encodes it, and `Location`s compare
+/// as text.
+pub(crate) fn gio_uri_text(uri: &glib::Uri) -> String {
+    let text = uri.to_str();
+    if text.is_ascii() {
+        return text.to_string();
+    }
+    glib::Uri::parse(&text, GIO_URI_ENCODED_FLAGS)
+        .map_or_else(|_| text.to_string(), |encoded| encoded.to_str().to_string())
+}
diff --git a/src/services/file_source.rs b/src/services/file_source.rs
index 900033c3c..60996bb8d 100644
--- a/src/services/file_source.rs
+++ b/src/services/file_source.rs
@@ -12,7 +12,7 @@ use std::{
 
 use super::{ItemIdentity, Proof};
 use crate::model::{
-    FileEntry, GIO_URI_BUILD_FLAGS, GIO_URI_PARSE_FLAGS, Location, MetadataValue,
+    FileEntry, GIO_URI_BUILD_FLAGS, GIO_URI_PARSE_FLAGS, Location, MetadataValue, gio_uri_text,
     uri_contains_credentials,
 };
 
@@ -344,49 +344,15 @@ pub struct UriCredentials {
     pub password: String,
 }
 
-/// Host text (authority minus user-info and port) of a `scheme://` URI, verbatim.
-fn host_text(uri: &str) -> Option<&str> {
-    let rest = &uri[uri.find("://")? + 3..];
-    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
-    let authority = &rest[..authority_end];
-    let hostport = authority.rsplit('@').next().unwrap_or(authority);
-    if hostport.is_empty() {
-        return None;
-    }
-    if let Some(bracketed) = hostport.strip_prefix('[') {
-        let end = bracketed.find(']')?;
-        Some(&hostport[..end + 2])
-    } else {
-        Some(hostport.split(':').next().filter(|host| !host.is_empty())?)
-    }
-}
-
-/// Like `Uri::to_str`, but the host keeps the input's original spelling.
-/// GUri IDNA-encodes non-ASCII hosts on re-serialization, which turns gvfs
-/// device URIs (mtp device names may contain CJK) into `xn--` names that the
-/// gvfs backend cannot resolve.
-fn to_str_preserving_host(input: &str, uri: &glib::Uri) -> String {
-    let normalized = uri.to_str().to_string();
-    match (host_text(input), host_text(&normalized)) {
-        (Some(raw_host), Some(norm_host)) if !raw_host.is_empty() && !norm_host.is_empty() => {
-            normalized.replacen(norm_host, raw_host, 1)
-        }
-        _ => normalized,
-    }
-}
-
 /// Removes URI user-info secrets while preserving the username separately.
 /// Path, query and fragment keep GIO's percent-encoding so non-UTF-8 names survive.
-/// The host is preserved verbatim from `input`: GUri re-serialization IDNA-encodes
-/// non-ASCII hosts (`mtp://OnePlus_一加_...` becomes `mtp://xn--...`), which gvfs
-/// backends cannot match to their device names (the location then never resolves).
 pub fn sanitize_uri_credentials(
     input: &str,
 ) -> Result<(String, Option<UriCredentials>), LocationValidationError> {
     let uri = glib::Uri::parse(input, GIO_URI_PARSE_FLAGS)
         .map_err(|_| LocationValidationError::InvalidUri)?;
     if !uri_contains_credentials(&uri) {
-        return Ok((to_str_preserving_host(input, &uri), None));
+        return Ok((gio_uri_text(&uri), None));
     }
 
     let mut username = uri.user().map(|user| user.to_string()).unwrap_or_default();
@@ -412,7 +378,7 @@ pub fn sanitize_uri_credentials(
             .map(str::to_owned);
     }
 
-    let rebuilt = glib::Uri::build_with_user(
+    let sanitized = gio_uri_text(&glib::Uri::build_with_user(
         GIO_URI_BUILD_FLAGS,
         &uri.scheme(),
         (!username.is_empty()).then_some(username.as_str()),
@@ -423,8 +389,7 @@ pub fn sanitize_uri_credentials(
         &uri.path(),
         uri.query().as_deref(),
         uri.fragment().as_deref(),
-    );
-    let sanitized = to_str_preserving_host(input, &rebuilt);
+    ));
     let credentials = UriCredentials {
         username,
         password: password.unwrap_or_default(),
diff --git a/src/services/file_source/tests.rs b/src/services/file_source/tests.rs
index 4b206bbbd..e557b356d 100644
--- a/src/services/file_source/tests.rs
+++ b/src/services/file_source/tests.rs
@@ -128,6 +128,10 @@ fn embedded_uri_credentials_are_separated_from_the_sanitized_uri() {
             "smb://user:secret@host/a%2Fb?x=%FF#f",
             "smb://user@host/a%2Fb?x=%FF#f",
         ),
+        (
+            "mtp://user:secret@Phone_%E4%B8%80/DCIM",
+            "mtp://user@Phone_%E4%B8%80/DCIM",
+        ),
     ] {
         assert_eq!(
             sanitize_uri_credentials(uri),
@@ -167,6 +171,21 @@ fn sanitized_uris_keep_gio_percent_encoding() {
         ("sftp://host/share/a%2Fb", "sftp://host/share/a%2Fb"),
         ("smb://host/caf%C3%A9", "smb://host/caf%C3%A9"),
         ("smb://host/my share", "smb://host/my%20share"),
+        (
+            "mtp://OnePlus_%E4%B8%80%E5%8A%A0_Ace_5_Pro_9d231cfe/",
+            "mtp://OnePlus_%E4%B8%80%E5%8A%A0_Ace_5_Pro_9d231cfe/",
+        ),
+        (
+            "mtp://OnePlus_一加_Ace/",
+            "mtp://OnePlus_%E4%B8%80%E5%8A%A0_Ace/",
+        ),
+        ("mtp://Phone%C2%A0X/DCIM", "mtp://Phone%C2%A0X/DCIM"),
+        (
+            "mtp://Xiaomi_%E5%B0%8F%E7%B1%B3_Redmi_Note_12_Turbo_0123456789abcdef0123456789abcdef/",
+            "mtp://Xiaomi_%E5%B0%8F%E7%B1%B3_Redmi_Note_12_Turbo_0123456789abcdef0123456789abcdef/",
+        ),
+        ("smb://MY SERVER/share", "smb://MY%20SERVER/share"),
+        ("sftp://a@b@c/x", "sftp://a@b%40c/x"),
     ] {
         assert_eq!(
             sanitize_uri_credentials(uri),
@@ -176,21 +195,6 @@ fn sanitized_uris_keep_gio_percent_encoding() {
     }
 }
 
-#[test]
-fn non_ascii_hosts_are_preserved_verbatim() {
-    // MTP device names may contain non-ASCII characters ("一加" below): GUri
-    // re-serialization IDNA-encodes the host (mtp://OnePlus_一加_... becomes
-    // mtp://xn--...), which the gvfs backend cannot match to its device name,
-    // so the location stays permanently NotMounted.
-    assert_eq!(
-        sanitize_uri_credentials("mtp://OnePlus_%E4%B8%80%E5%8A%A0_Ace_5_Pro_9d231cfe/"),
-        Ok((
-            "mtp://OnePlus_%E4%B8%80%E5%8A%A0_Ace_5_Pro_9d231cfe/".to_owned(),
-            None
-        )),
-    );
-}
-
 #[test]
 fn malformed_uris_fail_without_echoing_input() {
     assert_eq!(

@l0gicgate
l0gicgate merged commit 35ee677 into lgse:main Nov 6, 2026
15 checks passed
l0gicgate added a commit that referenced this pull request Nov 7, 2026
…on (#1924)

* feat(preview): start first-time video previews at a configured position

Add a "Video preview start" percentage (0-99, default 0) under
Settings > General > Browsing, stored as `preview_video_start`. A video
preview with a known duration and no position remembered this session
seeks there once its header arrives; a remembered position from #1326
still wins, and audio, GIF, and streams of unknown length start at the
beginning.

Closes #1910

* fix(preview): add Hungarian strings and align video start clamp

* test(preview): pin the video start in the external-player handoff test

KeyboardFixture seeds the exhaustive preferences fixture, which now sets
preview_video_start to 20, so the clip opened at 20 % and the handoff
reported --start=12.000 instead of the position reached by playing.

* fix(preview): reopen a video left at its start or end at 0:00

`DecodedMedia::close` forgot the position of a video closed within its
first second or at its end, so with a non-zero Video preview start the
next open jumped to the configured percent again. Seeking back to watch
an intro, or watching to the end, was overridden on the next preview,
and the Settings description ("A video you already previewed resumes
where you left it") did not hold.

Remember such a video at 0 instead. `resume_position` still ignores
positions within the first second, so it reopens at 0:00, and
`set_start_percent` applies the configured start only to a video not
previewed earlier this session. Audio is still forgotten as before.

* fix(preview): import recall_media_position outside test builds

set_start_percent calls it in production code, so the #[cfg(test)] gate broke the non-test build.

* fix(preview): remember a video at 0:00 only when a start is configured

With the start at 0, every previewed video and GIF was stored at 0 in the
128-entry position cache, evicting real resume positions and keeping a
video skimmed at 0 from getting a start configured later in the session.

* fix(preview): start raw H.264/H.265 streams at the beginning

The helper seeks raw elementary streams by decoding up to the target, so a
configured start on a long stream could exceed the first-frame timeout.
Issue #1910 asks for these streams to start at 0.

* style(preferences): format the stored import list

* test(preview): wait for the decoder header before checking the video start

settle ticked without sleeping, so the fake stream's Prepared could arrive
after the check and the cases expecting no restart passed without
exercising the start decision.

* test(preview): cover video of unknown length in the start test

* fix(settings): drop the unlocalized percent label from the video start row

The row description already says the value is a percent of the video's length.

* test(preferences): keep only the clamping video start rows

In-range values only echoed the input; the saved fixture and the setter
persistence test already cover round-tripping.

* test(preview): wait for a scheduled restart to reach the loader in settle

A wrong restart only reaches the loader once the cancelled worker exits,
which can take longer than the fixed tick count, so the start-at-0:00
cases could pass without seeing it. start_session clears restart after
calling the loader.

* fix(preview): skip the start restart when it rounds to the first frame

A short clip at a small percent got a start before its first frame tick,
which restarted the decoder at tick 0 for nothing.

* docs(preferences): note the video start must be set when the preview opens

* test(preview): cover raw video streams ignoring the configured start

An MP4 preview starts at 20 % as a control, then > continues into a raw
H.264 stream, which must start at the beginning.

* test(preview): check the clip's start at its first frame

Waiting for the timestamp to pass 11 s relied on the settle helper's
10 s timeout to fail when the start was not applied.

* fix: close out the leftover items from the 1.2.0 release-candidate QA sweep (#2070)

* refactor(paste): share what a collision's item kinds allow

Name the rule that a file and a folder never replace one another, and
that only two folders merge, as Collision::between and Collision::allows,
and keep it on the paste collision as its kinds rather than as two loose
flags. Apply to All's split of the collisions an answer covers and the
"a file and a folder can't replace one another" explanation become
helpers, so the undo and redo replay prompt can use the same rules.
No behaviour change.

Refs #2017

* fix(undo): offer no Replace where a replayed move meets the other kind

Undo and Redo of a move asked about an item already at the destination
with Replace always offered, so a file meeting a folder of the same name
(or a folder meeting a file) could be told to replace it, and the replay
then failed that item. Apply to All with Replace carried the failure to
every such item.

The presence probe now reports whether an item it finds is a folder, a
link counting as a file, as the paste's own check does. The replay
prompt applies the paste's collision rules to the moved item and the one
in its way: it hides Replace and says why, and Apply to All with Replace
leaves those items their own prompt. A replay prompt with neither
Replace nor Keep Both starts on Skip, or on Cancel when Skip is hidden.
An item whose kind cannot be read is still offered Replace.

Refs #2017

* build(test-image): install libheif for real AVIF and HEIC files

ImageMagick in the pinned image had no HEIF coder library, so it wrote
PNG bytes under .avif/.heic names. libheif from the same dated snapshot
brings the built-in aom, x265 and libde265 codecs, and also enables the
glycin heif loader that GDK Pixbuf uses inside the preview sandbox.

Refs #2019

* test(qa): fail AVIF and HEIC fixtures that lack an ISO BMFF brand

ImageMagick exits 0 and writes the input format when it lacks an encoder,
which let camera-formats-preview-sandbox pass on PNG bytes. The magick
fixture step now requires an ftyp box with the brand its extension names.

Refs #2019

* test: drop a private main context's leftover tasks on their own thread

A GIO call started on a test's private main context keeps the context
alive from its GTask. g_task_thread_pool_thread unrefs the task after
attaching the completion idle, so the test thread can dispatch the
callback, finish and drop its context first, leaving the pool thread
with the last reference. Finalizing the context there destroyed any
spawn_local future still attached to it, and glib-rs dropped the future
on the wrong thread and aborted the whole test process.

PendingVolumeLookup::start, exercised by the adapters::volume tests, is
one such shape: its query_info_async calls run on GIO pool threads and
its timeout task outlives the lookup.

Tests now create private contexts through test_support::PrivateContext,
which destroys every source left on the context when it is dropped, on
the thread that created them. Clippy rejects glib::MainContext::new so
new tests cannot bypass it.

Refs #1963

* test(qa): accept AVIF and HEIC brands anywhere in the ftyp box

Read the whole ftyp box, including a 64-bit largesize or a box running
to the end of the file, and accept the expected brand as the major or a
compatible brand, so avis sequences and mif1-major files pass. Bytes
without a leading ftyp box, such as PNG, are still rejected. The docs
now credit glycin-heif, not a GDK Pixbuf loader, with decoding.

Refs #2019

* fix(columns): open the selected folder's child column on returning to Columns

Switching back to Columns rebuilt every column the browser still held,
so a child column the List or Icons selection had since left reopened
with its open-path fill and the breadcrumb on it.

The selection now drives the child: a child that is no longer selected
closes before the columns are rebuilt, and a lone selected folder opens
as the new child. An empty selection reopens no child, and the
breadcrumb ends at the active folder.

Refs #2016

* fix(conflicts): start a prompt with neither Replace nor Keep Both on Cancel

A replay prompt for an item meeting the other kind offers neither, and
started on Skip, which drops the item from the undo entry. Start on
Cancel instead, the one answer that never changes the history.

Refs #2017

* fix(undo): keep a replay that moves nothing in the history

Skip with Apply to All, or skipping each conflict, left nothing to move,
and the replay then discarded its undo or redo entry, although Cancel,
which also moves nothing, keeps it. Now that an item meeting the other
kind cannot be replaced, a prompt could offer Skip where it was the
only answer besides Cancel, and so drop the entry that way.

A replay whose every conflict is skipped now keeps its entry, as Cancel
does. The prompt offers Skip, and Apply to All beside it, only while an
answer can still move something: an item already accepted, or a later
conflict that Replace can resolve. Otherwise it offers Cancel alone.
A partial replay still drops only the records it skipped.

Refs #2017

* fix(list): start a grouped first visit on the first row shown

A first visit by typed path, sidebar or any route that asks for the
automatic cursor picked the first entry in name order. In a grouped List
that row can sit in a later group, so the cursor landed on the visually
last file or scrolled a large folder to its middle. A double-click left
the cursor to the view and was right.

The browser now knows when its listings show file-type groups, and the
automatic pick takes the first entry of the first visible group. The
group order and the per-folder grouping rules (Recent, unsettled camera
folders) move into the app so the GTK sorter and the pick share them.

Refs #2016

* fix(list): keep a grouped first visit at the top of the list

A grouped List publishes a large folder's rows in name order, so a
group that sorts first arrives above the row GTK focused when the first
rows came in. A pointer first visit has no cursor to hold on to, so
focus followed that row into the middle of the list. Once the listing
is complete, such a pane now focuses the first row shown.

Scrolling a grouped List to its first row also shows the heading above
it, so the automatic cursor leaves the view at the very top.

Refs #2016

* test(qa): cover the first-visit cursor of a grouped List

Opens a grouped List by typed path and by double-click on a listing
large enough to publish in chunks, and checks the first row shown takes
the cursor, then that a revisit restores the remembered one. The
grouped-first-row mutation reverts the automatic pick to name order.

Refs #2016

* test: sweep a private main context until no source is left

Dropping a leftover source's future can attach another source, which a
single pass missed. Repeat from the last probed id until a pass destroys
nothing, and cover it with a task attached during the sweep while
another reference keeps the context alive.

Also disallow glib::MainContext::with_flags, word the Clippy reason for
production code too, and document that Default::default() escapes the
path check and that sources attached after the drop are leaked on
purpose.

Refs #1963

* fix(columns): respect pending navigations and mirroring when returning to Columns

Following the selection on the switch back to Columns closed and opened
columns, which bumps the navigation generation, so a navigation still
validating (a remote folder opened in List) was dropped. The step now
changes nothing while a navigation is pending.

A selection made in List or Icons is not an activation, and with
"Mirror columns selection" off Columns never opens a child from a
selection, so the selected folder opens only while mirroring is on.
Closing a child the selection no longer holds stays unconditional.

Rename the step to follow_selection_on_return, extend its unit cases
(load cursor on a folder, several items without the open child, a held
validation), add mirroring-off runs to the QA scenario and rate it.

Refs #2016

* docs(columns): describe the child column after returning to Columns

Refs #2016

* fix(list): refocus the first row only on an untouched first visit

Focusing a pane without a cursor scrolled every List and Icons pane to
its first row, and the load-finish refocus also ran after reloads and
Back or Forward visits whose saved position a scroll had abandoned.

Focus without a cursor returns to GTK's own row again. Only a first
visit with no saved position, through to its load finishing with no
pointer, scroll, touch or key input in the pane, moves focus to the
first row shown, and only in a grouped pane with no cursor. A reload
drops the watch.

Refs #2016

* fix(navigation): pick a grouped first row without needless type lookups

The automatic pick read every entry's type on the main thread, missing
the bounded type cache on large folders. A type sort already lists the
entries in group order, and under any other sort the first visible
folder leads, so only a folder-free listing not sorted by type needs
the lookups.

A grouped listing arriving in batches now picks its first row once it
is complete instead of from the first batch, and a step without a
cursor starts on the first row shown rather than the first by name.

Refs #2016

* test(qa): check a large grouped first visit stays at the top

Adds a typed first visit to a grouped folder large enough to publish in
chunks, and checks both large visits keep the first row and its heading
in view. Drops the grouped-first-row mutation: the behaviour is not a
critical workflow, and unit tests pin the pick.

Refs #2016

* fix(search): search only the mounts the Devices sidebar shows

Ctrl+K global search added every /dev-backed mount from the raw mount
table to the volume monitor's mounts, so it walked system subvolume
mounts such as /var/cache/pacman/pkg that Devices hides. Search roots
are now Home plus the native roots of the volumes and volume-less mounts
that Devices lists, taken from the same volume-monitor enumeration, which
the sidebar now shares. The roots are still computed on each Ctrl+K, so
mount and unmount changes apply the next time search opens.

Closes #533
Refs #2016

* test(qa): drop the heading geometry checks from the grouped first visit

AGENTS.md rules out layout assertions. The visible check on the first
row still shows each large first visit stayed at the top; the heading
reveal was verified by hand.

Refs #2016

* test(preview): sample smooth scrolling only after the layout settles

The smooth-scrolling test sampled hit testing after fixed 20 ms
wall-clock waits. On a loaded machine GTK can paint newly mapped rows at
their estimated one-line text height before validating their layout,
then grow them a frame later, which re-anchors the list and moves later
rows down. A sample taken in that window and one taken after it read
different, but each correct, layouts, so the order check failed
depending on timing.

Wait on painted frames instead: sample after the mapped rows, their
materialization and the scroll adjustment are unchanged across two
painted frames with no ready main-context work, and drive momentum by
frame count. Hit testing itself already matches GTK's own pick.

Refs #1970

* test(search): cover the volume-monitor root selection directly

Split the Devices mount selection for global search into plain-data
MountRoot and MountListing facts and a pure local_device_roots, so a
table-driven test covers volume mounts, own-row mounts, shadowed and
volume-listed mounts, pathless roots and non-native GVfs roots. A root
now counts only when it is native and has a path, as location_for_file
reads it. The sidebar shares the own-row predicate.

Drop the test-only early return from device_mount_roots; global search
is instead checked against a mount table holding fixture mounts the
volume monitor never lists, which fails if a raw mount-table step
returns.

Refs #533

* fix(list): tie the first-visit watch to its navigation and depth

A parent column's load finishing, such as a monitor relist, used up the
child pane's first-visit watch, so the child's own load skipped its
refocus. The watch now records its depth and only that depth's load
ends it.

Rebuilds for relocations, truncations and mode switches also armed a
watch whenever the folder was still loading, though they are not first
visits. Only the rebuild for a navigation's new column arms one now.

The watch and the restore's input cancel share one user-input
predicate, and a unit test pins that input during the visit keeps its
load from refocusing.

Refs #2016

* fix(navigation): start Up and Shift+arrow without a cursor at the end shown

Up with no cursor took the last entry by name, and Shift+arrow with no
cursor started from the first or last by name. In a grouped List they
now start from the last or first row shown, as Down already does.

Refs #2016

* refactor(test): share the frame paint wait between test helpers

present_window and the virtual preview scrolling test each requested a
frame and ran the main context until it painted, with the same
ten-second timeout. Move that wait into test_support::wait_for_paint
and use it from both; present_window keeps its assertion and messages.

Refs #1970

* test(preview): settle the scrolling test on two equal painted frames

Settling also waited for an empty main context after each paint, but
GTK always queues fresh work after a paint, so nearly every step paid
for a third frame although its rows had stopped moving after the
second. Every frame already runs all ready work before it paints, so
two equal painted frames are settled. This keeps every hit-test sample
and cuts the test from about 40 s to 30 s; update its CI weight.

Refs #1970

* docs: describe the grouped fallback cursor and list the image's libheif separately

* style(tests): fold the PrivateContext import into the probe tests' crate block

* test(qa): refresh the context-menu baseline for the creation rows and sort button

* fix(columns): keep the child column while its parent reloads

A reload empties the column until its selection is restored, so returning
to Columns during one read an empty selection and closed a child that was
still selected.

* style: drop comments that restate the names beside them

* refactor: restore the code health of the files this change touches

Name the load's cursor predicates, extract the range origin and the focus
target, split the first-row table from its test, and move the ISO BMFF check
and the returning-to-Columns tests into their own modules. No behavior
changes.

---------

Co-authored-by: Pierre Berube <[email protected]>

* fix(uri): preserve non-ASCII URI hosts across sanitization (#2072)

Assisted-by: MiMo-V2.6-Pro

* style(preferences): drop the comment labelling the video start getter

* test(preview): split the configured start test into shorter helpers

* refactor(settings): move the video preview options into a submodule

Adding the start row pushed general.rs past CodeScene's file size limit.

---------

Co-authored-by: William Feht <[email protected]>
Co-authored-by: Pierre Berube <[email protected]>
Co-authored-by: Jeff Zhou <[email protected]>
@zhouwg
zhouwg deleted the kan-v0.3.1 branch November 26, 2026 03:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants