Ignore mouse event on transparent areas
Hi, everybody! It would be great to have the same feature as the electron has. Please see the link below.
https://www.electronjs.org/docs/api/browser-window#winsetignoremouseeventsignore-options
The feature is about ignoring and passing the mouse event. I need to have this feature in the transparent locations within the Tauri window. Thanks in advance :)
Found this implementation in Electron C++ code. Maybe this could help. https://github.com/electron/electron/blob/b8261f15916eb94428d5672716f85c56720b1501/shell/browser/native_window_views.cc#L1047
FYI, electron's setIgnoreMouseEvents will ignore all mouse events and not just on transparent areas.
Detecting whether an area within a window is transparent or not is a near impossible task, even electron gave up on the idea and will introduce an api for manipulating the window shape instead.
I will close this issue, and if you want the same functionality as electron's setIgnoreMouseEvents (no transparent detection), please file a feature request at https://github.com/tauri-apps/tao
Hi, since https://github.com/tauri-apps/tao/pull/421 was merged into tao, can that function be exposed in tauri's api?
Is there any new progress?
It was part of Tauri's v1.2 release: https://github.com/tauri-apps/tauri/pull/5032 (the PR missed a changefile so it doesn't show up on the changelog :/ )
But this problem is still not solved because the forward option is missing. So set_ignore_cursor_events can be used but it cannot be disabled, because all mouse events are ignored and you can not detect if user hovers over transparent area.
I can do this in electron, but I can't find a method similar to win.webContents.capturePage in Tauri.
import { screen, BrowserWindow } from "electron";
export function useIgnoreMouseEventsByAlpha(win: BrowserWindow) {
const updateIgnoreMouseEvents = async (x: number, y: number) => {
if (!win.isVisible()) return;
// capture 1x1 image of mouse position.
const image = await win.webContents.capturePage({
x,
y,
width: 1,
height: 1,
});
var buffer = image.getBitmap();
// set ignore mouse events by alpha.
win.setIgnoreMouseEvents(!buffer[3]);
};
const pointInterval = setInterval(() => {
const point = screen.getCursorScreenPoint();
const [x, y] = win.getPosition();
const [w, h] = win.getSize();
if (point.x > x && point.x < x + w && point.y > y && point.y < y + h) {
updateIgnoreMouseEvents(point.x - x, point.y - y);
}
}, 100);
win.on("close", () => {
clearInterval(pointInterval);
});
}
I have developed the following code, which has a certain performance overhead, but the switching speed of the set_ignore_cursor_events is fast enough.
use core::time::Duration;
use png::Decoder;
use serde::Serialize;
use std::error::Error;
use std::sync::mpsc;
use std::{
io::Cursor,
sync::{Arc, Mutex},
thread,
};
use tauri::{Window, WindowEvent};
use windows::Win32::Foundation::POINT;
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
/**
* Decode PNG data
*/
pub fn decode_png(data: &[u8]) -> Result<(Vec<u8>, u32, u32), png::DecodingError> {
let decoder = Decoder::new(Cursor::new(data));
let mut reader = decoder.read_info()?;
let mut img_data = vec![0; reader.output_buffer_size()];
let info = reader.next_frame(&mut img_data)?;
Ok((img_data, info.width, info.height))
}
/**
* Get pixel color at x and y coordinates, the bitmap is RGBA8888 format.
*/
pub fn get_pixel_color(bitmap: &[u8], width: u32, x: u32, y: u32) -> Option<(u8, u8, u8, u8)> {
let index = ((y * width + x) as usize) * 4; // Each pixel has 4 bytes (RGBA)
if index + 3 < bitmap.len() {
Some((
bitmap[index],
bitmap[index + 1],
bitmap[index + 2],
bitmap[index + 3],
))
} else {
None
}
}
/**
* Capture window preview, synchronous, resource-intensive
*/
fn capture_preview(window: &Window) -> Result<Vec<u8>, String> {
if !window.is_visible().map_err(|x| x.to_string())? {
return Err("Window is not visible".into());
}
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();
let tx2 = tx.clone();
let _ = window.with_webview(move |webview| {
#[cfg(windows)]
unsafe {
use webview2_com::CapturePreviewCompletedHandler;
use webview2_com::Microsoft::Web::WebView2::Win32::{
ICoreWebView2_15, COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG,
};
use windows::core::Interface;
use windows::Win32::UI::Shell::SHCreateMemStream;
let stream1 = match SHCreateMemStream(std::ptr::null(), 0) {
Some(stream) => stream,
None => {
let _ = tx.send(Err("Unable to create image stream".to_string()));
return;
}
};
let stream2 = match stream1.Clone() {
Ok(stream) => stream,
Err(error) => {
let _ = tx.send(Err(error.to_string()));
return;
}
};
let handler = CapturePreviewCompletedHandler::create(Box::new(move |result| {
if let Err(err) = result {
tx1.send(Err(err.to_string())).unwrap();
return Err(err.into());
}
let mut data: Vec<u8> = Vec::new();
let mut buffer: [u8; 4096] = [0; 4096];
loop {
let mut bytes_read: u32 = 0;
let result = stream2.Read(
buffer.as_mut_ptr() as *mut ::core::ffi::c_void,
buffer.len() as u32,
&mut bytes_read,
);
if result.is_err() {
let _ = tx.send(Err(result.message().to_string()));
return Ok(());
}
if bytes_read == 0 {
break;
}
data.extend_from_slice(&buffer[..bytes_read as usize]);
}
tx1.send(Ok(data)).unwrap();
return Ok(());
}));
let result = webview
.controller()
.CoreWebView2()
.unwrap()
.cast::<ICoreWebView2_15>()
.unwrap()
.CapturePreview(
COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG,
&stream1,
&handler,
);
if let Err(err) = result {
tx2.send(Err(err.to_string())).unwrap();
}
}
#[cfg(all(target_os = "linux", not(windows)))]
unsafe {
tx.send(Err("Unsupported platform: Linux".to_string()))
.unwrap();
}
#[cfg(all(target_os = "macos", not(windows)))]
unsafe {
tx.send(Err("Unsupported platform: macOS".to_string()))
.unwrap();
}
});
match rx.recv() {
Ok(data) => data,
Err(err) => Err(err.to_string()),
}
}
#[derive(Serialize, Debug, Clone)]
pub struct Point2D {
pub x: i32,
pub y: i32,
}
/// Get current cursor position
pub fn get_cursor_position() -> Result<Point2D, String> {
#[cfg(windows)]
unsafe {
let mut pos = POINT { x: 0, y: 0 };
GetCursorPos(&mut pos);
return Ok(Point2D { x: pos.x, y: pos.y });
}
#[cfg(all(target_os = "linux", not(windows)))]
unsafe {
return Err("Unsupported platform: Linux".to_string());
}
#[cfg(all(target_os = "macos", not(windows)))]
unsafe {
return Err("Unsupported platform: macOS".to_string());
}
}
/// Check if the cursor is on the given window, return bool and relative position.
pub fn is_mouse_on_window(window: Arc<Window>) -> Result<(bool, Point2D), Box<dyn Error>> {
if let Ok(true) = window.is_visible() {
let cur_pos = get_cursor_position()?;
let win_pos = window.inner_position()?;
let win_size = window.inner_size()?;
let pix_pos: Point2D = Point2D {
x: cur_pos.x - win_pos.x,
y: cur_pos.y - win_pos.y,
};
if (pix_pos.x > 0 && pix_pos.x < win_size.width as i32)
&& (pix_pos.y > 0 && pix_pos.y < win_size.height as i32)
{
return Ok((true, pix_pos));
}
}
return Ok((false, Point2D { x: 0, y: 0 }));
}
/// Switch ignore cursor events based on alpha.
pub fn use_mouse_through(window1: Arc<Window>) {
let window2 = window1.clone();
let kill_signal1 = Arc::new(Mutex::new(false));
let kill_signal2 = kill_signal1.clone();
let kill_signal3 = kill_signal1.clone();
let buffer1: Arc<Mutex<(Vec<u8>, u32, u32)>> = Arc::new(Mutex::new((Vec::new(), 0, 0)));
let buffer2 = buffer1.clone();
// When the window is destroyed, set the kill signal for threads.
window1.clone().on_window_event(move |event| match event {
WindowEvent::Destroyed => {
println!("[use_mouse_through] A window is destroyed, Set the kill signal.");
*kill_signal1.lock().unwrap() = true;
}
_ => {}
});
// Capture preview thread
thread::spawn(move || loop {
if *kill_signal2.lock().unwrap() {
println!("[use_mouse_through] Thread break of capture preview.");
break;
}
match is_mouse_on_window(window1.clone()) {
Ok((true, _)) => {
if let Ok(png_data) = capture_preview(&window1) {
if let Ok((bitmap, width, height)) = decode_png(&png_data) {
let mut buffer = buffer1.lock().unwrap();
buffer.0.clear();
buffer.0.extend_from_slice(&bitmap);
buffer.1 = width;
buffer.2 = height;
}
}
}
Ok((false, _)) => {}
Err(_) => break,
}
thread::sleep(Duration::from_millis(100));
});
// Switch ignore cursor events thread
thread::spawn(move || loop {
if *kill_signal3.lock().unwrap() {
println!("[use_mouse_through] Thread break of switch ignore cursor events.");
break;
}
match is_mouse_on_window(window2.clone()) {
Ok((true, pix_pos)) => {
let buffer = buffer2.lock().unwrap();
if let Some(color) =
get_pixel_color(&buffer.0, buffer.1, pix_pos.x as u32, pix_pos.y as u32)
{
let _ = window2.set_ignore_cursor_events(color.3 == 0);
}
}
Ok((false, _)) => {}
Err(_) => break,
}
thread::sleep(Duration::from_millis(16));
});
}
@LZQCN tauri v2 的版本有么