Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main'
Browse files Browse the repository at this point in the history
  • Loading branch information
Vrtgs committed Aug 24, 2024
2 parents 5689304 + 47212e2 commit 4167243
Show file tree
Hide file tree
Showing 5 changed files with 161 additions and 1 deletion.
8 changes: 8 additions & 0 deletions thirtyfour/src/common/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::common::{
capabilities::desiredcapabilities::make_w3c_caps,
cookie::Cookie,
keys::TypingData,
print::PrintParameters,
types::{ElementId, OptionRect, SessionId, TimeoutConfiguration, WindowHandle},
};
use crate::IntoArcStr;
Expand Down Expand Up @@ -248,6 +249,7 @@ pub enum Command {
AcceptAlert,
GetAlertText,
SendAlertText(TypingData),
PrintPage(PrintParameters),
TakeScreenshot,
TakeElementScreenshot(ElementId),
ExtensionCommand(Box<dyn ExtensionCommand + Send + Sync>),
Expand Down Expand Up @@ -493,6 +495,12 @@ impl FormatRequestData for Command {
"value": typing_data.as_vec(), "text": typing_data.to_string()
}))
}
Command::PrintPage(params) => {
RequestData::new(Method::POST, format!("/session/{}/print", session_id)).add_body(
serde_json::to_value(params)
.expect("Fail to parse Print Page Parameters to json"),
)
}
Command::TakeScreenshot => {
RequestData::new(Method::GET, format!("/session/{}/screenshot", session_id))
}
Expand Down
2 changes: 2 additions & 0 deletions thirtyfour/src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ pub mod config;
pub mod cookie;
/// Types for working with keyboard input.
pub mod keys;
/// Types used with print commands.
pub mod print;
/// Type for request method and body.
pub mod requestdata;
/// Common types used within thirtyfour.
Expand Down
126 changes: 126 additions & 0 deletions thirtyfour/src/common/print.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
use serde::{de, Deserialize, Deserializer, Serialize};
use std::sync::Arc;

/// Enum representing the ranges of pages to print
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PrintPageRange {
/// Single page
Integer(u64),
/// Range of pages hyphen-separated.
Range(Arc<str>),
}

/// Parameters of printing operation
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PrintParameters {
/// Print orientation
pub orientation: PrintOrientation,
/// Print scale
#[serde(deserialize_with = "deserialize_to_print_scale_f64")]
pub scale: f64,
/// Print background
pub background: bool,
/// Dimentions of page
pub page: PrintPage,
/// Margins of the print
pub margin: PrintMargins,
/// Ranges of pages to print
pub page_ranges: Arc<[PrintPageRange]>,
/// Shrink page to fit
pub shrink_to_fit: bool,
}

impl Default for PrintParameters {
fn default() -> Self {
PrintParameters {
orientation: PrintOrientation::default(),
scale: 1.0,
background: false,
page: PrintPage::default(),
margin: PrintMargins::default(),
page_ranges: Arc::new([]),
shrink_to_fit: true,
}
}
}

/// Enum representing the printing orientation
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PrintOrientation {
/// Print in landscape mode
Landscape,
/// Print in portrait mode
#[default]
Portrait,
}

/// Page dimentions with units in cm
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrintPage {
/// Page width, units in cm
#[serde(deserialize_with = "deserialize_to_positive_f64")]
pub width: f64,
/// Page height, units in cm
#[serde(deserialize_with = "deserialize_to_positive_f64")]
pub height: f64,
}

impl Default for PrintPage {
fn default() -> Self {
PrintPage {
width: 21.59,
height: 27.94,
}
}
}

/// Page margins
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrintMargins {
/// Top margin, units in cm
pub top: f64,
/// Bottom margin, units in cm
pub bottom: f64,
/// Left margin, units in cm
pub left: f64,
/// Right margin, units in cm
pub right: f64,
}

impl Default for PrintMargins {
fn default() -> Self {
PrintMargins {
top: 1.0,
bottom: 1.0,
left: 1.0,
right: 1.0,
}
}
}

fn deserialize_to_positive_f64<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
D: Deserializer<'de>,
{
let val = f64::deserialize(deserializer)?;
if val < 0.0 {
return Err(de::Error::custom(format!("{} is negative", val)));
};
Ok(val)
}

fn deserialize_to_print_scale_f64<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
D: Deserializer<'de>,
{
let val = f64::deserialize(deserializer)?;
if !(0.1..=2.0).contains(&val) {
return Err(de::Error::custom(format!("{} is outside range 0.1-2", val)));
};
Ok(val)
}
11 changes: 11 additions & 0 deletions thirtyfour/src/session/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use crate::action_chain::ActionChain;
use crate::common::command::{Command, FormatRequestData};
use crate::common::config::WebDriverConfig;
use crate::common::cookie::Cookie;
use crate::common::print::PrintParameters;
use crate::error::WebDriverResult;
use crate::prelude::WebDriverError;
use crate::session::scriptret::ScriptRet;
Expand Down Expand Up @@ -1040,6 +1041,16 @@ impl SessionHandle {
Ok(())
}

/// Print the current window and return it as a PDF.
pub async fn print_page(&self, parameters: PrintParameters) -> WebDriverResult<Vec<u8>> {
base64_decode(&self.print_page_base64(parameters).await?)
}

/// Print the current window and return it as a PDF, base64 encoded.
pub async fn print_page_base64(&self, parameters: PrintParameters) -> WebDriverResult<String> {
self.cmd(Command::PrintPage(parameters)).await?.value()
}

/// Take a screenshot of the current window and return it as PNG, base64 encoded.
pub async fn screenshot_as_png_base64(&self) -> WebDriverResult<String> {
self.cmd(Command::TakeScreenshot).await?.value()
Expand Down
15 changes: 14 additions & 1 deletion thirtyfour/tests/window.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use common::*;
use rstest::rstest;
use thirtyfour::{prelude::*, support::block_on};
use thirtyfour::{common::print::PrintParameters, prelude::*, support::block_on};

mod common;

Expand Down Expand Up @@ -245,3 +245,16 @@ fn screenshot(test_harness: TestHarness<'_>) -> WebDriverResult<()> {
Ok(())
})
}

#[rstest]
fn print_page(test_harness: TestHarness<'_>) -> WebDriverResult<()> {
let c = test_harness.driver();
block_on(async {
let url = sample_page_url();
c.goto(&url).await?;

let printing_data = c.print_page(PrintParameters::default()).await?;
assert!(!printing_data.is_empty(), "printing data is empty");
Ok(())
})
}

0 comments on commit 4167243

Please sign in to comment.