Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
//! Camera, microphone, screen share, geolocation, and spellcheck for pages on Linux.
//!
//! WebKitGTK refuses `getUserMedia`, `getDisplayMedia`, and geolocation unless
//! the embedder answers its `permission-request` signal, and neither wry nor
//! Pake did for screen share or geolocation (and screen share previously fell
//! into the microphone label). Linux has no system prompt for this as macOS
//! and WebView2 do, so Pake asks once per site, permission kind, and run.
use crate::util::UiLanguage;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PermissionKind {
CameraAndMicrophone,
Camera,
Microphone,
Screen,
Location,
}
impl PermissionKind {
pub fn from_media(audio: bool, video: bool, display: bool) -> Self {
if display {
PermissionKind::Screen
} else {
match (audio, video) {
(true, true) => PermissionKind::CameraAndMicrophone,
(false, true) => PermissionKind::Camera,
_ => PermissionKind::Microphone,
}
}
}
fn key_suffix(self) -> &'static str {
match self {
PermissionKind::CameraAndMicrophone => "11",
PermissionKind::Camera => "01",
PermissionKind::Microphone => "10",
PermissionKind::Screen => "screen",
PermissionKind::Location => "location",
}
}
}
#[cfg(target_os = "linux")]
pub fn install(webview: &tauri::webview::PlatformWebview) {
use gtk::prelude::*;
use std::cell::RefCell;
use std::collections::HashMap;
use webkit2gtk::glib::translate::ToGlibPtr;
use webkit2gtk::{
DeviceInfoPermissionRequest, GeolocationPermissionRequest, PermissionRequestExt,
SettingsExt, UserMediaPermissionRequest, UserMediaPermissionRequestExt, WebContextExt,
WebViewExt,
};
thread_local! {
/// The answers given in this run, by host and permission kind.
static ANSWERS: RefCell<HashMap<String, bool>> = RefCell::new(HashMap::new());
}
fn answer(request: &webkit2gtk::PermissionRequest, allowed: bool) {
if allowed {
request.allow();
} else {
request.deny();
}
}
fn host_was_allowed_media(host: &str) -> bool {
let prefix = format!("{host}|");
ANSWERS.with(|answers| {
answers.borrow().iter().any(|(key, allowed)| {
*allowed
&& key.starts_with(&prefix)
&& !key.ends_with("|location")
&& !key.ends_with("|screen")
})
})
}
let gtk_webview = webview.inner();
if let Some(settings) = WebViewExt::settings(>k_webview) {
settings.set_enable_media_stream(true);
settings.set_enable_webrtc(true);
}
if let Some(context) = WebViewExt::context(>k_webview) {
context.set_spell_checking_enabled(true);
}
gtk_webview.connect_permission_request(|webview, request| {
let host = webview
.uri()
.and_then(|uri| tauri::Url::parse(uri.as_str()).ok())
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_default();
// Device labels in enumerateDevices follow what the site was already allowed.
if request.is::<DeviceInfoPermissionRequest>() {
if host_was_allowed_media(&host) {
request.allow();
} else {
request.deny();
}
return true;
}
let kind = if request.is::<GeolocationPermissionRequest>() {
PermissionKind::Location
} else if let Some(media) = request.downcast_ref::<UserMediaPermissionRequest>() {
let display = unsafe {
webkit2gtk::ffi::webkit_user_media_permission_is_for_display_device(
media.to_glib_none().0,
) != 0
};
PermissionKind::from_media(
media.is_for_audio_device(),
media.is_for_video_device(),
display,
)
} else {
return false;
};
let key = answer_key_for_kind(&host, kind);
if let Some(allowed) = ANSWERS.with(|answers| answers.borrow().get(&key).copied()) {
answer(request, allowed);
return true;
}
let parent = webview
.toplevel()
.and_then(|widget| widget.downcast::<gtk::Window>().ok());
let (question, deny, allow) = prompt_text_for_kind(&host, kind, UiLanguage::system());
let dialog = gtk::MessageDialog::new(
parent.as_ref(),
gtk::DialogFlags::MODAL | gtk::DialogFlags::DESTROY_WITH_PARENT,
gtk::MessageType::Question,
gtk::ButtonsType::None,
&question,
);
dialog.add_button(deny, gtk::ResponseType::Reject);
dialog.add_button(allow, gtk::ResponseType::Accept);
let request = request.clone();
// The request is answered once: destroying the dialog raises no second response, where
// close() would send a delete-event and with it another one.
let answered = std::cell::Cell::new(false);
dialog.connect_response(move |dialog, response| {
if answered.replace(true) {
return;
}
// Closing the dialog without choosing is a refusal that is asked again next time.
if matches!(
response,
gtk::ResponseType::Accept | gtk::ResponseType::Reject
) {
let allowed = response == gtk::ResponseType::Accept;
ANSWERS.with(|answers| answers.borrow_mut().insert(key.clone(), allowed));
answer(&request, allowed);
} else {
request.deny();
}
unsafe { dialog.destroy() };
});
dialog.show();
true
});
}
pub(crate) fn answer_key_for_kind(host: &str, kind: PermissionKind) -> String {
format!("{host}|{}", kind.key_suffix())
}
#[cfg(test)]
pub(crate) fn answer_key(host: &str, audio: bool, video: bool) -> String {
answer_key_for_kind(host, PermissionKind::from_media(audio, video, false))
}
/// Localized permission prompt question and its two buttons (refusal first) across all 5 UI languages.
pub(crate) fn prompt_text_for_kind(
host: &str,
kind: PermissionKind,
language: UiLanguage,
) -> (String, &'static str, &'static str) {
let site = if host.is_empty() { "This page" } else { host };
match language {
UiLanguage::English => {
let question = match kind {
PermissionKind::CameraAndMicrophone => {
format!("{site} wants to use your camera and microphone")
}
PermissionKind::Camera => format!("{site} wants to use your camera"),
PermissionKind::Microphone => format!("{site} wants to use your microphone"),
PermissionKind::Screen => format!("{site} wants to share your screen"),
PermissionKind::Location => format!("{site} wants to access your location"),
};
(question, "Don't Allow", "Allow")
}
UiLanguage::SimplifiedChinese => {
let site = if host.is_empty() { "此页面" } else { host };
let target = match kind {
PermissionKind::CameraAndMicrophone => "使用摄像头和麦克风",
PermissionKind::Camera => "使用摄像头",
PermissionKind::Microphone => "使用麦克风",
PermissionKind::Screen => "共享您的屏幕",
PermissionKind::Location => "获取您的位置信息",
};
(format!("{site} 想{target}"), "不允许", "允许")
}
UiLanguage::TraditionalChinese => {
let site = if host.is_empty() { "此頁面" } else { host };
let target = match kind {
PermissionKind::CameraAndMicrophone => "使用攝影機與麥克風",
PermissionKind::Camera => "使用攝影機",
PermissionKind::Microphone => "使用麥克風",
PermissionKind::Screen => "分享您的螢幕畫面",
PermissionKind::Location => "存取您的位置資訊",
};
(format!("{site} 想要{target}"), "不允許", "允許")
}
UiLanguage::German => {
let site = if host.is_empty() { "Diese Seite" } else { host };
let question = match kind {
PermissionKind::CameraAndMicrophone => {
format!("{site} möchte auf Ihre Kamera und Ihr Mikrofon zugreifen")
}
PermissionKind::Camera => format!("{site} möchte auf Ihre Kamera zugreifen"),
PermissionKind::Microphone => format!("{site} möchte auf Ihr Mikrofon zugreifen"),
PermissionKind::Screen => format!("{site} möchte Ihren Bildschirm teilen"),
PermissionKind::Location => format!("{site} möchte auf Ihren Standort zugreifen"),
};
(question, "Nicht erlauben", "Erlauben")
}
UiLanguage::French => {
let site = if host.is_empty() { "Cette page" } else { host };
let question = match kind {
PermissionKind::CameraAndMicrophone => {
format!("{site} souhaite utiliser votre caméra et votre microphone")
}
PermissionKind::Camera => format!("{site} souhaite utiliser votre caméra"),
PermissionKind::Microphone => format!("{site} souhaite utiliser votre microphone"),
PermissionKind::Screen => format!("{site} souhaite partager votre écran"),
PermissionKind::Location => format!("{site} souhaite accéder à votre position"),
};
(question, "Ne pas autoriser", "Autoriser")
}
}
}
#[cfg(test)]
pub(crate) fn prompt_text(
host: &str,
audio: bool,
video: bool,
chinese: bool,
) -> (String, &'static str, &'static str) {
let language = if chinese {
UiLanguage::SimplifiedChinese
} else {
UiLanguage::English
};
prompt_text_for_kind(
host,
PermissionKind::from_media(audio, video, false),
language,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_prompt_names_the_site_and_only_the_devices_asked_for() {
assert_eq!(
prompt_text("meet.google.com", true, true, false).0,
"meet.google.com wants to use your camera and microphone"
);
assert_eq!(
prompt_text("chatgpt.com", true, false, false).0,
"chatgpt.com wants to use your microphone"
);
assert_eq!(
prompt_text("meet.google.com", false, true, true),
("meet.google.com 想使用摄像头".to_string(), "不允许", "允许")
);
}
#[test]
fn screen_share_and_geolocation_use_distinct_prompts_in_all_five_languages() {
assert_eq!(
PermissionKind::from_media(false, false, true),
PermissionKind::Screen
);
for language in UiLanguage::all() {
let (screen_q, deny, allow) =
prompt_text_for_kind("meet.google.com", PermissionKind::Screen, language);
let (mic_q, _, _) =
prompt_text_for_kind("meet.google.com", PermissionKind::Microphone, language);
let (loc_q, _, _) =
prompt_text_for_kind("maps.google.com", PermissionKind::Location, language);
assert_ne!(
screen_q, mic_q,
"screen share called microphone in {language:?}"
);
assert_ne!(loc_q, mic_q);
assert_ne!(deny, allow);
}
}
#[test]
fn an_answer_is_kept_per_site_and_device_kinds() {
assert_ne!(
answer_key("a.example", true, false),
answer_key("a.example", true, true)
);
assert_ne!(
answer_key("a.example", true, true),
answer_key("b.example", true, true)
);
assert_ne!(
answer_key_for_kind("a.example", PermissionKind::Microphone),
answer_key_for_kind("a.example", PermissionKind::Screen)
);
assert_ne!(
answer_key_for_kind("a.example", PermissionKind::Screen),
answer_key_for_kind("a.example", PermissionKind::Location)
);
}
}