| 1 | // Copyright © SixtyFPS GmbH <info@slint.dev> |
| 2 | // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0 |
| 3 | |
| 4 | use napi::{ |
| 5 | bindgen_prelude::{FromNapiValue, Object}, |
| 6 | JsUnknown, Result, |
| 7 | }; |
| 8 | |
| 9 | /// SlintPoint implements {@link Size}. |
| 10 | #[napi ] |
| 11 | pub struct SlintSize { |
| 12 | pub width: f64, |
| 13 | pub height: f64, |
| 14 | } |
| 15 | |
| 16 | #[napi ] |
| 17 | impl SlintSize { |
| 18 | /// Constructs a size from the given width and height. |
| 19 | #[napi (constructor)] |
| 20 | pub fn new(width: f64, height: f64) -> Result<Self> { |
| 21 | if width < 0. { |
| 22 | return Err(napi::Error::from_reason("width cannot be negative" .to_string())); |
| 23 | } |
| 24 | |
| 25 | if height < 0. { |
| 26 | return Err(napi::Error::from_reason("height cannot be negative" .to_string())); |
| 27 | } |
| 28 | |
| 29 | Ok(Self { width, height }) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl FromNapiValue for SlintSize { |
| 34 | unsafe fn from_napi_value( |
| 35 | env: napi::sys::napi_env, |
| 36 | napi_val: napi::sys::napi_value, |
| 37 | ) -> napi::Result<Self> { |
| 38 | let obj = unsafe { Object::from_napi_value(env, napi_val)? }; |
| 39 | let width: f64 = obj |
| 40 | .get::<_, JsUnknown>("width" ) |
| 41 | .ok() |
| 42 | .flatten() |
| 43 | .and_then(|p| p.coerce_to_number().ok()) |
| 44 | .and_then(|f64_num| f64_num.try_into().ok()) |
| 45 | .ok_or_else( |
| 46 | || napi::Error::from_reason( |
| 47 | "Cannot convert object to Size, because the provided object does not have an f64 width property" .to_string() |
| 48 | ))?; |
| 49 | let height: f64 = obj |
| 50 | .get::<_, JsUnknown>("height" ) |
| 51 | .ok() |
| 52 | .flatten() |
| 53 | .and_then(|p| p.coerce_to_number().ok()) |
| 54 | .and_then(|f64_num| f64_num.try_into().ok()) |
| 55 | .ok_or_else( |
| 56 | || napi::Error::from_reason( |
| 57 | "Cannot convert object to Size, because the provided object does not have an f64 height property" .to_string() |
| 58 | ))?; |
| 59 | |
| 60 | Ok(SlintSize { width, height }) |
| 61 | } |
| 62 | } |
| 63 | |