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
5 changes: 4 additions & 1 deletion crates/app/src/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,10 @@ pub(crate) type Core = browser_core::Core<DataStore>;
pub(crate) type ProfileRuntime = browser_core::ProfileRuntime<DataStore>;

pub(crate) fn data_dir() -> PathBuf {
browser_core::data_dir(None).unwrap_or_default()
let dir = browser_core::data_dir(None);
#[cfg(windows)]
let dir = dir.or_else(|| Some(engine::local_app_data()?.join("Tarn")));
dir.unwrap_or_default()
}

/// Purges Chromium's data when its owner is gone or a purge is pending; before CEF starts or once it is gone.
Expand Down
2 changes: 2 additions & 0 deletions crates/app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,8 @@ pub fn run() {
}
#[cfg(windows)]
engine::chromium::prepare_browser_process();
#[cfg(windows)]
engine::refresh_browser_registration();
engine::startup::mark("main");
record_panics(browser::data_dir());
#[cfg(feature = "chromium")]
Expand Down
94 changes: 80 additions & 14 deletions crates/engine/src/host_windows.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use std::path::PathBuf;

use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use url::Url;
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, CreateRoundRectRgn, ScreenToClient, SetWindowRgn};
use windows_sys::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
use windows_sys::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx, CoTaskMemFree};
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_SZ, RegGetValueW, RegSetKeyValueW};
use windows_sys::Win32::UI::HiDpi::GetDpiForWindow;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, GetKeyState, SetFocus, VK_MENU, VK_SHIFT};
use windows_sys::Win32::UI::Shell::{
DefSubclassProc, ILCreateFromPathW, ILFree, RemoveWindowSubclass, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify, SHOpenFolderAndSelectItems,
SetWindowSubclass, ShellExecuteW,
DefSubclassProc, FOLDERID_LocalAppData, ILCreateFromPathW, ILFree, RemoveWindowSubclass, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify,
SHGetKnownFolderPath, SHOpenFolderAndSelectItems, SetWindowSubclass, ShellExecuteW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
GWLP_HWNDPARENT, GetClientRect, GetForegroundWindow, GetWindowRect, GetWindowThreadProcessId, HTTRANSPARENT, HWND_TOP, MB_ICONWARNING, MB_OK, MessageBoxW,
Expand Down Expand Up @@ -245,7 +247,7 @@ fn set_value(key: &str, name: Option<&str>, value: &str) -> bool {

fn value(key: &str, name: &str) -> Option<String> {
let (key, name) = (wide(key), wide(name));
let mut buffer = [0u16; 256];
let mut buffer = [0u16; 2048];
let mut size = u32::try_from(size_of_val(&buffer)).unwrap_or(0);
// SAFETY: NUL-terminated strings; `buffer` holds `size` bytes, and RRF_RT_REG_SZ ends it with NUL.
let status =
Expand All @@ -263,9 +265,45 @@ pub fn is_default_browser() -> bool {
/// `is_default_browser`.
pub fn make_default_browser() {
let Some(exe) = std::env::current_exe().ok().and_then(|p| p.to_str().map(str::to_owned)) else { return };
// Chromium, which parses this command line first, takes everything after the marker as one
// URL, so a link cannot add switches.
let command = format!("\"{exe}\" {SINGLE_ARGUMENT} %1");
if !register_browser(&exe) {
return;
}
let (verb, target) = (wide("open"), wide("ms-settings:defaultapps?registeredAppUser=Tarn"));
// SAFETY: NUL-terminated strings that outlive the call.
unsafe { ShellExecuteW(std::ptr::null_mut(), verb.as_ptr(), target.as_ptr(), std::ptr::null(), std::ptr::null(), SW_SHOWNORMAL) };
}

/// Points an earlier Make Default at the installed `tarn.exe` once the install folder moved, as it
/// does when the user profile moves to another drive. Development builds leave it alone.
pub fn refresh_browser_registration() {
let Some(installed) = local_app_data().map(|d| d.join(r"Programs\Tarn\tarn.exe")) else { return };
let running = std::env::current_exe().and_then(std::fs::canonicalize).ok();
let (Some(exe), true) = (installed.to_str(), running.is_some() && running == std::fs::canonicalize(&installed).ok()) else { return };
let found = [
value(&format!(r"Software\Classes\{PROG_ID}\shell\open\command"), ""),
value(&format!(r"{CLIENT}\shell\open\command"), ""),
value(r"Software\RegisteredApplications", "Tarn"),
];
if registration_stale(exe, &found) {
register_browser(exe);
}
}

/// Whether an earlier registration, also one a failed write left unfinished, names another
/// executable than `exe`.
fn registration_stale(exe: &str, found: &[Option<String>; 3]) -> bool {
let current = [open_command(exe), format!("\"{exe}\""), format!(r"{CLIENT}\Capabilities")];
found.iter().any(Option::is_some) && found.iter().zip(&current).any(|(found, current)| !found.as_ref().is_some_and(|f| f.eq_ignore_ascii_case(current)))
}

/// Chromium, which parses this command line first, takes everything after the marker as one URL,
/// so a link cannot add switches.
fn open_command(exe: &str) -> String {
format!("\"{exe}\" {SINGLE_ARGUMENT} %1")
}

fn register_browser(exe: &str) -> bool {
let command = open_command(exe);
let classes = format!(r"Software\Classes\{PROG_ID}");
let registered = set_value(&classes, None, "Tarn URL")
&& set_value(&format!(r"{classes}\DefaultIcon"), None, &format!("{exe},0"))
Expand All @@ -276,14 +314,28 @@ pub fn make_default_browser() {
&& set_value(&format!(r"{CLIENT}\Capabilities"), Some("ApplicationDescription"), "A private web browser.")
&& ["http", "https"].iter().all(|scheme| set_value(&format!(r"{CLIENT}\Capabilities\URLAssociations"), Some(scheme), PROG_ID))
&& set_value(r"Software\RegisteredApplications", Some("Tarn"), &format!(r"{CLIENT}\Capabilities"));
if !registered {
return;
if registered {
// SAFETY: tells the shell file associations changed; no item arguments.
unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED as i32, SHCNF_IDLIST, std::ptr::null(), std::ptr::null()) };
}
// SAFETY: tells the shell file associations changed; no item arguments.
unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED as i32, SHCNF_IDLIST, std::ptr::null(), std::ptr::null()) };
let (verb, target) = (wide("open"), wide("ms-settings:defaultapps?registeredAppUser=Tarn"));
// SAFETY: NUL-terminated strings that outlive the call.
unsafe { ShellExecuteW(std::ptr::null_mut(), verb.as_ptr(), target.as_ptr(), std::ptr::null(), std::ptr::null(), SW_SHOWNORMAL) };
registered
}

/// The user's Local AppData folder as the shell resolves it, the folder the installer uses too;
/// for when `LOCALAPPDATA` is missing from the environment.
pub fn local_app_data() -> Option<PathBuf> {
use std::os::windows::ffi::OsStringExt;
let mut path: windows_sys::core::PWSTR = std::ptr::null_mut();
// SAFETY: `path` receives a NUL-terminated string the shell allocates, freed below.
let status = unsafe { SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, std::ptr::null_mut(), &mut path) };
let dir = (status >= 0 && !path.is_null()).then(|| {
// SAFETY: `path` is a valid NUL-terminated wide string until it is freed below.
let units = unsafe { std::slice::from_raw_parts(path, (0..).take_while(|&i| *path.add(i) != 0).count()) };
PathBuf::from(std::ffi::OsString::from_wide(units))
});
// SAFETY: frees the shell's allocation; null is allowed.
unsafe { CoTaskMemFree(path.cast()) };
dir.filter(|d| d.is_absolute())
}

/// A modal alert for when no window can show the message; returns once the user dismisses it.
Expand Down Expand Up @@ -365,4 +417,18 @@ mod tests {
assert!(super::external_allowed(&Url::parse(allowed).unwrap()), "{allowed}");
}
}

