Skip to content
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

feat: add MacOS print options #1259

Merged
merged 8 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
8 changes: 8 additions & 0 deletions .changes/macos_print_options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"wry": minor
---

Default the margin when printing on MacOS to 0 so it is closer to the behavior
of when printing on the web. It also add a new function to WebViewExtMacOS
called print_with_options which allows the user to modify the margins that
will be sent down to the AppKit print operation (NSPrintInfo).
augustoccesar marked this conversation as resolved.
Show resolved Hide resolved
93 changes: 93 additions & 0 deletions examples/print.rs
augustoccesar marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use tao::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoopBuilder},
window::WindowBuilder,
};
use wry::http::Request;
use wry::WebViewBuilder;

enum UserEvent {
Print,
}

fn main() -> wry::Result<()> {
let event_loop = EventLoopBuilder::<UserEvent>::with_user_event().build();
let proxy = event_loop.create_proxy();
let window = WindowBuilder::new().build(&event_loop).unwrap();

#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
))]
let builder = WebViewBuilder::new(&window);

#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "ios",
target_os = "android"
)))]
let builder = {
use tao::platform::unix::WindowExtUnix;
use wry::WebViewBuilderExtUnix;
let vbox = window.default_vbox().unwrap();
WebViewBuilder::new_gtk(vbox)
};

let ipc_handler = move |req: Request<String>| {
let body = req.body();
match body.as_str() {
"print" => {
let _ = proxy.send_event(UserEvent::Print);
}
_ => {}
}
};

let webview = builder
.with_html(
r#"
<button onclick="window.ipc.postMessage('print')">Print window</button>
"#,
)
.with_ipc_handler(ipc_handler)
.build()?;

event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;

match event {
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
Event::UserEvent(UserEvent::Print) => {
#[cfg(target_os = "macos")]
{
use wry::{PrintOptions, WebViewExtMacOS};

let print_options = PrintOptions {
margins: wry::PrintMargin {
top: 20.0,
right: 0.0,
bottom: 0.0,
left: 20.0,
},
};

webview.print_with_options(&print_options).unwrap();
}

#[cfg(not(target_os = "macos"))]
webview.print().unwrap();
}
_ => {}
}
});
}
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ use webkitgtk::*;
pub(crate) mod wkwebview;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use wkwebview::*;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub use wkwebview::{PrintMargin, PrintOptions};

#[cfg(target_os = "windows")]
pub(crate) mod webview2;
Expand Down Expand Up @@ -1598,6 +1600,8 @@ pub trait WebViewExtMacOS {
fn ns_window(&self) -> cocoa::base::id;
/// Attaches this webview to the given NSWindow and removes it from the current one.
fn reparent(&self, window: cocoa::base::id) -> Result<()>;
// Prints with extra options
fn print_with_options(&self, options: &PrintOptions) -> Result<()>;
}

#[cfg(target_os = "macos")]
Expand All @@ -1620,6 +1624,10 @@ impl WebViewExtMacOS for WebView {
fn reparent(&self, window: cocoa::base::id) -> Result<()> {
self.webview.reparent(window)
}

fn print_with_options(&self, options: &PrintOptions) -> Result<()> {
self.webview.print_with_options(options)
}
}

/// Additional methods on `WebView` that are specific to iOS.
Expand Down
34 changes: 34 additions & 0 deletions src/wkwebview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ use std::{
sync::{Arc, Mutex},
};

use core_graphics::base::CGFloat;
use core_graphics::geometry::{CGPoint, CGRect, CGSize};

use objc::{
declare::ClassDecl,
runtime::{Class, Object, Sel, BOOL},
Expand Down Expand Up @@ -79,6 +81,30 @@ const NS_JSON_WRITING_FRAGMENTS_ALLOWED: u64 = 4;
static COUNTER: Counter = Counter::new();
static WEBVIEW_IDS: Lazy<Mutex<HashSet<u32>>> = Lazy::new(Default::default);

#[derive(Debug)]
pub struct PrintMargin {
pub top: f32,
pub right: f32,
pub bottom: f32,
pub left: f32,
}

impl Default for PrintMargin {
fn default() -> Self {
PrintMargin {
top: 0.0,
right: 0.0,
bottom: 0.0,
left: 0.0,
}
}
}
augustoccesar marked this conversation as resolved.
Show resolved Hide resolved

#[derive(Debug, Default)]
augustoccesar marked this conversation as resolved.
Show resolved Hide resolved
pub struct PrintOptions {
pub margins: PrintMargin,
}

pub(crate) struct InnerWebView {
pub webview: id,
pub manager: id,
Expand Down Expand Up @@ -1122,6 +1148,10 @@ r#"Object.defineProperty(window, 'ipc', {
}

pub fn print(&self) -> crate::Result<()> {
self.print_with_options(&PrintOptions::default())
}

pub fn print_with_options(&self, options: &PrintOptions) -> crate::Result<()> {
// Safety: objc runtime calls are unsafe
#[cfg(target_os = "macos")]
unsafe {
Expand All @@ -1133,6 +1163,10 @@ r#"Object.defineProperty(window, 'ipc', {
// Create a shared print info
let print_info: id = msg_send![class!(NSPrintInfo), sharedPrintInfo];
let print_info: id = msg_send![print_info, init];
let () = msg_send![print_info, setTopMargin:CGFloat::from(options.margins.top)];
let () = msg_send![print_info, setRightMargin:CGFloat::from(options.margins.right)];
let () = msg_send![print_info, setBottomMargin:CGFloat::from(options.margins.bottom)];
let () = msg_send![print_info, setLeftMargin:CGFloat::from(options.margins.left)];
// Create new print operation from the webview content
let print_operation: id = msg_send![self.webview, printOperationWithPrintInfo: print_info];
// Allow the modal to detach from the current thread and be non-blocker
Expand Down
Loading