Эх сурвалжийг харах

Open external links in system browser

Johannes Zellner 5 сар өмнө
parent
commit
677d812b2d
1 өөрчлөгдсөн 62 нэмэгдсэн , 9 устгасан
  1. 62 9
      src/main.rs

+ 62 - 9
src/main.rs

@@ -159,6 +159,30 @@ fn navigation_targets_blank_frame(action: &NavigationAction) -> bool {
         .is_some_and(|n| n.eq_ignore_ascii_case("_blank"))
 }
 
+/// Extract the origin (scheme + host + port) from a URL.
+fn url_origin(url: &str) -> Option<String> {
+    let parsed = url::Url::parse(url).ok()?;
+    let scheme = parsed.scheme();
+    let host = parsed.host_str()?;
+    let port = parsed.port_or_known_default()?;
+    Some(format!("{}://{}:{}", scheme, host, port))
+}
+
+/// Check if two URLs share the same origin (scheme + host + port).
+fn is_same_origin(url_a: &str, url_b: &str) -> bool {
+    match (url_origin(url_a), url_origin(url_b)) {
+        (Some(a), Some(b)) => a == b,
+        _ => false,
+    }
+}
+
+/// Open a URI in the system's default browser.
+fn open_in_system_browser(uri: &str) {
+    if let Err(e) = gtk4::gio::AppInfo::launch_default_for_uri(uri, Option::<&gtk4::gio::AppLaunchContext>::None) {
+        eprintln!("appiphany: failed to open URI in system browser: {}", e);
+    }
+}
+
 /// `window.open()` and `target="_blank"` both go through [`PolicyDecisionType::NewWindowAction`].
 /// Links that target `_blank` load in this view; other new-window requests get a real window via
 /// [`WebViewExt::connect_create`].
@@ -166,33 +190,59 @@ fn wire_webview_window_policy(
     host_window: &ApplicationWindow,
     webview: &WebView,
     network_session: &NetworkSession,
+    initial_url: String,
 ) {
     let network_for_create = network_session.clone();
     let host_window_for_create = host_window.clone();
+    let initial_url_for_nav = initial_url.clone();
+    let initial_url_for_create = initial_url.clone();
+    let initial_url_for_create_2 = initial_url.clone();
 
     webview.connect_decide_policy(move |w, decision, decision_type| {
-        if decision_type != PolicyDecisionType::NewWindowAction {
-            return false;
-        }
         let Some(nav_decision) = decision.dynamic_cast_ref::<NavigationPolicyDecision>() else {
             return false;
         };
         let Some(action) = nav_decision.navigation_action() else {
-            decision.ignore();
-            return true;
+            return false;
         };
+        let Some(uri) = action.request().and_then(|r| r.uri()) else {
+            return false;
+        };
+
+        if decision_type == PolicyDecisionType::NavigationAction {
+            if action.navigation_type() == NavigationType::LinkClicked
+                && !is_same_origin(&initial_url_for_nav, &uri)
+            {
+                decision.ignore();
+                open_in_system_browser(&uri);
+                return true;
+            }
+            return false;
+        }
+
+        if decision_type != PolicyDecisionType::NewWindowAction {
+            return false;
+        }
 
         if action.navigation_type() == NavigationType::LinkClicked
             && action.mouse_button() != 2
             && navigation_targets_blank_frame(&action)
         {
             decision.ignore();
-            if let Some(uri) = action.request().and_then(|r| r.uri()) {
+            if is_same_origin(&initial_url_for_create, &uri) {
                 w.load_uri(&uri);
+            } else {
+                open_in_system_browser(&uri);
             }
             return true;
         }
 
+        if !is_same_origin(&initial_url_for_create, &uri) {
+            decision.ignore();
+            open_in_system_browser(&uri);
+            return true;
+        }
+
         decision.use_();
         true
     });
@@ -206,7 +256,7 @@ fn wire_webview_window_policy(
             .default_height(768)
             .build();
 
-        let popup = build_appiphany_webview(&window, &network_for_create, Some(parent));
+        let popup = build_appiphany_webview(&window, &network_for_create, Some(parent), initial_url_for_create_2.clone());
         let shell = build_overlay_with_webview(&popup);
         window.set_content(Some(&shell));
         window.present();
@@ -218,10 +268,13 @@ fn wire_webview_window_policy(
 ///
 /// `related_to` should be the opener when this view is created for `window.open()` so WebKit can
 /// share the rendering process with the parent.
+/// `initial_url` is used to determine whether navigation should stay in the app or open in the
+/// system browser.
 fn build_appiphany_webview(
     window: &ApplicationWindow,
     network_session: &NetworkSession,
     related_to: Option<&WebView>,
+    initial_url: String,
 ) -> WebView {
     let ucm = UserContentManager::new();
     if !ucm.register_script_message_handler(WINDOW_DRAG_MESSAGE_HANDLER, None) {
@@ -261,7 +314,7 @@ fn build_appiphany_webview(
         );
     }
 
-    wire_webview_window_policy(window, &webview, network_session);
+    wire_webview_window_policy(window, &webview, network_session, initial_url);
 
     webview
 }
@@ -347,7 +400,7 @@ fn open_web_window(app: &Application, url: &str) {
         .build();
 
     let network_session = network_session_for_app(app);
-    let webview = build_appiphany_webview(&window, &network_session, None);
+    let webview = build_appiphany_webview(&window, &network_session, None, url.to_string());
     let shell = build_overlay_with_webview(&webview);
     window.set_content(Some(&shell));
     webview.load_uri(url);