#[test]
fn a_moved_or_unfinished_registration_is_stale() {
let exe = r"D:\Users\a\AppData\Local\Programs\Tarn\tarn.exe";
let old = r"C:\Users\a\AppData\Local\Programs\Tarn\tarn.exe";
let of = |exe: &str| [Some(super::open_command(exe)), Some(format!("\"{exe}\"")), Some(format!(r"{}\Capabilities", super::CLIENT))];
assert!(!super::registration_stale(exe, &[None, None, None]), "never registered");
assert!(!super::registration_stale(exe, &of(exe)));
assert!(!super::registration_stale(exe, &of(&exe.to_uppercase())), "case differs only");
assert!(super::registration_stale(exe, &of(old)), "install folder moved");
let [command, _, listed] = of(exe);
assert!(super::registration_stale(exe, &[command.clone(), None, listed]), "a write failed after the link command");
assert!(super::registration_stale(exe, &[command, Some(format!("\"{exe}\"")), None]), "never listed in Default Apps");
}
}
4 changes: 2 additions & 2 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ pub use data_store_windows::{DataStore, FilterLists, builtin_rules_failed};
pub use events::{Event, Protection};
#[cfg(windows)]
pub use host_windows::{
Host, MIN_ZOOM, Popup, alert, app_active, bundle_identifier, is_default_browser, make_default_browser, open_external, option_held, reduce_motion,
reveal_in_finder, shift_held,
Host, MIN_ZOOM, Popup, alert, app_active, bundle_identifier, is_default_browser, local_app_data, make_default_browser, open_external, option_held,
reduce_motion, refresh_browser_registration, reveal_in_finder, shift_held,
};
pub use nav_policy::SiteFor;
#[cfg(any(target_os = "macos", windows))]
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/tests/tarn_extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ mod window {
let uuid = "6A1B2C3D-0000-4000-8000-00000000E715";
let data = DataStore::persistent(uuid, uuid, Rc::new(|_| {})).unwrap();
let rules = format!(
r#"[{{"trigger":{{"url-filter":"^http://127\\.0\\.0\\.1:{port}/blocked\\.js"}},"action":{{"type":"block"}}}},{{"trigger":{{"url-filter":"^https://extension\\.tarnbrowser\\.com/"}},"action":{{"type":"block"}}}}]"#
r#"[{{"trigger":{{"url-filter":"^http://127\\.0\\.0\\.1:{port}/blocked\\.js"}},"action":{{"type":"block"}}}},{{"trigger":{{"url-filter":"^https://extensions\\.tarnbrowser\\.com/"}},"action":{{"type":"block"}}}}]"#
);
let compiled: Rc<RefCell<Option<FilterLists>>> = Rc::default();
let slot = compiled.clone();
Expand Down
4 changes: 2 additions & 2 deletions crates/store/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,8 @@ pub struct Store {
impl Store {
pub fn open(dir: &Path) -> Result<Self> {
let path = dir.join("tarn.db");
// Windows: the data folder lives under %LOCALAPPDATA%, whose inherited ACL already admits
// only the user, SYSTEM and Administrators.
// Windows: the data folder lives under the user's Local AppData, whose inherited ACL
// already admits only the user, SYSTEM and Administrators.
#[cfg(unix)]
{
DirBuilder::new().recursive(true).mode(0o700).create(dir)?;
Expand Down
7 changes: 6 additions & 1 deletion docs/windows-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,12 @@ WebView2 plan and are kept for the security mapping; where they disagree, this s
another window), GPUI gets a move just outside it, which clears the hover it would otherwise
keep. Key presses with Ctrl or Alt (except editing keys) also go to GPUI.
- **Platform:** AI token in the Credential Manager, memory pressure from `GlobalMemoryStatusEx`,
data in `%LOCALAPPDATA%\Tarn` (user-only ACL inherited, no Unix modes).
data in `%LOCALAPPDATA%\Tarn`, or the shell's Local AppData known folder (the one the installer
and uninstaller use) when the variable is missing (user-only ACL inherited, no Unix modes). The
installer needs no administrator rights and always installs into the current
`{localappdata}\Programs\Tarn` (`UsePreviousAppDir=no`); at start the installed `tarn.exe`
re-points an earlier Make Default registration that names another path, a development build's
included.
- **Window and input:** the toolbar and the settings header are the caption (the hook starts the
system move; a double click maximizes), with Windows minimize/maximize/close buttons. Pop-ups
opened without focus (address suggestions, hover cards, peek) stay inactive until clicked,
Expand Down
2 changes: 1 addition & 1 deletion linux/src/webview/display_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ fn only_the_users_own_navigation_to_a_store_link_asks_to_install() {
let web = open(&state);
let block: Rc<RefCell<Option<UserContentFilter>>> = Rc::default();
let slot = block.clone();
let rules = r#"[{"trigger":{"url-filter":"^https://extension\\.tarnbrowser\\.com/"},"action":{"type":"block"}}]"#;
let rules = r#"[{"trigger":{"url-filter":"^https://extensions\\.tarnbrowser\\.com/"},"action":{"type":"block"}}]"#;
filters::compile_one("store-block.test".into(), rules.into(), move |f| *slot.borrow_mut() = Some(f));
assert!(spin_until(|| block.borrow().is_some(), 20), "the test's rule compiled");
state.content.borrow().as_ref().unwrap().add_filter(block.borrow().as_ref().unwrap());
Expand Down
2 changes: 2 additions & 0 deletions packaging/windows/tarn.iss
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ VersionInfoVersion={#AppVersion}
PrivilegesRequired=lowest
DefaultDirName={localappdata}\Programs\Tarn
DisableDirPage=yes
; A profile moved to another drive or renamed would otherwise get the old folder, which PrepareToInstall refuses.
UsePreviousAppDir=no
DisableProgramGroupPage=yes
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
Expand Down
Loading