Skip to content

Chromium Sentry Dim/Kill #280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jun 27, 2025
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
89 changes: 89 additions & 0 deletions dev/tools/src/bin/close_tab.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//! Dim a window to a given opacity

use clap::Parser;
use dialoguer::Select;
use dialoguer::theme::ColorfulTheme;
use platform::web::BrowserDetector;
use tools::filters::{
ProcessFilter, ProcessWindowGroup, WindowDetails, WindowFilter, match_running_windows,
};
use util::error::Result;
use util::{Target, config};

#[derive(Parser, Debug, Clone)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Window title text to filter by
#[arg()]
title: Option<String>,
}

fn main() -> Result<()> {
util::set_target(Target::Engine);
let config = config::get_config()?;
util::setup(&config)?;
platform::setup()?;

let args = Args::parse();
let matches = match_running_windows(
&WindowFilter {
title: args.title,
..Default::default()
},
&ProcessFilter {
name: Some("Google Chrome".to_string()),
..Default::default()
},
)?;

let browser = BrowserDetector::new()?;
if let Some(details) = select_window(&matches)? {
browser.close_current_tab(&details.window)?;
} else {
eprintln!("No windows found matching the criteria");
}

Ok(())
}

fn select_window(groups: &[ProcessWindowGroup]) -> Result<Option<&WindowDetails>> {
if groups.is_empty() {
return Ok(None);
}

// Flatten all windows into a single list with process info
let mut all_windows = Vec::new();
for group in groups {
for window in &group.windows {
all_windows.push((group, window));
}
}

if all_windows.is_empty() {
return Ok(None);
}

if all_windows.len() == 1 {
return Ok(Some(all_windows[0].1));
}

// Create selection items
let items: Vec<String> = all_windows
.iter()
.map(|(group, window)| {
format!(
"{} (pid: {}) - \"{}\" (hwnd: {:08x})",
group.process.name, group.process.pid, window.title, window.window.hwnd.0 as usize
)
})
.collect();

// Show selection prompt
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Select a window to dim")
.items(&items)
.default(0)
.interact()?;

Ok(Some(all_windows[selection].1))
}
91 changes: 91 additions & 0 deletions dev/tools/src/bin/tab_track.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! List out browser information

use std::sync::Mutex;

use platform::events::WindowTitleWatcher;
use platform::objects::{EventLoop, Target, Window};
use platform::web::{BrowserDetector, BrowserUrl};
use tools::filters::{ProcessFilter, WindowFilter, match_running_windows};
use util::error::Result;
// use util::tracing::info;
use util::{Target as UtilTarget, config, future as tokio};

// fn perf<T>(f: impl Fn() -> T, act: &str) -> T {
// let start = std::time::Instant::now();
// let result = f();
// info!("{}: {:?}", act, start.elapsed());
// result
// }

struct UnsafeSyncSendBrowserDetect {
browser: BrowserDetector,
}

impl UnsafeSyncSendBrowserDetect {
fn new() -> Result<Self> {
let browser = BrowserDetector::new()?;
Ok(Self { browser })
}

pub fn chromium_url(&self, window: &Window) -> Result<BrowserUrl> {
self.browser.chromium_url(window)
}
}

unsafe impl Send for UnsafeSyncSendBrowserDetect {}
unsafe impl Sync for UnsafeSyncSendBrowserDetect {}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
util::set_target(UtilTarget::Engine);
let config = config::get_config()?;
util::setup(&config)?;
platform::setup()?;

let window_group = match_running_windows(
&WindowFilter {
..Default::default()
},
&ProcessFilter {
name: Some("Google Chrome".to_string()),
..Default::default()
},
)?;
let chrome = window_group.first().unwrap();

let browser = UnsafeSyncSendBrowserDetect::new()?;

let m = Mutex::new(());

let _h = WindowTitleWatcher::new(
Target::Id(chrome.process.pid),
Box::new(move |window| {
let start = std::time::Instant::now();
let _guard = m.lock().unwrap();

let browser_info = browser.chromium_url(&window)?;

let dimset = if let Some(url) = browser_info.url {
if !url.contains("youtube") {
window.dim(0.5f64)?;
} else {
window.dim(1.0f64)?;
}
Some(url)
} else {
None
};
println!(
"{:08x}:{:?}, {:?}",
window.hwnd.0 as usize,
dimset,
start.elapsed()
);
Ok(())
}),
)?;

EventLoop::new().run();

Ok(())
}
38 changes: 32 additions & 6 deletions src/engine/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub struct Store {
pub struct WebsiteCache {
// This never gets cleared, but it's ok since it's a small set of urls?
websites: HashMap<BaseWebsiteUrl, AppDetails>,
// This never gets cleared, but it's ok since it's a small set of apps?
apps: HashMap<Ref<App>, BaseWebsiteUrl>,
// Web state
state: web::State,
}
Expand Down Expand Up @@ -86,6 +88,7 @@ impl Cache {
},
web: WebsiteCache {
websites: HashMap::new(),
apps: HashMap::new(),
state: browser_state,
},
platform: PlatformCache {
Expand All @@ -95,8 +98,8 @@ impl Cache {
}
}

/// Get all processes for an [App].
pub fn processes_for_app(&self, app: &Ref<App>) -> HashSet<KillableProcessId> {
/// Get all processes for an [App]. Will return nothing for websites.
pub fn platform_processes_for_app(&self, app: &Ref<App>) -> HashSet<KillableProcessId> {
let entry = self.platform.processes.get(app);
if let Some(entry) = entry {
match &entry.identity {
Expand All @@ -108,18 +111,20 @@ impl Cache {
.iter()
.map(|ptid| KillableProcessId::Win32(ptid.pid))
.collect(),
// TODO handle Website entries
_ => {
todo!()
panic!(
"unsupported app identity for `platform_processes_for_app`: {:?}",
entry.identity
);
}
}
} else {
HashSet::new()
}
}

/// Get all windows for an [App].
pub fn windows_for_app(&self, app: &Ref<App>) -> impl Iterator<Item = &Window> {
/// Get all windows for an [App]. Will return nothing for websites.
pub fn platform_windows_for_app(&self, app: &Ref<App>) -> impl Iterator<Item = &Window> {
self.platform
.processes
.get(app)
Expand All @@ -134,6 +139,11 @@ impl Cache {
})
}

/// Get the websites for an [App]. If the app is not a website, will return nothing.
pub fn websites_for_app(&self, app: &Ref<App>) -> impl Iterator<Item = &BaseWebsiteUrl> {
self.web.apps.get(app).into_iter()
}

/// Remove a process and associated windows from the [Cache].
pub async fn remove_process(&mut self, process: ProcessId) {
let removed_windows = self
Expand Down Expand Up @@ -277,6 +287,7 @@ impl Cache {
}

let created = { create(self).await? };
self.web.apps.insert(created.app.clone(), base_url.clone());
Ok(self.web.websites.entry(base_url).or_insert(created))
}

Expand All @@ -285,6 +296,21 @@ impl Cache {
state.browser_windows.get(window).copied()
}

/// Get all browser windows.
pub async fn browser_windows(&self) -> HashSet<Window> {
let state = self.web.state.read().await;
state
.browser_windows
.iter()
.filter_map(
|(window, is_browser)| {
if *is_browser { Some(window) } else { None }
},
)
.cloned()
.collect()
}

// pub async fn get_or_insert_session_for_window(&mut self, window: Window, create: impl Future<Output = Result<SessionDetails>>) -> Result<&SessionDetails> {

// unimplemented!()
Expand Down
Loading