wayBetter for X 1.0.2

This commit is contained in:
CRTkafa 2026-10-02 02:54:04 +07:00
parent 785c8cc72c
commit 435f05bd3e
212 changed files with 10208 additions and 2345 deletions

View file

@ -6,16 +6,14 @@
//! `XSite` fills in its hooks.
use crate::{
alerts::{self, AlertGate, AlertSettings, KeywordHit, Throttle},
alerts::{self, AlertGate, KeywordHit, Throttle},
capture::CaptureSession,
compose,
db::Store,
desktop_popover,
model::*,
plugins, profiles,
policy,
site::SITE,
theme::{x_default, ThemeScopes, XTheme, X_THEMES},
};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
@ -24,7 +22,8 @@ use tauri::{AppHandle, Manager, State, Webview};
use url::Url;
use waybetter_host::app::{self as wb, AppConfig, NewTab, SiteHooks, TabClosed};
use waybetter_host::host::emit_tab_state as emit_state;
pub(crate) use waybetter_host::host::{data_file, emit_shell, read_json, shell_only, tab_only, tab_webview, write_json};
pub(crate) use waybetter_host::vault_commands::lock as vault;
pub(crate) use waybetter_host::host::{emit_shell, shell_only, tab_only, tab_webview};
use waybetter_host::tabs::{self, ColumnConfig, TabLayout, TabRole, TabState};
// Settings backup/sync, workspaces, plugin palette commands and developer mode (shell-only).
@ -35,36 +34,20 @@ mod settings;
const LEGACY_IDENTIFIER: &str = "dev.xworkspace.desktop";
/// The page for new tabs and the first launch until the owner sets another.
const HOME_URL: &str = "https://x.com/home";
/// Written only when the owner opts in to theming X ("Apply theme to X").
const THEME_FILE: &str = "x-theme.v2.json";
/// Pre-opt-in builds wrote this automatically; it must not keep recoloring X.
const LEGACY_THEME_FILE: &str = "x-theme.json";
/// Account and pane themes and the chrome setting (`theme::ThemeScopes`); absent = defaults.
const THEME_SCOPES_FILE: &str = "x-theme-scopes.json";
/// The account profiles (the framework keeps them; backups read and import them).
const PROFILES_FILE: &str = wb::PROFILES_FILE;
const ALERTS_FILE: &str = "alerts.json";
// ---------------------------------------------------------------------------------------------
// State
struct NativeData {
store: Store,
/// Composer→draft mappings per tab; navigation in a tab rotates only that tab's mappings.
captures: HashMap<String, CaptureSession>,
theme: Option<XTheme>,
/// Which theme each tab shows (pane, account, global) and whether the chrome follows it.
theme_scopes: ThemeScopes,
/// The Theme Builder's unsaved draft, shown in every X tab until it is saved or closed.
theme_preview: Option<XTheme>,
/// Tab webview label -> X's left navigation repeats one already on screen (see `pane_script`).
tab_nav_redundant: HashMap<String, bool>,
/// Tab webview label -> its deck column config (Power User Mode; `column_configure`).
tab_columns: HashMap<String, ColumnConfig>,
/// Tab webview label -> the palette commands its plugins registered (`tab_report.commands`).
tab_commands: HashMap<String, Vec<crate::palette_commands::PaletteCommand>>,
/// Keyword alerts (local only) and their dedupe/rate limit.
alerts: AlertSettings,
/// Keyword alert dedupe/rate limit (the settings are the host's: `waybetter_host::alerts_commands`).
alert_gate: AlertGate,
/// Capture-failure notifications: at most one per tab every few minutes.
capture_failures: Throttle,
@ -91,19 +74,13 @@ fn lock(state: &AppState) -> Result<MutexGuard<'_, NativeData>, String> {
// ---------------------------------------------------------------------------------------------
// Workspace commands (shell only)
#[tauri::command]
async fn draft_list(webview: Webview, state: State<'_, AppState>) -> Result<Vec<Draft>, String> {
shell_only(&webview)?;
lock(&state)?.store.list_drafts()
}
/// Vault reads for the drafts popover (desktop_popover.rs checks the caller first).
pub(crate) fn vault_drafts(app: &AppHandle) -> Result<Vec<Draft>, String> {
lock(&app.state::<AppState>())?.store.list_drafts()
vault(app)?.list_drafts()
}
pub(crate) fn vault_draft(app: &AppHandle, id: &str) -> Result<Option<Draft>, String> {
lock(&app.state::<AppState>())?.store.get_draft(id)
vault(app)?.get_draft(id)
}
/// Whether tab `label` has a captured draft for exactly this post page that none of its live
@ -114,58 +91,11 @@ pub(crate) fn resumable_draft(app: &AppHandle, label: &str, url: &Url) -> Result
if !crate::popover::is_reply_context(url) {
return Ok(false);
}
let drafts = data.store.list_drafts()?;
let drafts = vault(app)?.list_drafts()?;
let live: HashSet<&str> = data.captures.get(label).map(|session| session.draft_ids().collect()).unwrap_or_default();
Ok(crate::popover::has_resumable_draft(&drafts, url, |id| live.contains(id)))
}
#[tauri::command]
async fn draft_save(
webview: Webview,
state: State<'_, AppState>,
input: SaveDraftInput,
) -> Result<Draft, String> {
shell_only(&webview)?;
lock(&state)?.store.save_draft(&input)
}
#[tauri::command]
async fn draft_revisions(
webview: Webview,
state: State<'_, AppState>,
draft_id: String,
) -> Result<Vec<DraftRevision>, String> {
shell_only(&webview)?;
lock(&state)?.store.revisions(&draft_id)
}
#[tauri::command]
async fn draft_status(
webview: Webview,
state: State<'_, AppState>,
id: String,
expected_revision: i64,
status: String,
) -> Result<Draft, String> {
shell_only(&webview)?;
lock(&state)?.store.set_status(&id, expected_revision, &status)
}
#[tauri::command]
async fn observation_list(
webview: Webview,
state: State<'_, AppState>,
) -> Result<Vec<Observation>, String> {
shell_only(&webview)?;
lock(&state)?.store.observations()
}
#[tauri::command]
async fn data_export(webview: Webview, state: State<'_, AppState>) -> Result<ExportData, String> {
shell_only(&webview)?;
lock(&state)?.store.export()
}
/// The X page may only append composer snapshots. Mappings are owned natively per tab.
#[tauri::command]
async fn capture_draft(
@ -182,11 +112,14 @@ async fn capture_draft(
return Err("UNSUPPORTED: remote capture is enabled only on macOS and Windows".into());
}
let mut data = lock(&state)?;
let NativeData { store, captures, capture_failures, .. } = &mut *data;
let NativeData { captures, capture_failures, .. } = &mut *data;
// The vault is locked after the capture state, always in this order (see `resumable_draft`).
let mut store = vault(webview.app_handle())?;
let result = captures
.entry(webview.label().to_owned())
.or_default()
.write(store, capture);
.write(&mut store, capture);
drop(store);
if let Err(error) = &result {
if alerts::capture_failure_notifies(error)
&& capture_failures.allow(webview.label(), std::time::Instant::now())
@ -275,38 +208,6 @@ async fn tab_insert_text(webview: Webview, app: AppHandle, id: String, text: Str
tab.eval(&script).map_err(|error| format!("TAB: {error}"))
}
#[tauri::command]
async fn alerts_get(webview: Webview, state: State<'_, AppState>) -> Result<AlertSettings, String> {
shell_only(&webview)?;
Ok(lock(&state)?.alerts.clone())
}
#[tauri::command]
async fn alerts_set(
webview: Webview,
app: AppHandle,
state: State<'_, AppState>,
settings: AlertSettings,
) -> Result<AlertSettings, String> {
shell_only(&webview)?;
let settings = settings.validated()?;
let script = alerts_script(&settings);
{
// Hold the lock across the write so concurrent saves cannot leave disk and memory disagreeing.
let mut data = lock(&state)?;
write_json(&app, ALERTS_FILE, &settings)?;
data.alerts = settings.clone();
}
eval_in_x_tabs(&app, &script);
Ok(settings)
}
/// Hands the X runtime the keywords to watch for (empty = alerts off, observer uninstalled).
fn alerts_script(settings: &AlertSettings) -> String {
let keywords = serde_json::to_string(settings.active_keywords()).unwrap_or_else(|_| "[]".into());
tabs::deliver_script(SITE.runtime_global, "alerts", "set", "__btAlerts", &keywords)
}
/// An X tab reports a configured keyword in a tweet it already received. Local notification only,
/// deduplicated per tweet and rate limited.
#[tauri::command]
@ -315,7 +216,7 @@ async fn keyword_alert(webview: Webview, state: State<'_, AppState>, hit: Keywor
policy::require_capture(webview.label(), &url)?;
let message = {
let mut data = lock(&state)?;
let message = alerts::check_hit(&data.alerts, &hit)?;
let message = alerts::check_hit(&waybetter_host::alerts_commands::settings(webview.app_handle())?, &hit)?;
if !data.alert_gate.allow(&hit, std::time::Instant::now()) {
return Ok(());
}
@ -332,138 +233,6 @@ async fn keyword_alert(webview: Webview, state: State<'_, AppState>, hit: Keywor
Ok(())
}
fn load_theme(app: &AppHandle) -> Option<XTheme> {
let theme: XTheme = read_json(app, THEME_FILE)?;
theme.validate(&X_THEMES).ok()?;
Some(theme)
}
fn load_theme_scopes(app: &AppHandle) -> ThemeScopes {
read_json::<ThemeScopes>(app, THEME_SCOPES_FILE).filter(|scopes| scopes.validate().is_ok()).unwrap_or_default()
}
/// The theme (and the Google font bytes it needs) for the X tab `label`: the Theme Builder's
/// preview while one is open, else its pane's, its account's or the global theme.
fn tab_theme(app: &AppHandle, state: &NativeData, label: &str) -> XTheme {
let global = state.theme.clone().unwrap_or_else(x_default);
match &state.theme_preview {
Some(preview) => preview.clone(),
None => {
let tab = policy::tab_id(label).unwrap_or_default();
state.theme_scopes.for_tab(&X_THEMES, &global, tab, wb::tab_profile(app, label).as_deref())
}
}
}
/// The X tab `label`'s native background: its theme's page color (see `XTheme::page_color`).
fn tab_background(app: &AppHandle, state: &NativeData, label: &str) -> Option<tauri::window::Color> {
tab_theme(app, state, label).page_color(&X_THEMES).map(|(r, g, b)| tauri::window::Color(r, g, b, 255))
}
fn tab_theme_scripts(app: &AppHandle, state: &NativeData, label: &str) -> Vec<String> {
let theme = tab_theme(app, state, label);
let mut scripts = Vec::new();
if let Some(fonts) = waybetter_host::fonts::page_script_for(&SITE, &theme.google_fonts()) {
scripts.push(fonts);
}
if let Ok(script) = theme.script(&X_THEMES, &SITE) {
scripts.push(script);
}
scripts
}
/// Sends every X tab its theme again (after the theme, the scopes, the preview or the fonts changed).
fn apply_themes(app: &AppHandle) {
// Safe mode: X pages keep X's own look; a theme chosen meanwhile applies when safe mode is left.
if waybetter_host::safe::active() {
return;
}
let Some(state) = app.try_state::<AppState>() else { return };
let per_tab: Vec<(Webview, Vec<String>, Option<tauri::window::Color>)> = {
let Ok(data) = state.0.lock() else { return };
app.webviews()
.into_iter()
.filter(|(label, tab)| policy::tab_id(label).is_some() && tab.url().is_ok_and(|url| policy::x_origin(&url)))
.map(|(label, tab)| (tab, tab_theme_scripts(app, &data, &label), tab_background(app, &data, &label)))
.collect()
};
for (tab, scripts, background) in per_tab {
let _ = tab.set_background_color(background);
for script in scripts {
let _ = tab.eval(&script);
}
}
}
/// Applies a theme to every X tab and persists it. `None` (or the `x` preset without an accent)
/// restores X's own look.
#[tauri::command]
async fn x_set_theme(
webview: Webview,
app: AppHandle,
state: State<'_, AppState>,
theme: Option<XTheme>,
) -> Result<(), String> {
shell_only(&webview)?;
let theme = theme.unwrap_or_else(x_default);
theme.validate(&X_THEMES)?;
if theme.is_empty(&X_THEMES) {
if let Some(path) = data_file(&app, THEME_FILE) {
let _ = std::fs::remove_file(path);
}
lock(&state)?.theme = None;
} else {
write_json(&app, THEME_FILE, &theme)?;
lock(&state)?.theme = Some(theme);
}
apply_themes(&app);
Ok(())
}
/// Account and pane themes and the chrome setting.
#[tauri::command]
async fn theme_scopes_get(webview: Webview, state: State<'_, AppState>) -> Result<ThemeScopes, String> {
shell_only(&webview)?;
Ok(lock(&state)?.theme_scopes.clone())
}
/// Saves account and pane themes (bounded, ids checked) and re-themes every X tab.
#[tauri::command]
async fn theme_scopes_set(webview: Webview, app: AppHandle, state: State<'_, AppState>, scopes: ThemeScopes) -> Result<(), String> {
shell_only(&webview)?;
scopes.validate()?;
if scopes.is_default() {
if let Some(path) = data_file(&app, THEME_SCOPES_FILE) {
let _ = std::fs::remove_file(path);
}
} else {
write_json(&app, THEME_SCOPES_FILE, &scopes)?;
}
lock(&state)?.theme_scopes = scopes;
apply_themes(&app);
Ok(())
}
/// The Theme Builder's live preview: an unsaved theme shown in every X tab (not persisted). `None`
/// ends the preview and gives every tab its own theme back.
#[tauri::command]
async fn x_preview_theme(webview: Webview, app: AppHandle, state: State<'_, AppState>, theme: Option<XTheme>) -> Result<(), String> {
shell_only(&webview)?;
if let Some(theme) = &theme {
theme.validate(&X_THEMES)?;
}
lock(&state)?.theme_preview = theme;
apply_themes(&app);
Ok(())
}
/// The persisted X theme (default when none).
#[tauri::command]
async fn x_theme_get(webview: Webview, state: State<'_, AppState>) -> Result<XTheme, String> {
shell_only(&webview)?;
Ok(lock(&state)?.theme.clone().unwrap_or_else(x_default))
}
/// Tells an X tab whether its left navigation repeats one already on screen; the runtime hides it
/// while the `singleSplitNav` feature is on. Queued in `__btPane` until the runtime exists.
fn pane_script(nav_redundant: bool) -> String {
@ -534,7 +303,7 @@ struct TabReport {
/// Injected into every tab: SPA URL/title/favicon changes and focus, for the address bar.
#[tauri::command]
async fn tab_report(webview: Webview, app: AppHandle, state: State<'_, AppState>, report: TabReport) -> Result<(), String> {
async fn tab_report(webview: Webview, app: AppHandle, report: TabReport) -> Result<(), String> {
let id = tab_only(&webview)?;
let seen = match (report.account, report.signed_out) {
(Some(account), _) => Some(profiles::AccountSeen::SignedIn(account)),
@ -547,11 +316,7 @@ async fn tab_report(webview: Webview, app: AppHandle, state: State<'_, AppState>
}
// Plugin palette commands: strings about this tab, only from a tab on x.com right now.
if let Some(list) = report.commands {
if webview.url().is_ok_and(|url| policy::x_origin(&url)) {
let list = crate::palette_commands::validate(list)?;
let mut data = lock(&state)?;
settings::tab_commands_reported(&app, &mut data, webview.label(), &id, Some(list));
}
waybetter_host::tab_commands::reported(&app, &webview, list)?;
}
// Only a number about this tab, only from a tab on x.com right now (column.rs).
let unread = webview.url().ok().and_then(|url| crate::column::accept_unread(webview.label(), &url, report.unread));
@ -589,12 +354,10 @@ fn as_x_url(url: &Url) -> Option<Url> {
/// Theme, custom CSS, feature flags and enabled plugins for a freshly loaded X document in tab
/// `label`. The flags, the link setting, custom CSS and the plugins are the host's page state
/// (`wb::page_scripts`); X's alerts and theme go between them, as they always did.
fn x_page_scripts(app: &AppHandle, state: &NativeData, label: &str) -> Vec<String> {
fn x_page_scripts(app: &AppHandle, label: &str) -> Vec<String> {
let Ok(page) = wb::page_scripts(app) else { return Vec::new() };
let mut scripts = vec![page.features, alerts_script(&state.alerts), page.links];
if state.theme.is_some() || state.theme_preview.is_some() || !state.theme_scopes.is_default() {
scripts.extend(tab_theme_scripts(app, state, label));
}
let mut scripts = vec![page.features, waybetter_host::alerts_commands::script(app), page.links];
scripts.extend(waybetter_host::theme_commands::page_scripts(app, label));
scripts.extend(page.css);
scripts.extend(page.plugins);
scripts
@ -630,9 +393,7 @@ impl SiteHooks for XSite {
}
fn tab_background(&self, app: &AppHandle, label: &str) -> Option<tauri::window::Color> {
let state = app.state::<AppState>();
let data = lock(&state).ok()?;
tab_background(app, &data, label)
waybetter_host::theme_commands::tab_background(app, label)
}
/// Legacy twitter.com links (other than login routes) load as the same path on x.com.
@ -656,21 +417,13 @@ impl SiteHooks for XSite {
Some(wb::page(app).ok()?.settings.external_in_browser())
}
/// A new document: its plugins register their palette commands again.
fn page_started(&self, app: &AppHandle, tab: &Webview) {
let Some(id) = policy::tab_id(tab.label()) else { return };
if let Ok(mut data) = app.state::<AppState>().0.lock() {
settings::tab_commands_reported(app, &mut data, tab.label(), id, None);
}
}
fn site_page_loaded(&self, app: &AppHandle, tab: &Webview, _url: &Url) {
let mut scripts = app
.state::<AppState>()
.0
.lock()
.map(|data| {
let mut scripts = x_page_scripts(app, &data, tab.label());
let mut scripts = x_page_scripts(app, tab.label());
let redundant = data.tab_nav_redundant.get(tab.label()).copied().unwrap_or(false);
scripts.push(pane_script(redundant));
if let Some(column) = data.tab_columns.get(tab.label()) {
@ -690,11 +443,6 @@ impl SiteHooks for XSite {
}
}
/// A Google font was installed or removed: every X tab gets its theme (and font bytes) again.
fn fonts_changed(&self, app: &AppHandle) {
apply_themes(app);
}
/// What a backup and sync carry from app data (the host adds the shell's own storage).
fn backup_sections(&self, app: &AppHandle) -> Result<serde_json::Map<String, serde_json::Value>, String> {
settings::backup_native(app)
@ -715,18 +463,14 @@ impl SiteHooks for XSite {
fn dev_theme_apply(&self, app: &AppHandle, path: &std::path::Path) -> Result<(), waybetter_host::devmode::DevError> {
let theme = crate::devmode::load_theme_file(path)?;
if let Ok(mut data) = lock(&app.state::<AppState>()) {
data.theme_preview = Some(theme);
}
apply_themes(app);
let _ = waybetter_host::theme_commands::set_preview(app, Some(theme));
waybetter_host::theme_commands::apply(app);
Ok(())
}
fn dev_theme_end(&self, app: &AppHandle) {
if let Ok(mut data) = lock(&app.state::<AppState>()) {
data.theme_preview = None;
}
apply_themes(app);
let _ = waybetter_host::theme_commands::set_preview(app, None);
waybetter_host::theme_commands::apply(app);
}
fn tab_created(&self, _app: &AppHandle) {
@ -791,32 +535,25 @@ fn config() -> AppConfig {
updater: true,
page_string_prefixes: crate::desktop_i18n::PAGE_PREFIXES,
home_url: Some(HOME_URL),
..AppConfig::new(&SITE, "wayBetter for X", &plugins::HOST).with_store(&crate::distribution::STORE).with_media().with_fonts().with_updates(&crate::desktop_update::CONFIG).with_sync().with_dev()
..AppConfig::new(&SITE, "wayBetter for X", &plugins::HOST).with_store(&crate::distribution::STORE).with_media().with_fonts().with_updates(&crate::desktop_update::CONFIG).with_sync().with_dev().with_themes(&crate::theme::THEMES).with_alerts(&alerts::ALERTS).with_vault(&VAULT)
}
}
/// X's drafts vault: where it lives in app data and X's rules for it (`db::RULES`).
static VAULT: waybetter_host::vault_commands::VaultConfig = waybetter_host::vault_commands::VaultConfig { file: "workspace.sqlite3", rules: &crate::db::RULES };
/// X's own state and services, after the host's (app data folder, profiles, language, the plugin
/// store, tweak flags and settings).
fn setup(handle: &AppHandle) -> Result<(), Box<dyn std::error::Error>> {
let directory = handle.path().app_data_dir()?;
let _ = std::fs::remove_file(directory.join(LEGACY_THEME_FILE));
let store = Store::open(directory.join("workspace.sqlite3")).map_err(std::io::Error::other)?;
let _ = std::fs::remove_file(directory.join(crate::theme::LEGACY_FILE));
handle.manage(AppState(Mutex::new(NativeData {
store,
captures: HashMap::new(),
theme: load_theme(handle),
theme_scopes: load_theme_scopes(handle),
theme_preview: None,
tab_nav_redundant: HashMap::new(),
tab_columns: HashMap::new(),
tab_commands: HashMap::new(),
alerts: read_json::<AlertSettings>(handle, ALERTS_FILE)
.and_then(|settings| settings.validated().ok())
.unwrap_or_default(),
alert_gate: AlertGate::default(),
capture_failures: Throttle::new(std::time::Duration::from_secs(300), std::time::Duration::from_secs(300), 3),
})));
desktop_popover::manage(handle);
Ok(())
}
@ -828,19 +565,7 @@ pub fn run() {
setup,
tauri::generate_context!(),
tauri::generate_handler![
draft_list,
draft_save,
draft_revisions,
draft_status,
observation_list,
data_export,
capture_draft,
x_set_theme,
x_theme_get,
theme_scopes_get,
theme_scopes_set,
x_preview_theme,
settings::tab_run_command,
column_configure,
tab_report,
drafts_picker_open,
@ -852,8 +577,6 @@ pub fn run() {
desktop_popover::popover_insert,
desktop_popover::popover_close,
desktop_popover::popover_open_vault,
alerts_get,
alerts_set,
keyword_alert,
crate::desktop_media::tab_attach_image,
],